1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
53 using namespace dwarf;
55 STATISTIC(NumTailCalls, "Number of tail calls");
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
65 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
66 default: llvm_unreachable("unknown subtarget type");
67 case X86Subtarget::isDarwin:
68 if (TM.getSubtarget<X86Subtarget>().is64Bit())
69 return new X8664_MachoTargetObjectFile();
70 return new TargetLoweringObjectFileMachO();
71 case X86Subtarget::isELF:
72 if (TM.getSubtarget<X86Subtarget>().is64Bit())
73 return new X8664_ELFTargetObjectFile(TM);
74 return new X8632_ELFTargetObjectFile(TM);
75 case X86Subtarget::isMingw:
76 case X86Subtarget::isCygwin:
77 case X86Subtarget::isWindows:
78 return new TargetLoweringObjectFileCOFF();
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83 : TargetLowering(TM, createTLOF(TM)) {
84 Subtarget = &TM.getSubtarget<X86Subtarget>();
85 X86ScalarSSEf64 = Subtarget->hasSSE2();
86 X86ScalarSSEf32 = Subtarget->hasSSE1();
87 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
89 RegInfo = TM.getRegisterInfo();
92 // Set up the TargetLowering object.
94 // X86 is weird, it always uses i8 for shift amounts and setcc results.
95 setShiftAmountType(MVT::i8);
96 setBooleanContents(ZeroOrOneBooleanContent);
97 setSchedulingPreference(SchedulingForRegPressure);
98 setStackPointerRegisterToSaveRestore(X86StackPtr);
100 if (Subtarget->isTargetDarwin()) {
101 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
102 setUseUnderscoreSetJmp(false);
103 setUseUnderscoreLongJmp(false);
104 } else if (Subtarget->isTargetMingw()) {
105 // MS runtime is weird: it exports _setjmp, but longjmp!
106 setUseUnderscoreSetJmp(true);
107 setUseUnderscoreLongJmp(false);
109 setUseUnderscoreSetJmp(true);
110 setUseUnderscoreLongJmp(true);
113 // Set up the register classes.
114 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
115 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
116 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
117 if (Subtarget->is64Bit())
118 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
120 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
122 // We don't accept any truncstore of integer registers.
123 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
124 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
125 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
126 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
127 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
128 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
130 // SETOEQ and SETUNE require checking two conditions.
131 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
132 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
133 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
134 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
135 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
136 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
138 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
140 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
141 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
142 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
144 if (Subtarget->is64Bit()) {
145 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
146 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
147 } else if (!UseSoftFloat) {
148 if (X86ScalarSSEf64) {
149 // We have an impenetrably clever algorithm for ui64->double only.
150 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
152 // We have an algorithm for SSE2, and we turn this into a 64-bit
153 // FILD for other targets.
154 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
157 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
159 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
160 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
163 // SSE has no i16 to fp conversion, only i32
164 if (X86ScalarSSEf32) {
165 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
166 // f32 and f64 cases are Legal, f80 case is not
167 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
169 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
170 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
173 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
174 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
177 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
178 // are Legal, f80 is custom lowered.
179 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
180 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
182 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
184 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
185 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
187 if (X86ScalarSSEf32) {
188 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
189 // f32 and f64 cases are Legal, f80 case is not
190 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
192 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
193 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
196 // Handle FP_TO_UINT by promoting the destination to a larger signed
198 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
199 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
200 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
202 if (Subtarget->is64Bit()) {
203 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
204 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
205 } else if (!UseSoftFloat) {
206 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
207 // Expand FP_TO_UINT into a select.
208 // FIXME: We would like to use a Custom expander here eventually to do
209 // the optimal thing for SSE vs. the default expansion in the legalizer.
210 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
212 // With SSE3 we can use fisttpll to convert to a signed i64; without
213 // SSE, we're stuck with a fistpll.
214 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
217 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
218 if (!X86ScalarSSEf64) {
219 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
220 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
223 // Scalar integer divide and remainder are lowered to use operations that
224 // produce two results, to match the available instructions. This exposes
225 // the two-result form to trivial CSE, which is able to combine x/y and x%y
226 // into a single instruction.
228 // Scalar integer multiply-high is also lowered to use two-result
229 // operations, to match the available instructions. However, plain multiply
230 // (low) operations are left as Legal, as there are single-result
231 // instructions for this in x86. Using the two-result multiply instructions
232 // when both high and low results are needed must be arranged by dagcombine.
233 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
234 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
235 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
236 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
237 setOperationAction(ISD::SREM , MVT::i8 , Expand);
238 setOperationAction(ISD::UREM , MVT::i8 , Expand);
239 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
240 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
241 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
242 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
243 setOperationAction(ISD::SREM , MVT::i16 , Expand);
244 setOperationAction(ISD::UREM , MVT::i16 , Expand);
245 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
246 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
247 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
248 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
249 setOperationAction(ISD::SREM , MVT::i32 , Expand);
250 setOperationAction(ISD::UREM , MVT::i32 , Expand);
251 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
252 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
253 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
254 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
255 setOperationAction(ISD::SREM , MVT::i64 , Expand);
256 setOperationAction(ISD::UREM , MVT::i64 , Expand);
258 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
259 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
260 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
261 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
262 if (Subtarget->is64Bit())
263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
267 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
268 setOperationAction(ISD::FREM , MVT::f32 , Expand);
269 setOperationAction(ISD::FREM , MVT::f64 , Expand);
270 setOperationAction(ISD::FREM , MVT::f80 , Expand);
271 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
273 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
274 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
275 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
276 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
277 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
278 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
279 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
280 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
281 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
282 if (Subtarget->is64Bit()) {
283 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
284 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
285 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
288 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
289 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
291 // These should be promoted to a larger select which is supported.
292 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
293 // X86 wants to expand cmov itself.
294 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
295 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
296 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
297 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
298 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
299 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
300 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
301 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
302 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
303 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
304 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
305 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
306 if (Subtarget->is64Bit()) {
307 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
308 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
310 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
313 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
314 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
315 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
316 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
317 if (Subtarget->is64Bit())
318 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
319 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
320 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
323 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
324 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
325 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
326 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
328 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
329 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
330 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
331 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
332 if (Subtarget->is64Bit()) {
333 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
334 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
335 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
338 if (Subtarget->hasSSE1())
339 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
341 if (!Subtarget->hasSSE2())
342 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
344 // Expand certain atomics
345 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
346 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
347 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
348 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
350 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
351 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
352 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
353 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
355 if (!Subtarget->is64Bit()) {
356 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
357 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
358 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
359 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
360 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
361 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
362 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
365 // FIXME - use subtarget debug flags
366 if (!Subtarget->isTargetDarwin() &&
367 !Subtarget->isTargetELF() &&
368 !Subtarget->isTargetCygMing()) {
369 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
372 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
373 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
374 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
375 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
376 if (Subtarget->is64Bit()) {
377 setExceptionPointerRegister(X86::RAX);
378 setExceptionSelectorRegister(X86::RDX);
380 setExceptionPointerRegister(X86::EAX);
381 setExceptionSelectorRegister(X86::EDX);
383 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
384 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
386 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
388 setOperationAction(ISD::TRAP, MVT::Other, Legal);
390 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
391 setOperationAction(ISD::VASTART , MVT::Other, Custom);
392 setOperationAction(ISD::VAEND , MVT::Other, Expand);
393 if (Subtarget->is64Bit()) {
394 setOperationAction(ISD::VAARG , MVT::Other, Custom);
395 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
397 setOperationAction(ISD::VAARG , MVT::Other, Expand);
398 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
401 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
402 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
403 if (Subtarget->is64Bit())
404 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
405 if (Subtarget->isTargetCygMing())
406 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
408 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
410 if (!UseSoftFloat && X86ScalarSSEf64) {
411 // f32 and f64 use SSE.
412 // Set up the FP register classes.
413 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
414 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
416 // Use ANDPD to simulate FABS.
417 setOperationAction(ISD::FABS , MVT::f64, Custom);
418 setOperationAction(ISD::FABS , MVT::f32, Custom);
420 // Use XORP to simulate FNEG.
421 setOperationAction(ISD::FNEG , MVT::f64, Custom);
422 setOperationAction(ISD::FNEG , MVT::f32, Custom);
424 // Use ANDPD and ORPD to simulate FCOPYSIGN.
425 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
426 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
428 // We don't support sin/cos/fmod
429 setOperationAction(ISD::FSIN , MVT::f64, Expand);
430 setOperationAction(ISD::FCOS , MVT::f64, Expand);
431 setOperationAction(ISD::FSIN , MVT::f32, Expand);
432 setOperationAction(ISD::FCOS , MVT::f32, Expand);
434 // Expand FP immediates into loads from the stack, except for the special
436 addLegalFPImmediate(APFloat(+0.0)); // xorpd
437 addLegalFPImmediate(APFloat(+0.0f)); // xorps
438 } else if (!UseSoftFloat && X86ScalarSSEf32) {
439 // Use SSE for f32, x87 for f64.
440 // Set up the FP register classes.
441 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
442 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
444 // Use ANDPS to simulate FABS.
445 setOperationAction(ISD::FABS , MVT::f32, Custom);
447 // Use XORP to simulate FNEG.
448 setOperationAction(ISD::FNEG , MVT::f32, Custom);
450 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
452 // Use ANDPS and ORPS to simulate FCOPYSIGN.
453 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
454 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
456 // We don't support sin/cos/fmod
457 setOperationAction(ISD::FSIN , MVT::f32, Expand);
458 setOperationAction(ISD::FCOS , MVT::f32, Expand);
460 // Special cases we handle for FP constants.
461 addLegalFPImmediate(APFloat(+0.0f)); // xorps
462 addLegalFPImmediate(APFloat(+0.0)); // FLD0
463 addLegalFPImmediate(APFloat(+1.0)); // FLD1
464 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
465 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
468 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
469 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
471 } else if (!UseSoftFloat) {
472 // f32 and f64 in x87.
473 // Set up the FP register classes.
474 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
475 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
477 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
478 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
479 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
480 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
483 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
484 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
486 addLegalFPImmediate(APFloat(+0.0)); // FLD0
487 addLegalFPImmediate(APFloat(+1.0)); // FLD1
488 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
489 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
490 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
491 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
492 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
493 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
496 // Long double always uses X87.
498 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
499 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
500 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
503 APFloat TmpFlt(+0.0);
504 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
506 addLegalFPImmediate(TmpFlt); // FLD0
508 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
509 APFloat TmpFlt2(+1.0);
510 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
512 addLegalFPImmediate(TmpFlt2); // FLD1
513 TmpFlt2.changeSign();
514 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
518 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
519 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
523 // Always use a library call for pow.
524 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
525 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
526 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
528 setOperationAction(ISD::FLOG, MVT::f80, Expand);
529 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
530 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
531 setOperationAction(ISD::FEXP, MVT::f80, Expand);
532 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
534 // First set operation action for all vector types to either promote
535 // (for widening) or expand (for scalarization). Then we will selectively
536 // turn on ones that can be effectively codegen'd.
537 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
538 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
539 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
554 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
555 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
588 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
592 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
593 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
594 setTruncStoreAction((MVT::SimpleValueType)VT,
595 (MVT::SimpleValueType)InnerVT, Expand);
596 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
597 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
598 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
601 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
602 // with -msoft-float, disable use of MMX as well.
603 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
604 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass, false);
605 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
606 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
607 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass, false);
608 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
610 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
611 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
612 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
613 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
615 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
616 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
617 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
618 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
620 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
621 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
623 setOperationAction(ISD::AND, MVT::v8i8, Promote);
624 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
625 setOperationAction(ISD::AND, MVT::v4i16, Promote);
626 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
627 setOperationAction(ISD::AND, MVT::v2i32, Promote);
628 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
629 setOperationAction(ISD::AND, MVT::v1i64, Legal);
631 setOperationAction(ISD::OR, MVT::v8i8, Promote);
632 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
633 setOperationAction(ISD::OR, MVT::v4i16, Promote);
634 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
635 setOperationAction(ISD::OR, MVT::v2i32, Promote);
636 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
637 setOperationAction(ISD::OR, MVT::v1i64, Legal);
639 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
640 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
641 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
642 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
643 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
644 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
645 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
647 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
648 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
649 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
650 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
651 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
652 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
653 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
654 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
655 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
657 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
658 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
659 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
661 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
663 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
664 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
666 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
668 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
669 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
670 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
671 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
673 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
675 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
676 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
677 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
678 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
679 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
680 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
684 if (!UseSoftFloat && Subtarget->hasSSE1()) {
685 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
687 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
688 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
689 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
690 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
691 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
692 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
693 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
694 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
695 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
696 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
697 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
698 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
701 if (!UseSoftFloat && Subtarget->hasSSE2()) {
702 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
704 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
705 // registers cannot be used even for integer operations.
706 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
707 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
708 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
709 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
711 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
712 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
713 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
714 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
715 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
716 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
717 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
718 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
719 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
720 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
721 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
722 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
723 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
724 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
725 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
726 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
728 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
729 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
730 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
731 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
733 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
734 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
735 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
736 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
737 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
739 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
740 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
741 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
742 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
743 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
745 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
746 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
747 EVT VT = (MVT::SimpleValueType)i;
748 // Do not attempt to custom lower non-power-of-2 vectors
749 if (!isPowerOf2_32(VT.getVectorNumElements()))
751 // Do not attempt to custom lower non-128-bit vectors
752 if (!VT.is128BitVector())
754 setOperationAction(ISD::BUILD_VECTOR,
755 VT.getSimpleVT().SimpleTy, Custom);
756 setOperationAction(ISD::VECTOR_SHUFFLE,
757 VT.getSimpleVT().SimpleTy, Custom);
758 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
759 VT.getSimpleVT().SimpleTy, Custom);
762 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
763 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
764 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
765 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
766 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
767 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
769 if (Subtarget->is64Bit()) {
770 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
771 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
774 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
775 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
776 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
779 // Do not attempt to promote non-128-bit vectors
780 if (!VT.is128BitVector()) {
784 setOperationAction(ISD::AND, SVT, Promote);
785 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
786 setOperationAction(ISD::OR, SVT, Promote);
787 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
788 setOperationAction(ISD::XOR, SVT, Promote);
789 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
790 setOperationAction(ISD::LOAD, SVT, Promote);
791 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
792 setOperationAction(ISD::SELECT, SVT, Promote);
793 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
796 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
798 // Custom lower v2i64 and v2f64 selects.
799 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
800 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
801 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
802 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
804 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
805 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
806 if (!DisableMMX && Subtarget->hasMMX()) {
807 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
808 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
812 if (Subtarget->hasSSE41()) {
813 // FIXME: Do we need to handle scalar-to-vector here?
814 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
816 // i8 and i16 vectors are custom , because the source register and source
817 // source memory operand types are not the same width. f32 vectors are
818 // custom since the immediate controlling the insert encodes additional
820 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
821 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
822 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
823 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
826 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
827 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
828 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
830 if (Subtarget->is64Bit()) {
831 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
832 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
836 if (Subtarget->hasSSE42()) {
837 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
840 if (!UseSoftFloat && Subtarget->hasAVX()) {
841 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
842 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
843 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
844 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
846 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
847 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
848 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
849 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
850 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
851 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
852 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
853 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
854 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
855 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
856 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
857 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
858 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
859 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
860 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
862 // Operations to consider commented out -v16i16 v32i8
863 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
864 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
865 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
866 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
867 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
868 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
869 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
870 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
871 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
872 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
873 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
874 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
875 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
876 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
878 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
879 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
880 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
881 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
883 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
884 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
885 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
887 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
889 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
890 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
891 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
892 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
893 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
894 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
897 // Not sure we want to do this since there are no 256-bit integer
900 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
901 // This includes 256-bit vectors
902 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
903 EVT VT = (MVT::SimpleValueType)i;
905 // Do not attempt to custom lower non-power-of-2 vectors
906 if (!isPowerOf2_32(VT.getVectorNumElements()))
909 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
910 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
911 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
914 if (Subtarget->is64Bit()) {
915 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
916 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
921 // Not sure we want to do this since there are no 256-bit integer
924 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
925 // Including 256-bit vectors
926 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
927 EVT VT = (MVT::SimpleValueType)i;
929 if (!VT.is256BitVector()) {
932 setOperationAction(ISD::AND, VT, Promote);
933 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
934 setOperationAction(ISD::OR, VT, Promote);
935 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
936 setOperationAction(ISD::XOR, VT, Promote);
937 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
938 setOperationAction(ISD::LOAD, VT, Promote);
939 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
940 setOperationAction(ISD::SELECT, VT, Promote);
941 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
944 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
948 // We want to custom lower some of our intrinsics.
949 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
951 // Add/Sub/Mul with overflow operations are custom lowered.
952 setOperationAction(ISD::SADDO, MVT::i32, Custom);
953 setOperationAction(ISD::SADDO, MVT::i64, Custom);
954 setOperationAction(ISD::UADDO, MVT::i32, Custom);
955 setOperationAction(ISD::UADDO, MVT::i64, Custom);
956 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
957 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
958 setOperationAction(ISD::USUBO, MVT::i32, Custom);
959 setOperationAction(ISD::USUBO, MVT::i64, Custom);
960 setOperationAction(ISD::SMULO, MVT::i32, Custom);
961 setOperationAction(ISD::SMULO, MVT::i64, Custom);
963 if (!Subtarget->is64Bit()) {
964 // These libcalls are not available in 32-bit.
965 setLibcallName(RTLIB::SHL_I128, 0);
966 setLibcallName(RTLIB::SRL_I128, 0);
967 setLibcallName(RTLIB::SRA_I128, 0);
970 // We have target-specific dag combine patterns for the following nodes:
971 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
972 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
973 setTargetDAGCombine(ISD::BUILD_VECTOR);
974 setTargetDAGCombine(ISD::SELECT);
975 setTargetDAGCombine(ISD::SHL);
976 setTargetDAGCombine(ISD::SRA);
977 setTargetDAGCombine(ISD::SRL);
978 setTargetDAGCombine(ISD::OR);
979 setTargetDAGCombine(ISD::STORE);
980 setTargetDAGCombine(ISD::MEMBARRIER);
981 setTargetDAGCombine(ISD::ZERO_EXTEND);
982 if (Subtarget->is64Bit())
983 setTargetDAGCombine(ISD::MUL);
985 computeRegisterProperties();
987 // FIXME: These should be based on subtarget info. Plus, the values should
988 // be smaller when we are in optimizing for size mode.
989 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
990 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
991 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
992 setPrefLoopAlignment(16);
993 benefitFromCodePlacementOpt = true;
997 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1002 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1003 /// the desired ByVal argument alignment.
1004 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1007 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1008 if (VTy->getBitWidth() == 128)
1010 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1011 unsigned EltAlign = 0;
1012 getMaxByValAlign(ATy->getElementType(), EltAlign);
1013 if (EltAlign > MaxAlign)
1014 MaxAlign = EltAlign;
1015 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1016 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1017 unsigned EltAlign = 0;
1018 getMaxByValAlign(STy->getElementType(i), EltAlign);
1019 if (EltAlign > MaxAlign)
1020 MaxAlign = EltAlign;
1028 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1029 /// function arguments in the caller parameter area. For X86, aggregates
1030 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1031 /// are at 4-byte boundaries.
1032 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1033 if (Subtarget->is64Bit()) {
1034 // Max of 8 and alignment of type.
1035 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1042 if (Subtarget->hasSSE1())
1043 getMaxByValAlign(Ty, Align);
1047 /// getOptimalMemOpType - Returns the target specific optimal type for load
1048 /// and store operations as a result of memset, memcpy, and memmove
1049 /// lowering. If DstAlign is zero that means it's safe to destination
1050 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1051 /// means there isn't a need to check it against alignment requirement,
1052 /// probably because the source does not need to be loaded. If
1053 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1054 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1055 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1056 /// constant so it does not need to be loaded.
1057 /// It returns EVT::Other if the type should be determined using generic
1058 /// target-independent logic.
1060 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1061 unsigned DstAlign, unsigned SrcAlign,
1062 bool NonScalarIntSafe,
1064 MachineFunction &MF) const {
1065 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1066 // linux. This is because the stack realignment code can't handle certain
1067 // cases like PR2962. This should be removed when PR2962 is fixed.
1068 const Function *F = MF.getFunction();
1069 if (NonScalarIntSafe &&
1070 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1072 (Subtarget->isUnalignedMemAccessFast() ||
1073 ((DstAlign == 0 || DstAlign >= 16) &&
1074 (SrcAlign == 0 || SrcAlign >= 16))) &&
1075 Subtarget->getStackAlignment() >= 16) {
1076 if (Subtarget->hasSSE2())
1078 if (Subtarget->hasSSE1())
1080 } else if (!MemcpyStrSrc && Size >= 8 &&
1081 !Subtarget->is64Bit() &&
1082 Subtarget->getStackAlignment() >= 8 &&
1083 Subtarget->hasSSE2()) {
1084 // Do not use f64 to lower memcpy if source is string constant. It's
1085 // better to use i32 to avoid the loads.
1089 if (Subtarget->is64Bit() && Size >= 8)
1094 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1095 /// current function. The returned value is a member of the
1096 /// MachineJumpTableInfo::JTEntryKind enum.
1097 unsigned X86TargetLowering::getJumpTableEncoding() const {
1098 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1100 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1101 Subtarget->isPICStyleGOT())
1102 return MachineJumpTableInfo::EK_Custom32;
1104 // Otherwise, use the normal jump table encoding heuristics.
1105 return TargetLowering::getJumpTableEncoding();
1108 /// getPICBaseSymbol - Return the X86-32 PIC base.
1110 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1111 MCContext &Ctx) const {
1112 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1113 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1114 Twine(MF->getFunctionNumber())+"$pb");
1119 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1120 const MachineBasicBlock *MBB,
1121 unsigned uid,MCContext &Ctx) const{
1122 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1123 Subtarget->isPICStyleGOT());
1124 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1126 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1127 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1130 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1132 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1133 SelectionDAG &DAG) const {
1134 if (!Subtarget->is64Bit())
1135 // This doesn't have DebugLoc associated with it, but is not really the
1136 // same as a Register.
1137 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1141 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1142 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1144 const MCExpr *X86TargetLowering::
1145 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1146 MCContext &Ctx) const {
1147 // X86-64 uses RIP relative addressing based on the jump table label.
1148 if (Subtarget->isPICStyleRIPRel())
1149 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1151 // Otherwise, the reference is relative to the PIC base.
1152 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1155 /// getFunctionAlignment - Return the Log2 alignment of this function.
1156 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1157 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1160 //===----------------------------------------------------------------------===//
1161 // Return Value Calling Convention Implementation
1162 //===----------------------------------------------------------------------===//
1164 #include "X86GenCallingConv.inc"
1167 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1168 const SmallVectorImpl<EVT> &OutTys,
1169 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1170 SelectionDAG &DAG) const {
1171 SmallVector<CCValAssign, 16> RVLocs;
1172 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1173 RVLocs, *DAG.getContext());
1174 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1178 X86TargetLowering::LowerReturn(SDValue Chain,
1179 CallingConv::ID CallConv, bool isVarArg,
1180 const SmallVectorImpl<ISD::OutputArg> &Outs,
1181 DebugLoc dl, SelectionDAG &DAG) const {
1182 MachineFunction &MF = DAG.getMachineFunction();
1183 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1185 SmallVector<CCValAssign, 16> RVLocs;
1186 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1187 RVLocs, *DAG.getContext());
1188 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1190 // Add the regs to the liveout set for the function.
1191 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1192 for (unsigned i = 0; i != RVLocs.size(); ++i)
1193 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1194 MRI.addLiveOut(RVLocs[i].getLocReg());
1198 SmallVector<SDValue, 6> RetOps;
1199 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1200 // Operand #1 = Bytes To Pop
1201 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1204 // Copy the result values into the output registers.
1205 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1206 CCValAssign &VA = RVLocs[i];
1207 assert(VA.isRegLoc() && "Can only return in registers!");
1208 SDValue ValToCopy = Outs[i].Val;
1210 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1211 // the RET instruction and handled by the FP Stackifier.
1212 if (VA.getLocReg() == X86::ST0 ||
1213 VA.getLocReg() == X86::ST1) {
1214 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1215 // change the value to the FP stack register class.
1216 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1217 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1218 RetOps.push_back(ValToCopy);
1219 // Don't emit a copytoreg.
1223 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1224 // which is returned in RAX / RDX.
1225 if (Subtarget->is64Bit()) {
1226 EVT ValVT = ValToCopy.getValueType();
1227 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1228 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1229 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1230 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1234 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1235 Flag = Chain.getValue(1);
1238 // The x86-64 ABI for returning structs by value requires that we copy
1239 // the sret argument into %rax for the return. We saved the argument into
1240 // a virtual register in the entry block, so now we copy the value out
1242 if (Subtarget->is64Bit() &&
1243 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1244 MachineFunction &MF = DAG.getMachineFunction();
1245 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1246 unsigned Reg = FuncInfo->getSRetReturnReg();
1248 Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1249 FuncInfo->setSRetReturnReg(Reg);
1251 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1253 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1254 Flag = Chain.getValue(1);
1256 // RAX now acts like a return value.
1257 MRI.addLiveOut(X86::RAX);
1260 RetOps[0] = Chain; // Update chain.
1262 // Add the flag if we have it.
1264 RetOps.push_back(Flag);
1266 return DAG.getNode(X86ISD::RET_FLAG, dl,
1267 MVT::Other, &RetOps[0], RetOps.size());
1270 /// LowerCallResult - Lower the result values of a call into the
1271 /// appropriate copies out of appropriate physical registers.
1274 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1275 CallingConv::ID CallConv, bool isVarArg,
1276 const SmallVectorImpl<ISD::InputArg> &Ins,
1277 DebugLoc dl, SelectionDAG &DAG,
1278 SmallVectorImpl<SDValue> &InVals) const {
1280 // Assign locations to each value returned by this call.
1281 SmallVector<CCValAssign, 16> RVLocs;
1282 bool Is64Bit = Subtarget->is64Bit();
1283 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1284 RVLocs, *DAG.getContext());
1285 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1287 // Copy all of the result registers out of their specified physreg.
1288 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1289 CCValAssign &VA = RVLocs[i];
1290 EVT CopyVT = VA.getValVT();
1292 // If this is x86-64, and we disabled SSE, we can't return FP values
1293 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1294 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1295 report_fatal_error("SSE register return with SSE disabled");
1298 // If this is a call to a function that returns an fp value on the floating
1299 // point stack, but where we prefer to use the value in xmm registers, copy
1300 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1301 if ((VA.getLocReg() == X86::ST0 ||
1302 VA.getLocReg() == X86::ST1) &&
1303 isScalarFPTypeInSSEReg(VA.getValVT())) {
1308 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1309 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1310 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1311 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1312 MVT::v2i64, InFlag).getValue(1);
1313 Val = Chain.getValue(0);
1314 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1315 Val, DAG.getConstant(0, MVT::i64));
1317 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1318 MVT::i64, InFlag).getValue(1);
1319 Val = Chain.getValue(0);
1321 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1323 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1324 CopyVT, InFlag).getValue(1);
1325 Val = Chain.getValue(0);
1327 InFlag = Chain.getValue(2);
1329 if (CopyVT != VA.getValVT()) {
1330 // Round the F80 the right size, which also moves to the appropriate xmm
1332 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1333 // This truncation won't change the value.
1334 DAG.getIntPtrConstant(1));
1337 InVals.push_back(Val);
1344 //===----------------------------------------------------------------------===//
1345 // C & StdCall & Fast Calling Convention implementation
1346 //===----------------------------------------------------------------------===//
1347 // StdCall calling convention seems to be standard for many Windows' API
1348 // routines and around. It differs from C calling convention just a little:
1349 // callee should clean up the stack, not caller. Symbols should be also
1350 // decorated in some fancy way :) It doesn't support any vector arguments.
1351 // For info on fast calling convention see Fast Calling Convention (tail call)
1352 // implementation LowerX86_32FastCCCallTo.
1354 /// CallIsStructReturn - Determines whether a call uses struct return
1356 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1360 return Outs[0].Flags.isSRet();
1363 /// ArgsAreStructReturn - Determines whether a function uses struct
1364 /// return semantics.
1366 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1370 return Ins[0].Flags.isSRet();
1373 /// IsCalleePop - Determines whether the callee is required to pop its
1374 /// own arguments. Callee pop is necessary to support tail calls.
1375 bool X86TargetLowering::IsCalleePop(bool IsVarArg,
1376 CallingConv::ID CallingConv) const {
1380 switch (CallingConv) {
1383 case CallingConv::X86_StdCall:
1384 return !Subtarget->is64Bit();
1385 case CallingConv::X86_FastCall:
1386 return !Subtarget->is64Bit();
1387 case CallingConv::Fast:
1388 return GuaranteedTailCallOpt;
1389 case CallingConv::GHC:
1390 return GuaranteedTailCallOpt;
1394 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1395 /// given CallingConvention value.
1396 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1397 if (Subtarget->is64Bit()) {
1398 if (CC == CallingConv::GHC)
1399 return CC_X86_64_GHC;
1400 else if (Subtarget->isTargetWin64())
1401 return CC_X86_Win64_C;
1406 if (CC == CallingConv::X86_FastCall)
1407 return CC_X86_32_FastCall;
1408 else if (CC == CallingConv::Fast)
1409 return CC_X86_32_FastCC;
1410 else if (CC == CallingConv::GHC)
1411 return CC_X86_32_GHC;
1416 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1417 /// by "Src" to address "Dst" with size and alignment information specified by
1418 /// the specific parameter attribute. The copy will be passed as a byval
1419 /// function parameter.
1421 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1422 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1424 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1425 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1426 /*isVolatile*/false, /*AlwaysInline=*/true,
1430 /// IsTailCallConvention - Return true if the calling convention is one that
1431 /// supports tail call optimization.
1432 static bool IsTailCallConvention(CallingConv::ID CC) {
1433 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1436 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1437 /// a tailcall target by changing its ABI.
1438 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1439 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1443 X86TargetLowering::LowerMemArgument(SDValue Chain,
1444 CallingConv::ID CallConv,
1445 const SmallVectorImpl<ISD::InputArg> &Ins,
1446 DebugLoc dl, SelectionDAG &DAG,
1447 const CCValAssign &VA,
1448 MachineFrameInfo *MFI,
1450 // Create the nodes corresponding to a load from this parameter slot.
1451 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1452 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1453 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1456 // If value is passed by pointer we have address passed instead of the value
1458 if (VA.getLocInfo() == CCValAssign::Indirect)
1459 ValVT = VA.getLocVT();
1461 ValVT = VA.getValVT();
1463 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1464 // changed with more analysis.
1465 // In case of tail call optimization mark all arguments mutable. Since they
1466 // could be overwritten by lowering of arguments in case of a tail call.
1467 if (Flags.isByVal()) {
1468 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1469 VA.getLocMemOffset(), isImmutable, false);
1470 return DAG.getFrameIndex(FI, getPointerTy());
1472 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1473 VA.getLocMemOffset(), isImmutable, false);
1474 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1475 return DAG.getLoad(ValVT, dl, Chain, FIN,
1476 PseudoSourceValue::getFixedStack(FI), 0,
1482 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1483 CallingConv::ID CallConv,
1485 const SmallVectorImpl<ISD::InputArg> &Ins,
1488 SmallVectorImpl<SDValue> &InVals)
1490 MachineFunction &MF = DAG.getMachineFunction();
1491 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1493 const Function* Fn = MF.getFunction();
1494 if (Fn->hasExternalLinkage() &&
1495 Subtarget->isTargetCygMing() &&
1496 Fn->getName() == "main")
1497 FuncInfo->setForceFramePointer(true);
1499 MachineFrameInfo *MFI = MF.getFrameInfo();
1500 bool Is64Bit = Subtarget->is64Bit();
1501 bool IsWin64 = Subtarget->isTargetWin64();
1503 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1504 "Var args not supported with calling convention fastcc or ghc");
1506 // Assign locations to all of the incoming arguments.
1507 SmallVector<CCValAssign, 16> ArgLocs;
1508 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1509 ArgLocs, *DAG.getContext());
1510 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1512 unsigned LastVal = ~0U;
1514 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1515 CCValAssign &VA = ArgLocs[i];
1516 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1518 assert(VA.getValNo() != LastVal &&
1519 "Don't support value assigned to multiple locs yet");
1520 LastVal = VA.getValNo();
1522 if (VA.isRegLoc()) {
1523 EVT RegVT = VA.getLocVT();
1524 TargetRegisterClass *RC = NULL;
1525 if (RegVT == MVT::i32)
1526 RC = X86::GR32RegisterClass;
1527 else if (Is64Bit && RegVT == MVT::i64)
1528 RC = X86::GR64RegisterClass;
1529 else if (RegVT == MVT::f32)
1530 RC = X86::FR32RegisterClass;
1531 else if (RegVT == MVT::f64)
1532 RC = X86::FR64RegisterClass;
1533 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1534 RC = X86::VR128RegisterClass;
1535 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1536 RC = X86::VR64RegisterClass;
1538 llvm_unreachable("Unknown argument type!");
1540 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1541 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1543 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1544 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1546 if (VA.getLocInfo() == CCValAssign::SExt)
1547 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1548 DAG.getValueType(VA.getValVT()));
1549 else if (VA.getLocInfo() == CCValAssign::ZExt)
1550 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1551 DAG.getValueType(VA.getValVT()));
1552 else if (VA.getLocInfo() == CCValAssign::BCvt)
1553 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1555 if (VA.isExtInLoc()) {
1556 // Handle MMX values passed in XMM regs.
1557 if (RegVT.isVector()) {
1558 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1559 ArgValue, DAG.getConstant(0, MVT::i64));
1560 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1562 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1565 assert(VA.isMemLoc());
1566 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1569 // If value is passed via pointer - do a load.
1570 if (VA.getLocInfo() == CCValAssign::Indirect)
1571 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1574 InVals.push_back(ArgValue);
1577 // The x86-64 ABI for returning structs by value requires that we copy
1578 // the sret argument into %rax for the return. Save the argument into
1579 // a virtual register so that we can access it from the return points.
1580 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1581 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1582 unsigned Reg = FuncInfo->getSRetReturnReg();
1584 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1585 FuncInfo->setSRetReturnReg(Reg);
1587 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1588 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1591 unsigned StackSize = CCInfo.getNextStackOffset();
1592 // Align stack specially for tail calls.
1593 if (FuncIsMadeTailCallSafe(CallConv))
1594 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1596 // If the function takes variable number of arguments, make a frame index for
1597 // the start of the first vararg value... for expansion of llvm.va_start.
1599 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1600 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,
1604 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1606 // FIXME: We should really autogenerate these arrays
1607 static const unsigned GPR64ArgRegsWin64[] = {
1608 X86::RCX, X86::RDX, X86::R8, X86::R9
1610 static const unsigned XMMArgRegsWin64[] = {
1611 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1613 static const unsigned GPR64ArgRegs64Bit[] = {
1614 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1616 static const unsigned XMMArgRegs64Bit[] = {
1617 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1618 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1620 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1623 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1624 GPR64ArgRegs = GPR64ArgRegsWin64;
1625 XMMArgRegs = XMMArgRegsWin64;
1627 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1628 GPR64ArgRegs = GPR64ArgRegs64Bit;
1629 XMMArgRegs = XMMArgRegs64Bit;
1631 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1633 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1636 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1637 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1638 "SSE register cannot be used when SSE is disabled!");
1639 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1640 "SSE register cannot be used when SSE is disabled!");
1641 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1642 // Kernel mode asks for SSE to be disabled, so don't push them
1644 TotalNumXMMRegs = 0;
1646 // For X86-64, if there are vararg parameters that are passed via
1647 // registers, then we must store them to their spots on the stack so they
1648 // may be loaded by deferencing the result of va_next.
1649 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1650 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1651 FuncInfo->setRegSaveFrameIndex(
1652 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1655 // Store the integer parameter registers.
1656 SmallVector<SDValue, 8> MemOps;
1657 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1659 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1660 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1661 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1662 DAG.getIntPtrConstant(Offset));
1663 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1664 X86::GR64RegisterClass);
1665 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1667 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1668 PseudoSourceValue::getFixedStack(
1669 FuncInfo->getRegSaveFrameIndex()),
1670 Offset, false, false, 0);
1671 MemOps.push_back(Store);
1675 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1676 // Now store the XMM (fp + vector) parameter registers.
1677 SmallVector<SDValue, 11> SaveXMMOps;
1678 SaveXMMOps.push_back(Chain);
1680 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1681 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1682 SaveXMMOps.push_back(ALVal);
1684 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1685 FuncInfo->getRegSaveFrameIndex()));
1686 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1687 FuncInfo->getVarArgsFPOffset()));
1689 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1690 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1691 X86::VR128RegisterClass);
1692 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1693 SaveXMMOps.push_back(Val);
1695 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1697 &SaveXMMOps[0], SaveXMMOps.size()));
1700 if (!MemOps.empty())
1701 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1702 &MemOps[0], MemOps.size());
1706 // Some CCs need callee pop.
1707 if (IsCalleePop(isVarArg, CallConv)) {
1708 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1710 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1711 // If this is an sret function, the return should pop the hidden pointer.
1712 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1713 FuncInfo->setBytesToPopOnReturn(4);
1717 // RegSaveFrameIndex is X86-64 only.
1718 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1719 if (CallConv == CallingConv::X86_FastCall)
1720 // fastcc functions can't have varargs.
1721 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1728 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1729 SDValue StackPtr, SDValue Arg,
1730 DebugLoc dl, SelectionDAG &DAG,
1731 const CCValAssign &VA,
1732 ISD::ArgFlagsTy Flags) const {
1733 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1734 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1735 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1736 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1737 if (Flags.isByVal()) {
1738 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1740 return DAG.getStore(Chain, dl, Arg, PtrOff,
1741 PseudoSourceValue::getStack(), LocMemOffset,
1745 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1746 /// optimization is performed and it is required.
1748 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1749 SDValue &OutRetAddr, SDValue Chain,
1750 bool IsTailCall, bool Is64Bit,
1751 int FPDiff, DebugLoc dl) const {
1752 // Adjust the Return address stack slot.
1753 EVT VT = getPointerTy();
1754 OutRetAddr = getReturnAddressFrameIndex(DAG);
1756 // Load the "old" Return address.
1757 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1758 return SDValue(OutRetAddr.getNode(), 1);
1761 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1762 /// optimization is performed and it is required (FPDiff!=0).
1764 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1765 SDValue Chain, SDValue RetAddrFrIdx,
1766 bool Is64Bit, int FPDiff, DebugLoc dl) {
1767 // Store the return address to the appropriate stack slot.
1768 if (!FPDiff) return Chain;
1769 // Calculate the new stack slot for the return address.
1770 int SlotSize = Is64Bit ? 8 : 4;
1771 int NewReturnAddrFI =
1772 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1773 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1774 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1775 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1776 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1782 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1783 CallingConv::ID CallConv, bool isVarArg,
1785 const SmallVectorImpl<ISD::OutputArg> &Outs,
1786 const SmallVectorImpl<ISD::InputArg> &Ins,
1787 DebugLoc dl, SelectionDAG &DAG,
1788 SmallVectorImpl<SDValue> &InVals) const {
1789 MachineFunction &MF = DAG.getMachineFunction();
1790 bool Is64Bit = Subtarget->is64Bit();
1791 bool IsStructRet = CallIsStructReturn(Outs);
1792 bool IsSibcall = false;
1795 // Check if it's really possible to do a tail call.
1796 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1797 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1800 // Sibcalls are automatically detected tailcalls which do not require
1802 if (!GuaranteedTailCallOpt && isTailCall)
1809 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1810 "Var args not supported with calling convention fastcc or ghc");
1812 // Analyze operands of the call, assigning locations to each operand.
1813 SmallVector<CCValAssign, 16> ArgLocs;
1814 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1815 ArgLocs, *DAG.getContext());
1816 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1818 // Get a count of how many bytes are to be pushed on the stack.
1819 unsigned NumBytes = CCInfo.getNextStackOffset();
1821 // This is a sibcall. The memory operands are available in caller's
1822 // own caller's stack.
1824 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1825 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1828 if (isTailCall && !IsSibcall) {
1829 // Lower arguments at fp - stackoffset + fpdiff.
1830 unsigned NumBytesCallerPushed =
1831 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1832 FPDiff = NumBytesCallerPushed - NumBytes;
1834 // Set the delta of movement of the returnaddr stackslot.
1835 // But only set if delta is greater than previous delta.
1836 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1837 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1841 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1843 SDValue RetAddrFrIdx;
1844 // Load return adress for tail calls.
1845 if (isTailCall && FPDiff)
1846 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1847 Is64Bit, FPDiff, dl);
1849 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1850 SmallVector<SDValue, 8> MemOpChains;
1853 // Walk the register/memloc assignments, inserting copies/loads. In the case
1854 // of tail call optimization arguments are handle later.
1855 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1856 CCValAssign &VA = ArgLocs[i];
1857 EVT RegVT = VA.getLocVT();
1858 SDValue Arg = Outs[i].Val;
1859 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1860 bool isByVal = Flags.isByVal();
1862 // Promote the value if needed.
1863 switch (VA.getLocInfo()) {
1864 default: llvm_unreachable("Unknown loc info!");
1865 case CCValAssign::Full: break;
1866 case CCValAssign::SExt:
1867 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1869 case CCValAssign::ZExt:
1870 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1872 case CCValAssign::AExt:
1873 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1874 // Special case: passing MMX values in XMM registers.
1875 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1876 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1877 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1879 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1881 case CCValAssign::BCvt:
1882 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1884 case CCValAssign::Indirect: {
1885 // Store the argument.
1886 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1887 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1888 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1889 PseudoSourceValue::getFixedStack(FI), 0,
1896 if (VA.isRegLoc()) {
1897 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1898 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1899 assert(VA.isMemLoc());
1900 if (StackPtr.getNode() == 0)
1901 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1902 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1903 dl, DAG, VA, Flags));
1907 if (!MemOpChains.empty())
1908 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1909 &MemOpChains[0], MemOpChains.size());
1911 // Build a sequence of copy-to-reg nodes chained together with token chain
1912 // and flag operands which copy the outgoing args into registers.
1914 // Tail call byval lowering might overwrite argument registers so in case of
1915 // tail call optimization the copies to registers are lowered later.
1917 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1918 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1919 RegsToPass[i].second, InFlag);
1920 InFlag = Chain.getValue(1);
1923 if (Subtarget->isPICStyleGOT()) {
1924 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1927 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1928 DAG.getNode(X86ISD::GlobalBaseReg,
1929 DebugLoc(), getPointerTy()),
1931 InFlag = Chain.getValue(1);
1933 // If we are tail calling and generating PIC/GOT style code load the
1934 // address of the callee into ECX. The value in ecx is used as target of
1935 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1936 // for tail calls on PIC/GOT architectures. Normally we would just put the
1937 // address of GOT into ebx and then call target@PLT. But for tail calls
1938 // ebx would be restored (since ebx is callee saved) before jumping to the
1941 // Note: The actual moving to ECX is done further down.
1942 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1943 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1944 !G->getGlobal()->hasProtectedVisibility())
1945 Callee = LowerGlobalAddress(Callee, DAG);
1946 else if (isa<ExternalSymbolSDNode>(Callee))
1947 Callee = LowerExternalSymbol(Callee, DAG);
1951 if (Is64Bit && isVarArg) {
1952 // From AMD64 ABI document:
1953 // For calls that may call functions that use varargs or stdargs
1954 // (prototype-less calls or calls to functions containing ellipsis (...) in
1955 // the declaration) %al is used as hidden argument to specify the number
1956 // of SSE registers used. The contents of %al do not need to match exactly
1957 // the number of registers, but must be an ubound on the number of SSE
1958 // registers used and is in the range 0 - 8 inclusive.
1960 // FIXME: Verify this on Win64
1961 // Count the number of XMM registers allocated.
1962 static const unsigned XMMArgRegs[] = {
1963 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1964 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1966 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1967 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1968 && "SSE registers cannot be used when SSE is disabled");
1970 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1971 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1972 InFlag = Chain.getValue(1);
1976 // For tail calls lower the arguments to the 'real' stack slot.
1978 // Force all the incoming stack arguments to be loaded from the stack
1979 // before any new outgoing arguments are stored to the stack, because the
1980 // outgoing stack slots may alias the incoming argument stack slots, and
1981 // the alias isn't otherwise explicit. This is slightly more conservative
1982 // than necessary, because it means that each store effectively depends
1983 // on every argument instead of just those arguments it would clobber.
1984 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1986 SmallVector<SDValue, 8> MemOpChains2;
1989 // Do not flag preceeding copytoreg stuff together with the following stuff.
1991 if (GuaranteedTailCallOpt) {
1992 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1993 CCValAssign &VA = ArgLocs[i];
1996 assert(VA.isMemLoc());
1997 SDValue Arg = Outs[i].Val;
1998 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1999 // Create frame index.
2000 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2001 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2002 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2003 FIN = DAG.getFrameIndex(FI, getPointerTy());
2005 if (Flags.isByVal()) {
2006 // Copy relative to framepointer.
2007 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2008 if (StackPtr.getNode() == 0)
2009 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2011 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2013 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2017 // Store relative to framepointer.
2018 MemOpChains2.push_back(
2019 DAG.getStore(ArgChain, dl, Arg, FIN,
2020 PseudoSourceValue::getFixedStack(FI), 0,
2026 if (!MemOpChains2.empty())
2027 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2028 &MemOpChains2[0], MemOpChains2.size());
2030 // Copy arguments to their registers.
2031 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2032 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2033 RegsToPass[i].second, InFlag);
2034 InFlag = Chain.getValue(1);
2038 // Store the return address to the appropriate stack slot.
2039 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2043 bool WasGlobalOrExternal = false;
2044 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2045 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2046 // In the 64-bit large code model, we have to make all calls
2047 // through a register, since the call instruction's 32-bit
2048 // pc-relative offset may not be large enough to hold the whole
2050 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2051 WasGlobalOrExternal = true;
2052 // If the callee is a GlobalAddress node (quite common, every direct call
2053 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2056 // We should use extra load for direct calls to dllimported functions in
2058 const GlobalValue *GV = G->getGlobal();
2059 if (!GV->hasDLLImportLinkage()) {
2060 unsigned char OpFlags = 0;
2062 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2063 // external symbols most go through the PLT in PIC mode. If the symbol
2064 // has hidden or protected visibility, or if it is static or local, then
2065 // we don't need to use the PLT - we can directly call it.
2066 if (Subtarget->isTargetELF() &&
2067 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2068 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2069 OpFlags = X86II::MO_PLT;
2070 } else if (Subtarget->isPICStyleStubAny() &&
2071 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2072 Subtarget->getDarwinVers() < 9) {
2073 // PC-relative references to external symbols should go through $stub,
2074 // unless we're building with the leopard linker or later, which
2075 // automatically synthesizes these stubs.
2076 OpFlags = X86II::MO_DARWIN_STUB;
2079 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2080 G->getOffset(), OpFlags);
2082 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2083 WasGlobalOrExternal = true;
2084 unsigned char OpFlags = 0;
2086 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2087 // symbols should go through the PLT.
2088 if (Subtarget->isTargetELF() &&
2089 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2090 OpFlags = X86II::MO_PLT;
2091 } else if (Subtarget->isPICStyleStubAny() &&
2092 Subtarget->getDarwinVers() < 9) {
2093 // PC-relative references to external symbols should go through $stub,
2094 // unless we're building with the leopard linker or later, which
2095 // automatically synthesizes these stubs.
2096 OpFlags = X86II::MO_DARWIN_STUB;
2099 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2103 // Returns a chain & a flag for retval copy to use.
2104 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2105 SmallVector<SDValue, 8> Ops;
2107 if (!IsSibcall && isTailCall) {
2108 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2109 DAG.getIntPtrConstant(0, true), InFlag);
2110 InFlag = Chain.getValue(1);
2113 Ops.push_back(Chain);
2114 Ops.push_back(Callee);
2117 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2119 // Add argument registers to the end of the list so that they are known live
2121 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2122 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2123 RegsToPass[i].second.getValueType()));
2125 // Add an implicit use GOT pointer in EBX.
2126 if (!isTailCall && Subtarget->isPICStyleGOT())
2127 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2129 // Add an implicit use of AL for x86 vararg functions.
2130 if (Is64Bit && isVarArg)
2131 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2133 if (InFlag.getNode())
2134 Ops.push_back(InFlag);
2137 // If this is the first return lowered for this function, add the regs
2138 // to the liveout set for the function.
2139 if (MF.getRegInfo().liveout_empty()) {
2140 SmallVector<CCValAssign, 16> RVLocs;
2141 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2143 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2144 for (unsigned i = 0; i != RVLocs.size(); ++i)
2145 if (RVLocs[i].isRegLoc())
2146 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2148 return DAG.getNode(X86ISD::TC_RETURN, dl,
2149 NodeTys, &Ops[0], Ops.size());
2152 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2153 InFlag = Chain.getValue(1);
2155 // Create the CALLSEQ_END node.
2156 unsigned NumBytesForCalleeToPush;
2157 if (IsCalleePop(isVarArg, CallConv))
2158 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2159 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2160 // If this is a call to a struct-return function, the callee
2161 // pops the hidden struct pointer, so we have to push it back.
2162 // This is common for Darwin/X86, Linux & Mingw32 targets.
2163 NumBytesForCalleeToPush = 4;
2165 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2167 // Returns a flag for retval copy to use.
2169 Chain = DAG.getCALLSEQ_END(Chain,
2170 DAG.getIntPtrConstant(NumBytes, true),
2171 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2174 InFlag = Chain.getValue(1);
2177 // Handle result values, copying them out of physregs into vregs that we
2179 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2180 Ins, dl, DAG, InVals);
2184 //===----------------------------------------------------------------------===//
2185 // Fast Calling Convention (tail call) implementation
2186 //===----------------------------------------------------------------------===//
2188 // Like std call, callee cleans arguments, convention except that ECX is
2189 // reserved for storing the tail called function address. Only 2 registers are
2190 // free for argument passing (inreg). Tail call optimization is performed
2192 // * tailcallopt is enabled
2193 // * caller/callee are fastcc
2194 // On X86_64 architecture with GOT-style position independent code only local
2195 // (within module) calls are supported at the moment.
2196 // To keep the stack aligned according to platform abi the function
2197 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2198 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2199 // If a tail called function callee has more arguments than the caller the
2200 // caller needs to make sure that there is room to move the RETADDR to. This is
2201 // achieved by reserving an area the size of the argument delta right after the
2202 // original REtADDR, but before the saved framepointer or the spilled registers
2203 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2215 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2216 /// for a 16 byte align requirement.
2218 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2219 SelectionDAG& DAG) const {
2220 MachineFunction &MF = DAG.getMachineFunction();
2221 const TargetMachine &TM = MF.getTarget();
2222 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2223 unsigned StackAlignment = TFI.getStackAlignment();
2224 uint64_t AlignMask = StackAlignment - 1;
2225 int64_t Offset = StackSize;
2226 uint64_t SlotSize = TD->getPointerSize();
2227 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2228 // Number smaller than 12 so just add the difference.
2229 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2231 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2232 Offset = ((~AlignMask) & Offset) + StackAlignment +
2233 (StackAlignment-SlotSize);
2238 /// MatchingStackOffset - Return true if the given stack call argument is
2239 /// already available in the same position (relatively) of the caller's
2240 /// incoming argument stack.
2242 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2243 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2244 const X86InstrInfo *TII) {
2245 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2247 if (Arg.getOpcode() == ISD::CopyFromReg) {
2248 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2249 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2251 MachineInstr *Def = MRI->getVRegDef(VR);
2254 if (!Flags.isByVal()) {
2255 if (!TII->isLoadFromStackSlot(Def, FI))
2258 unsigned Opcode = Def->getOpcode();
2259 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2260 Def->getOperand(1).isFI()) {
2261 FI = Def->getOperand(1).getIndex();
2262 Bytes = Flags.getByValSize();
2266 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2267 if (Flags.isByVal())
2268 // ByVal argument is passed in as a pointer but it's now being
2269 // dereferenced. e.g.
2270 // define @foo(%struct.X* %A) {
2271 // tail call @bar(%struct.X* byval %A)
2274 SDValue Ptr = Ld->getBasePtr();
2275 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2278 FI = FINode->getIndex();
2282 assert(FI != INT_MAX);
2283 if (!MFI->isFixedObjectIndex(FI))
2285 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2288 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2289 /// for tail call optimization. Targets which want to do tail call
2290 /// optimization should implement this function.
2292 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2293 CallingConv::ID CalleeCC,
2295 bool isCalleeStructRet,
2296 bool isCallerStructRet,
2297 const SmallVectorImpl<ISD::OutputArg> &Outs,
2298 const SmallVectorImpl<ISD::InputArg> &Ins,
2299 SelectionDAG& DAG) const {
2300 if (!IsTailCallConvention(CalleeCC) &&
2301 CalleeCC != CallingConv::C)
2304 // If -tailcallopt is specified, make fastcc functions tail-callable.
2305 const MachineFunction &MF = DAG.getMachineFunction();
2306 const Function *CallerF = DAG.getMachineFunction().getFunction();
2307 CallingConv::ID CallerCC = CallerF->getCallingConv();
2308 bool CCMatch = CallerCC == CalleeCC;
2310 if (GuaranteedTailCallOpt) {
2311 if (IsTailCallConvention(CalleeCC) && CCMatch)
2316 // Look for obvious safe cases to perform tail call optimization that does not
2317 // requite ABI changes. This is what gcc calls sibcall.
2319 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2320 // emit a special epilogue.
2321 if (RegInfo->needsStackRealignment(MF))
2324 // Do not sibcall optimize vararg calls unless the call site is not passing any
2326 if (isVarArg && !Outs.empty())
2329 // Also avoid sibcall optimization if either caller or callee uses struct
2330 // return semantics.
2331 if (isCalleeStructRet || isCallerStructRet)
2334 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2335 // Therefore if it's not used by the call it is not safe to optimize this into
2337 bool Unused = false;
2338 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2345 SmallVector<CCValAssign, 16> RVLocs;
2346 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2347 RVLocs, *DAG.getContext());
2348 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2349 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2350 CCValAssign &VA = RVLocs[i];
2351 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2356 // If the calling conventions do not match, then we'd better make sure the
2357 // results are returned in the same way as what the caller expects.
2359 SmallVector<CCValAssign, 16> RVLocs1;
2360 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2361 RVLocs1, *DAG.getContext());
2362 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2364 SmallVector<CCValAssign, 16> RVLocs2;
2365 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2366 RVLocs2, *DAG.getContext());
2367 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2369 if (RVLocs1.size() != RVLocs2.size())
2371 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2372 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2374 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2376 if (RVLocs1[i].isRegLoc()) {
2377 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2380 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2386 // If the callee takes no arguments then go on to check the results of the
2388 if (!Outs.empty()) {
2389 // Check if stack adjustment is needed. For now, do not do this if any
2390 // argument is passed on the stack.
2391 SmallVector<CCValAssign, 16> ArgLocs;
2392 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2393 ArgLocs, *DAG.getContext());
2394 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2395 if (CCInfo.getNextStackOffset()) {
2396 MachineFunction &MF = DAG.getMachineFunction();
2397 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2399 if (Subtarget->isTargetWin64())
2400 // Win64 ABI has additional complications.
2403 // Check if the arguments are already laid out in the right way as
2404 // the caller's fixed stack objects.
2405 MachineFrameInfo *MFI = MF.getFrameInfo();
2406 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2407 const X86InstrInfo *TII =
2408 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2409 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2410 CCValAssign &VA = ArgLocs[i];
2411 EVT RegVT = VA.getLocVT();
2412 SDValue Arg = Outs[i].Val;
2413 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2414 if (VA.getLocInfo() == CCValAssign::Indirect)
2416 if (!VA.isRegLoc()) {
2417 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2429 X86TargetLowering::createFastISel(MachineFunction &mf,
2430 DenseMap<const Value *, unsigned> &vm,
2431 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2432 DenseMap<const AllocaInst *, int> &am,
2433 std::vector<std::pair<MachineInstr*, unsigned> > &pn
2435 , SmallSet<const Instruction *, 8> &cil
2438 return X86::createFastISel(mf, vm, bm, am, pn
2446 //===----------------------------------------------------------------------===//
2447 // Other Lowering Hooks
2448 //===----------------------------------------------------------------------===//
2451 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2452 MachineFunction &MF = DAG.getMachineFunction();
2453 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2454 int ReturnAddrIndex = FuncInfo->getRAIndex();
2456 if (ReturnAddrIndex == 0) {
2457 // Set up a frame object for the return address.
2458 uint64_t SlotSize = TD->getPointerSize();
2459 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2461 FuncInfo->setRAIndex(ReturnAddrIndex);
2464 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2468 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2469 bool hasSymbolicDisplacement) {
2470 // Offset should fit into 32 bit immediate field.
2471 if (!isInt<32>(Offset))
2474 // If we don't have a symbolic displacement - we don't have any extra
2476 if (!hasSymbolicDisplacement)
2479 // FIXME: Some tweaks might be needed for medium code model.
2480 if (M != CodeModel::Small && M != CodeModel::Kernel)
2483 // For small code model we assume that latest object is 16MB before end of 31
2484 // bits boundary. We may also accept pretty large negative constants knowing
2485 // that all objects are in the positive half of address space.
2486 if (M == CodeModel::Small && Offset < 16*1024*1024)
2489 // For kernel code model we know that all object resist in the negative half
2490 // of 32bits address space. We may not accept negative offsets, since they may
2491 // be just off and we may accept pretty large positive ones.
2492 if (M == CodeModel::Kernel && Offset > 0)
2498 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2499 /// specific condition code, returning the condition code and the LHS/RHS of the
2500 /// comparison to make.
2501 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2502 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2504 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2505 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2506 // X > -1 -> X == 0, jump !sign.
2507 RHS = DAG.getConstant(0, RHS.getValueType());
2508 return X86::COND_NS;
2509 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2510 // X < 0 -> X == 0, jump on sign.
2512 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2514 RHS = DAG.getConstant(0, RHS.getValueType());
2515 return X86::COND_LE;
2519 switch (SetCCOpcode) {
2520 default: llvm_unreachable("Invalid integer condition!");
2521 case ISD::SETEQ: return X86::COND_E;
2522 case ISD::SETGT: return X86::COND_G;
2523 case ISD::SETGE: return X86::COND_GE;
2524 case ISD::SETLT: return X86::COND_L;
2525 case ISD::SETLE: return X86::COND_LE;
2526 case ISD::SETNE: return X86::COND_NE;
2527 case ISD::SETULT: return X86::COND_B;
2528 case ISD::SETUGT: return X86::COND_A;
2529 case ISD::SETULE: return X86::COND_BE;
2530 case ISD::SETUGE: return X86::COND_AE;
2534 // First determine if it is required or is profitable to flip the operands.
2536 // If LHS is a foldable load, but RHS is not, flip the condition.
2537 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2538 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2539 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2540 std::swap(LHS, RHS);
2543 switch (SetCCOpcode) {
2549 std::swap(LHS, RHS);
2553 // On a floating point condition, the flags are set as follows:
2555 // 0 | 0 | 0 | X > Y
2556 // 0 | 0 | 1 | X < Y
2557 // 1 | 0 | 0 | X == Y
2558 // 1 | 1 | 1 | unordered
2559 switch (SetCCOpcode) {
2560 default: llvm_unreachable("Condcode should be pre-legalized away");
2562 case ISD::SETEQ: return X86::COND_E;
2563 case ISD::SETOLT: // flipped
2565 case ISD::SETGT: return X86::COND_A;
2566 case ISD::SETOLE: // flipped
2568 case ISD::SETGE: return X86::COND_AE;
2569 case ISD::SETUGT: // flipped
2571 case ISD::SETLT: return X86::COND_B;
2572 case ISD::SETUGE: // flipped
2574 case ISD::SETLE: return X86::COND_BE;
2576 case ISD::SETNE: return X86::COND_NE;
2577 case ISD::SETUO: return X86::COND_P;
2578 case ISD::SETO: return X86::COND_NP;
2580 case ISD::SETUNE: return X86::COND_INVALID;
2584 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2585 /// code. Current x86 isa includes the following FP cmov instructions:
2586 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2587 static bool hasFPCMov(unsigned X86CC) {
2603 /// isFPImmLegal - Returns true if the target can instruction select the
2604 /// specified FP immediate natively. If false, the legalizer will
2605 /// materialize the FP immediate as a load from a constant pool.
2606 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2607 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2608 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2614 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2615 /// the specified range (L, H].
2616 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2617 return (Val < 0) || (Val >= Low && Val < Hi);
2620 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2621 /// specified value.
2622 static bool isUndefOrEqual(int Val, int CmpVal) {
2623 if (Val < 0 || Val == CmpVal)
2628 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2629 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2630 /// the second operand.
2631 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2632 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2633 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2634 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2635 return (Mask[0] < 2 && Mask[1] < 2);
2639 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2640 SmallVector<int, 8> M;
2642 return ::isPSHUFDMask(M, N->getValueType(0));
2645 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2646 /// is suitable for input to PSHUFHW.
2647 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2648 if (VT != MVT::v8i16)
2651 // Lower quadword copied in order or undef.
2652 for (int i = 0; i != 4; ++i)
2653 if (Mask[i] >= 0 && Mask[i] != i)
2656 // Upper quadword shuffled.
2657 for (int i = 4; i != 8; ++i)
2658 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2664 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2665 SmallVector<int, 8> M;
2667 return ::isPSHUFHWMask(M, N->getValueType(0));
2670 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2671 /// is suitable for input to PSHUFLW.
2672 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2673 if (VT != MVT::v8i16)
2676 // Upper quadword copied in order.
2677 for (int i = 4; i != 8; ++i)
2678 if (Mask[i] >= 0 && Mask[i] != i)
2681 // Lower quadword shuffled.
2682 for (int i = 0; i != 4; ++i)
2689 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2690 SmallVector<int, 8> M;
2692 return ::isPSHUFLWMask(M, N->getValueType(0));
2695 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2696 /// is suitable for input to PALIGNR.
2697 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2699 int i, e = VT.getVectorNumElements();
2701 // Do not handle v2i64 / v2f64 shuffles with palignr.
2702 if (e < 4 || !hasSSSE3)
2705 for (i = 0; i != e; ++i)
2709 // All undef, not a palignr.
2713 // Determine if it's ok to perform a palignr with only the LHS, since we
2714 // don't have access to the actual shuffle elements to see if RHS is undef.
2715 bool Unary = Mask[i] < (int)e;
2716 bool NeedsUnary = false;
2718 int s = Mask[i] - i;
2720 // Check the rest of the elements to see if they are consecutive.
2721 for (++i; i != e; ++i) {
2726 Unary = Unary && (m < (int)e);
2727 NeedsUnary = NeedsUnary || (m < s);
2729 if (NeedsUnary && !Unary)
2731 if (Unary && m != ((s+i) & (e-1)))
2733 if (!Unary && m != (s+i))
2739 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2740 SmallVector<int, 8> M;
2742 return ::isPALIGNRMask(M, N->getValueType(0), true);
2745 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2746 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2747 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2748 int NumElems = VT.getVectorNumElements();
2749 if (NumElems != 2 && NumElems != 4)
2752 int Half = NumElems / 2;
2753 for (int i = 0; i < Half; ++i)
2754 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2756 for (int i = Half; i < NumElems; ++i)
2757 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2763 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2764 SmallVector<int, 8> M;
2766 return ::isSHUFPMask(M, N->getValueType(0));
2769 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2770 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2771 /// half elements to come from vector 1 (which would equal the dest.) and
2772 /// the upper half to come from vector 2.
2773 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2774 int NumElems = VT.getVectorNumElements();
2776 if (NumElems != 2 && NumElems != 4)
2779 int Half = NumElems / 2;
2780 for (int i = 0; i < Half; ++i)
2781 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2783 for (int i = Half; i < NumElems; ++i)
2784 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2789 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2790 SmallVector<int, 8> M;
2792 return isCommutedSHUFPMask(M, N->getValueType(0));
2795 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2796 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2797 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2798 if (N->getValueType(0).getVectorNumElements() != 4)
2801 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2802 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2803 isUndefOrEqual(N->getMaskElt(1), 7) &&
2804 isUndefOrEqual(N->getMaskElt(2), 2) &&
2805 isUndefOrEqual(N->getMaskElt(3), 3);
2808 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2809 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2811 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2812 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2817 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2818 isUndefOrEqual(N->getMaskElt(1), 3) &&
2819 isUndefOrEqual(N->getMaskElt(2), 2) &&
2820 isUndefOrEqual(N->getMaskElt(3), 3);
2823 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2824 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2825 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2826 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2828 if (NumElems != 2 && NumElems != 4)
2831 for (unsigned i = 0; i < NumElems/2; ++i)
2832 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2835 for (unsigned i = NumElems/2; i < NumElems; ++i)
2836 if (!isUndefOrEqual(N->getMaskElt(i), i))
2842 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2843 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2844 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2845 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2847 if (NumElems != 2 && NumElems != 4)
2850 for (unsigned i = 0; i < NumElems/2; ++i)
2851 if (!isUndefOrEqual(N->getMaskElt(i), i))
2854 for (unsigned i = 0; i < NumElems/2; ++i)
2855 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2861 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2862 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2863 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2864 bool V2IsSplat = false) {
2865 int NumElts = VT.getVectorNumElements();
2866 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2869 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2871 int BitI1 = Mask[i+1];
2872 if (!isUndefOrEqual(BitI, j))
2875 if (!isUndefOrEqual(BitI1, NumElts))
2878 if (!isUndefOrEqual(BitI1, j + NumElts))
2885 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2886 SmallVector<int, 8> M;
2888 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2891 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2892 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2893 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2894 bool V2IsSplat = false) {
2895 int NumElts = VT.getVectorNumElements();
2896 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2899 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2901 int BitI1 = Mask[i+1];
2902 if (!isUndefOrEqual(BitI, j + NumElts/2))
2905 if (isUndefOrEqual(BitI1, NumElts))
2908 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2915 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2916 SmallVector<int, 8> M;
2918 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2921 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2922 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2924 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2925 int NumElems = VT.getVectorNumElements();
2926 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2929 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2931 int BitI1 = Mask[i+1];
2932 if (!isUndefOrEqual(BitI, j))
2934 if (!isUndefOrEqual(BitI1, j))
2940 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2941 SmallVector<int, 8> M;
2943 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2946 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2947 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2949 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2950 int NumElems = VT.getVectorNumElements();
2951 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2954 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2956 int BitI1 = Mask[i+1];
2957 if (!isUndefOrEqual(BitI, j))
2959 if (!isUndefOrEqual(BitI1, j))
2965 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2966 SmallVector<int, 8> M;
2968 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2971 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2972 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2973 /// MOVSD, and MOVD, i.e. setting the lowest element.
2974 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2975 if (VT.getVectorElementType().getSizeInBits() < 32)
2978 int NumElts = VT.getVectorNumElements();
2980 if (!isUndefOrEqual(Mask[0], NumElts))
2983 for (int i = 1; i < NumElts; ++i)
2984 if (!isUndefOrEqual(Mask[i], i))
2990 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2991 SmallVector<int, 8> M;
2993 return ::isMOVLMask(M, N->getValueType(0));
2996 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2997 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2998 /// element of vector 2 and the other elements to come from vector 1 in order.
2999 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3000 bool V2IsSplat = false, bool V2IsUndef = false) {
3001 int NumOps = VT.getVectorNumElements();
3002 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3005 if (!isUndefOrEqual(Mask[0], 0))
3008 for (int i = 1; i < NumOps; ++i)
3009 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3010 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3011 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3017 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3018 bool V2IsUndef = false) {
3019 SmallVector<int, 8> M;
3021 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3024 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3025 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3026 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3027 if (N->getValueType(0).getVectorNumElements() != 4)
3030 // Expect 1, 1, 3, 3
3031 for (unsigned i = 0; i < 2; ++i) {
3032 int Elt = N->getMaskElt(i);
3033 if (Elt >= 0 && Elt != 1)
3038 for (unsigned i = 2; i < 4; ++i) {
3039 int Elt = N->getMaskElt(i);
3040 if (Elt >= 0 && Elt != 3)
3045 // Don't use movshdup if it can be done with a shufps.
3046 // FIXME: verify that matching u, u, 3, 3 is what we want.
3050 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3051 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3052 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3053 if (N->getValueType(0).getVectorNumElements() != 4)
3056 // Expect 0, 0, 2, 2
3057 for (unsigned i = 0; i < 2; ++i)
3058 if (N->getMaskElt(i) > 0)
3062 for (unsigned i = 2; i < 4; ++i) {
3063 int Elt = N->getMaskElt(i);
3064 if (Elt >= 0 && Elt != 2)
3069 // Don't use movsldup if it can be done with a shufps.
3073 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3074 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3075 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3076 int e = N->getValueType(0).getVectorNumElements() / 2;
3078 for (int i = 0; i < e; ++i)
3079 if (!isUndefOrEqual(N->getMaskElt(i), i))
3081 for (int i = 0; i < e; ++i)
3082 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3087 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3088 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3089 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3090 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3091 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3093 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3095 for (int i = 0; i < NumOperands; ++i) {
3096 int Val = SVOp->getMaskElt(NumOperands-i-1);
3097 if (Val < 0) Val = 0;
3098 if (Val >= NumOperands) Val -= NumOperands;
3100 if (i != NumOperands - 1)
3106 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3107 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3108 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3109 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3111 // 8 nodes, but we only care about the last 4.
3112 for (unsigned i = 7; i >= 4; --i) {
3113 int Val = SVOp->getMaskElt(i);
3122 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3123 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3124 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3125 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3127 // 8 nodes, but we only care about the first 4.
3128 for (int i = 3; i >= 0; --i) {
3129 int Val = SVOp->getMaskElt(i);
3138 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3139 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3140 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3141 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3142 EVT VVT = N->getValueType(0);
3143 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3147 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3148 Val = SVOp->getMaskElt(i);
3152 return (Val - i) * EltSize;
3155 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3157 bool X86::isZeroNode(SDValue Elt) {
3158 return ((isa<ConstantSDNode>(Elt) &&
3159 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3160 (isa<ConstantFPSDNode>(Elt) &&
3161 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3164 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3165 /// their permute mask.
3166 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3167 SelectionDAG &DAG) {
3168 EVT VT = SVOp->getValueType(0);
3169 unsigned NumElems = VT.getVectorNumElements();
3170 SmallVector<int, 8> MaskVec;
3172 for (unsigned i = 0; i != NumElems; ++i) {
3173 int idx = SVOp->getMaskElt(i);
3175 MaskVec.push_back(idx);
3176 else if (idx < (int)NumElems)
3177 MaskVec.push_back(idx + NumElems);
3179 MaskVec.push_back(idx - NumElems);
3181 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3182 SVOp->getOperand(0), &MaskVec[0]);
3185 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3186 /// the two vector operands have swapped position.
3187 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3188 unsigned NumElems = VT.getVectorNumElements();
3189 for (unsigned i = 0; i != NumElems; ++i) {
3193 else if (idx < (int)NumElems)
3194 Mask[i] = idx + NumElems;
3196 Mask[i] = idx - NumElems;
3200 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3201 /// match movhlps. The lower half elements should come from upper half of
3202 /// V1 (and in order), and the upper half elements should come from the upper
3203 /// half of V2 (and in order).
3204 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3205 if (Op->getValueType(0).getVectorNumElements() != 4)
3207 for (unsigned i = 0, e = 2; i != e; ++i)
3208 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3210 for (unsigned i = 2; i != 4; ++i)
3211 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3216 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3217 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3219 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3220 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3222 N = N->getOperand(0).getNode();
3223 if (!ISD::isNON_EXTLoad(N))
3226 *LD = cast<LoadSDNode>(N);
3230 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3231 /// match movlp{s|d}. The lower half elements should come from lower half of
3232 /// V1 (and in order), and the upper half elements should come from the upper
3233 /// half of V2 (and in order). And since V1 will become the source of the
3234 /// MOVLP, it must be either a vector load or a scalar load to vector.
3235 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3236 ShuffleVectorSDNode *Op) {
3237 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3239 // Is V2 is a vector load, don't do this transformation. We will try to use
3240 // load folding shufps op.
3241 if (ISD::isNON_EXTLoad(V2))
3244 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3246 if (NumElems != 2 && NumElems != 4)
3248 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3249 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3251 for (unsigned i = NumElems/2; i != NumElems; ++i)
3252 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3257 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3259 static bool isSplatVector(SDNode *N) {
3260 if (N->getOpcode() != ISD::BUILD_VECTOR)
3263 SDValue SplatValue = N->getOperand(0);
3264 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3265 if (N->getOperand(i) != SplatValue)
3270 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3271 /// to an zero vector.
3272 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3273 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3274 SDValue V1 = N->getOperand(0);
3275 SDValue V2 = N->getOperand(1);
3276 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3277 for (unsigned i = 0; i != NumElems; ++i) {
3278 int Idx = N->getMaskElt(i);
3279 if (Idx >= (int)NumElems) {
3280 unsigned Opc = V2.getOpcode();
3281 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3283 if (Opc != ISD::BUILD_VECTOR ||
3284 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3286 } else if (Idx >= 0) {
3287 unsigned Opc = V1.getOpcode();
3288 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3290 if (Opc != ISD::BUILD_VECTOR ||
3291 !X86::isZeroNode(V1.getOperand(Idx)))
3298 /// getZeroVector - Returns a vector of specified type with all zero elements.
3300 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3302 assert(VT.isVector() && "Expected a vector type");
3304 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3305 // type. This ensures they get CSE'd.
3307 if (VT.getSizeInBits() == 64) { // MMX
3308 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3309 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3310 } else if (HasSSE2) { // SSE2
3311 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3312 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3314 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3315 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3317 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3320 /// getOnesVector - Returns a vector of specified type with all bits set.
3322 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3323 assert(VT.isVector() && "Expected a vector type");
3325 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3326 // type. This ensures they get CSE'd.
3327 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3329 if (VT.getSizeInBits() == 64) // MMX
3330 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3332 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3333 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3337 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3338 /// that point to V2 points to its first element.
3339 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3340 EVT VT = SVOp->getValueType(0);
3341 unsigned NumElems = VT.getVectorNumElements();
3343 bool Changed = false;
3344 SmallVector<int, 8> MaskVec;
3345 SVOp->getMask(MaskVec);
3347 for (unsigned i = 0; i != NumElems; ++i) {
3348 if (MaskVec[i] > (int)NumElems) {
3349 MaskVec[i] = NumElems;
3354 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3355 SVOp->getOperand(1), &MaskVec[0]);
3356 return SDValue(SVOp, 0);
3359 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3360 /// operation of specified width.
3361 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3363 unsigned NumElems = VT.getVectorNumElements();
3364 SmallVector<int, 8> Mask;
3365 Mask.push_back(NumElems);
3366 for (unsigned i = 1; i != NumElems; ++i)
3368 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3371 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3372 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3374 unsigned NumElems = VT.getVectorNumElements();
3375 SmallVector<int, 8> Mask;
3376 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3378 Mask.push_back(i + NumElems);
3380 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3383 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3384 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3386 unsigned NumElems = VT.getVectorNumElements();
3387 unsigned Half = NumElems/2;
3388 SmallVector<int, 8> Mask;
3389 for (unsigned i = 0; i != Half; ++i) {
3390 Mask.push_back(i + Half);
3391 Mask.push_back(i + NumElems + Half);
3393 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3396 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3397 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3399 if (SV->getValueType(0).getVectorNumElements() <= 4)
3400 return SDValue(SV, 0);
3402 EVT PVT = MVT::v4f32;
3403 EVT VT = SV->getValueType(0);
3404 DebugLoc dl = SV->getDebugLoc();
3405 SDValue V1 = SV->getOperand(0);
3406 int NumElems = VT.getVectorNumElements();
3407 int EltNo = SV->getSplatIndex();
3409 // unpack elements to the correct location
3410 while (NumElems > 4) {
3411 if (EltNo < NumElems/2) {
3412 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3414 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3415 EltNo -= NumElems/2;
3420 // Perform the splat.
3421 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3422 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3423 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3424 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3427 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3428 /// vector of zero or undef vector. This produces a shuffle where the low
3429 /// element of V2 is swizzled into the zero/undef vector, landing at element
3430 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3431 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3432 bool isZero, bool HasSSE2,
3433 SelectionDAG &DAG) {
3434 EVT VT = V2.getValueType();
3436 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3437 unsigned NumElems = VT.getVectorNumElements();
3438 SmallVector<int, 16> MaskVec;
3439 for (unsigned i = 0; i != NumElems; ++i)
3440 // If this is the insertion idx, put the low elt of V2 here.
3441 MaskVec.push_back(i == Idx ? NumElems : i);
3442 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3445 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3446 /// a shuffle that is zero.
3448 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3449 bool Low, SelectionDAG &DAG) {
3450 unsigned NumZeros = 0;
3451 for (int i = 0; i < NumElems; ++i) {
3452 unsigned Index = Low ? i : NumElems-i-1;
3453 int Idx = SVOp->getMaskElt(Index);
3458 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3459 if (Elt.getNode() && X86::isZeroNode(Elt))
3467 /// isVectorShift - Returns true if the shuffle can be implemented as a
3468 /// logical left or right shift of a vector.
3469 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3470 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3471 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3472 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3475 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3478 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3482 bool SeenV1 = false;
3483 bool SeenV2 = false;
3484 for (unsigned i = NumZeros; i < NumElems; ++i) {
3485 unsigned Val = isLeft ? (i - NumZeros) : i;
3486 int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3489 unsigned Idx = (unsigned) Idx_;
3499 if (SeenV1 && SeenV2)
3502 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3508 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3510 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3511 unsigned NumNonZero, unsigned NumZero,
3513 const TargetLowering &TLI) {
3517 DebugLoc dl = Op.getDebugLoc();
3520 for (unsigned i = 0; i < 16; ++i) {
3521 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3522 if (ThisIsNonZero && First) {
3524 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3526 V = DAG.getUNDEF(MVT::v8i16);
3531 SDValue ThisElt(0, 0), LastElt(0, 0);
3532 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3533 if (LastIsNonZero) {
3534 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3535 MVT::i16, Op.getOperand(i-1));
3537 if (ThisIsNonZero) {
3538 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3539 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3540 ThisElt, DAG.getConstant(8, MVT::i8));
3542 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3546 if (ThisElt.getNode())
3547 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3548 DAG.getIntPtrConstant(i/2));
3552 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3555 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3557 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3558 unsigned NumNonZero, unsigned NumZero,
3560 const TargetLowering &TLI) {
3564 DebugLoc dl = Op.getDebugLoc();
3567 for (unsigned i = 0; i < 8; ++i) {
3568 bool isNonZero = (NonZeros & (1 << i)) != 0;
3572 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3574 V = DAG.getUNDEF(MVT::v8i16);
3577 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3578 MVT::v8i16, V, Op.getOperand(i),
3579 DAG.getIntPtrConstant(i));
3586 /// getVShift - Return a vector logical shift node.
3588 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3589 unsigned NumBits, SelectionDAG &DAG,
3590 const TargetLowering &TLI, DebugLoc dl) {
3591 bool isMMX = VT.getSizeInBits() == 64;
3592 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3593 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3594 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3595 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3596 DAG.getNode(Opc, dl, ShVT, SrcOp,
3597 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3601 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3602 SelectionDAG &DAG) const {
3604 // Check if the scalar load can be widened into a vector load. And if
3605 // the address is "base + cst" see if the cst can be "absorbed" into
3606 // the shuffle mask.
3607 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3608 SDValue Ptr = LD->getBasePtr();
3609 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3611 EVT PVT = LD->getValueType(0);
3612 if (PVT != MVT::i32 && PVT != MVT::f32)
3617 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3618 FI = FINode->getIndex();
3620 } else if (Ptr.getOpcode() == ISD::ADD &&
3621 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3622 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3623 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3624 Offset = Ptr.getConstantOperandVal(1);
3625 Ptr = Ptr.getOperand(0);
3630 SDValue Chain = LD->getChain();
3631 // Make sure the stack object alignment is at least 16.
3632 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3633 if (DAG.InferPtrAlignment(Ptr) < 16) {
3634 if (MFI->isFixedObjectIndex(FI)) {
3635 // Can't change the alignment. FIXME: It's possible to compute
3636 // the exact stack offset and reference FI + adjust offset instead.
3637 // If someone *really* cares about this. That's the way to implement it.
3640 MFI->setObjectAlignment(FI, 16);
3644 // (Offset % 16) must be multiple of 4. Then address is then
3645 // Ptr + (Offset & ~15).
3648 if ((Offset % 16) & 3)
3650 int64_t StartOffset = Offset & ~15;
3652 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3653 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3655 int EltNo = (Offset - StartOffset) >> 2;
3656 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3657 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3658 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3660 // Canonicalize it to a v4i32 shuffle.
3661 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3662 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3663 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3664 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3670 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
3671 /// vector of type 'VT', see if the elements can be replaced by a single large
3672 /// load which has the same value as a build_vector whose operands are 'elts'.
3674 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3676 /// FIXME: we'd also like to handle the case where the last elements are zero
3677 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3678 /// There's even a handy isZeroNode for that purpose.
3679 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3680 DebugLoc &dl, SelectionDAG &DAG) {
3681 EVT EltVT = VT.getVectorElementType();
3682 unsigned NumElems = Elts.size();
3684 LoadSDNode *LDBase = NULL;
3685 unsigned LastLoadedElt = -1U;
3687 // For each element in the initializer, see if we've found a load or an undef.
3688 // If we don't find an initial load element, or later load elements are
3689 // non-consecutive, bail out.
3690 for (unsigned i = 0; i < NumElems; ++i) {
3691 SDValue Elt = Elts[i];
3693 if (!Elt.getNode() ||
3694 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3697 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3699 LDBase = cast<LoadSDNode>(Elt.getNode());
3703 if (Elt.getOpcode() == ISD::UNDEF)
3706 LoadSDNode *LD = cast<LoadSDNode>(Elt);
3707 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3712 // If we have found an entire vector of loads and undefs, then return a large
3713 // load of the entire vector width starting at the base pointer. If we found
3714 // consecutive loads for the low half, generate a vzext_load node.
3715 if (LastLoadedElt == NumElems - 1) {
3716 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3717 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3718 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3719 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3720 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3721 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3722 LDBase->isVolatile(), LDBase->isNonTemporal(),
3723 LDBase->getAlignment());
3724 } else if (NumElems == 4 && LastLoadedElt == 1) {
3725 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3726 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3727 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3728 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3734 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3735 DebugLoc dl = Op.getDebugLoc();
3736 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3737 if (ISD::isBuildVectorAllZeros(Op.getNode())
3738 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3739 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3740 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3741 // eliminated on x86-32 hosts.
3742 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3745 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3746 return getOnesVector(Op.getValueType(), DAG, dl);
3747 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3750 EVT VT = Op.getValueType();
3751 EVT ExtVT = VT.getVectorElementType();
3752 unsigned EVTBits = ExtVT.getSizeInBits();
3754 unsigned NumElems = Op.getNumOperands();
3755 unsigned NumZero = 0;
3756 unsigned NumNonZero = 0;
3757 unsigned NonZeros = 0;
3758 bool IsAllConstants = true;
3759 SmallSet<SDValue, 8> Values;
3760 for (unsigned i = 0; i < NumElems; ++i) {
3761 SDValue Elt = Op.getOperand(i);
3762 if (Elt.getOpcode() == ISD::UNDEF)
3765 if (Elt.getOpcode() != ISD::Constant &&
3766 Elt.getOpcode() != ISD::ConstantFP)
3767 IsAllConstants = false;
3768 if (X86::isZeroNode(Elt))
3771 NonZeros |= (1 << i);
3776 if (NumNonZero == 0) {
3777 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3778 return DAG.getUNDEF(VT);
3781 // Special case for single non-zero, non-undef, element.
3782 if (NumNonZero == 1) {
3783 unsigned Idx = CountTrailingZeros_32(NonZeros);
3784 SDValue Item = Op.getOperand(Idx);
3786 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3787 // the value are obviously zero, truncate the value to i32 and do the
3788 // insertion that way. Only do this if the value is non-constant or if the
3789 // value is a constant being inserted into element 0. It is cheaper to do
3790 // a constant pool load than it is to do a movd + shuffle.
3791 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3792 (!IsAllConstants || Idx == 0)) {
3793 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3794 // Handle MMX and SSE both.
3795 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3796 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3798 // Truncate the value (which may itself be a constant) to i32, and
3799 // convert it to a vector with movd (S2V+shuffle to zero extend).
3800 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3801 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3802 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3803 Subtarget->hasSSE2(), DAG);
3805 // Now we have our 32-bit value zero extended in the low element of
3806 // a vector. If Idx != 0, swizzle it into place.
3808 SmallVector<int, 4> Mask;
3809 Mask.push_back(Idx);
3810 for (unsigned i = 1; i != VecElts; ++i)
3812 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3813 DAG.getUNDEF(Item.getValueType()),
3816 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3820 // If we have a constant or non-constant insertion into the low element of
3821 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3822 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3823 // depending on what the source datatype is.
3826 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3827 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3828 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3829 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3830 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3831 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3833 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3834 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3835 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3836 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3837 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3838 Subtarget->hasSSE2(), DAG);
3839 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3843 // Is it a vector logical left shift?
3844 if (NumElems == 2 && Idx == 1 &&
3845 X86::isZeroNode(Op.getOperand(0)) &&
3846 !X86::isZeroNode(Op.getOperand(1))) {
3847 unsigned NumBits = VT.getSizeInBits();
3848 return getVShift(true, VT,
3849 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3850 VT, Op.getOperand(1)),
3851 NumBits/2, DAG, *this, dl);
3854 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3857 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3858 // is a non-constant being inserted into an element other than the low one,
3859 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3860 // movd/movss) to move this into the low element, then shuffle it into
3862 if (EVTBits == 32) {
3863 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3865 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3866 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3867 Subtarget->hasSSE2(), DAG);
3868 SmallVector<int, 8> MaskVec;
3869 for (unsigned i = 0; i < NumElems; i++)
3870 MaskVec.push_back(i == Idx ? 0 : 1);
3871 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3875 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3876 if (Values.size() == 1) {
3877 if (EVTBits == 32) {
3878 // Instead of a shuffle like this:
3879 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3880 // Check if it's possible to issue this instead.
3881 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3882 unsigned Idx = CountTrailingZeros_32(NonZeros);
3883 SDValue Item = Op.getOperand(Idx);
3884 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3885 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3890 // A vector full of immediates; various special cases are already
3891 // handled, so this is best done with a single constant-pool load.
3895 // Let legalizer expand 2-wide build_vectors.
3896 if (EVTBits == 64) {
3897 if (NumNonZero == 1) {
3898 // One half is zero or undef.
3899 unsigned Idx = CountTrailingZeros_32(NonZeros);
3900 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3901 Op.getOperand(Idx));
3902 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3903 Subtarget->hasSSE2(), DAG);
3908 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3909 if (EVTBits == 8 && NumElems == 16) {
3910 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3912 if (V.getNode()) return V;
3915 if (EVTBits == 16 && NumElems == 8) {
3916 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3918 if (V.getNode()) return V;
3921 // If element VT is == 32 bits, turn it into a number of shuffles.
3922 SmallVector<SDValue, 8> V;
3924 if (NumElems == 4 && NumZero > 0) {
3925 for (unsigned i = 0; i < 4; ++i) {
3926 bool isZero = !(NonZeros & (1 << i));
3928 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3930 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3933 for (unsigned i = 0; i < 2; ++i) {
3934 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3937 V[i] = V[i*2]; // Must be a zero vector.
3940 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3943 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3946 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3951 SmallVector<int, 8> MaskVec;
3952 bool Reverse = (NonZeros & 0x3) == 2;
3953 for (unsigned i = 0; i < 2; ++i)
3954 MaskVec.push_back(Reverse ? 1-i : i);
3955 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3956 for (unsigned i = 0; i < 2; ++i)
3957 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3958 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3961 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3962 // Check for a build vector of consecutive loads.
3963 for (unsigned i = 0; i < NumElems; ++i)
3964 V[i] = Op.getOperand(i);
3966 // Check for elements which are consecutive loads.
3967 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3971 // For SSE 4.1, use inserts into undef.
3972 if (getSubtarget()->hasSSE41()) {
3973 V[0] = DAG.getUNDEF(VT);
3974 for (unsigned i = 0; i < NumElems; ++i)
3975 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3976 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3977 Op.getOperand(i), DAG.getIntPtrConstant(i));
3981 // Otherwise, expand into a number of unpckl*
3983 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3984 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3985 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3986 for (unsigned i = 0; i < NumElems; ++i)
3987 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3989 while (NumElems != 0) {
3990 for (unsigned i = 0; i < NumElems; ++i)
3991 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4000 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4001 // We support concatenate two MMX registers and place them in a MMX
4002 // register. This is better than doing a stack convert.
4003 DebugLoc dl = Op.getDebugLoc();
4004 EVT ResVT = Op.getValueType();
4005 assert(Op.getNumOperands() == 2);
4006 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4007 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4009 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4010 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4011 InVec = Op.getOperand(1);
4012 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4013 unsigned NumElts = ResVT.getVectorNumElements();
4014 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4015 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4016 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4018 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4019 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4020 Mask[0] = 0; Mask[1] = 2;
4021 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4023 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4026 // v8i16 shuffles - Prefer shuffles in the following order:
4027 // 1. [all] pshuflw, pshufhw, optional move
4028 // 2. [ssse3] 1 x pshufb
4029 // 3. [ssse3] 2 x pshufb + 1 x por
4030 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4032 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4034 const X86TargetLowering &TLI) {
4035 SDValue V1 = SVOp->getOperand(0);
4036 SDValue V2 = SVOp->getOperand(1);
4037 DebugLoc dl = SVOp->getDebugLoc();
4038 SmallVector<int, 8> MaskVals;
4040 // Determine if more than 1 of the words in each of the low and high quadwords
4041 // of the result come from the same quadword of one of the two inputs. Undef
4042 // mask values count as coming from any quadword, for better codegen.
4043 SmallVector<unsigned, 4> LoQuad(4);
4044 SmallVector<unsigned, 4> HiQuad(4);
4045 BitVector InputQuads(4);
4046 for (unsigned i = 0; i < 8; ++i) {
4047 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4048 int EltIdx = SVOp->getMaskElt(i);
4049 MaskVals.push_back(EltIdx);
4058 InputQuads.set(EltIdx / 4);
4061 int BestLoQuad = -1;
4062 unsigned MaxQuad = 1;
4063 for (unsigned i = 0; i < 4; ++i) {
4064 if (LoQuad[i] > MaxQuad) {
4066 MaxQuad = LoQuad[i];
4070 int BestHiQuad = -1;
4072 for (unsigned i = 0; i < 4; ++i) {
4073 if (HiQuad[i] > MaxQuad) {
4075 MaxQuad = HiQuad[i];
4079 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4080 // of the two input vectors, shuffle them into one input vector so only a
4081 // single pshufb instruction is necessary. If There are more than 2 input
4082 // quads, disable the next transformation since it does not help SSSE3.
4083 bool V1Used = InputQuads[0] || InputQuads[1];
4084 bool V2Used = InputQuads[2] || InputQuads[3];
4085 if (TLI.getSubtarget()->hasSSSE3()) {
4086 if (InputQuads.count() == 2 && V1Used && V2Used) {
4087 BestLoQuad = InputQuads.find_first();
4088 BestHiQuad = InputQuads.find_next(BestLoQuad);
4090 if (InputQuads.count() > 2) {
4096 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4097 // the shuffle mask. If a quad is scored as -1, that means that it contains
4098 // words from all 4 input quadwords.
4100 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4101 SmallVector<int, 8> MaskV;
4102 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4103 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4104 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4105 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4106 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4107 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4109 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4110 // source words for the shuffle, to aid later transformations.
4111 bool AllWordsInNewV = true;
4112 bool InOrder[2] = { true, true };
4113 for (unsigned i = 0; i != 8; ++i) {
4114 int idx = MaskVals[i];
4116 InOrder[i/4] = false;
4117 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4119 AllWordsInNewV = false;
4123 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4124 if (AllWordsInNewV) {
4125 for (int i = 0; i != 8; ++i) {
4126 int idx = MaskVals[i];
4129 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4130 if ((idx != i) && idx < 4)
4132 if ((idx != i) && idx > 3)
4141 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4142 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4143 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4144 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4145 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4149 // If we have SSSE3, and all words of the result are from 1 input vector,
4150 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4151 // is present, fall back to case 4.
4152 if (TLI.getSubtarget()->hasSSSE3()) {
4153 SmallVector<SDValue,16> pshufbMask;
4155 // If we have elements from both input vectors, set the high bit of the
4156 // shuffle mask element to zero out elements that come from V2 in the V1
4157 // mask, and elements that come from V1 in the V2 mask, so that the two
4158 // results can be OR'd together.
4159 bool TwoInputs = V1Used && V2Used;
4160 for (unsigned i = 0; i != 8; ++i) {
4161 int EltIdx = MaskVals[i] * 2;
4162 if (TwoInputs && (EltIdx >= 16)) {
4163 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4164 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4167 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4168 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4170 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4171 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4172 DAG.getNode(ISD::BUILD_VECTOR, dl,
4173 MVT::v16i8, &pshufbMask[0], 16));
4175 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4177 // Calculate the shuffle mask for the second input, shuffle it, and
4178 // OR it with the first shuffled input.
4180 for (unsigned i = 0; i != 8; ++i) {
4181 int EltIdx = MaskVals[i] * 2;
4183 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4184 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4187 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4188 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4190 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4191 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4192 DAG.getNode(ISD::BUILD_VECTOR, dl,
4193 MVT::v16i8, &pshufbMask[0], 16));
4194 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4195 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4198 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4199 // and update MaskVals with new element order.
4200 BitVector InOrder(8);
4201 if (BestLoQuad >= 0) {
4202 SmallVector<int, 8> MaskV;
4203 for (int i = 0; i != 4; ++i) {
4204 int idx = MaskVals[i];
4206 MaskV.push_back(-1);
4208 } else if ((idx / 4) == BestLoQuad) {
4209 MaskV.push_back(idx & 3);
4212 MaskV.push_back(-1);
4215 for (unsigned i = 4; i != 8; ++i)
4217 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4221 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4222 // and update MaskVals with the new element order.
4223 if (BestHiQuad >= 0) {
4224 SmallVector<int, 8> MaskV;
4225 for (unsigned i = 0; i != 4; ++i)
4227 for (unsigned i = 4; i != 8; ++i) {
4228 int idx = MaskVals[i];
4230 MaskV.push_back(-1);
4232 } else if ((idx / 4) == BestHiQuad) {
4233 MaskV.push_back((idx & 3) + 4);
4236 MaskV.push_back(-1);
4239 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4243 // In case BestHi & BestLo were both -1, which means each quadword has a word
4244 // from each of the four input quadwords, calculate the InOrder bitvector now
4245 // before falling through to the insert/extract cleanup.
4246 if (BestLoQuad == -1 && BestHiQuad == -1) {
4248 for (int i = 0; i != 8; ++i)
4249 if (MaskVals[i] < 0 || MaskVals[i] == i)
4253 // The other elements are put in the right place using pextrw and pinsrw.
4254 for (unsigned i = 0; i != 8; ++i) {
4257 int EltIdx = MaskVals[i];
4260 SDValue ExtOp = (EltIdx < 8)
4261 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4262 DAG.getIntPtrConstant(EltIdx))
4263 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4264 DAG.getIntPtrConstant(EltIdx - 8));
4265 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4266 DAG.getIntPtrConstant(i));
4271 // v16i8 shuffles - Prefer shuffles in the following order:
4272 // 1. [ssse3] 1 x pshufb
4273 // 2. [ssse3] 2 x pshufb + 1 x por
4274 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4276 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4278 const X86TargetLowering &TLI) {
4279 SDValue V1 = SVOp->getOperand(0);
4280 SDValue V2 = SVOp->getOperand(1);
4281 DebugLoc dl = SVOp->getDebugLoc();
4282 SmallVector<int, 16> MaskVals;
4283 SVOp->getMask(MaskVals);
4285 // If we have SSSE3, case 1 is generated when all result bytes come from
4286 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4287 // present, fall back to case 3.
4288 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4291 for (unsigned i = 0; i < 16; ++i) {
4292 int EltIdx = MaskVals[i];
4301 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4302 if (TLI.getSubtarget()->hasSSSE3()) {
4303 SmallVector<SDValue,16> pshufbMask;
4305 // If all result elements are from one input vector, then only translate
4306 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4308 // Otherwise, we have elements from both input vectors, and must zero out
4309 // elements that come from V2 in the first mask, and V1 in the second mask
4310 // so that we can OR them together.
4311 bool TwoInputs = !(V1Only || V2Only);
4312 for (unsigned i = 0; i != 16; ++i) {
4313 int EltIdx = MaskVals[i];
4314 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4315 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4318 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4320 // If all the elements are from V2, assign it to V1 and return after
4321 // building the first pshufb.
4324 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4325 DAG.getNode(ISD::BUILD_VECTOR, dl,
4326 MVT::v16i8, &pshufbMask[0], 16));
4330 // Calculate the shuffle mask for the second input, shuffle it, and
4331 // OR it with the first shuffled input.
4333 for (unsigned i = 0; i != 16; ++i) {
4334 int EltIdx = MaskVals[i];
4336 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4339 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4341 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4342 DAG.getNode(ISD::BUILD_VECTOR, dl,
4343 MVT::v16i8, &pshufbMask[0], 16));
4344 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4347 // No SSSE3 - Calculate in place words and then fix all out of place words
4348 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4349 // the 16 different words that comprise the two doublequadword input vectors.
4350 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4351 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4352 SDValue NewV = V2Only ? V2 : V1;
4353 for (int i = 0; i != 8; ++i) {
4354 int Elt0 = MaskVals[i*2];
4355 int Elt1 = MaskVals[i*2+1];
4357 // This word of the result is all undef, skip it.
4358 if (Elt0 < 0 && Elt1 < 0)
4361 // This word of the result is already in the correct place, skip it.
4362 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4364 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4367 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4368 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4371 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4372 // using a single extract together, load it and store it.
4373 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4374 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4375 DAG.getIntPtrConstant(Elt1 / 2));
4376 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4377 DAG.getIntPtrConstant(i));
4381 // If Elt1 is defined, extract it from the appropriate source. If the
4382 // source byte is not also odd, shift the extracted word left 8 bits
4383 // otherwise clear the bottom 8 bits if we need to do an or.
4385 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4386 DAG.getIntPtrConstant(Elt1 / 2));
4387 if ((Elt1 & 1) == 0)
4388 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4389 DAG.getConstant(8, TLI.getShiftAmountTy()));
4391 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4392 DAG.getConstant(0xFF00, MVT::i16));
4394 // If Elt0 is defined, extract it from the appropriate source. If the
4395 // source byte is not also even, shift the extracted word right 8 bits. If
4396 // Elt1 was also defined, OR the extracted values together before
4397 // inserting them in the result.
4399 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4400 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4401 if ((Elt0 & 1) != 0)
4402 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4403 DAG.getConstant(8, TLI.getShiftAmountTy()));
4405 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4406 DAG.getConstant(0x00FF, MVT::i16));
4407 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4410 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4411 DAG.getIntPtrConstant(i));
4413 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4416 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4417 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4418 /// done when every pair / quad of shuffle mask elements point to elements in
4419 /// the right sequence. e.g.
4420 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4422 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4424 const TargetLowering &TLI, DebugLoc dl) {
4425 EVT VT = SVOp->getValueType(0);
4426 SDValue V1 = SVOp->getOperand(0);
4427 SDValue V2 = SVOp->getOperand(1);
4428 unsigned NumElems = VT.getVectorNumElements();
4429 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4430 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4431 EVT MaskEltVT = MaskVT.getVectorElementType();
4433 switch (VT.getSimpleVT().SimpleTy) {
4434 default: assert(false && "Unexpected!");
4435 case MVT::v4f32: NewVT = MVT::v2f64; break;
4436 case MVT::v4i32: NewVT = MVT::v2i64; break;
4437 case MVT::v8i16: NewVT = MVT::v4i32; break;
4438 case MVT::v16i8: NewVT = MVT::v4i32; break;
4441 if (NewWidth == 2) {
4447 int Scale = NumElems / NewWidth;
4448 SmallVector<int, 8> MaskVec;
4449 for (unsigned i = 0; i < NumElems; i += Scale) {
4451 for (int j = 0; j < Scale; ++j) {
4452 int EltIdx = SVOp->getMaskElt(i+j);
4456 StartIdx = EltIdx - (EltIdx % Scale);
4457 if (EltIdx != StartIdx + j)
4461 MaskVec.push_back(-1);
4463 MaskVec.push_back(StartIdx / Scale);
4466 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4467 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4468 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4471 /// getVZextMovL - Return a zero-extending vector move low node.
4473 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4474 SDValue SrcOp, SelectionDAG &DAG,
4475 const X86Subtarget *Subtarget, DebugLoc dl) {
4476 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4477 LoadSDNode *LD = NULL;
4478 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4479 LD = dyn_cast<LoadSDNode>(SrcOp);
4481 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4483 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4484 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4485 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4486 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4487 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4489 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4490 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4491 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4492 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4500 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4501 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4502 DAG.getNode(ISD::BIT_CONVERT, dl,
4506 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4509 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4510 SDValue V1 = SVOp->getOperand(0);
4511 SDValue V2 = SVOp->getOperand(1);
4512 DebugLoc dl = SVOp->getDebugLoc();
4513 EVT VT = SVOp->getValueType(0);
4515 SmallVector<std::pair<int, int>, 8> Locs;
4517 SmallVector<int, 8> Mask1(4U, -1);
4518 SmallVector<int, 8> PermMask;
4519 SVOp->getMask(PermMask);
4523 for (unsigned i = 0; i != 4; ++i) {
4524 int Idx = PermMask[i];
4526 Locs[i] = std::make_pair(-1, -1);
4528 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4530 Locs[i] = std::make_pair(0, NumLo);
4534 Locs[i] = std::make_pair(1, NumHi);
4536 Mask1[2+NumHi] = Idx;
4542 if (NumLo <= 2 && NumHi <= 2) {
4543 // If no more than two elements come from either vector. This can be
4544 // implemented with two shuffles. First shuffle gather the elements.
4545 // The second shuffle, which takes the first shuffle as both of its
4546 // vector operands, put the elements into the right order.
4547 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4549 SmallVector<int, 8> Mask2(4U, -1);
4551 for (unsigned i = 0; i != 4; ++i) {
4552 if (Locs[i].first == -1)
4555 unsigned Idx = (i < 2) ? 0 : 4;
4556 Idx += Locs[i].first * 2 + Locs[i].second;
4561 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4562 } else if (NumLo == 3 || NumHi == 3) {
4563 // Otherwise, we must have three elements from one vector, call it X, and
4564 // one element from the other, call it Y. First, use a shufps to build an
4565 // intermediate vector with the one element from Y and the element from X
4566 // that will be in the same half in the final destination (the indexes don't
4567 // matter). Then, use a shufps to build the final vector, taking the half
4568 // containing the element from Y from the intermediate, and the other half
4571 // Normalize it so the 3 elements come from V1.
4572 CommuteVectorShuffleMask(PermMask, VT);
4576 // Find the element from V2.
4578 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4579 int Val = PermMask[HiIndex];
4586 Mask1[0] = PermMask[HiIndex];
4588 Mask1[2] = PermMask[HiIndex^1];
4590 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4593 Mask1[0] = PermMask[0];
4594 Mask1[1] = PermMask[1];
4595 Mask1[2] = HiIndex & 1 ? 6 : 4;
4596 Mask1[3] = HiIndex & 1 ? 4 : 6;
4597 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4599 Mask1[0] = HiIndex & 1 ? 2 : 0;
4600 Mask1[1] = HiIndex & 1 ? 0 : 2;
4601 Mask1[2] = PermMask[2];
4602 Mask1[3] = PermMask[3];
4607 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4611 // Break it into (shuffle shuffle_hi, shuffle_lo).
4613 SmallVector<int,8> LoMask(4U, -1);
4614 SmallVector<int,8> HiMask(4U, -1);
4616 SmallVector<int,8> *MaskPtr = &LoMask;
4617 unsigned MaskIdx = 0;
4620 for (unsigned i = 0; i != 4; ++i) {
4627 int Idx = PermMask[i];
4629 Locs[i] = std::make_pair(-1, -1);
4630 } else if (Idx < 4) {
4631 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4632 (*MaskPtr)[LoIdx] = Idx;
4635 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4636 (*MaskPtr)[HiIdx] = Idx;
4641 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4642 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4643 SmallVector<int, 8> MaskOps;
4644 for (unsigned i = 0; i != 4; ++i) {
4645 if (Locs[i].first == -1) {
4646 MaskOps.push_back(-1);
4648 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4649 MaskOps.push_back(Idx);
4652 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4656 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4657 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4658 SDValue V1 = Op.getOperand(0);
4659 SDValue V2 = Op.getOperand(1);
4660 EVT VT = Op.getValueType();
4661 DebugLoc dl = Op.getDebugLoc();
4662 unsigned NumElems = VT.getVectorNumElements();
4663 bool isMMX = VT.getSizeInBits() == 64;
4664 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4665 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4666 bool V1IsSplat = false;
4667 bool V2IsSplat = false;
4669 if (isZeroShuffle(SVOp))
4670 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4672 // Promote splats to v4f32.
4673 if (SVOp->isSplat()) {
4674 if (isMMX || NumElems < 4)
4676 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4679 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4681 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4682 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4683 if (NewOp.getNode())
4684 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4685 LowerVECTOR_SHUFFLE(NewOp, DAG));
4686 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4687 // FIXME: Figure out a cleaner way to do this.
4688 // Try to make use of movq to zero out the top part.
4689 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4690 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4691 if (NewOp.getNode()) {
4692 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4693 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4694 DAG, Subtarget, dl);
4696 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4697 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4698 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4699 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4700 DAG, Subtarget, dl);
4704 if (X86::isPSHUFDMask(SVOp))
4707 // Check if this can be converted into a logical shift.
4708 bool isLeft = false;
4711 bool isShift = getSubtarget()->hasSSE2() &&
4712 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4713 if (isShift && ShVal.hasOneUse()) {
4714 // If the shifted value has multiple uses, it may be cheaper to use
4715 // v_set0 + movlhps or movhlps, etc.
4716 EVT EltVT = VT.getVectorElementType();
4717 ShAmt *= EltVT.getSizeInBits();
4718 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4721 if (X86::isMOVLMask(SVOp)) {
4724 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4725 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4730 // FIXME: fold these into legal mask.
4731 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4732 X86::isMOVSLDUPMask(SVOp) ||
4733 X86::isMOVHLPSMask(SVOp) ||
4734 X86::isMOVLHPSMask(SVOp) ||
4735 X86::isMOVLPMask(SVOp)))
4738 if (ShouldXformToMOVHLPS(SVOp) ||
4739 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4740 return CommuteVectorShuffle(SVOp, DAG);
4743 // No better options. Use a vshl / vsrl.
4744 EVT EltVT = VT.getVectorElementType();
4745 ShAmt *= EltVT.getSizeInBits();
4746 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4749 bool Commuted = false;
4750 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4751 // 1,1,1,1 -> v8i16 though.
4752 V1IsSplat = isSplatVector(V1.getNode());
4753 V2IsSplat = isSplatVector(V2.getNode());
4755 // Canonicalize the splat or undef, if present, to be on the RHS.
4756 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4757 Op = CommuteVectorShuffle(SVOp, DAG);
4758 SVOp = cast<ShuffleVectorSDNode>(Op);
4759 V1 = SVOp->getOperand(0);
4760 V2 = SVOp->getOperand(1);
4761 std::swap(V1IsSplat, V2IsSplat);
4762 std::swap(V1IsUndef, V2IsUndef);
4766 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4767 // Shuffling low element of v1 into undef, just return v1.
4770 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4771 // the instruction selector will not match, so get a canonical MOVL with
4772 // swapped operands to undo the commute.
4773 return getMOVL(DAG, dl, VT, V2, V1);
4776 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4777 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4778 X86::isUNPCKLMask(SVOp) ||
4779 X86::isUNPCKHMask(SVOp))
4783 // Normalize mask so all entries that point to V2 points to its first
4784 // element then try to match unpck{h|l} again. If match, return a
4785 // new vector_shuffle with the corrected mask.
4786 SDValue NewMask = NormalizeMask(SVOp, DAG);
4787 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4788 if (NSVOp != SVOp) {
4789 if (X86::isUNPCKLMask(NSVOp, true)) {
4791 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4798 // Commute is back and try unpck* again.
4799 // FIXME: this seems wrong.
4800 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4801 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4802 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4803 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4804 X86::isUNPCKLMask(NewSVOp) ||
4805 X86::isUNPCKHMask(NewSVOp))
4809 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4811 // Normalize the node to match x86 shuffle ops if needed
4812 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4813 return CommuteVectorShuffle(SVOp, DAG);
4815 // Check for legal shuffle and return?
4816 SmallVector<int, 16> PermMask;
4817 SVOp->getMask(PermMask);
4818 if (isShuffleMaskLegal(PermMask, VT))
4821 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4822 if (VT == MVT::v8i16) {
4823 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4824 if (NewOp.getNode())
4828 if (VT == MVT::v16i8) {
4829 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4830 if (NewOp.getNode())
4834 // Handle all 4 wide cases with a number of shuffles except for MMX.
4835 if (NumElems == 4 && !isMMX)
4836 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4842 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4843 SelectionDAG &DAG) const {
4844 EVT VT = Op.getValueType();
4845 DebugLoc dl = Op.getDebugLoc();
4846 if (VT.getSizeInBits() == 8) {
4847 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4848 Op.getOperand(0), Op.getOperand(1));
4849 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4850 DAG.getValueType(VT));
4851 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4852 } else if (VT.getSizeInBits() == 16) {
4853 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4854 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4856 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4857 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4858 DAG.getNode(ISD::BIT_CONVERT, dl,
4862 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4863 Op.getOperand(0), Op.getOperand(1));
4864 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4865 DAG.getValueType(VT));
4866 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4867 } else if (VT == MVT::f32) {
4868 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4869 // the result back to FR32 register. It's only worth matching if the
4870 // result has a single use which is a store or a bitcast to i32. And in
4871 // the case of a store, it's not worth it if the index is a constant 0,
4872 // because a MOVSSmr can be used instead, which is smaller and faster.
4873 if (!Op.hasOneUse())
4875 SDNode *User = *Op.getNode()->use_begin();
4876 if ((User->getOpcode() != ISD::STORE ||
4877 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4878 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4879 (User->getOpcode() != ISD::BIT_CONVERT ||
4880 User->getValueType(0) != MVT::i32))
4882 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4883 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4886 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4887 } else if (VT == MVT::i32) {
4888 // ExtractPS works with constant index.
4889 if (isa<ConstantSDNode>(Op.getOperand(1)))
4897 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4898 SelectionDAG &DAG) const {
4899 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4902 if (Subtarget->hasSSE41()) {
4903 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4908 EVT VT = Op.getValueType();
4909 DebugLoc dl = Op.getDebugLoc();
4910 // TODO: handle v16i8.
4911 if (VT.getSizeInBits() == 16) {
4912 SDValue Vec = Op.getOperand(0);
4913 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4915 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4916 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4917 DAG.getNode(ISD::BIT_CONVERT, dl,
4920 // Transform it so it match pextrw which produces a 32-bit result.
4921 EVT EltVT = MVT::i32;
4922 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4923 Op.getOperand(0), Op.getOperand(1));
4924 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4925 DAG.getValueType(VT));
4926 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4927 } else if (VT.getSizeInBits() == 32) {
4928 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4932 // SHUFPS the element to the lowest double word, then movss.
4933 int Mask[4] = { Idx, -1, -1, -1 };
4934 EVT VVT = Op.getOperand(0).getValueType();
4935 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4936 DAG.getUNDEF(VVT), Mask);
4937 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4938 DAG.getIntPtrConstant(0));
4939 } else if (VT.getSizeInBits() == 64) {
4940 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4941 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4942 // to match extract_elt for f64.
4943 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4947 // UNPCKHPD the element to the lowest double word, then movsd.
4948 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4949 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4950 int Mask[2] = { 1, -1 };
4951 EVT VVT = Op.getOperand(0).getValueType();
4952 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4953 DAG.getUNDEF(VVT), Mask);
4954 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4955 DAG.getIntPtrConstant(0));
4962 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4963 SelectionDAG &DAG) const {
4964 EVT VT = Op.getValueType();
4965 EVT EltVT = VT.getVectorElementType();
4966 DebugLoc dl = Op.getDebugLoc();
4968 SDValue N0 = Op.getOperand(0);
4969 SDValue N1 = Op.getOperand(1);
4970 SDValue N2 = Op.getOperand(2);
4972 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4973 isa<ConstantSDNode>(N2)) {
4975 if (VT == MVT::v8i16)
4976 Opc = X86ISD::PINSRW;
4977 else if (VT == MVT::v4i16)
4978 Opc = X86ISD::MMX_PINSRW;
4979 else if (VT == MVT::v16i8)
4980 Opc = X86ISD::PINSRB;
4982 Opc = X86ISD::PINSRB;
4984 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4986 if (N1.getValueType() != MVT::i32)
4987 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4988 if (N2.getValueType() != MVT::i32)
4989 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4990 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4991 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4992 // Bits [7:6] of the constant are the source select. This will always be
4993 // zero here. The DAG Combiner may combine an extract_elt index into these
4994 // bits. For example (insert (extract, 3), 2) could be matched by putting
4995 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4996 // Bits [5:4] of the constant are the destination select. This is the
4997 // value of the incoming immediate.
4998 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4999 // combine either bitwise AND or insert of float 0.0 to set these bits.
5000 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5001 // Create this as a scalar to vector..
5002 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5003 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5004 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5005 // PINSR* works with constant index.
5012 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5013 EVT VT = Op.getValueType();
5014 EVT EltVT = VT.getVectorElementType();
5016 if (Subtarget->hasSSE41())
5017 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5019 if (EltVT == MVT::i8)
5022 DebugLoc dl = Op.getDebugLoc();
5023 SDValue N0 = Op.getOperand(0);
5024 SDValue N1 = Op.getOperand(1);
5025 SDValue N2 = Op.getOperand(2);
5027 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5028 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5029 // as its second argument.
5030 if (N1.getValueType() != MVT::i32)
5031 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5032 if (N2.getValueType() != MVT::i32)
5033 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5034 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5035 dl, VT, N0, N1, N2);
5041 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5042 DebugLoc dl = Op.getDebugLoc();
5043 if (Op.getValueType() == MVT::v2f32)
5044 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5045 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5046 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5047 Op.getOperand(0))));
5049 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5050 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5052 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5053 EVT VT = MVT::v2i32;
5054 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5061 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5062 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5065 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5066 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5067 // one of the above mentioned nodes. It has to be wrapped because otherwise
5068 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5069 // be used to form addressing mode. These wrapped nodes will be selected
5072 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5073 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5075 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5077 unsigned char OpFlag = 0;
5078 unsigned WrapperKind = X86ISD::Wrapper;
5079 CodeModel::Model M = getTargetMachine().getCodeModel();
5081 if (Subtarget->isPICStyleRIPRel() &&
5082 (M == CodeModel::Small || M == CodeModel::Kernel))
5083 WrapperKind = X86ISD::WrapperRIP;
5084 else if (Subtarget->isPICStyleGOT())
5085 OpFlag = X86II::MO_GOTOFF;
5086 else if (Subtarget->isPICStyleStubPIC())
5087 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5089 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5091 CP->getOffset(), OpFlag);
5092 DebugLoc DL = CP->getDebugLoc();
5093 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5094 // With PIC, the address is actually $g + Offset.
5096 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5097 DAG.getNode(X86ISD::GlobalBaseReg,
5098 DebugLoc(), getPointerTy()),
5105 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5106 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5108 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5110 unsigned char OpFlag = 0;
5111 unsigned WrapperKind = X86ISD::Wrapper;
5112 CodeModel::Model M = getTargetMachine().getCodeModel();
5114 if (Subtarget->isPICStyleRIPRel() &&
5115 (M == CodeModel::Small || M == CodeModel::Kernel))
5116 WrapperKind = X86ISD::WrapperRIP;
5117 else if (Subtarget->isPICStyleGOT())
5118 OpFlag = X86II::MO_GOTOFF;
5119 else if (Subtarget->isPICStyleStubPIC())
5120 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5122 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5124 DebugLoc DL = JT->getDebugLoc();
5125 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5127 // With PIC, the address is actually $g + Offset.
5129 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5130 DAG.getNode(X86ISD::GlobalBaseReg,
5131 DebugLoc(), getPointerTy()),
5139 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5140 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5142 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5144 unsigned char OpFlag = 0;
5145 unsigned WrapperKind = X86ISD::Wrapper;
5146 CodeModel::Model M = getTargetMachine().getCodeModel();
5148 if (Subtarget->isPICStyleRIPRel() &&
5149 (M == CodeModel::Small || M == CodeModel::Kernel))
5150 WrapperKind = X86ISD::WrapperRIP;
5151 else if (Subtarget->isPICStyleGOT())
5152 OpFlag = X86II::MO_GOTOFF;
5153 else if (Subtarget->isPICStyleStubPIC())
5154 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5156 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5158 DebugLoc DL = Op.getDebugLoc();
5159 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5162 // With PIC, the address is actually $g + Offset.
5163 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5164 !Subtarget->is64Bit()) {
5165 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5166 DAG.getNode(X86ISD::GlobalBaseReg,
5167 DebugLoc(), getPointerTy()),
5175 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5176 // Create the TargetBlockAddressAddress node.
5177 unsigned char OpFlags =
5178 Subtarget->ClassifyBlockAddressReference();
5179 CodeModel::Model M = getTargetMachine().getCodeModel();
5180 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5181 DebugLoc dl = Op.getDebugLoc();
5182 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5183 /*isTarget=*/true, OpFlags);
5185 if (Subtarget->isPICStyleRIPRel() &&
5186 (M == CodeModel::Small || M == CodeModel::Kernel))
5187 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5189 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5191 // With PIC, the address is actually $g + Offset.
5192 if (isGlobalRelativeToPICBase(OpFlags)) {
5193 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5194 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5202 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5204 SelectionDAG &DAG) const {
5205 // Create the TargetGlobalAddress node, folding in the constant
5206 // offset if it is legal.
5207 unsigned char OpFlags =
5208 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5209 CodeModel::Model M = getTargetMachine().getCodeModel();
5211 if (OpFlags == X86II::MO_NO_FLAG &&
5212 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5213 // A direct static reference to a global.
5214 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5217 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5220 if (Subtarget->isPICStyleRIPRel() &&
5221 (M == CodeModel::Small || M == CodeModel::Kernel))
5222 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5224 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5226 // With PIC, the address is actually $g + Offset.
5227 if (isGlobalRelativeToPICBase(OpFlags)) {
5228 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5229 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5233 // For globals that require a load from a stub to get the address, emit the
5235 if (isGlobalStubReference(OpFlags))
5236 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5237 PseudoSourceValue::getGOT(), 0, false, false, 0);
5239 // If there was a non-zero offset that we didn't fold, create an explicit
5242 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5243 DAG.getConstant(Offset, getPointerTy()));
5249 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5250 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5251 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5252 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5256 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5257 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5258 unsigned char OperandFlags) {
5259 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5260 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5261 DebugLoc dl = GA->getDebugLoc();
5262 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5263 GA->getValueType(0),
5267 SDValue Ops[] = { Chain, TGA, *InFlag };
5268 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5270 SDValue Ops[] = { Chain, TGA };
5271 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5274 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5275 MFI->setHasCalls(true);
5277 SDValue Flag = Chain.getValue(1);
5278 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5281 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5283 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5286 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5287 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5288 DAG.getNode(X86ISD::GlobalBaseReg,
5289 DebugLoc(), PtrVT), InFlag);
5290 InFlag = Chain.getValue(1);
5292 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5295 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5297 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5299 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5300 X86::RAX, X86II::MO_TLSGD);
5303 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5304 // "local exec" model.
5305 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5306 const EVT PtrVT, TLSModel::Model model,
5308 DebugLoc dl = GA->getDebugLoc();
5309 // Get the Thread Pointer
5310 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5312 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5315 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5316 NULL, 0, false, false, 0);
5318 unsigned char OperandFlags = 0;
5319 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5321 unsigned WrapperKind = X86ISD::Wrapper;
5322 if (model == TLSModel::LocalExec) {
5323 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5324 } else if (is64Bit) {
5325 assert(model == TLSModel::InitialExec);
5326 OperandFlags = X86II::MO_GOTTPOFF;
5327 WrapperKind = X86ISD::WrapperRIP;
5329 assert(model == TLSModel::InitialExec);
5330 OperandFlags = X86II::MO_INDNTPOFF;
5333 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5335 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5336 GA->getOffset(), OperandFlags);
5337 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5339 if (model == TLSModel::InitialExec)
5340 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5341 PseudoSourceValue::getGOT(), 0, false, false, 0);
5343 // The address of the thread local variable is the add of the thread
5344 // pointer with the offset of the variable.
5345 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5349 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5350 // TODO: implement the "local dynamic" model
5351 // TODO: implement the "initial exec"model for pic executables
5352 assert(Subtarget->isTargetELF() &&
5353 "TLS not implemented for non-ELF targets");
5354 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5355 const GlobalValue *GV = GA->getGlobal();
5357 // If GV is an alias then use the aliasee for determining
5358 // thread-localness.
5359 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5360 GV = GA->resolveAliasedGlobal(false);
5362 TLSModel::Model model = getTLSModel(GV,
5363 getTargetMachine().getRelocationModel());
5366 case TLSModel::GeneralDynamic:
5367 case TLSModel::LocalDynamic: // not implemented
5368 if (Subtarget->is64Bit())
5369 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5370 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5372 case TLSModel::InitialExec:
5373 case TLSModel::LocalExec:
5374 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5375 Subtarget->is64Bit());
5378 llvm_unreachable("Unreachable");
5383 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5384 /// take a 2 x i32 value to shift plus a shift amount.
5385 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5386 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5387 EVT VT = Op.getValueType();
5388 unsigned VTBits = VT.getSizeInBits();
5389 DebugLoc dl = Op.getDebugLoc();
5390 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5391 SDValue ShOpLo = Op.getOperand(0);
5392 SDValue ShOpHi = Op.getOperand(1);
5393 SDValue ShAmt = Op.getOperand(2);
5394 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5395 DAG.getConstant(VTBits - 1, MVT::i8))
5396 : DAG.getConstant(0, VT);
5399 if (Op.getOpcode() == ISD::SHL_PARTS) {
5400 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5401 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5403 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5404 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5407 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5408 DAG.getConstant(VTBits, MVT::i8));
5409 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5410 AndNode, DAG.getConstant(0, MVT::i8));
5413 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5414 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5415 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5417 if (Op.getOpcode() == ISD::SHL_PARTS) {
5418 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5419 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5421 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5422 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5425 SDValue Ops[2] = { Lo, Hi };
5426 return DAG.getMergeValues(Ops, 2, dl);
5429 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5430 SelectionDAG &DAG) const {
5431 EVT SrcVT = Op.getOperand(0).getValueType();
5433 if (SrcVT.isVector()) {
5434 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5440 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5441 "Unknown SINT_TO_FP to lower!");
5443 // These are really Legal; return the operand so the caller accepts it as
5445 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5447 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5448 Subtarget->is64Bit()) {
5452 DebugLoc dl = Op.getDebugLoc();
5453 unsigned Size = SrcVT.getSizeInBits()/8;
5454 MachineFunction &MF = DAG.getMachineFunction();
5455 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5456 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5457 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5459 PseudoSourceValue::getFixedStack(SSFI), 0,
5461 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5464 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5466 SelectionDAG &DAG) const {
5468 DebugLoc dl = Op.getDebugLoc();
5470 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5472 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5474 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5475 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5476 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5477 Tys, Ops, array_lengthof(Ops));
5480 Chain = Result.getValue(1);
5481 SDValue InFlag = Result.getValue(2);
5483 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5484 // shouldn't be necessary except that RFP cannot be live across
5485 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5486 MachineFunction &MF = DAG.getMachineFunction();
5487 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5488 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5489 Tys = DAG.getVTList(MVT::Other);
5491 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5493 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5494 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5495 PseudoSourceValue::getFixedStack(SSFI), 0,
5502 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5503 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5504 SelectionDAG &DAG) const {
5505 // This algorithm is not obvious. Here it is in C code, more or less:
5507 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5508 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5509 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5511 // Copy ints to xmm registers.
5512 __m128i xh = _mm_cvtsi32_si128( hi );
5513 __m128i xl = _mm_cvtsi32_si128( lo );
5515 // Combine into low half of a single xmm register.
5516 __m128i x = _mm_unpacklo_epi32( xh, xl );
5520 // Merge in appropriate exponents to give the integer bits the right
5522 x = _mm_unpacklo_epi32( x, exp );
5524 // Subtract away the biases to deal with the IEEE-754 double precision
5526 d = _mm_sub_pd( (__m128d) x, bias );
5528 // All conversions up to here are exact. The correctly rounded result is
5529 // calculated using the current rounding mode using the following
5531 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5532 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5533 // store doesn't really need to be here (except
5534 // maybe to zero the other double)
5539 DebugLoc dl = Op.getDebugLoc();
5540 LLVMContext *Context = DAG.getContext();
5542 // Build some magic constants.
5543 std::vector<Constant*> CV0;
5544 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5545 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5546 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5547 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5548 Constant *C0 = ConstantVector::get(CV0);
5549 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5551 std::vector<Constant*> CV1;
5553 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5555 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5556 Constant *C1 = ConstantVector::get(CV1);
5557 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5559 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5560 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5562 DAG.getIntPtrConstant(1)));
5563 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5564 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5566 DAG.getIntPtrConstant(0)));
5567 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5568 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5569 PseudoSourceValue::getConstantPool(), 0,
5571 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5572 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5573 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5574 PseudoSourceValue::getConstantPool(), 0,
5576 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5578 // Add the halves; easiest way is to swap them into another reg first.
5579 int ShufMask[2] = { 1, -1 };
5580 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5581 DAG.getUNDEF(MVT::v2f64), ShufMask);
5582 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5583 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5584 DAG.getIntPtrConstant(0));
5587 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5588 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5589 SelectionDAG &DAG) const {
5590 DebugLoc dl = Op.getDebugLoc();
5591 // FP constant to bias correct the final result.
5592 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5595 // Load the 32-bit value into an XMM register.
5596 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5597 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5599 DAG.getIntPtrConstant(0)));
5601 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5602 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5603 DAG.getIntPtrConstant(0));
5605 // Or the load with the bias.
5606 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5607 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5608 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5610 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5611 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5612 MVT::v2f64, Bias)));
5613 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5614 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5615 DAG.getIntPtrConstant(0));
5617 // Subtract the bias.
5618 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5620 // Handle final rounding.
5621 EVT DestVT = Op.getValueType();
5623 if (DestVT.bitsLT(MVT::f64)) {
5624 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5625 DAG.getIntPtrConstant(0));
5626 } else if (DestVT.bitsGT(MVT::f64)) {
5627 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5630 // Handle final rounding.
5634 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5635 SelectionDAG &DAG) const {
5636 SDValue N0 = Op.getOperand(0);
5637 DebugLoc dl = Op.getDebugLoc();
5639 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5640 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5641 // the optimization here.
5642 if (DAG.SignBitIsZero(N0))
5643 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5645 EVT SrcVT = N0.getValueType();
5646 if (SrcVT == MVT::i64) {
5647 // We only handle SSE2 f64 target here; caller can expand the rest.
5648 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5651 return LowerUINT_TO_FP_i64(Op, DAG);
5652 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5653 return LowerUINT_TO_FP_i32(Op, DAG);
5656 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5658 // Make a 64-bit buffer, and use it to build an FILD.
5659 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5660 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5661 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5662 getPointerTy(), StackSlot, WordOff);
5663 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5664 StackSlot, NULL, 0, false, false, 0);
5665 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5666 OffsetSlot, NULL, 0, false, false, 0);
5667 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5670 std::pair<SDValue,SDValue> X86TargetLowering::
5671 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5672 DebugLoc dl = Op.getDebugLoc();
5674 EVT DstTy = Op.getValueType();
5677 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5681 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5682 DstTy.getSimpleVT() >= MVT::i16 &&
5683 "Unknown FP_TO_SINT to lower!");
5685 // These are really Legal.
5686 if (DstTy == MVT::i32 &&
5687 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5688 return std::make_pair(SDValue(), SDValue());
5689 if (Subtarget->is64Bit() &&
5690 DstTy == MVT::i64 &&
5691 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5692 return std::make_pair(SDValue(), SDValue());
5694 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5696 MachineFunction &MF = DAG.getMachineFunction();
5697 unsigned MemSize = DstTy.getSizeInBits()/8;
5698 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5699 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5702 switch (DstTy.getSimpleVT().SimpleTy) {
5703 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5704 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5705 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5706 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5709 SDValue Chain = DAG.getEntryNode();
5710 SDValue Value = Op.getOperand(0);
5711 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5712 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5713 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5714 PseudoSourceValue::getFixedStack(SSFI), 0,
5716 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5718 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5720 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5721 Chain = Value.getValue(1);
5722 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5723 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5726 // Build the FP_TO_INT*_IN_MEM
5727 SDValue Ops[] = { Chain, Value, StackSlot };
5728 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5730 return std::make_pair(FIST, StackSlot);
5733 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5734 SelectionDAG &DAG) const {
5735 if (Op.getValueType().isVector()) {
5736 if (Op.getValueType() == MVT::v2i32 &&
5737 Op.getOperand(0).getValueType() == MVT::v2f64) {
5743 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5744 SDValue FIST = Vals.first, StackSlot = Vals.second;
5745 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5746 if (FIST.getNode() == 0) return Op;
5749 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5750 FIST, StackSlot, NULL, 0, false, false, 0);
5753 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5754 SelectionDAG &DAG) const {
5755 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5756 SDValue FIST = Vals.first, StackSlot = Vals.second;
5757 assert(FIST.getNode() && "Unexpected failure");
5760 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5761 FIST, StackSlot, NULL, 0, false, false, 0);
5764 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5765 SelectionDAG &DAG) const {
5766 LLVMContext *Context = DAG.getContext();
5767 DebugLoc dl = Op.getDebugLoc();
5768 EVT VT = Op.getValueType();
5771 EltVT = VT.getVectorElementType();
5772 std::vector<Constant*> CV;
5773 if (EltVT == MVT::f64) {
5774 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5778 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5784 Constant *C = ConstantVector::get(CV);
5785 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5786 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5787 PseudoSourceValue::getConstantPool(), 0,
5789 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5792 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5793 LLVMContext *Context = DAG.getContext();
5794 DebugLoc dl = Op.getDebugLoc();
5795 EVT VT = Op.getValueType();
5798 EltVT = VT.getVectorElementType();
5799 std::vector<Constant*> CV;
5800 if (EltVT == MVT::f64) {
5801 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5805 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5811 Constant *C = ConstantVector::get(CV);
5812 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5813 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5814 PseudoSourceValue::getConstantPool(), 0,
5816 if (VT.isVector()) {
5817 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5818 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5819 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5821 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5823 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5827 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5828 LLVMContext *Context = DAG.getContext();
5829 SDValue Op0 = Op.getOperand(0);
5830 SDValue Op1 = Op.getOperand(1);
5831 DebugLoc dl = Op.getDebugLoc();
5832 EVT VT = Op.getValueType();
5833 EVT SrcVT = Op1.getValueType();
5835 // If second operand is smaller, extend it first.
5836 if (SrcVT.bitsLT(VT)) {
5837 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5840 // And if it is bigger, shrink it first.
5841 if (SrcVT.bitsGT(VT)) {
5842 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5846 // At this point the operands and the result should have the same
5847 // type, and that won't be f80 since that is not custom lowered.
5849 // First get the sign bit of second operand.
5850 std::vector<Constant*> CV;
5851 if (SrcVT == MVT::f64) {
5852 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5853 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5855 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5856 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5857 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5858 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5860 Constant *C = ConstantVector::get(CV);
5861 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5862 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5863 PseudoSourceValue::getConstantPool(), 0,
5865 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5867 // Shift sign bit right or left if the two operands have different types.
5868 if (SrcVT.bitsGT(VT)) {
5869 // Op0 is MVT::f32, Op1 is MVT::f64.
5870 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5871 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5872 DAG.getConstant(32, MVT::i32));
5873 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5874 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5875 DAG.getIntPtrConstant(0));
5878 // Clear first operand sign bit.
5880 if (VT == MVT::f64) {
5881 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5882 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5884 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5885 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5886 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5887 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5889 C = ConstantVector::get(CV);
5890 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5891 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5892 PseudoSourceValue::getConstantPool(), 0,
5894 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5896 // Or the value with the sign bit.
5897 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5900 /// Emit nodes that will be selected as "test Op0,Op0", or something
5902 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5903 SelectionDAG &DAG) const {
5904 DebugLoc dl = Op.getDebugLoc();
5906 // CF and OF aren't always set the way we want. Determine which
5907 // of these we need.
5908 bool NeedCF = false;
5909 bool NeedOF = false;
5911 case X86::COND_A: case X86::COND_AE:
5912 case X86::COND_B: case X86::COND_BE:
5915 case X86::COND_G: case X86::COND_GE:
5916 case X86::COND_L: case X86::COND_LE:
5917 case X86::COND_O: case X86::COND_NO:
5923 // See if we can use the EFLAGS value from the operand instead of
5924 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5925 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5926 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5927 unsigned Opcode = 0;
5928 unsigned NumOperands = 0;
5929 switch (Op.getNode()->getOpcode()) {
5931 // Due to an isel shortcoming, be conservative if this add is
5932 // likely to be selected as part of a load-modify-store
5933 // instruction. When the root node in a match is a store, isel
5934 // doesn't know how to remap non-chain non-flag uses of other
5935 // nodes in the match, such as the ADD in this case. This leads
5936 // to the ADD being left around and reselected, with the result
5937 // being two adds in the output. Alas, even if none our users
5938 // are stores, that doesn't prove we're O.K. Ergo, if we have
5939 // any parents that aren't CopyToReg or SETCC, eschew INC/DEC.
5940 // A better fix seems to require climbing the DAG back to the
5941 // root, and it doesn't seem to be worth the effort.
5942 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5943 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5944 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
5946 if (ConstantSDNode *C =
5947 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5948 // An add of one will be selected as an INC.
5949 if (C->getAPIntValue() == 1) {
5950 Opcode = X86ISD::INC;
5954 // An add of negative one (subtract of one) will be selected as a DEC.
5955 if (C->getAPIntValue().isAllOnesValue()) {
5956 Opcode = X86ISD::DEC;
5961 // Otherwise use a regular EFLAGS-setting add.
5962 Opcode = X86ISD::ADD;
5966 // If the primary and result isn't used, don't bother using X86ISD::AND,
5967 // because a TEST instruction will be better.
5968 bool NonFlagUse = false;
5969 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5970 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5972 unsigned UOpNo = UI.getOperandNo();
5973 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5974 // Look pass truncate.
5975 UOpNo = User->use_begin().getOperandNo();
5976 User = *User->use_begin();
5978 if (User->getOpcode() != ISD::BRCOND &&
5979 User->getOpcode() != ISD::SETCC &&
5980 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5992 // Due to the ISEL shortcoming noted above, be conservative if this op is
5993 // likely to be selected as part of a load-modify-store instruction.
5994 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5995 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5996 if (UI->getOpcode() == ISD::STORE)
5998 // Otherwise use a regular EFLAGS-setting instruction.
5999 switch (Op.getNode()->getOpcode()) {
6000 case ISD::SUB: Opcode = X86ISD::SUB; break;
6001 case ISD::OR: Opcode = X86ISD::OR; break;
6002 case ISD::XOR: Opcode = X86ISD::XOR; break;
6003 case ISD::AND: Opcode = X86ISD::AND; break;
6004 default: llvm_unreachable("unexpected operator!");
6015 return SDValue(Op.getNode(), 1);
6021 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6022 SmallVector<SDValue, 4> Ops;
6023 for (unsigned i = 0; i != NumOperands; ++i)
6024 Ops.push_back(Op.getOperand(i));
6025 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6026 DAG.ReplaceAllUsesWith(Op, New);
6027 return SDValue(New.getNode(), 1);
6031 // Otherwise just emit a CMP with 0, which is the TEST pattern.
6032 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6033 DAG.getConstant(0, Op.getValueType()));
6036 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6038 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6039 SelectionDAG &DAG) const {
6040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6041 if (C->getAPIntValue() == 0)
6042 return EmitTest(Op0, X86CC, DAG);
6044 DebugLoc dl = Op0.getDebugLoc();
6045 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6048 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6049 /// if it's possible.
6050 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6051 DebugLoc dl, SelectionDAG &DAG) const {
6052 SDValue Op0 = And.getOperand(0);
6053 SDValue Op1 = And.getOperand(1);
6054 if (Op0.getOpcode() == ISD::TRUNCATE)
6055 Op0 = Op0.getOperand(0);
6056 if (Op1.getOpcode() == ISD::TRUNCATE)
6057 Op1 = Op1.getOperand(0);
6060 if (Op1.getOpcode() == ISD::SHL) {
6061 if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6062 if (And10C->getZExtValue() == 1) {
6064 RHS = Op1.getOperand(1);
6066 } else if (Op0.getOpcode() == ISD::SHL) {
6067 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6068 if (And00C->getZExtValue() == 1) {
6070 RHS = Op0.getOperand(1);
6072 } else if (Op1.getOpcode() == ISD::Constant) {
6073 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6074 SDValue AndLHS = Op0;
6075 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6076 LHS = AndLHS.getOperand(0);
6077 RHS = AndLHS.getOperand(1);
6081 if (LHS.getNode()) {
6082 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6083 // instruction. Since the shift amount is in-range-or-undefined, we know
6084 // that doing a bittest on the i32 value is ok. We extend to i32 because
6085 // the encoding for the i16 version is larger than the i32 version.
6086 // Also promote i16 to i32 for performance / code size reason.
6087 if (LHS.getValueType() == MVT::i8 ||
6088 LHS.getValueType() == MVT::i16)
6089 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6091 // If the operand types disagree, extend the shift amount to match. Since
6092 // BT ignores high bits (like shifts) we can use anyextend.
6093 if (LHS.getValueType() != RHS.getValueType())
6094 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6096 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6097 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6098 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6099 DAG.getConstant(Cond, MVT::i8), BT);
6105 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6106 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6107 SDValue Op0 = Op.getOperand(0);
6108 SDValue Op1 = Op.getOperand(1);
6109 DebugLoc dl = Op.getDebugLoc();
6110 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6112 // Optimize to BT if possible.
6113 // Lower (X & (1 << N)) == 0 to BT(X, N).
6114 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6115 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6116 if (Op0.getOpcode() == ISD::AND &&
6118 Op1.getOpcode() == ISD::Constant &&
6119 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6120 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6121 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6122 if (NewSetCC.getNode())
6126 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6127 if (Op0.getOpcode() == X86ISD::SETCC &&
6128 Op1.getOpcode() == ISD::Constant &&
6129 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6130 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6131 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6132 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6133 bool Invert = (CC == ISD::SETNE) ^
6134 cast<ConstantSDNode>(Op1)->isNullValue();
6136 CCode = X86::GetOppositeBranchCondition(CCode);
6137 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6138 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6141 bool isFP = Op1.getValueType().isFloatingPoint();
6142 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6143 if (X86CC == X86::COND_INVALID)
6146 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6148 // Use sbb x, x to materialize carry bit into a GPR.
6149 if (X86CC == X86::COND_B)
6150 return DAG.getNode(ISD::AND, dl, MVT::i8,
6151 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6152 DAG.getConstant(X86CC, MVT::i8), Cond),
6153 DAG.getConstant(1, MVT::i8));
6155 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6156 DAG.getConstant(X86CC, MVT::i8), Cond);
6159 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6161 SDValue Op0 = Op.getOperand(0);
6162 SDValue Op1 = Op.getOperand(1);
6163 SDValue CC = Op.getOperand(2);
6164 EVT VT = Op.getValueType();
6165 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6166 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6167 DebugLoc dl = Op.getDebugLoc();
6171 EVT VT0 = Op0.getValueType();
6172 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6173 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6176 switch (SetCCOpcode) {
6179 case ISD::SETEQ: SSECC = 0; break;
6181 case ISD::SETGT: Swap = true; // Fallthrough
6183 case ISD::SETOLT: SSECC = 1; break;
6185 case ISD::SETGE: Swap = true; // Fallthrough
6187 case ISD::SETOLE: SSECC = 2; break;
6188 case ISD::SETUO: SSECC = 3; break;
6190 case ISD::SETNE: SSECC = 4; break;
6191 case ISD::SETULE: Swap = true;
6192 case ISD::SETUGE: SSECC = 5; break;
6193 case ISD::SETULT: Swap = true;
6194 case ISD::SETUGT: SSECC = 6; break;
6195 case ISD::SETO: SSECC = 7; break;
6198 std::swap(Op0, Op1);
6200 // In the two special cases we can't handle, emit two comparisons.
6202 if (SetCCOpcode == ISD::SETUEQ) {
6204 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6205 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6206 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6208 else if (SetCCOpcode == ISD::SETONE) {
6210 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6211 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6212 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6214 llvm_unreachable("Illegal FP comparison");
6216 // Handle all other FP comparisons here.
6217 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6220 // We are handling one of the integer comparisons here. Since SSE only has
6221 // GT and EQ comparisons for integer, swapping operands and multiple
6222 // operations may be required for some comparisons.
6223 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6224 bool Swap = false, Invert = false, FlipSigns = false;
6226 switch (VT.getSimpleVT().SimpleTy) {
6229 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6231 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6233 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6234 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6237 switch (SetCCOpcode) {
6239 case ISD::SETNE: Invert = true;
6240 case ISD::SETEQ: Opc = EQOpc; break;
6241 case ISD::SETLT: Swap = true;
6242 case ISD::SETGT: Opc = GTOpc; break;
6243 case ISD::SETGE: Swap = true;
6244 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6245 case ISD::SETULT: Swap = true;
6246 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6247 case ISD::SETUGE: Swap = true;
6248 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6251 std::swap(Op0, Op1);
6253 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6254 // bits of the inputs before performing those operations.
6256 EVT EltVT = VT.getVectorElementType();
6257 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6259 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6260 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6262 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6263 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6266 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6268 // If the logical-not of the result is required, perform that now.
6270 Result = DAG.getNOT(dl, Result, VT);
6275 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6276 static bool isX86LogicalCmp(SDValue Op) {
6277 unsigned Opc = Op.getNode()->getOpcode();
6278 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6280 if (Op.getResNo() == 1 &&
6281 (Opc == X86ISD::ADD ||
6282 Opc == X86ISD::SUB ||
6283 Opc == X86ISD::SMUL ||
6284 Opc == X86ISD::UMUL ||
6285 Opc == X86ISD::INC ||
6286 Opc == X86ISD::DEC ||
6287 Opc == X86ISD::OR ||
6288 Opc == X86ISD::XOR ||
6289 Opc == X86ISD::AND))
6295 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6296 bool addTest = true;
6297 SDValue Cond = Op.getOperand(0);
6298 DebugLoc dl = Op.getDebugLoc();
6301 if (Cond.getOpcode() == ISD::SETCC) {
6302 SDValue NewCond = LowerSETCC(Cond, DAG);
6303 if (NewCond.getNode())
6307 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6308 SDValue Op1 = Op.getOperand(1);
6309 SDValue Op2 = Op.getOperand(2);
6310 if (Cond.getOpcode() == X86ISD::SETCC &&
6311 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6312 SDValue Cmp = Cond.getOperand(1);
6313 if (Cmp.getOpcode() == X86ISD::CMP) {
6314 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6315 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6316 ConstantSDNode *RHSC =
6317 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6318 if (N1C && N1C->isAllOnesValue() &&
6319 N2C && N2C->isNullValue() &&
6320 RHSC && RHSC->isNullValue()) {
6321 SDValue CmpOp0 = Cmp.getOperand(0);
6322 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6323 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6324 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6325 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6330 // Look pass (and (setcc_carry (cmp ...)), 1).
6331 if (Cond.getOpcode() == ISD::AND &&
6332 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6333 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6334 if (C && C->getAPIntValue() == 1)
6335 Cond = Cond.getOperand(0);
6338 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6339 // setting operand in place of the X86ISD::SETCC.
6340 if (Cond.getOpcode() == X86ISD::SETCC ||
6341 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6342 CC = Cond.getOperand(0);
6344 SDValue Cmp = Cond.getOperand(1);
6345 unsigned Opc = Cmp.getOpcode();
6346 EVT VT = Op.getValueType();
6348 bool IllegalFPCMov = false;
6349 if (VT.isFloatingPoint() && !VT.isVector() &&
6350 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6351 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6353 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6354 Opc == X86ISD::BT) { // FIXME
6361 // Look pass the truncate.
6362 if (Cond.getOpcode() == ISD::TRUNCATE)
6363 Cond = Cond.getOperand(0);
6365 // We know the result of AND is compared against zero. Try to match
6367 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6368 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6369 if (NewSetCC.getNode()) {
6370 CC = NewSetCC.getOperand(0);
6371 Cond = NewSetCC.getOperand(1);
6378 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6379 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6382 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6383 // condition is true.
6384 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6385 SDValue Ops[] = { Op2, Op1, CC, Cond };
6386 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6389 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6390 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6391 // from the AND / OR.
6392 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6393 Opc = Op.getOpcode();
6394 if (Opc != ISD::OR && Opc != ISD::AND)
6396 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6397 Op.getOperand(0).hasOneUse() &&
6398 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6399 Op.getOperand(1).hasOneUse());
6402 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6403 // 1 and that the SETCC node has a single use.
6404 static bool isXor1OfSetCC(SDValue Op) {
6405 if (Op.getOpcode() != ISD::XOR)
6407 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6408 if (N1C && N1C->getAPIntValue() == 1) {
6409 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6410 Op.getOperand(0).hasOneUse();
6415 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6416 bool addTest = true;
6417 SDValue Chain = Op.getOperand(0);
6418 SDValue Cond = Op.getOperand(1);
6419 SDValue Dest = Op.getOperand(2);
6420 DebugLoc dl = Op.getDebugLoc();
6423 if (Cond.getOpcode() == ISD::SETCC) {
6424 SDValue NewCond = LowerSETCC(Cond, DAG);
6425 if (NewCond.getNode())
6429 // FIXME: LowerXALUO doesn't handle these!!
6430 else if (Cond.getOpcode() == X86ISD::ADD ||
6431 Cond.getOpcode() == X86ISD::SUB ||
6432 Cond.getOpcode() == X86ISD::SMUL ||
6433 Cond.getOpcode() == X86ISD::UMUL)
6434 Cond = LowerXALUO(Cond, DAG);
6437 // Look pass (and (setcc_carry (cmp ...)), 1).
6438 if (Cond.getOpcode() == ISD::AND &&
6439 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6440 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6441 if (C && C->getAPIntValue() == 1)
6442 Cond = Cond.getOperand(0);
6445 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6446 // setting operand in place of the X86ISD::SETCC.
6447 if (Cond.getOpcode() == X86ISD::SETCC ||
6448 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6449 CC = Cond.getOperand(0);
6451 SDValue Cmp = Cond.getOperand(1);
6452 unsigned Opc = Cmp.getOpcode();
6453 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6454 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6458 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6462 // These can only come from an arithmetic instruction with overflow,
6463 // e.g. SADDO, UADDO.
6464 Cond = Cond.getNode()->getOperand(1);
6471 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6472 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6473 if (CondOpc == ISD::OR) {
6474 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6475 // two branches instead of an explicit OR instruction with a
6477 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6478 isX86LogicalCmp(Cmp)) {
6479 CC = Cond.getOperand(0).getOperand(0);
6480 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6481 Chain, Dest, CC, Cmp);
6482 CC = Cond.getOperand(1).getOperand(0);
6486 } else { // ISD::AND
6487 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6488 // two branches instead of an explicit AND instruction with a
6489 // separate test. However, we only do this if this block doesn't
6490 // have a fall-through edge, because this requires an explicit
6491 // jmp when the condition is false.
6492 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6493 isX86LogicalCmp(Cmp) &&
6494 Op.getNode()->hasOneUse()) {
6495 X86::CondCode CCode =
6496 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6497 CCode = X86::GetOppositeBranchCondition(CCode);
6498 CC = DAG.getConstant(CCode, MVT::i8);
6499 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6500 // Look for an unconditional branch following this conditional branch.
6501 // We need this because we need to reverse the successors in order
6502 // to implement FCMP_OEQ.
6503 if (User.getOpcode() == ISD::BR) {
6504 SDValue FalseBB = User.getOperand(1);
6506 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6507 assert(NewBR == User);
6510 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6511 Chain, Dest, CC, Cmp);
6512 X86::CondCode CCode =
6513 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6514 CCode = X86::GetOppositeBranchCondition(CCode);
6515 CC = DAG.getConstant(CCode, MVT::i8);
6521 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6522 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6523 // It should be transformed during dag combiner except when the condition
6524 // is set by a arithmetics with overflow node.
6525 X86::CondCode CCode =
6526 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6527 CCode = X86::GetOppositeBranchCondition(CCode);
6528 CC = DAG.getConstant(CCode, MVT::i8);
6529 Cond = Cond.getOperand(0).getOperand(1);
6535 // Look pass the truncate.
6536 if (Cond.getOpcode() == ISD::TRUNCATE)
6537 Cond = Cond.getOperand(0);
6539 // We know the result of AND is compared against zero. Try to match
6541 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6542 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6543 if (NewSetCC.getNode()) {
6544 CC = NewSetCC.getOperand(0);
6545 Cond = NewSetCC.getOperand(1);
6552 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6553 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6555 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6556 Chain, Dest, CC, Cond);
6560 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6561 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6562 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6563 // that the guard pages used by the OS virtual memory manager are allocated in
6564 // correct sequence.
6566 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6567 SelectionDAG &DAG) const {
6568 assert(Subtarget->isTargetCygMing() &&
6569 "This should be used only on Cygwin/Mingw targets");
6570 DebugLoc dl = Op.getDebugLoc();
6573 SDValue Chain = Op.getOperand(0);
6574 SDValue Size = Op.getOperand(1);
6575 // FIXME: Ensure alignment here
6579 EVT IntPtr = getPointerTy();
6580 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6582 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6583 Flag = Chain.getValue(1);
6585 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6587 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6588 Flag = Chain.getValue(1);
6590 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6592 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6593 return DAG.getMergeValues(Ops1, 2, dl);
6596 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6597 MachineFunction &MF = DAG.getMachineFunction();
6598 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6600 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6601 DebugLoc dl = Op.getDebugLoc();
6603 if (!Subtarget->is64Bit()) {
6604 // vastart just stores the address of the VarArgsFrameIndex slot into the
6605 // memory location argument.
6606 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6608 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6613 // gp_offset (0 - 6 * 8)
6614 // fp_offset (48 - 48 + 8 * 16)
6615 // overflow_arg_area (point to parameters coming in memory).
6617 SmallVector<SDValue, 8> MemOps;
6618 SDValue FIN = Op.getOperand(1);
6620 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6621 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6623 FIN, SV, 0, false, false, 0);
6624 MemOps.push_back(Store);
6627 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6628 FIN, DAG.getIntPtrConstant(4));
6629 Store = DAG.getStore(Op.getOperand(0), dl,
6630 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6632 FIN, SV, 0, false, false, 0);
6633 MemOps.push_back(Store);
6635 // Store ptr to overflow_arg_area
6636 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6637 FIN, DAG.getIntPtrConstant(4));
6638 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6640 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6642 MemOps.push_back(Store);
6644 // Store ptr to reg_save_area.
6645 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6646 FIN, DAG.getIntPtrConstant(8));
6647 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6649 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6651 MemOps.push_back(Store);
6652 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6653 &MemOps[0], MemOps.size());
6656 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6657 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6658 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6659 SDValue Chain = Op.getOperand(0);
6660 SDValue SrcPtr = Op.getOperand(1);
6661 SDValue SrcSV = Op.getOperand(2);
6663 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6667 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6668 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6669 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6670 SDValue Chain = Op.getOperand(0);
6671 SDValue DstPtr = Op.getOperand(1);
6672 SDValue SrcPtr = Op.getOperand(2);
6673 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6674 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6675 DebugLoc dl = Op.getDebugLoc();
6677 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6678 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6679 false, DstSV, 0, SrcSV, 0);
6683 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6684 DebugLoc dl = Op.getDebugLoc();
6685 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6687 default: return SDValue(); // Don't custom lower most intrinsics.
6688 // Comparison intrinsics.
6689 case Intrinsic::x86_sse_comieq_ss:
6690 case Intrinsic::x86_sse_comilt_ss:
6691 case Intrinsic::x86_sse_comile_ss:
6692 case Intrinsic::x86_sse_comigt_ss:
6693 case Intrinsic::x86_sse_comige_ss:
6694 case Intrinsic::x86_sse_comineq_ss:
6695 case Intrinsic::x86_sse_ucomieq_ss:
6696 case Intrinsic::x86_sse_ucomilt_ss:
6697 case Intrinsic::x86_sse_ucomile_ss:
6698 case Intrinsic::x86_sse_ucomigt_ss:
6699 case Intrinsic::x86_sse_ucomige_ss:
6700 case Intrinsic::x86_sse_ucomineq_ss:
6701 case Intrinsic::x86_sse2_comieq_sd:
6702 case Intrinsic::x86_sse2_comilt_sd:
6703 case Intrinsic::x86_sse2_comile_sd:
6704 case Intrinsic::x86_sse2_comigt_sd:
6705 case Intrinsic::x86_sse2_comige_sd:
6706 case Intrinsic::x86_sse2_comineq_sd:
6707 case Intrinsic::x86_sse2_ucomieq_sd:
6708 case Intrinsic::x86_sse2_ucomilt_sd:
6709 case Intrinsic::x86_sse2_ucomile_sd:
6710 case Intrinsic::x86_sse2_ucomigt_sd:
6711 case Intrinsic::x86_sse2_ucomige_sd:
6712 case Intrinsic::x86_sse2_ucomineq_sd: {
6714 ISD::CondCode CC = ISD::SETCC_INVALID;
6717 case Intrinsic::x86_sse_comieq_ss:
6718 case Intrinsic::x86_sse2_comieq_sd:
6722 case Intrinsic::x86_sse_comilt_ss:
6723 case Intrinsic::x86_sse2_comilt_sd:
6727 case Intrinsic::x86_sse_comile_ss:
6728 case Intrinsic::x86_sse2_comile_sd:
6732 case Intrinsic::x86_sse_comigt_ss:
6733 case Intrinsic::x86_sse2_comigt_sd:
6737 case Intrinsic::x86_sse_comige_ss:
6738 case Intrinsic::x86_sse2_comige_sd:
6742 case Intrinsic::x86_sse_comineq_ss:
6743 case Intrinsic::x86_sse2_comineq_sd:
6747 case Intrinsic::x86_sse_ucomieq_ss:
6748 case Intrinsic::x86_sse2_ucomieq_sd:
6749 Opc = X86ISD::UCOMI;
6752 case Intrinsic::x86_sse_ucomilt_ss:
6753 case Intrinsic::x86_sse2_ucomilt_sd:
6754 Opc = X86ISD::UCOMI;
6757 case Intrinsic::x86_sse_ucomile_ss:
6758 case Intrinsic::x86_sse2_ucomile_sd:
6759 Opc = X86ISD::UCOMI;
6762 case Intrinsic::x86_sse_ucomigt_ss:
6763 case Intrinsic::x86_sse2_ucomigt_sd:
6764 Opc = X86ISD::UCOMI;
6767 case Intrinsic::x86_sse_ucomige_ss:
6768 case Intrinsic::x86_sse2_ucomige_sd:
6769 Opc = X86ISD::UCOMI;
6772 case Intrinsic::x86_sse_ucomineq_ss:
6773 case Intrinsic::x86_sse2_ucomineq_sd:
6774 Opc = X86ISD::UCOMI;
6779 SDValue LHS = Op.getOperand(1);
6780 SDValue RHS = Op.getOperand(2);
6781 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6782 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6783 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6784 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6785 DAG.getConstant(X86CC, MVT::i8), Cond);
6786 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6788 // ptest intrinsics. The intrinsic these come from are designed to return
6789 // an integer value, not just an instruction so lower it to the ptest
6790 // pattern and a setcc for the result.
6791 case Intrinsic::x86_sse41_ptestz:
6792 case Intrinsic::x86_sse41_ptestc:
6793 case Intrinsic::x86_sse41_ptestnzc:{
6796 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6797 case Intrinsic::x86_sse41_ptestz:
6799 X86CC = X86::COND_E;
6801 case Intrinsic::x86_sse41_ptestc:
6803 X86CC = X86::COND_B;
6805 case Intrinsic::x86_sse41_ptestnzc:
6807 X86CC = X86::COND_A;
6811 SDValue LHS = Op.getOperand(1);
6812 SDValue RHS = Op.getOperand(2);
6813 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6814 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6815 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6816 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6819 // Fix vector shift instructions where the last operand is a non-immediate
6821 case Intrinsic::x86_sse2_pslli_w:
6822 case Intrinsic::x86_sse2_pslli_d:
6823 case Intrinsic::x86_sse2_pslli_q:
6824 case Intrinsic::x86_sse2_psrli_w:
6825 case Intrinsic::x86_sse2_psrli_d:
6826 case Intrinsic::x86_sse2_psrli_q:
6827 case Intrinsic::x86_sse2_psrai_w:
6828 case Intrinsic::x86_sse2_psrai_d:
6829 case Intrinsic::x86_mmx_pslli_w:
6830 case Intrinsic::x86_mmx_pslli_d:
6831 case Intrinsic::x86_mmx_pslli_q:
6832 case Intrinsic::x86_mmx_psrli_w:
6833 case Intrinsic::x86_mmx_psrli_d:
6834 case Intrinsic::x86_mmx_psrli_q:
6835 case Intrinsic::x86_mmx_psrai_w:
6836 case Intrinsic::x86_mmx_psrai_d: {
6837 SDValue ShAmt = Op.getOperand(2);
6838 if (isa<ConstantSDNode>(ShAmt))
6841 unsigned NewIntNo = 0;
6842 EVT ShAmtVT = MVT::v4i32;
6844 case Intrinsic::x86_sse2_pslli_w:
6845 NewIntNo = Intrinsic::x86_sse2_psll_w;
6847 case Intrinsic::x86_sse2_pslli_d:
6848 NewIntNo = Intrinsic::x86_sse2_psll_d;
6850 case Intrinsic::x86_sse2_pslli_q:
6851 NewIntNo = Intrinsic::x86_sse2_psll_q;
6853 case Intrinsic::x86_sse2_psrli_w:
6854 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6856 case Intrinsic::x86_sse2_psrli_d:
6857 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6859 case Intrinsic::x86_sse2_psrli_q:
6860 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6862 case Intrinsic::x86_sse2_psrai_w:
6863 NewIntNo = Intrinsic::x86_sse2_psra_w;
6865 case Intrinsic::x86_sse2_psrai_d:
6866 NewIntNo = Intrinsic::x86_sse2_psra_d;
6869 ShAmtVT = MVT::v2i32;
6871 case Intrinsic::x86_mmx_pslli_w:
6872 NewIntNo = Intrinsic::x86_mmx_psll_w;
6874 case Intrinsic::x86_mmx_pslli_d:
6875 NewIntNo = Intrinsic::x86_mmx_psll_d;
6877 case Intrinsic::x86_mmx_pslli_q:
6878 NewIntNo = Intrinsic::x86_mmx_psll_q;
6880 case Intrinsic::x86_mmx_psrli_w:
6881 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6883 case Intrinsic::x86_mmx_psrli_d:
6884 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6886 case Intrinsic::x86_mmx_psrli_q:
6887 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6889 case Intrinsic::x86_mmx_psrai_w:
6890 NewIntNo = Intrinsic::x86_mmx_psra_w;
6892 case Intrinsic::x86_mmx_psrai_d:
6893 NewIntNo = Intrinsic::x86_mmx_psra_d;
6895 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6901 // The vector shift intrinsics with scalars uses 32b shift amounts but
6902 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6906 ShOps[1] = DAG.getConstant(0, MVT::i32);
6907 if (ShAmtVT == MVT::v4i32) {
6908 ShOps[2] = DAG.getUNDEF(MVT::i32);
6909 ShOps[3] = DAG.getUNDEF(MVT::i32);
6910 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6912 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6915 EVT VT = Op.getValueType();
6916 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6917 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6918 DAG.getConstant(NewIntNo, MVT::i32),
6919 Op.getOperand(1), ShAmt);
6924 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
6925 SelectionDAG &DAG) const {
6926 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6927 DebugLoc dl = Op.getDebugLoc();
6930 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6932 DAG.getConstant(TD->getPointerSize(),
6933 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6934 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6935 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6937 NULL, 0, false, false, 0);
6940 // Just load the return address.
6941 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6942 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6943 RetAddrFI, NULL, 0, false, false, 0);
6946 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6947 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6948 MFI->setFrameAddressIsTaken(true);
6949 EVT VT = Op.getValueType();
6950 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6951 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6952 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6953 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6955 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
6960 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6961 SelectionDAG &DAG) const {
6962 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6965 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
6966 MachineFunction &MF = DAG.getMachineFunction();
6967 SDValue Chain = Op.getOperand(0);
6968 SDValue Offset = Op.getOperand(1);
6969 SDValue Handler = Op.getOperand(2);
6970 DebugLoc dl = Op.getDebugLoc();
6972 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6974 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6976 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6977 DAG.getIntPtrConstant(-TD->getPointerSize()));
6978 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6979 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
6980 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6981 MF.getRegInfo().addLiveOut(StoreAddrReg);
6983 return DAG.getNode(X86ISD::EH_RETURN, dl,
6985 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6988 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6989 SelectionDAG &DAG) const {
6990 SDValue Root = Op.getOperand(0);
6991 SDValue Trmp = Op.getOperand(1); // trampoline
6992 SDValue FPtr = Op.getOperand(2); // nested function
6993 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6994 DebugLoc dl = Op.getDebugLoc();
6996 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6998 if (Subtarget->is64Bit()) {
6999 SDValue OutChains[6];
7001 // Large code-model.
7002 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7003 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7005 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7006 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7008 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7010 // Load the pointer to the nested function into R11.
7011 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7012 SDValue Addr = Trmp;
7013 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7014 Addr, TrmpAddr, 0, false, false, 0);
7016 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7017 DAG.getConstant(2, MVT::i64));
7018 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7021 // Load the 'nest' parameter value into R10.
7022 // R10 is specified in X86CallingConv.td
7023 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7024 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7025 DAG.getConstant(10, MVT::i64));
7026 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7027 Addr, TrmpAddr, 10, false, false, 0);
7029 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7030 DAG.getConstant(12, MVT::i64));
7031 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7034 // Jump to the nested function.
7035 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7036 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7037 DAG.getConstant(20, MVT::i64));
7038 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7039 Addr, TrmpAddr, 20, false, false, 0);
7041 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7042 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7043 DAG.getConstant(22, MVT::i64));
7044 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7045 TrmpAddr, 22, false, false, 0);
7048 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7049 return DAG.getMergeValues(Ops, 2, dl);
7051 const Function *Func =
7052 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7053 CallingConv::ID CC = Func->getCallingConv();
7058 llvm_unreachable("Unsupported calling convention");
7059 case CallingConv::C:
7060 case CallingConv::X86_StdCall: {
7061 // Pass 'nest' parameter in ECX.
7062 // Must be kept in sync with X86CallingConv.td
7065 // Check that ECX wasn't needed by an 'inreg' parameter.
7066 const FunctionType *FTy = Func->getFunctionType();
7067 const AttrListPtr &Attrs = Func->getAttributes();
7069 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7070 unsigned InRegCount = 0;
7073 for (FunctionType::param_iterator I = FTy->param_begin(),
7074 E = FTy->param_end(); I != E; ++I, ++Idx)
7075 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7076 // FIXME: should only count parameters that are lowered to integers.
7077 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7079 if (InRegCount > 2) {
7080 report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7085 case CallingConv::X86_FastCall:
7086 case CallingConv::Fast:
7087 // Pass 'nest' parameter in EAX.
7088 // Must be kept in sync with X86CallingConv.td
7093 SDValue OutChains[4];
7096 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7097 DAG.getConstant(10, MVT::i32));
7098 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7100 // This is storing the opcode for MOV32ri.
7101 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7102 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7103 OutChains[0] = DAG.getStore(Root, dl,
7104 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7105 Trmp, TrmpAddr, 0, false, false, 0);
7107 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7108 DAG.getConstant(1, MVT::i32));
7109 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7112 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7113 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7114 DAG.getConstant(5, MVT::i32));
7115 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7116 TrmpAddr, 5, false, false, 1);
7118 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7119 DAG.getConstant(6, MVT::i32));
7120 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7124 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7125 return DAG.getMergeValues(Ops, 2, dl);
7129 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7130 SelectionDAG &DAG) const {
7132 The rounding mode is in bits 11:10 of FPSR, and has the following
7139 FLT_ROUNDS, on the other hand, expects the following:
7146 To perform the conversion, we do:
7147 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7150 MachineFunction &MF = DAG.getMachineFunction();
7151 const TargetMachine &TM = MF.getTarget();
7152 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7153 unsigned StackAlignment = TFI.getStackAlignment();
7154 EVT VT = Op.getValueType();
7155 DebugLoc dl = Op.getDebugLoc();
7157 // Save FP Control Word to stack slot
7158 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7159 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7161 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7162 DAG.getEntryNode(), StackSlot);
7164 // Load FP Control Word from stack slot
7165 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7168 // Transform as necessary
7170 DAG.getNode(ISD::SRL, dl, MVT::i16,
7171 DAG.getNode(ISD::AND, dl, MVT::i16,
7172 CWD, DAG.getConstant(0x800, MVT::i16)),
7173 DAG.getConstant(11, MVT::i8));
7175 DAG.getNode(ISD::SRL, dl, MVT::i16,
7176 DAG.getNode(ISD::AND, dl, MVT::i16,
7177 CWD, DAG.getConstant(0x400, MVT::i16)),
7178 DAG.getConstant(9, MVT::i8));
7181 DAG.getNode(ISD::AND, dl, MVT::i16,
7182 DAG.getNode(ISD::ADD, dl, MVT::i16,
7183 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7184 DAG.getConstant(1, MVT::i16)),
7185 DAG.getConstant(3, MVT::i16));
7188 return DAG.getNode((VT.getSizeInBits() < 16 ?
7189 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7192 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7193 EVT VT = Op.getValueType();
7195 unsigned NumBits = VT.getSizeInBits();
7196 DebugLoc dl = Op.getDebugLoc();
7198 Op = Op.getOperand(0);
7199 if (VT == MVT::i8) {
7200 // Zero extend to i32 since there is not an i8 bsr.
7202 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7205 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7206 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7207 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7209 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7212 DAG.getConstant(NumBits+NumBits-1, OpVT),
7213 DAG.getConstant(X86::COND_E, MVT::i8),
7216 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7218 // Finally xor with NumBits-1.
7219 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7222 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7226 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7227 EVT VT = Op.getValueType();
7229 unsigned NumBits = VT.getSizeInBits();
7230 DebugLoc dl = Op.getDebugLoc();
7232 Op = Op.getOperand(0);
7233 if (VT == MVT::i8) {
7235 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7238 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7239 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7240 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7242 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7245 DAG.getConstant(NumBits, OpVT),
7246 DAG.getConstant(X86::COND_E, MVT::i8),
7249 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7252 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7256 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7257 EVT VT = Op.getValueType();
7258 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7259 DebugLoc dl = Op.getDebugLoc();
7261 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7262 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7263 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7264 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7265 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7267 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7268 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7269 // return AloBlo + AloBhi + AhiBlo;
7271 SDValue A = Op.getOperand(0);
7272 SDValue B = Op.getOperand(1);
7274 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7275 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7276 A, DAG.getConstant(32, MVT::i32));
7277 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7278 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7279 B, DAG.getConstant(32, MVT::i32));
7280 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7281 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7283 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7284 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7286 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7287 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7289 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7290 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7291 AloBhi, DAG.getConstant(32, MVT::i32));
7292 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7293 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7294 AhiBlo, DAG.getConstant(32, MVT::i32));
7295 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7296 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7301 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7302 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7303 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7304 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7305 // has only one use.
7306 SDNode *N = Op.getNode();
7307 SDValue LHS = N->getOperand(0);
7308 SDValue RHS = N->getOperand(1);
7309 unsigned BaseOp = 0;
7311 DebugLoc dl = Op.getDebugLoc();
7313 switch (Op.getOpcode()) {
7314 default: llvm_unreachable("Unknown ovf instruction!");
7316 // A subtract of one will be selected as a INC. Note that INC doesn't
7317 // set CF, so we can't do this for UADDO.
7318 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7319 if (C->getAPIntValue() == 1) {
7320 BaseOp = X86ISD::INC;
7324 BaseOp = X86ISD::ADD;
7328 BaseOp = X86ISD::ADD;
7332 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7333 // set CF, so we can't do this for USUBO.
7334 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7335 if (C->getAPIntValue() == 1) {
7336 BaseOp = X86ISD::DEC;
7340 BaseOp = X86ISD::SUB;
7344 BaseOp = X86ISD::SUB;
7348 BaseOp = X86ISD::SMUL;
7352 BaseOp = X86ISD::UMUL;
7357 // Also sets EFLAGS.
7358 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7359 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7362 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7363 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7365 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7369 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7370 EVT T = Op.getValueType();
7371 DebugLoc dl = Op.getDebugLoc();
7374 switch(T.getSimpleVT().SimpleTy) {
7376 assert(false && "Invalid value type!");
7377 case MVT::i8: Reg = X86::AL; size = 1; break;
7378 case MVT::i16: Reg = X86::AX; size = 2; break;
7379 case MVT::i32: Reg = X86::EAX; size = 4; break;
7381 assert(Subtarget->is64Bit() && "Node not type legal!");
7382 Reg = X86::RAX; size = 8;
7385 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7386 Op.getOperand(2), SDValue());
7387 SDValue Ops[] = { cpIn.getValue(0),
7390 DAG.getTargetConstant(size, MVT::i8),
7392 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7393 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7395 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7399 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7400 SelectionDAG &DAG) const {
7401 assert(Subtarget->is64Bit() && "Result not type legalized?");
7402 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7403 SDValue TheChain = Op.getOperand(0);
7404 DebugLoc dl = Op.getDebugLoc();
7405 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7406 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7407 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7409 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7410 DAG.getConstant(32, MVT::i8));
7412 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7415 return DAG.getMergeValues(Ops, 2, dl);
7418 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7419 SDNode *Node = Op.getNode();
7420 DebugLoc dl = Node->getDebugLoc();
7421 EVT T = Node->getValueType(0);
7422 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7423 DAG.getConstant(0, T), Node->getOperand(2));
7424 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7425 cast<AtomicSDNode>(Node)->getMemoryVT(),
7426 Node->getOperand(0),
7427 Node->getOperand(1), negOp,
7428 cast<AtomicSDNode>(Node)->getSrcValue(),
7429 cast<AtomicSDNode>(Node)->getAlignment());
7432 /// LowerOperation - Provide custom lowering hooks for some operations.
7434 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7435 switch (Op.getOpcode()) {
7436 default: llvm_unreachable("Should not custom lower this!");
7437 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7438 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7439 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7440 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7441 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7442 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7443 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7444 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7445 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7446 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7447 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7448 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7449 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7450 case ISD::SHL_PARTS:
7451 case ISD::SRA_PARTS:
7452 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7453 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7454 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7455 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7456 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7457 case ISD::FABS: return LowerFABS(Op, DAG);
7458 case ISD::FNEG: return LowerFNEG(Op, DAG);
7459 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7460 case ISD::SETCC: return LowerSETCC(Op, DAG);
7461 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7462 case ISD::SELECT: return LowerSELECT(Op, DAG);
7463 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7464 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7465 case ISD::VASTART: return LowerVASTART(Op, DAG);
7466 case ISD::VAARG: return LowerVAARG(Op, DAG);
7467 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7468 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7469 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7470 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7471 case ISD::FRAME_TO_ARGS_OFFSET:
7472 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7473 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7474 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7475 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7476 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7477 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7478 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7479 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7485 case ISD::UMULO: return LowerXALUO(Op, DAG);
7486 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7490 void X86TargetLowering::
7491 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7492 SelectionDAG &DAG, unsigned NewOp) const {
7493 EVT T = Node->getValueType(0);
7494 DebugLoc dl = Node->getDebugLoc();
7495 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7497 SDValue Chain = Node->getOperand(0);
7498 SDValue In1 = Node->getOperand(1);
7499 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7500 Node->getOperand(2), DAG.getIntPtrConstant(0));
7501 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7502 Node->getOperand(2), DAG.getIntPtrConstant(1));
7503 SDValue Ops[] = { Chain, In1, In2L, In2H };
7504 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7506 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7507 cast<MemSDNode>(Node)->getMemOperand());
7508 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7509 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7510 Results.push_back(Result.getValue(2));
7513 /// ReplaceNodeResults - Replace a node with an illegal result type
7514 /// with a new node built out of custom code.
7515 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7516 SmallVectorImpl<SDValue>&Results,
7517 SelectionDAG &DAG) const {
7518 DebugLoc dl = N->getDebugLoc();
7519 switch (N->getOpcode()) {
7521 assert(false && "Do not know how to custom type legalize this operation!");
7523 case ISD::FP_TO_SINT: {
7524 std::pair<SDValue,SDValue> Vals =
7525 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7526 SDValue FIST = Vals.first, StackSlot = Vals.second;
7527 if (FIST.getNode() != 0) {
7528 EVT VT = N->getValueType(0);
7529 // Return a load from the stack slot.
7530 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7535 case ISD::READCYCLECOUNTER: {
7536 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7537 SDValue TheChain = N->getOperand(0);
7538 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7539 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7541 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7543 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7544 SDValue Ops[] = { eax, edx };
7545 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7546 Results.push_back(edx.getValue(1));
7549 case ISD::ATOMIC_CMP_SWAP: {
7550 EVT T = N->getValueType(0);
7551 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7552 SDValue cpInL, cpInH;
7553 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7554 DAG.getConstant(0, MVT::i32));
7555 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7556 DAG.getConstant(1, MVT::i32));
7557 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7558 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7560 SDValue swapInL, swapInH;
7561 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7562 DAG.getConstant(0, MVT::i32));
7563 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7564 DAG.getConstant(1, MVT::i32));
7565 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7567 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7568 swapInL.getValue(1));
7569 SDValue Ops[] = { swapInH.getValue(0),
7571 swapInH.getValue(1) };
7572 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7573 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7574 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7575 MVT::i32, Result.getValue(1));
7576 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7577 MVT::i32, cpOutL.getValue(2));
7578 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7579 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7580 Results.push_back(cpOutH.getValue(1));
7583 case ISD::ATOMIC_LOAD_ADD:
7584 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7586 case ISD::ATOMIC_LOAD_AND:
7587 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7589 case ISD::ATOMIC_LOAD_NAND:
7590 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7592 case ISD::ATOMIC_LOAD_OR:
7593 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7595 case ISD::ATOMIC_LOAD_SUB:
7596 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7598 case ISD::ATOMIC_LOAD_XOR:
7599 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7601 case ISD::ATOMIC_SWAP:
7602 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7607 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7609 default: return NULL;
7610 case X86ISD::BSF: return "X86ISD::BSF";
7611 case X86ISD::BSR: return "X86ISD::BSR";
7612 case X86ISD::SHLD: return "X86ISD::SHLD";
7613 case X86ISD::SHRD: return "X86ISD::SHRD";
7614 case X86ISD::FAND: return "X86ISD::FAND";
7615 case X86ISD::FOR: return "X86ISD::FOR";
7616 case X86ISD::FXOR: return "X86ISD::FXOR";
7617 case X86ISD::FSRL: return "X86ISD::FSRL";
7618 case X86ISD::FILD: return "X86ISD::FILD";
7619 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7620 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7621 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7622 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7623 case X86ISD::FLD: return "X86ISD::FLD";
7624 case X86ISD::FST: return "X86ISD::FST";
7625 case X86ISD::CALL: return "X86ISD::CALL";
7626 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7627 case X86ISD::BT: return "X86ISD::BT";
7628 case X86ISD::CMP: return "X86ISD::CMP";
7629 case X86ISD::COMI: return "X86ISD::COMI";
7630 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7631 case X86ISD::SETCC: return "X86ISD::SETCC";
7632 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7633 case X86ISD::CMOV: return "X86ISD::CMOV";
7634 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7635 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7636 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7637 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7638 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7639 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7640 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7641 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7642 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7643 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7644 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7645 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7646 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7647 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7648 case X86ISD::FMAX: return "X86ISD::FMAX";
7649 case X86ISD::FMIN: return "X86ISD::FMIN";
7650 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7651 case X86ISD::FRCP: return "X86ISD::FRCP";
7652 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7653 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7654 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7655 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7656 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7657 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7658 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7659 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7660 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7661 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7662 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7663 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7664 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7665 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7666 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7667 case X86ISD::VSHL: return "X86ISD::VSHL";
7668 case X86ISD::VSRL: return "X86ISD::VSRL";
7669 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7670 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7671 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7672 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7673 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7674 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7675 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7676 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7677 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7678 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7679 case X86ISD::ADD: return "X86ISD::ADD";
7680 case X86ISD::SUB: return "X86ISD::SUB";
7681 case X86ISD::SMUL: return "X86ISD::SMUL";
7682 case X86ISD::UMUL: return "X86ISD::UMUL";
7683 case X86ISD::INC: return "X86ISD::INC";
7684 case X86ISD::DEC: return "X86ISD::DEC";
7685 case X86ISD::OR: return "X86ISD::OR";
7686 case X86ISD::XOR: return "X86ISD::XOR";
7687 case X86ISD::AND: return "X86ISD::AND";
7688 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7689 case X86ISD::PTEST: return "X86ISD::PTEST";
7690 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7691 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
7695 // isLegalAddressingMode - Return true if the addressing mode represented
7696 // by AM is legal for this target, for a load/store of the specified type.
7697 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7698 const Type *Ty) const {
7699 // X86 supports extremely general addressing modes.
7700 CodeModel::Model M = getTargetMachine().getCodeModel();
7702 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7703 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7708 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7710 // If a reference to this global requires an extra load, we can't fold it.
7711 if (isGlobalStubReference(GVFlags))
7714 // If BaseGV requires a register for the PIC base, we cannot also have a
7715 // BaseReg specified.
7716 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7719 // If lower 4G is not available, then we must use rip-relative addressing.
7720 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7730 // These scales always work.
7735 // These scales are formed with basereg+scalereg. Only accept if there is
7740 default: // Other stuff never works.
7748 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7749 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7751 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7752 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7753 if (NumBits1 <= NumBits2)
7758 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7759 if (!VT1.isInteger() || !VT2.isInteger())
7761 unsigned NumBits1 = VT1.getSizeInBits();
7762 unsigned NumBits2 = VT2.getSizeInBits();
7763 if (NumBits1 <= NumBits2)
7768 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7769 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7770 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7773 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7774 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7775 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7778 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7779 // i16 instructions are longer (0x66 prefix) and potentially slower.
7780 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7783 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7784 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7785 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7786 /// are assumed to be legal.
7788 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7790 // Very little shuffling can be done for 64-bit vectors right now.
7791 if (VT.getSizeInBits() == 64)
7792 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7794 // FIXME: pshufb, blends, shifts.
7795 return (VT.getVectorNumElements() == 2 ||
7796 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7797 isMOVLMask(M, VT) ||
7798 isSHUFPMask(M, VT) ||
7799 isPSHUFDMask(M, VT) ||
7800 isPSHUFHWMask(M, VT) ||
7801 isPSHUFLWMask(M, VT) ||
7802 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7803 isUNPCKLMask(M, VT) ||
7804 isUNPCKHMask(M, VT) ||
7805 isUNPCKL_v_undef_Mask(M, VT) ||
7806 isUNPCKH_v_undef_Mask(M, VT));
7810 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7812 unsigned NumElts = VT.getVectorNumElements();
7813 // FIXME: This collection of masks seems suspect.
7816 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7817 return (isMOVLMask(Mask, VT) ||
7818 isCommutedMOVLMask(Mask, VT, true) ||
7819 isSHUFPMask(Mask, VT) ||
7820 isCommutedSHUFPMask(Mask, VT));
7825 //===----------------------------------------------------------------------===//
7826 // X86 Scheduler Hooks
7827 //===----------------------------------------------------------------------===//
7829 // private utility function
7831 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7832 MachineBasicBlock *MBB,
7840 TargetRegisterClass *RC,
7841 bool invSrc) const {
7842 // For the atomic bitwise operator, we generate
7845 // ld t1 = [bitinstr.addr]
7846 // op t2 = t1, [bitinstr.val]
7848 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7850 // fallthrough -->nextMBB
7851 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7852 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7853 MachineFunction::iterator MBBIter = MBB;
7856 /// First build the CFG
7857 MachineFunction *F = MBB->getParent();
7858 MachineBasicBlock *thisMBB = MBB;
7859 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7860 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7861 F->insert(MBBIter, newMBB);
7862 F->insert(MBBIter, nextMBB);
7864 // Move all successors to thisMBB to nextMBB
7865 nextMBB->transferSuccessors(thisMBB);
7867 // Update thisMBB to fall through to newMBB
7868 thisMBB->addSuccessor(newMBB);
7870 // newMBB jumps to itself and fall through to nextMBB
7871 newMBB->addSuccessor(nextMBB);
7872 newMBB->addSuccessor(newMBB);
7874 // Insert instructions into newMBB based on incoming instruction
7875 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7876 "unexpected number of operands");
7877 DebugLoc dl = bInstr->getDebugLoc();
7878 MachineOperand& destOper = bInstr->getOperand(0);
7879 MachineOperand* argOpers[2 + X86AddrNumOperands];
7880 int numArgs = bInstr->getNumOperands() - 1;
7881 for (int i=0; i < numArgs; ++i)
7882 argOpers[i] = &bInstr->getOperand(i+1);
7884 // x86 address has 4 operands: base, index, scale, and displacement
7885 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7886 int valArgIndx = lastAddrIndx + 1;
7888 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7889 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7890 for (int i=0; i <= lastAddrIndx; ++i)
7891 (*MIB).addOperand(*argOpers[i]);
7893 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7895 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7900 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7901 assert((argOpers[valArgIndx]->isReg() ||
7902 argOpers[valArgIndx]->isImm()) &&
7904 if (argOpers[valArgIndx]->isReg())
7905 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7907 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7909 (*MIB).addOperand(*argOpers[valArgIndx]);
7911 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7914 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7915 for (int i=0; i <= lastAddrIndx; ++i)
7916 (*MIB).addOperand(*argOpers[i]);
7918 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7919 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7920 bInstr->memoperands_end());
7922 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7926 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
7928 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7932 // private utility function: 64 bit atomics on 32 bit host.
7934 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7935 MachineBasicBlock *MBB,
7940 bool invSrc) const {
7941 // For the atomic bitwise operator, we generate
7942 // thisMBB (instructions are in pairs, except cmpxchg8b)
7943 // ld t1,t2 = [bitinstr.addr]
7945 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7946 // op t5, t6 <- out1, out2, [bitinstr.val]
7947 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7948 // mov ECX, EBX <- t5, t6
7949 // mov EAX, EDX <- t1, t2
7950 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7951 // mov t3, t4 <- EAX, EDX
7953 // result in out1, out2
7954 // fallthrough -->nextMBB
7956 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7957 const unsigned LoadOpc = X86::MOV32rm;
7958 const unsigned copyOpc = X86::MOV32rr;
7959 const unsigned NotOpc = X86::NOT32r;
7960 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7961 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7962 MachineFunction::iterator MBBIter = MBB;
7965 /// First build the CFG
7966 MachineFunction *F = MBB->getParent();
7967 MachineBasicBlock *thisMBB = MBB;
7968 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7969 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7970 F->insert(MBBIter, newMBB);
7971 F->insert(MBBIter, nextMBB);
7973 // Move all successors to thisMBB to nextMBB
7974 nextMBB->transferSuccessors(thisMBB);
7976 // Update thisMBB to fall through to newMBB
7977 thisMBB->addSuccessor(newMBB);
7979 // newMBB jumps to itself and fall through to nextMBB
7980 newMBB->addSuccessor(nextMBB);
7981 newMBB->addSuccessor(newMBB);
7983 DebugLoc dl = bInstr->getDebugLoc();
7984 // Insert instructions into newMBB based on incoming instruction
7985 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7986 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7987 "unexpected number of operands");
7988 MachineOperand& dest1Oper = bInstr->getOperand(0);
7989 MachineOperand& dest2Oper = bInstr->getOperand(1);
7990 MachineOperand* argOpers[2 + X86AddrNumOperands];
7991 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7992 argOpers[i] = &bInstr->getOperand(i+2);
7994 // x86 address has 5 operands: base, index, scale, displacement, and segment.
7995 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7997 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7998 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7999 for (int i=0; i <= lastAddrIndx; ++i)
8000 (*MIB).addOperand(*argOpers[i]);
8001 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8002 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8003 // add 4 to displacement.
8004 for (int i=0; i <= lastAddrIndx-2; ++i)
8005 (*MIB).addOperand(*argOpers[i]);
8006 MachineOperand newOp3 = *(argOpers[3]);
8008 newOp3.setImm(newOp3.getImm()+4);
8010 newOp3.setOffset(newOp3.getOffset()+4);
8011 (*MIB).addOperand(newOp3);
8012 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8014 // t3/4 are defined later, at the bottom of the loop
8015 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8016 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8017 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8018 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8019 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8020 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8022 // The subsequent operations should be using the destination registers of
8023 //the PHI instructions.
8025 t1 = F->getRegInfo().createVirtualRegister(RC);
8026 t2 = F->getRegInfo().createVirtualRegister(RC);
8027 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8028 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8030 t1 = dest1Oper.getReg();
8031 t2 = dest2Oper.getReg();
8034 int valArgIndx = lastAddrIndx + 1;
8035 assert((argOpers[valArgIndx]->isReg() ||
8036 argOpers[valArgIndx]->isImm()) &&
8038 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8039 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8040 if (argOpers[valArgIndx]->isReg())
8041 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8043 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8044 if (regOpcL != X86::MOV32rr)
8046 (*MIB).addOperand(*argOpers[valArgIndx]);
8047 assert(argOpers[valArgIndx + 1]->isReg() ==
8048 argOpers[valArgIndx]->isReg());
8049 assert(argOpers[valArgIndx + 1]->isImm() ==
8050 argOpers[valArgIndx]->isImm());
8051 if (argOpers[valArgIndx + 1]->isReg())
8052 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8054 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8055 if (regOpcH != X86::MOV32rr)
8057 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8059 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8061 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8064 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8066 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8069 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8070 for (int i=0; i <= lastAddrIndx; ++i)
8071 (*MIB).addOperand(*argOpers[i]);
8073 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8074 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8075 bInstr->memoperands_end());
8077 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8078 MIB.addReg(X86::EAX);
8079 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8080 MIB.addReg(X86::EDX);
8083 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8085 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8089 // private utility function
8091 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8092 MachineBasicBlock *MBB,
8093 unsigned cmovOpc) const {
8094 // For the atomic min/max operator, we generate
8097 // ld t1 = [min/max.addr]
8098 // mov t2 = [min/max.val]
8100 // cmov[cond] t2 = t1
8102 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8104 // fallthrough -->nextMBB
8106 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8107 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8108 MachineFunction::iterator MBBIter = MBB;
8111 /// First build the CFG
8112 MachineFunction *F = MBB->getParent();
8113 MachineBasicBlock *thisMBB = MBB;
8114 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8115 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8116 F->insert(MBBIter, newMBB);
8117 F->insert(MBBIter, nextMBB);
8119 // Move all successors of thisMBB to nextMBB
8120 nextMBB->transferSuccessors(thisMBB);
8122 // Update thisMBB to fall through to newMBB
8123 thisMBB->addSuccessor(newMBB);
8125 // newMBB jumps to newMBB and fall through to nextMBB
8126 newMBB->addSuccessor(nextMBB);
8127 newMBB->addSuccessor(newMBB);
8129 DebugLoc dl = mInstr->getDebugLoc();
8130 // Insert instructions into newMBB based on incoming instruction
8131 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8132 "unexpected number of operands");
8133 MachineOperand& destOper = mInstr->getOperand(0);
8134 MachineOperand* argOpers[2 + X86AddrNumOperands];
8135 int numArgs = mInstr->getNumOperands() - 1;
8136 for (int i=0; i < numArgs; ++i)
8137 argOpers[i] = &mInstr->getOperand(i+1);
8139 // x86 address has 4 operands: base, index, scale, and displacement
8140 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8141 int valArgIndx = lastAddrIndx + 1;
8143 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8144 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8145 for (int i=0; i <= lastAddrIndx; ++i)
8146 (*MIB).addOperand(*argOpers[i]);
8148 // We only support register and immediate values
8149 assert((argOpers[valArgIndx]->isReg() ||
8150 argOpers[valArgIndx]->isImm()) &&
8153 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8154 if (argOpers[valArgIndx]->isReg())
8155 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8157 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8158 (*MIB).addOperand(*argOpers[valArgIndx]);
8160 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8163 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8168 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8169 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8173 // Cmp and exchange if none has modified the memory location
8174 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8175 for (int i=0; i <= lastAddrIndx; ++i)
8176 (*MIB).addOperand(*argOpers[i]);
8178 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8179 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8180 mInstr->memoperands_end());
8182 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8183 MIB.addReg(X86::EAX);
8186 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8188 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8192 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8193 // all of this code can be replaced with that in the .td file.
8195 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8196 unsigned numArgs, bool memArg) const {
8198 MachineFunction *F = BB->getParent();
8199 DebugLoc dl = MI->getDebugLoc();
8200 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8204 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8206 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8208 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8210 for (unsigned i = 0; i < numArgs; ++i) {
8211 MachineOperand &Op = MI->getOperand(i+1);
8213 if (!(Op.isReg() && Op.isImplicit()))
8217 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8220 F->DeleteMachineInstr(MI);
8226 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8228 MachineBasicBlock *MBB) const {
8229 // Emit code to save XMM registers to the stack. The ABI says that the
8230 // number of registers to save is given in %al, so it's theoretically
8231 // possible to do an indirect jump trick to avoid saving all of them,
8232 // however this code takes a simpler approach and just executes all
8233 // of the stores if %al is non-zero. It's less code, and it's probably
8234 // easier on the hardware branch predictor, and stores aren't all that
8235 // expensive anyway.
8237 // Create the new basic blocks. One block contains all the XMM stores,
8238 // and one block is the final destination regardless of whether any
8239 // stores were performed.
8240 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8241 MachineFunction *F = MBB->getParent();
8242 MachineFunction::iterator MBBIter = MBB;
8244 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8245 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8246 F->insert(MBBIter, XMMSaveMBB);
8247 F->insert(MBBIter, EndMBB);
8250 // Move any original successors of MBB to the end block.
8251 EndMBB->transferSuccessors(MBB);
8252 // The original block will now fall through to the XMM save block.
8253 MBB->addSuccessor(XMMSaveMBB);
8254 // The XMMSaveMBB will fall through to the end block.
8255 XMMSaveMBB->addSuccessor(EndMBB);
8257 // Now add the instructions.
8258 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8259 DebugLoc DL = MI->getDebugLoc();
8261 unsigned CountReg = MI->getOperand(0).getReg();
8262 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8263 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8265 if (!Subtarget->isTargetWin64()) {
8266 // If %al is 0, branch around the XMM save block.
8267 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8268 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8269 MBB->addSuccessor(EndMBB);
8272 // In the XMM save block, save all the XMM argument registers.
8273 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8274 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8275 MachineMemOperand *MMO =
8276 F->getMachineMemOperand(
8277 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8278 MachineMemOperand::MOStore, Offset,
8279 /*Size=*/16, /*Align=*/16);
8280 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8281 .addFrameIndex(RegSaveFrameIndex)
8282 .addImm(/*Scale=*/1)
8283 .addReg(/*IndexReg=*/0)
8284 .addImm(/*Disp=*/Offset)
8285 .addReg(/*Segment=*/0)
8286 .addReg(MI->getOperand(i).getReg())
8287 .addMemOperand(MMO);
8290 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8296 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8297 MachineBasicBlock *BB) const {
8298 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8299 DebugLoc DL = MI->getDebugLoc();
8301 // To "insert" a SELECT_CC instruction, we actually have to insert the
8302 // diamond control-flow pattern. The incoming instruction knows the
8303 // destination vreg to set, the condition code register to branch on, the
8304 // true/false values to select between, and a branch opcode to use.
8305 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8306 MachineFunction::iterator It = BB;
8312 // cmpTY ccX, r1, r2
8314 // fallthrough --> copy0MBB
8315 MachineBasicBlock *thisMBB = BB;
8316 MachineFunction *F = BB->getParent();
8317 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8318 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8320 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8321 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8322 F->insert(It, copy0MBB);
8323 F->insert(It, sinkMBB);
8324 // Update machine-CFG edges by first adding all successors of the current
8325 // block to the new block which will contain the Phi node for the select.
8326 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8327 E = BB->succ_end(); I != E; ++I)
8328 sinkMBB->addSuccessor(*I);
8329 // Next, remove all successors of the current block, and add the true
8330 // and fallthrough blocks as its successors.
8331 while (!BB->succ_empty())
8332 BB->removeSuccessor(BB->succ_begin());
8333 // Add the true and fallthrough blocks as its successors.
8334 BB->addSuccessor(copy0MBB);
8335 BB->addSuccessor(sinkMBB);
8338 // %FalseValue = ...
8339 // # fallthrough to sinkMBB
8340 copy0MBB->addSuccessor(sinkMBB);
8343 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8345 BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8346 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8347 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8349 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8354 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8355 MachineBasicBlock *BB) const {
8356 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8357 DebugLoc DL = MI->getDebugLoc();
8358 MachineFunction *F = BB->getParent();
8360 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8361 // non-trivial part is impdef of ESP.
8362 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8365 BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8366 .addExternalSymbol("_alloca")
8367 .addReg(X86::EAX, RegState::Implicit)
8368 .addReg(X86::ESP, RegState::Implicit)
8369 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8370 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8372 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8377 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8378 MachineBasicBlock *BB) const {
8379 switch (MI->getOpcode()) {
8380 default: assert(false && "Unexpected instr type to insert");
8381 case X86::MINGW_ALLOCA:
8382 return EmitLoweredMingwAlloca(MI, BB);
8384 case X86::CMOV_V1I64:
8385 case X86::CMOV_FR32:
8386 case X86::CMOV_FR64:
8387 case X86::CMOV_V4F32:
8388 case X86::CMOV_V2F64:
8389 case X86::CMOV_V2I64:
8390 case X86::CMOV_GR16:
8391 case X86::CMOV_GR32:
8392 case X86::CMOV_RFP32:
8393 case X86::CMOV_RFP64:
8394 case X86::CMOV_RFP80:
8395 return EmitLoweredSelect(MI, BB);
8397 case X86::FP32_TO_INT16_IN_MEM:
8398 case X86::FP32_TO_INT32_IN_MEM:
8399 case X86::FP32_TO_INT64_IN_MEM:
8400 case X86::FP64_TO_INT16_IN_MEM:
8401 case X86::FP64_TO_INT32_IN_MEM:
8402 case X86::FP64_TO_INT64_IN_MEM:
8403 case X86::FP80_TO_INT16_IN_MEM:
8404 case X86::FP80_TO_INT32_IN_MEM:
8405 case X86::FP80_TO_INT64_IN_MEM: {
8406 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8407 DebugLoc DL = MI->getDebugLoc();
8409 // Change the floating point control register to use "round towards zero"
8410 // mode when truncating to an integer value.
8411 MachineFunction *F = BB->getParent();
8412 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8413 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8415 // Load the old value of the high byte of the control word...
8417 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8418 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8421 // Set the high part to be round to zero...
8422 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8425 // Reload the modified control word now...
8426 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8428 // Restore the memory image of control word to original value
8429 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8432 // Get the X86 opcode to use.
8434 switch (MI->getOpcode()) {
8435 default: llvm_unreachable("illegal opcode!");
8436 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8437 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8438 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8439 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8440 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8441 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8442 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8443 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8444 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8448 MachineOperand &Op = MI->getOperand(0);
8450 AM.BaseType = X86AddressMode::RegBase;
8451 AM.Base.Reg = Op.getReg();
8453 AM.BaseType = X86AddressMode::FrameIndexBase;
8454 AM.Base.FrameIndex = Op.getIndex();
8456 Op = MI->getOperand(1);
8458 AM.Scale = Op.getImm();
8459 Op = MI->getOperand(2);
8461 AM.IndexReg = Op.getImm();
8462 Op = MI->getOperand(3);
8463 if (Op.isGlobal()) {
8464 AM.GV = Op.getGlobal();
8466 AM.Disp = Op.getImm();
8468 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8469 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8471 // Reload the original control word now.
8472 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8474 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8477 // String/text processing lowering.
8478 case X86::PCMPISTRM128REG:
8479 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8480 case X86::PCMPISTRM128MEM:
8481 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8482 case X86::PCMPESTRM128REG:
8483 return EmitPCMP(MI, BB, 5, false /* in mem */);
8484 case X86::PCMPESTRM128MEM:
8485 return EmitPCMP(MI, BB, 5, true /* in mem */);
8488 case X86::ATOMAND32:
8489 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8490 X86::AND32ri, X86::MOV32rm,
8491 X86::LCMPXCHG32, X86::MOV32rr,
8492 X86::NOT32r, X86::EAX,
8493 X86::GR32RegisterClass);
8495 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8496 X86::OR32ri, X86::MOV32rm,
8497 X86::LCMPXCHG32, X86::MOV32rr,
8498 X86::NOT32r, X86::EAX,
8499 X86::GR32RegisterClass);
8500 case X86::ATOMXOR32:
8501 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8502 X86::XOR32ri, X86::MOV32rm,
8503 X86::LCMPXCHG32, X86::MOV32rr,
8504 X86::NOT32r, X86::EAX,
8505 X86::GR32RegisterClass);
8506 case X86::ATOMNAND32:
8507 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8508 X86::AND32ri, X86::MOV32rm,
8509 X86::LCMPXCHG32, X86::MOV32rr,
8510 X86::NOT32r, X86::EAX,
8511 X86::GR32RegisterClass, true);
8512 case X86::ATOMMIN32:
8513 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8514 case X86::ATOMMAX32:
8515 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8516 case X86::ATOMUMIN32:
8517 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8518 case X86::ATOMUMAX32:
8519 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8521 case X86::ATOMAND16:
8522 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8523 X86::AND16ri, X86::MOV16rm,
8524 X86::LCMPXCHG16, X86::MOV16rr,
8525 X86::NOT16r, X86::AX,
8526 X86::GR16RegisterClass);
8528 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8529 X86::OR16ri, X86::MOV16rm,
8530 X86::LCMPXCHG16, X86::MOV16rr,
8531 X86::NOT16r, X86::AX,
8532 X86::GR16RegisterClass);
8533 case X86::ATOMXOR16:
8534 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8535 X86::XOR16ri, X86::MOV16rm,
8536 X86::LCMPXCHG16, X86::MOV16rr,
8537 X86::NOT16r, X86::AX,
8538 X86::GR16RegisterClass);
8539 case X86::ATOMNAND16:
8540 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8541 X86::AND16ri, X86::MOV16rm,
8542 X86::LCMPXCHG16, X86::MOV16rr,
8543 X86::NOT16r, X86::AX,
8544 X86::GR16RegisterClass, true);
8545 case X86::ATOMMIN16:
8546 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8547 case X86::ATOMMAX16:
8548 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8549 case X86::ATOMUMIN16:
8550 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8551 case X86::ATOMUMAX16:
8552 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8555 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8556 X86::AND8ri, X86::MOV8rm,
8557 X86::LCMPXCHG8, X86::MOV8rr,
8558 X86::NOT8r, X86::AL,
8559 X86::GR8RegisterClass);
8561 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8562 X86::OR8ri, X86::MOV8rm,
8563 X86::LCMPXCHG8, X86::MOV8rr,
8564 X86::NOT8r, X86::AL,
8565 X86::GR8RegisterClass);
8567 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8568 X86::XOR8ri, X86::MOV8rm,
8569 X86::LCMPXCHG8, X86::MOV8rr,
8570 X86::NOT8r, X86::AL,
8571 X86::GR8RegisterClass);
8572 case X86::ATOMNAND8:
8573 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8574 X86::AND8ri, X86::MOV8rm,
8575 X86::LCMPXCHG8, X86::MOV8rr,
8576 X86::NOT8r, X86::AL,
8577 X86::GR8RegisterClass, true);
8578 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8579 // This group is for 64-bit host.
8580 case X86::ATOMAND64:
8581 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8582 X86::AND64ri32, X86::MOV64rm,
8583 X86::LCMPXCHG64, X86::MOV64rr,
8584 X86::NOT64r, X86::RAX,
8585 X86::GR64RegisterClass);
8587 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8588 X86::OR64ri32, X86::MOV64rm,
8589 X86::LCMPXCHG64, X86::MOV64rr,
8590 X86::NOT64r, X86::RAX,
8591 X86::GR64RegisterClass);
8592 case X86::ATOMXOR64:
8593 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8594 X86::XOR64ri32, X86::MOV64rm,
8595 X86::LCMPXCHG64, X86::MOV64rr,
8596 X86::NOT64r, X86::RAX,
8597 X86::GR64RegisterClass);
8598 case X86::ATOMNAND64:
8599 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8600 X86::AND64ri32, X86::MOV64rm,
8601 X86::LCMPXCHG64, X86::MOV64rr,
8602 X86::NOT64r, X86::RAX,
8603 X86::GR64RegisterClass, true);
8604 case X86::ATOMMIN64:
8605 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8606 case X86::ATOMMAX64:
8607 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8608 case X86::ATOMUMIN64:
8609 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8610 case X86::ATOMUMAX64:
8611 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8613 // This group does 64-bit operations on a 32-bit host.
8614 case X86::ATOMAND6432:
8615 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8616 X86::AND32rr, X86::AND32rr,
8617 X86::AND32ri, X86::AND32ri,
8619 case X86::ATOMOR6432:
8620 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8621 X86::OR32rr, X86::OR32rr,
8622 X86::OR32ri, X86::OR32ri,
8624 case X86::ATOMXOR6432:
8625 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8626 X86::XOR32rr, X86::XOR32rr,
8627 X86::XOR32ri, X86::XOR32ri,
8629 case X86::ATOMNAND6432:
8630 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8631 X86::AND32rr, X86::AND32rr,
8632 X86::AND32ri, X86::AND32ri,
8634 case X86::ATOMADD6432:
8635 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8636 X86::ADD32rr, X86::ADC32rr,
8637 X86::ADD32ri, X86::ADC32ri,
8639 case X86::ATOMSUB6432:
8640 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8641 X86::SUB32rr, X86::SBB32rr,
8642 X86::SUB32ri, X86::SBB32ri,
8644 case X86::ATOMSWAP6432:
8645 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8646 X86::MOV32rr, X86::MOV32rr,
8647 X86::MOV32ri, X86::MOV32ri,
8649 case X86::VASTART_SAVE_XMM_REGS:
8650 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8654 //===----------------------------------------------------------------------===//
8655 // X86 Optimization Hooks
8656 //===----------------------------------------------------------------------===//
8658 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8662 const SelectionDAG &DAG,
8663 unsigned Depth) const {
8664 unsigned Opc = Op.getOpcode();
8665 assert((Opc >= ISD::BUILTIN_OP_END ||
8666 Opc == ISD::INTRINSIC_WO_CHAIN ||
8667 Opc == ISD::INTRINSIC_W_CHAIN ||
8668 Opc == ISD::INTRINSIC_VOID) &&
8669 "Should use MaskedValueIsZero if you don't know whether Op"
8670 " is a target node!");
8672 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8684 // These nodes' second result is a boolean.
8685 if (Op.getResNo() == 0)
8689 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8690 Mask.getBitWidth() - 1);
8695 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8696 /// node is a GlobalAddress + offset.
8697 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8698 const GlobalValue* &GA,
8699 int64_t &Offset) const {
8700 if (N->getOpcode() == X86ISD::Wrapper) {
8701 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8702 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8703 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8707 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8710 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8711 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8712 /// if the load addresses are consecutive, non-overlapping, and in the right
8714 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8715 const TargetLowering &TLI) {
8716 DebugLoc dl = N->getDebugLoc();
8717 EVT VT = N->getValueType(0);
8718 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8720 if (VT.getSizeInBits() != 128)
8723 SmallVector<SDValue, 16> Elts;
8724 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8725 Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8727 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8730 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8731 /// and convert it from being a bunch of shuffles and extracts to a simple
8732 /// store and scalar loads to extract the elements.
8733 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8734 const TargetLowering &TLI) {
8735 SDValue InputVector = N->getOperand(0);
8737 // Only operate on vectors of 4 elements, where the alternative shuffling
8738 // gets to be more expensive.
8739 if (InputVector.getValueType() != MVT::v4i32)
8742 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8743 // single use which is a sign-extend or zero-extend, and all elements are
8745 SmallVector<SDNode *, 4> Uses;
8746 unsigned ExtractedElements = 0;
8747 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8748 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8749 if (UI.getUse().getResNo() != InputVector.getResNo())
8752 SDNode *Extract = *UI;
8753 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8756 if (Extract->getValueType(0) != MVT::i32)
8758 if (!Extract->hasOneUse())
8760 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8761 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8763 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8766 // Record which element was extracted.
8767 ExtractedElements |=
8768 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8770 Uses.push_back(Extract);
8773 // If not all the elements were used, this may not be worthwhile.
8774 if (ExtractedElements != 15)
8777 // Ok, we've now decided to do the transformation.
8778 DebugLoc dl = InputVector.getDebugLoc();
8780 // Store the value to a temporary stack slot.
8781 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8782 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8785 // Replace each use (extract) with a load of the appropriate element.
8786 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8787 UE = Uses.end(); UI != UE; ++UI) {
8788 SDNode *Extract = *UI;
8790 // Compute the element's address.
8791 SDValue Idx = Extract->getOperand(1);
8793 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8794 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8795 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8797 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8800 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8801 NULL, 0, false, false, 0);
8803 // Replace the exact with the load.
8804 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8807 // The replacement was made in place; don't return anything.
8811 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8812 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8813 const X86Subtarget *Subtarget) {
8814 DebugLoc DL = N->getDebugLoc();
8815 SDValue Cond = N->getOperand(0);
8816 // Get the LHS/RHS of the select.
8817 SDValue LHS = N->getOperand(1);
8818 SDValue RHS = N->getOperand(2);
8820 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8821 // instructions match the semantics of the common C idiom x<y?x:y but not
8822 // x<=y?x:y, because of how they handle negative zero (which can be
8823 // ignored in unsafe-math mode).
8824 if (Subtarget->hasSSE2() &&
8825 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8826 Cond.getOpcode() == ISD::SETCC) {
8827 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8829 unsigned Opcode = 0;
8830 // Check for x CC y ? x : y.
8831 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8832 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8836 // Converting this to a min would handle NaNs incorrectly, and swapping
8837 // the operands would cause it to handle comparisons between positive
8838 // and negative zero incorrectly.
8839 if (!FiniteOnlyFPMath() &&
8840 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8841 if (!UnsafeFPMath &&
8842 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8844 std::swap(LHS, RHS);
8846 Opcode = X86ISD::FMIN;
8849 // Converting this to a min would handle comparisons between positive
8850 // and negative zero incorrectly.
8851 if (!UnsafeFPMath &&
8852 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8854 Opcode = X86ISD::FMIN;
8857 // Converting this to a min would handle both negative zeros and NaNs
8858 // incorrectly, but we can swap the operands to fix both.
8859 std::swap(LHS, RHS);
8863 Opcode = X86ISD::FMIN;
8867 // Converting this to a max would handle comparisons between positive
8868 // and negative zero incorrectly.
8869 if (!UnsafeFPMath &&
8870 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8872 Opcode = X86ISD::FMAX;
8875 // Converting this to a max would handle NaNs incorrectly, and swapping
8876 // the operands would cause it to handle comparisons between positive
8877 // and negative zero incorrectly.
8878 if (!FiniteOnlyFPMath() &&
8879 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8880 if (!UnsafeFPMath &&
8881 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8883 std::swap(LHS, RHS);
8885 Opcode = X86ISD::FMAX;
8888 // Converting this to a max would handle both negative zeros and NaNs
8889 // incorrectly, but we can swap the operands to fix both.
8890 std::swap(LHS, RHS);
8894 Opcode = X86ISD::FMAX;
8897 // Check for x CC y ? y : x -- a min/max with reversed arms.
8898 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8899 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
8903 // Converting this to a min would handle comparisons between positive
8904 // and negative zero incorrectly, and swapping the operands would
8905 // cause it to handle NaNs incorrectly.
8906 if (!UnsafeFPMath &&
8907 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
8908 if (!FiniteOnlyFPMath() &&
8909 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8911 std::swap(LHS, RHS);
8913 Opcode = X86ISD::FMIN;
8916 // Converting this to a min would handle NaNs incorrectly.
8917 if (!UnsafeFPMath &&
8918 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8920 Opcode = X86ISD::FMIN;
8923 // Converting this to a min would handle both negative zeros and NaNs
8924 // incorrectly, but we can swap the operands to fix both.
8925 std::swap(LHS, RHS);
8929 Opcode = X86ISD::FMIN;
8933 // Converting this to a max would handle NaNs incorrectly.
8934 if (!FiniteOnlyFPMath() &&
8935 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8937 Opcode = X86ISD::FMAX;
8940 // Converting this to a max would handle comparisons between positive
8941 // and negative zero incorrectly, and swapping the operands would
8942 // cause it to handle NaNs incorrectly.
8943 if (!UnsafeFPMath &&
8944 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
8945 if (!FiniteOnlyFPMath() &&
8946 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8948 std::swap(LHS, RHS);
8950 Opcode = X86ISD::FMAX;
8953 // Converting this to a max would handle both negative zeros and NaNs
8954 // incorrectly, but we can swap the operands to fix both.
8955 std::swap(LHS, RHS);
8959 Opcode = X86ISD::FMAX;
8965 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8968 // If this is a select between two integer constants, try to do some
8970 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8971 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8972 // Don't do this for crazy integer types.
8973 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8974 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8975 // so that TrueC (the true value) is larger than FalseC.
8976 bool NeedsCondInvert = false;
8978 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8979 // Efficiently invertible.
8980 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8981 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8982 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8983 NeedsCondInvert = true;
8984 std::swap(TrueC, FalseC);
8987 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8988 if (FalseC->getAPIntValue() == 0 &&
8989 TrueC->getAPIntValue().isPowerOf2()) {
8990 if (NeedsCondInvert) // Invert the condition if needed.
8991 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8992 DAG.getConstant(1, Cond.getValueType()));
8994 // Zero extend the condition if needed.
8995 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8997 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8998 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8999 DAG.getConstant(ShAmt, MVT::i8));
9002 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9003 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9004 if (NeedsCondInvert) // Invert the condition if needed.
9005 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9006 DAG.getConstant(1, Cond.getValueType()));
9008 // Zero extend the condition if needed.
9009 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9010 FalseC->getValueType(0), Cond);
9011 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9012 SDValue(FalseC, 0));
9015 // Optimize cases that will turn into an LEA instruction. This requires
9016 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9017 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9018 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9019 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9021 bool isFastMultiplier = false;
9023 switch ((unsigned char)Diff) {
9025 case 1: // result = add base, cond
9026 case 2: // result = lea base( , cond*2)
9027 case 3: // result = lea base(cond, cond*2)
9028 case 4: // result = lea base( , cond*4)
9029 case 5: // result = lea base(cond, cond*4)
9030 case 8: // result = lea base( , cond*8)
9031 case 9: // result = lea base(cond, cond*8)
9032 isFastMultiplier = true;
9037 if (isFastMultiplier) {
9038 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9039 if (NeedsCondInvert) // Invert the condition if needed.
9040 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9041 DAG.getConstant(1, Cond.getValueType()));
9043 // Zero extend the condition if needed.
9044 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9046 // Scale the condition by the difference.
9048 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9049 DAG.getConstant(Diff, Cond.getValueType()));
9051 // Add the base if non-zero.
9052 if (FalseC->getAPIntValue() != 0)
9053 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9054 SDValue(FalseC, 0));
9064 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9065 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9066 TargetLowering::DAGCombinerInfo &DCI) {
9067 DebugLoc DL = N->getDebugLoc();
9069 // If the flag operand isn't dead, don't touch this CMOV.
9070 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9073 // If this is a select between two integer constants, try to do some
9074 // optimizations. Note that the operands are ordered the opposite of SELECT
9076 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9077 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9078 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9079 // larger than FalseC (the false value).
9080 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9082 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9083 CC = X86::GetOppositeBranchCondition(CC);
9084 std::swap(TrueC, FalseC);
9087 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9088 // This is efficient for any integer data type (including i8/i16) and
9090 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9091 SDValue Cond = N->getOperand(3);
9092 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9093 DAG.getConstant(CC, MVT::i8), Cond);
9095 // Zero extend the condition if needed.
9096 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9098 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9099 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9100 DAG.getConstant(ShAmt, MVT::i8));
9101 if (N->getNumValues() == 2) // Dead flag value?
9102 return DCI.CombineTo(N, Cond, SDValue());
9106 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9107 // for any integer data type, including i8/i16.
9108 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9109 SDValue Cond = N->getOperand(3);
9110 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9111 DAG.getConstant(CC, MVT::i8), Cond);
9113 // Zero extend the condition if needed.
9114 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9115 FalseC->getValueType(0), Cond);
9116 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9117 SDValue(FalseC, 0));
9119 if (N->getNumValues() == 2) // Dead flag value?
9120 return DCI.CombineTo(N, Cond, SDValue());
9124 // Optimize cases that will turn into an LEA instruction. This requires
9125 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9126 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9127 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9128 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9130 bool isFastMultiplier = false;
9132 switch ((unsigned char)Diff) {
9134 case 1: // result = add base, cond
9135 case 2: // result = lea base( , cond*2)
9136 case 3: // result = lea base(cond, cond*2)
9137 case 4: // result = lea base( , cond*4)
9138 case 5: // result = lea base(cond, cond*4)
9139 case 8: // result = lea base( , cond*8)
9140 case 9: // result = lea base(cond, cond*8)
9141 isFastMultiplier = true;
9146 if (isFastMultiplier) {
9147 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9148 SDValue Cond = N->getOperand(3);
9149 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9150 DAG.getConstant(CC, MVT::i8), Cond);
9151 // Zero extend the condition if needed.
9152 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9154 // Scale the condition by the difference.
9156 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9157 DAG.getConstant(Diff, Cond.getValueType()));
9159 // Add the base if non-zero.
9160 if (FalseC->getAPIntValue() != 0)
9161 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9162 SDValue(FalseC, 0));
9163 if (N->getNumValues() == 2) // Dead flag value?
9164 return DCI.CombineTo(N, Cond, SDValue());
9174 /// PerformMulCombine - Optimize a single multiply with constant into two
9175 /// in order to implement it with two cheaper instructions, e.g.
9176 /// LEA + SHL, LEA + LEA.
9177 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9178 TargetLowering::DAGCombinerInfo &DCI) {
9179 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9182 EVT VT = N->getValueType(0);
9186 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9189 uint64_t MulAmt = C->getZExtValue();
9190 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9193 uint64_t MulAmt1 = 0;
9194 uint64_t MulAmt2 = 0;
9195 if ((MulAmt % 9) == 0) {
9197 MulAmt2 = MulAmt / 9;
9198 } else if ((MulAmt % 5) == 0) {
9200 MulAmt2 = MulAmt / 5;
9201 } else if ((MulAmt % 3) == 0) {
9203 MulAmt2 = MulAmt / 3;
9206 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9207 DebugLoc DL = N->getDebugLoc();
9209 if (isPowerOf2_64(MulAmt2) &&
9210 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9211 // If second multiplifer is pow2, issue it first. We want the multiply by
9212 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9214 std::swap(MulAmt1, MulAmt2);
9217 if (isPowerOf2_64(MulAmt1))
9218 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9219 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9221 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9222 DAG.getConstant(MulAmt1, VT));
9224 if (isPowerOf2_64(MulAmt2))
9225 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9226 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9228 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9229 DAG.getConstant(MulAmt2, VT));
9231 // Do not add new nodes to DAG combiner worklist.
9232 DCI.CombineTo(N, NewMul, false);
9237 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9238 SDValue N0 = N->getOperand(0);
9239 SDValue N1 = N->getOperand(1);
9240 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9241 EVT VT = N0.getValueType();
9243 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9244 // since the result of setcc_c is all zero's or all ones.
9245 if (N1C && N0.getOpcode() == ISD::AND &&
9246 N0.getOperand(1).getOpcode() == ISD::Constant) {
9247 SDValue N00 = N0.getOperand(0);
9248 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9249 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9250 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9251 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9252 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9253 APInt ShAmt = N1C->getAPIntValue();
9254 Mask = Mask.shl(ShAmt);
9256 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9257 N00, DAG.getConstant(Mask, VT));
9264 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9266 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9267 const X86Subtarget *Subtarget) {
9268 EVT VT = N->getValueType(0);
9269 if (!VT.isVector() && VT.isInteger() &&
9270 N->getOpcode() == ISD::SHL)
9271 return PerformSHLCombine(N, DAG);
9273 // On X86 with SSE2 support, we can transform this to a vector shift if
9274 // all elements are shifted by the same amount. We can't do this in legalize
9275 // because the a constant vector is typically transformed to a constant pool
9276 // so we have no knowledge of the shift amount.
9277 if (!Subtarget->hasSSE2())
9280 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9283 SDValue ShAmtOp = N->getOperand(1);
9284 EVT EltVT = VT.getVectorElementType();
9285 DebugLoc DL = N->getDebugLoc();
9286 SDValue BaseShAmt = SDValue();
9287 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9288 unsigned NumElts = VT.getVectorNumElements();
9290 for (; i != NumElts; ++i) {
9291 SDValue Arg = ShAmtOp.getOperand(i);
9292 if (Arg.getOpcode() == ISD::UNDEF) continue;
9296 for (; i != NumElts; ++i) {
9297 SDValue Arg = ShAmtOp.getOperand(i);
9298 if (Arg.getOpcode() == ISD::UNDEF) continue;
9299 if (Arg != BaseShAmt) {
9303 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9304 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9305 SDValue InVec = ShAmtOp.getOperand(0);
9306 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9307 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9309 for (; i != NumElts; ++i) {
9310 SDValue Arg = InVec.getOperand(i);
9311 if (Arg.getOpcode() == ISD::UNDEF) continue;
9315 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9316 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9317 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9318 if (C->getZExtValue() == SplatIdx)
9319 BaseShAmt = InVec.getOperand(1);
9322 if (BaseShAmt.getNode() == 0)
9323 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9324 DAG.getIntPtrConstant(0));
9328 // The shift amount is an i32.
9329 if (EltVT.bitsGT(MVT::i32))
9330 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9331 else if (EltVT.bitsLT(MVT::i32))
9332 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9334 // The shift amount is identical so we can do a vector shift.
9335 SDValue ValOp = N->getOperand(0);
9336 switch (N->getOpcode()) {
9338 llvm_unreachable("Unknown shift opcode!");
9341 if (VT == MVT::v2i64)
9342 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9343 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9345 if (VT == MVT::v4i32)
9346 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9347 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9349 if (VT == MVT::v8i16)
9350 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9351 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9355 if (VT == MVT::v4i32)
9356 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9357 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9359 if (VT == MVT::v8i16)
9360 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9361 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9365 if (VT == MVT::v2i64)
9366 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9367 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9369 if (VT == MVT::v4i32)
9370 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9371 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9373 if (VT == MVT::v8i16)
9374 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9375 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9382 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9383 TargetLowering::DAGCombinerInfo &DCI,
9384 const X86Subtarget *Subtarget) {
9385 if (DCI.isBeforeLegalizeOps())
9388 EVT VT = N->getValueType(0);
9389 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9392 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9393 SDValue N0 = N->getOperand(0);
9394 SDValue N1 = N->getOperand(1);
9395 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9397 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9399 if (!N0.hasOneUse() || !N1.hasOneUse())
9402 SDValue ShAmt0 = N0.getOperand(1);
9403 if (ShAmt0.getValueType() != MVT::i8)
9405 SDValue ShAmt1 = N1.getOperand(1);
9406 if (ShAmt1.getValueType() != MVT::i8)
9408 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9409 ShAmt0 = ShAmt0.getOperand(0);
9410 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9411 ShAmt1 = ShAmt1.getOperand(0);
9413 DebugLoc DL = N->getDebugLoc();
9414 unsigned Opc = X86ISD::SHLD;
9415 SDValue Op0 = N0.getOperand(0);
9416 SDValue Op1 = N1.getOperand(0);
9417 if (ShAmt0.getOpcode() == ISD::SUB) {
9419 std::swap(Op0, Op1);
9420 std::swap(ShAmt0, ShAmt1);
9423 unsigned Bits = VT.getSizeInBits();
9424 if (ShAmt1.getOpcode() == ISD::SUB) {
9425 SDValue Sum = ShAmt1.getOperand(0);
9426 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9427 if (SumC->getSExtValue() == Bits &&
9428 ShAmt1.getOperand(1) == ShAmt0)
9429 return DAG.getNode(Opc, DL, VT,
9431 DAG.getNode(ISD::TRUNCATE, DL,
9434 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9435 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9437 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9438 return DAG.getNode(Opc, DL, VT,
9439 N0.getOperand(0), N1.getOperand(0),
9440 DAG.getNode(ISD::TRUNCATE, DL,
9447 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9448 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9449 const X86Subtarget *Subtarget) {
9450 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9451 // the FP state in cases where an emms may be missing.
9452 // A preferable solution to the general problem is to figure out the right
9453 // places to insert EMMS. This qualifies as a quick hack.
9455 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9456 StoreSDNode *St = cast<StoreSDNode>(N);
9457 EVT VT = St->getValue().getValueType();
9458 if (VT.getSizeInBits() != 64)
9461 const Function *F = DAG.getMachineFunction().getFunction();
9462 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9463 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9464 && Subtarget->hasSSE2();
9465 if ((VT.isVector() ||
9466 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9467 isa<LoadSDNode>(St->getValue()) &&
9468 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9469 St->getChain().hasOneUse() && !St->isVolatile()) {
9470 SDNode* LdVal = St->getValue().getNode();
9472 int TokenFactorIndex = -1;
9473 SmallVector<SDValue, 8> Ops;
9474 SDNode* ChainVal = St->getChain().getNode();
9475 // Must be a store of a load. We currently handle two cases: the load
9476 // is a direct child, and it's under an intervening TokenFactor. It is
9477 // possible to dig deeper under nested TokenFactors.
9478 if (ChainVal == LdVal)
9479 Ld = cast<LoadSDNode>(St->getChain());
9480 else if (St->getValue().hasOneUse() &&
9481 ChainVal->getOpcode() == ISD::TokenFactor) {
9482 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9483 if (ChainVal->getOperand(i).getNode() == LdVal) {
9484 TokenFactorIndex = i;
9485 Ld = cast<LoadSDNode>(St->getValue());
9487 Ops.push_back(ChainVal->getOperand(i));
9491 if (!Ld || !ISD::isNormalLoad(Ld))
9494 // If this is not the MMX case, i.e. we are just turning i64 load/store
9495 // into f64 load/store, avoid the transformation if there are multiple
9496 // uses of the loaded value.
9497 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9500 DebugLoc LdDL = Ld->getDebugLoc();
9501 DebugLoc StDL = N->getDebugLoc();
9502 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9503 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9505 if (Subtarget->is64Bit() || F64IsLegal) {
9506 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9507 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9508 Ld->getBasePtr(), Ld->getSrcValue(),
9509 Ld->getSrcValueOffset(), Ld->isVolatile(),
9510 Ld->isNonTemporal(), Ld->getAlignment());
9511 SDValue NewChain = NewLd.getValue(1);
9512 if (TokenFactorIndex != -1) {
9513 Ops.push_back(NewChain);
9514 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9517 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9518 St->getSrcValue(), St->getSrcValueOffset(),
9519 St->isVolatile(), St->isNonTemporal(),
9520 St->getAlignment());
9523 // Otherwise, lower to two pairs of 32-bit loads / stores.
9524 SDValue LoAddr = Ld->getBasePtr();
9525 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9526 DAG.getConstant(4, MVT::i32));
9528 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9529 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9530 Ld->isVolatile(), Ld->isNonTemporal(),
9531 Ld->getAlignment());
9532 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9533 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9534 Ld->isVolatile(), Ld->isNonTemporal(),
9535 MinAlign(Ld->getAlignment(), 4));
9537 SDValue NewChain = LoLd.getValue(1);
9538 if (TokenFactorIndex != -1) {
9539 Ops.push_back(LoLd);
9540 Ops.push_back(HiLd);
9541 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9545 LoAddr = St->getBasePtr();
9546 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9547 DAG.getConstant(4, MVT::i32));
9549 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9550 St->getSrcValue(), St->getSrcValueOffset(),
9551 St->isVolatile(), St->isNonTemporal(),
9552 St->getAlignment());
9553 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9555 St->getSrcValueOffset() + 4,
9557 St->isNonTemporal(),
9558 MinAlign(St->getAlignment(), 4));
9559 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9564 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9565 /// X86ISD::FXOR nodes.
9566 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9567 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9568 // F[X]OR(0.0, x) -> x
9569 // F[X]OR(x, 0.0) -> x
9570 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9571 if (C->getValueAPF().isPosZero())
9572 return N->getOperand(1);
9573 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9574 if (C->getValueAPF().isPosZero())
9575 return N->getOperand(0);
9579 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9580 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9581 // FAND(0.0, x) -> 0.0
9582 // FAND(x, 0.0) -> 0.0
9583 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9584 if (C->getValueAPF().isPosZero())
9585 return N->getOperand(0);
9586 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9587 if (C->getValueAPF().isPosZero())
9588 return N->getOperand(1);
9592 static SDValue PerformBTCombine(SDNode *N,
9594 TargetLowering::DAGCombinerInfo &DCI) {
9595 // BT ignores high bits in the bit index operand.
9596 SDValue Op1 = N->getOperand(1);
9597 if (Op1.hasOneUse()) {
9598 unsigned BitWidth = Op1.getValueSizeInBits();
9599 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9600 APInt KnownZero, KnownOne;
9601 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9602 !DCI.isBeforeLegalizeOps());
9603 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9604 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9605 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9606 DCI.CommitTargetLoweringOpt(TLO);
9611 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9612 SDValue Op = N->getOperand(0);
9613 if (Op.getOpcode() == ISD::BIT_CONVERT)
9614 Op = Op.getOperand(0);
9615 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9616 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9617 VT.getVectorElementType().getSizeInBits() ==
9618 OpVT.getVectorElementType().getSizeInBits()) {
9619 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9624 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9625 // Locked instructions, in turn, have implicit fence semantics (all memory
9626 // operations are flushed before issuing the locked instruction, and the
9627 // are not buffered), so we can fold away the common pattern of
9628 // fence-atomic-fence.
9629 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9630 SDValue atomic = N->getOperand(0);
9631 switch (atomic.getOpcode()) {
9632 case ISD::ATOMIC_CMP_SWAP:
9633 case ISD::ATOMIC_SWAP:
9634 case ISD::ATOMIC_LOAD_ADD:
9635 case ISD::ATOMIC_LOAD_SUB:
9636 case ISD::ATOMIC_LOAD_AND:
9637 case ISD::ATOMIC_LOAD_OR:
9638 case ISD::ATOMIC_LOAD_XOR:
9639 case ISD::ATOMIC_LOAD_NAND:
9640 case ISD::ATOMIC_LOAD_MIN:
9641 case ISD::ATOMIC_LOAD_MAX:
9642 case ISD::ATOMIC_LOAD_UMIN:
9643 case ISD::ATOMIC_LOAD_UMAX:
9649 SDValue fence = atomic.getOperand(0);
9650 if (fence.getOpcode() != ISD::MEMBARRIER)
9653 switch (atomic.getOpcode()) {
9654 case ISD::ATOMIC_CMP_SWAP:
9655 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9656 atomic.getOperand(1), atomic.getOperand(2),
9657 atomic.getOperand(3));
9658 case ISD::ATOMIC_SWAP:
9659 case ISD::ATOMIC_LOAD_ADD:
9660 case ISD::ATOMIC_LOAD_SUB:
9661 case ISD::ATOMIC_LOAD_AND:
9662 case ISD::ATOMIC_LOAD_OR:
9663 case ISD::ATOMIC_LOAD_XOR:
9664 case ISD::ATOMIC_LOAD_NAND:
9665 case ISD::ATOMIC_LOAD_MIN:
9666 case ISD::ATOMIC_LOAD_MAX:
9667 case ISD::ATOMIC_LOAD_UMIN:
9668 case ISD::ATOMIC_LOAD_UMAX:
9669 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9670 atomic.getOperand(1), atomic.getOperand(2));
9676 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9677 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9678 // (and (i32 x86isd::setcc_carry), 1)
9679 // This eliminates the zext. This transformation is necessary because
9680 // ISD::SETCC is always legalized to i8.
9681 DebugLoc dl = N->getDebugLoc();
9682 SDValue N0 = N->getOperand(0);
9683 EVT VT = N->getValueType(0);
9684 if (N0.getOpcode() == ISD::AND &&
9686 N0.getOperand(0).hasOneUse()) {
9687 SDValue N00 = N0.getOperand(0);
9688 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9690 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9691 if (!C || C->getZExtValue() != 1)
9693 return DAG.getNode(ISD::AND, dl, VT,
9694 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9695 N00.getOperand(0), N00.getOperand(1)),
9696 DAG.getConstant(1, VT));
9702 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9703 DAGCombinerInfo &DCI) const {
9704 SelectionDAG &DAG = DCI.DAG;
9705 switch (N->getOpcode()) {
9707 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9708 case ISD::EXTRACT_VECTOR_ELT:
9709 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9710 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9711 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9712 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9715 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9716 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
9717 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9719 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9720 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9721 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9722 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9723 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9724 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9730 /// isTypeDesirableForOp - Return true if the target has native support for
9731 /// the specified value type and it is 'desirable' to use the type for the
9732 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9733 /// instruction encodings are longer and some i16 instructions are slow.
9734 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9735 if (!isTypeLegal(VT))
9744 case ISD::SIGN_EXTEND:
9745 case ISD::ZERO_EXTEND:
9746 case ISD::ANY_EXTEND:
9759 static bool MayFoldLoad(SDValue Op) {
9760 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9763 static bool MayFoldIntoStore(SDValue Op) {
9764 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9767 /// IsDesirableToPromoteOp - This method query the target whether it is
9768 /// beneficial for dag combiner to promote the specified node. If true, it
9769 /// should return the desired promotion type by reference.
9770 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9771 EVT VT = Op.getValueType();
9775 bool Promote = false;
9776 bool Commute = false;
9777 switch (Op.getOpcode()) {
9780 LoadSDNode *LD = cast<LoadSDNode>(Op);
9781 // If the non-extending load has a single use and it's not live out, then it
9783 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9785 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9786 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9787 // The only case where we'd want to promote LOAD (rather then it being
9788 // promoted as an operand is when it's only use is liveout.
9789 if (UI->getOpcode() != ISD::CopyToReg)
9796 case ISD::SIGN_EXTEND:
9797 case ISD::ZERO_EXTEND:
9798 case ISD::ANY_EXTEND:
9803 SDValue N0 = Op.getOperand(0);
9804 // Look out for (store (shl (load), x)).
9805 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
9818 SDValue N0 = Op.getOperand(0);
9819 SDValue N1 = Op.getOperand(1);
9820 if (!Commute && MayFoldLoad(N1))
9822 // Avoid disabling potential load folding opportunities.
9823 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
9825 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
9835 //===----------------------------------------------------------------------===//
9836 // X86 Inline Assembly Support
9837 //===----------------------------------------------------------------------===//
9839 static bool LowerToBSwap(CallInst *CI) {
9840 // FIXME: this should verify that we are targetting a 486 or better. If not,
9841 // we will turn this bswap into something that will be lowered to logical ops
9842 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9843 // so don't worry about this.
9845 // Verify this is a simple bswap.
9846 if (CI->getNumOperands() != 2 ||
9847 CI->getType() != CI->getOperand(1)->getType() ||
9848 !CI->getType()->isIntegerTy())
9851 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9852 if (!Ty || Ty->getBitWidth() % 16 != 0)
9855 // Okay, we can do this xform, do so now.
9856 const Type *Tys[] = { Ty };
9857 Module *M = CI->getParent()->getParent()->getParent();
9858 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9860 Value *Op = CI->getOperand(1);
9861 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9863 CI->replaceAllUsesWith(Op);
9864 CI->eraseFromParent();
9868 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9869 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9870 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9872 std::string AsmStr = IA->getAsmString();
9874 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9875 SmallVector<StringRef, 4> AsmPieces;
9876 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9878 switch (AsmPieces.size()) {
9879 default: return false;
9881 AsmStr = AsmPieces[0];
9883 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9886 if (AsmPieces.size() == 2 &&
9887 (AsmPieces[0] == "bswap" ||
9888 AsmPieces[0] == "bswapq" ||
9889 AsmPieces[0] == "bswapl") &&
9890 (AsmPieces[1] == "$0" ||
9891 AsmPieces[1] == "${0:q}")) {
9892 // No need to check constraints, nothing other than the equivalent of
9893 // "=r,0" would be valid here.
9894 return LowerToBSwap(CI);
9896 // rorw $$8, ${0:w} --> llvm.bswap.i16
9897 if (CI->getType()->isIntegerTy(16) &&
9898 AsmPieces.size() == 3 &&
9899 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9900 AsmPieces[1] == "$$8," &&
9901 AsmPieces[2] == "${0:w}" &&
9902 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9904 const std::string &Constraints = IA->getConstraintString();
9905 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9906 std::sort(AsmPieces.begin(), AsmPieces.end());
9907 if (AsmPieces.size() == 4 &&
9908 AsmPieces[0] == "~{cc}" &&
9909 AsmPieces[1] == "~{dirflag}" &&
9910 AsmPieces[2] == "~{flags}" &&
9911 AsmPieces[3] == "~{fpsr}") {
9912 return LowerToBSwap(CI);
9917 if (CI->getType()->isIntegerTy(64) &&
9918 Constraints.size() >= 2 &&
9919 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9920 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9921 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9922 SmallVector<StringRef, 4> Words;
9923 SplitString(AsmPieces[0], Words, " \t");
9924 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9926 SplitString(AsmPieces[1], Words, " \t");
9927 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9929 SplitString(AsmPieces[2], Words, " \t,");
9930 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9931 Words[2] == "%edx") {
9932 return LowerToBSwap(CI);
9944 /// getConstraintType - Given a constraint letter, return the type of
9945 /// constraint it is for this target.
9946 X86TargetLowering::ConstraintType
9947 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9948 if (Constraint.size() == 1) {
9949 switch (Constraint[0]) {
9961 return C_RegisterClass;
9969 return TargetLowering::getConstraintType(Constraint);
9972 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9973 /// with another that has more specific requirements based on the type of the
9974 /// corresponding operand.
9975 const char *X86TargetLowering::
9976 LowerXConstraint(EVT ConstraintVT) const {
9977 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9978 // 'f' like normal targets.
9979 if (ConstraintVT.isFloatingPoint()) {
9980 if (Subtarget->hasSSE2())
9982 if (Subtarget->hasSSE1())
9986 return TargetLowering::LowerXConstraint(ConstraintVT);
9989 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9990 /// vector. If it is invalid, don't add anything to Ops.
9991 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9994 std::vector<SDValue>&Ops,
9995 SelectionDAG &DAG) const {
9996 SDValue Result(0, 0);
9998 switch (Constraint) {
10001 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10002 if (C->getZExtValue() <= 31) {
10003 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10009 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10010 if (C->getZExtValue() <= 63) {
10011 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10017 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10018 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10019 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10025 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10026 if (C->getZExtValue() <= 255) {
10027 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10033 // 32-bit signed value
10034 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10035 const ConstantInt *CI = C->getConstantIntValue();
10036 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10037 C->getSExtValue())) {
10038 // Widen to 64 bits here to get it sign extended.
10039 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10042 // FIXME gcc accepts some relocatable values here too, but only in certain
10043 // memory models; it's complicated.
10048 // 32-bit unsigned value
10049 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10050 const ConstantInt *CI = C->getConstantIntValue();
10051 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10052 C->getZExtValue())) {
10053 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10057 // FIXME gcc accepts some relocatable values here too, but only in certain
10058 // memory models; it's complicated.
10062 // Literal immediates are always ok.
10063 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10064 // Widen to 64 bits here to get it sign extended.
10065 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10069 // If we are in non-pic codegen mode, we allow the address of a global (with
10070 // an optional displacement) to be used with 'i'.
10071 GlobalAddressSDNode *GA = 0;
10072 int64_t Offset = 0;
10074 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10076 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10077 Offset += GA->getOffset();
10079 } else if (Op.getOpcode() == ISD::ADD) {
10080 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10081 Offset += C->getZExtValue();
10082 Op = Op.getOperand(0);
10085 } else if (Op.getOpcode() == ISD::SUB) {
10086 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10087 Offset += -C->getZExtValue();
10088 Op = Op.getOperand(0);
10093 // Otherwise, this isn't something we can handle, reject it.
10097 const GlobalValue *GV = GA->getGlobal();
10098 // If we require an extra load to get this address, as in PIC mode, we
10099 // can't accept it.
10100 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10101 getTargetMachine())))
10105 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10107 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10113 if (Result.getNode()) {
10114 Ops.push_back(Result);
10117 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10121 std::vector<unsigned> X86TargetLowering::
10122 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10124 if (Constraint.size() == 1) {
10125 // FIXME: not handling fp-stack yet!
10126 switch (Constraint[0]) { // GCC X86 Constraint Letters
10127 default: break; // Unknown constraint letter
10128 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10129 if (Subtarget->is64Bit()) {
10130 if (VT == MVT::i32)
10131 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10132 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10133 X86::R10D,X86::R11D,X86::R12D,
10134 X86::R13D,X86::R14D,X86::R15D,
10135 X86::EBP, X86::ESP, 0);
10136 else if (VT == MVT::i16)
10137 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10138 X86::SI, X86::DI, X86::R8W,X86::R9W,
10139 X86::R10W,X86::R11W,X86::R12W,
10140 X86::R13W,X86::R14W,X86::R15W,
10141 X86::BP, X86::SP, 0);
10142 else if (VT == MVT::i8)
10143 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10144 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10145 X86::R10B,X86::R11B,X86::R12B,
10146 X86::R13B,X86::R14B,X86::R15B,
10147 X86::BPL, X86::SPL, 0);
10149 else if (VT == MVT::i64)
10150 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10151 X86::RSI, X86::RDI, X86::R8, X86::R9,
10152 X86::R10, X86::R11, X86::R12,
10153 X86::R13, X86::R14, X86::R15,
10154 X86::RBP, X86::RSP, 0);
10158 // 32-bit fallthrough
10159 case 'Q': // Q_REGS
10160 if (VT == MVT::i32)
10161 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10162 else if (VT == MVT::i16)
10163 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10164 else if (VT == MVT::i8)
10165 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10166 else if (VT == MVT::i64)
10167 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10172 return std::vector<unsigned>();
10175 std::pair<unsigned, const TargetRegisterClass*>
10176 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10178 // First, see if this is a constraint that directly corresponds to an LLVM
10180 if (Constraint.size() == 1) {
10181 // GCC Constraint Letters
10182 switch (Constraint[0]) {
10184 case 'r': // GENERAL_REGS
10185 case 'l': // INDEX_REGS
10187 return std::make_pair(0U, X86::GR8RegisterClass);
10188 if (VT == MVT::i16)
10189 return std::make_pair(0U, X86::GR16RegisterClass);
10190 if (VT == MVT::i32 || !Subtarget->is64Bit())
10191 return std::make_pair(0U, X86::GR32RegisterClass);
10192 return std::make_pair(0U, X86::GR64RegisterClass);
10193 case 'R': // LEGACY_REGS
10195 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10196 if (VT == MVT::i16)
10197 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10198 if (VT == MVT::i32 || !Subtarget->is64Bit())
10199 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10200 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10201 case 'f': // FP Stack registers.
10202 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10203 // value to the correct fpstack register class.
10204 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10205 return std::make_pair(0U, X86::RFP32RegisterClass);
10206 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10207 return std::make_pair(0U, X86::RFP64RegisterClass);
10208 return std::make_pair(0U, X86::RFP80RegisterClass);
10209 case 'y': // MMX_REGS if MMX allowed.
10210 if (!Subtarget->hasMMX()) break;
10211 return std::make_pair(0U, X86::VR64RegisterClass);
10212 case 'Y': // SSE_REGS if SSE2 allowed
10213 if (!Subtarget->hasSSE2()) break;
10215 case 'x': // SSE_REGS if SSE1 allowed
10216 if (!Subtarget->hasSSE1()) break;
10218 switch (VT.getSimpleVT().SimpleTy) {
10220 // Scalar SSE types.
10223 return std::make_pair(0U, X86::FR32RegisterClass);
10226 return std::make_pair(0U, X86::FR64RegisterClass);
10234 return std::make_pair(0U, X86::VR128RegisterClass);
10240 // Use the default implementation in TargetLowering to convert the register
10241 // constraint into a member of a register class.
10242 std::pair<unsigned, const TargetRegisterClass*> Res;
10243 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10245 // Not found as a standard register?
10246 if (Res.second == 0) {
10247 // Map st(0) -> st(7) -> ST0
10248 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10249 tolower(Constraint[1]) == 's' &&
10250 tolower(Constraint[2]) == 't' &&
10251 Constraint[3] == '(' &&
10252 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10253 Constraint[5] == ')' &&
10254 Constraint[6] == '}') {
10256 Res.first = X86::ST0+Constraint[4]-'0';
10257 Res.second = X86::RFP80RegisterClass;
10261 // GCC allows "st(0)" to be called just plain "st".
10262 if (StringRef("{st}").equals_lower(Constraint)) {
10263 Res.first = X86::ST0;
10264 Res.second = X86::RFP80RegisterClass;
10269 if (StringRef("{flags}").equals_lower(Constraint)) {
10270 Res.first = X86::EFLAGS;
10271 Res.second = X86::CCRRegisterClass;
10275 // 'A' means EAX + EDX.
10276 if (Constraint == "A") {
10277 Res.first = X86::EAX;
10278 Res.second = X86::GR32_ADRegisterClass;
10284 // Otherwise, check to see if this is a register class of the wrong value
10285 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10286 // turn into {ax},{dx}.
10287 if (Res.second->hasType(VT))
10288 return Res; // Correct type already, nothing to do.
10290 // All of the single-register GCC register classes map their values onto
10291 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10292 // really want an 8-bit or 32-bit register, map to the appropriate register
10293 // class and return the appropriate register.
10294 if (Res.second == X86::GR16RegisterClass) {
10295 if (VT == MVT::i8) {
10296 unsigned DestReg = 0;
10297 switch (Res.first) {
10299 case X86::AX: DestReg = X86::AL; break;
10300 case X86::DX: DestReg = X86::DL; break;
10301 case X86::CX: DestReg = X86::CL; break;
10302 case X86::BX: DestReg = X86::BL; break;
10305 Res.first = DestReg;
10306 Res.second = X86::GR8RegisterClass;
10308 } else if (VT == MVT::i32) {
10309 unsigned DestReg = 0;
10310 switch (Res.first) {
10312 case X86::AX: DestReg = X86::EAX; break;
10313 case X86::DX: DestReg = X86::EDX; break;
10314 case X86::CX: DestReg = X86::ECX; break;
10315 case X86::BX: DestReg = X86::EBX; break;
10316 case X86::SI: DestReg = X86::ESI; break;
10317 case X86::DI: DestReg = X86::EDI; break;
10318 case X86::BP: DestReg = X86::EBP; break;
10319 case X86::SP: DestReg = X86::ESP; break;
10322 Res.first = DestReg;
10323 Res.second = X86::GR32RegisterClass;
10325 } else if (VT == MVT::i64) {
10326 unsigned DestReg = 0;
10327 switch (Res.first) {
10329 case X86::AX: DestReg = X86::RAX; break;
10330 case X86::DX: DestReg = X86::RDX; break;
10331 case X86::CX: DestReg = X86::RCX; break;
10332 case X86::BX: DestReg = X86::RBX; break;
10333 case X86::SI: DestReg = X86::RSI; break;
10334 case X86::DI: DestReg = X86::RDI; break;
10335 case X86::BP: DestReg = X86::RBP; break;
10336 case X86::SP: DestReg = X86::RSP; break;
10339 Res.first = DestReg;
10340 Res.second = X86::GR64RegisterClass;
10343 } else if (Res.second == X86::FR32RegisterClass ||
10344 Res.second == X86::FR64RegisterClass ||
10345 Res.second == X86::VR128RegisterClass) {
10346 // Handle references to XMM physical registers that got mapped into the
10347 // wrong class. This can happen with constraints like {xmm0} where the
10348 // target independent register mapper will just pick the first match it can
10349 // find, ignoring the required type.
10350 if (VT == MVT::f32)
10351 Res.second = X86::FR32RegisterClass;
10352 else if (VT == MVT::f64)
10353 Res.second = X86::FR64RegisterClass;
10354 else if (X86::VR128RegisterClass->hasType(VT))
10355 Res.second = X86::VR128RegisterClass;