Add 8-bit regclass and pattern for sext_inreg
[llvm/msp430.git] / lib / Target / X86 / X86ISelLowering.cpp
blob72aadef384fb9ad5a4f052d03cfcc7380dcda77f
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
13 //===----------------------------------------------------------------------===//
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/Support/CommandLine.h"
42 using namespace llvm;
44 static cl::opt<bool>
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
47 // Forward declarations.
48 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
49 SDValue V2);
51 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
52 : TargetLowering(TM) {
53 Subtarget = &TM.getSubtarget<X86Subtarget>();
54 X86ScalarSSEf64 = Subtarget->hasSSE2();
55 X86ScalarSSEf32 = Subtarget->hasSSE1();
56 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
58 bool Fast = false;
60 RegInfo = TM.getRegisterInfo();
61 TD = getTargetData();
63 // Set up the TargetLowering object.
65 // X86 is weird, it always uses i8 for shift amounts and setcc results.
66 setShiftAmountType(MVT::i8);
67 setBooleanContents(ZeroOrOneBooleanContent);
68 setSchedulingPreference(SchedulingForRegPressure);
69 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
70 setStackPointerRegisterToSaveRestore(X86StackPtr);
72 if (Subtarget->isTargetDarwin()) {
73 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
74 setUseUnderscoreSetJmp(false);
75 setUseUnderscoreLongJmp(false);
76 } else if (Subtarget->isTargetMingw()) {
77 // MS runtime is weird: it exports _setjmp, but longjmp!
78 setUseUnderscoreSetJmp(true);
79 setUseUnderscoreLongJmp(false);
80 } else {
81 setUseUnderscoreSetJmp(true);
82 setUseUnderscoreLongJmp(true);
85 // Set up the register classes.
86 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
87 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
88 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
89 if (Subtarget->is64Bit())
90 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
92 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
94 // We don't accept any truncstore of integer registers.
95 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
96 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
97 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
98 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
99 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
100 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
102 // SETOEQ and SETUNE require checking two conditions.
103 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
104 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
105 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
107 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
108 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
110 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
111 // operation.
112 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
114 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
116 if (Subtarget->is64Bit()) {
117 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
118 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
119 } else {
120 if (!UseSoftFloat && !NoImplicitFloat && X86ScalarSSEf64) {
121 // We have an impenetrably clever algorithm for ui64->double only.
122 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
124 // We have faster algorithm for ui32->single only.
125 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
126 } else {
127 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
131 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
132 // this operation.
133 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
134 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
136 if (!UseSoftFloat && !NoImplicitFloat) {
137 // SSE has no i16 to fp conversion, only i32
138 if (X86ScalarSSEf32) {
139 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
140 // f32 and f64 cases are Legal, f80 case is not
141 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
142 } else {
143 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
144 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
146 } else {
147 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
148 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
151 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
152 // are Legal, f80 is custom lowered.
153 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
154 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
156 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
157 // this operation.
158 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
159 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
161 if (X86ScalarSSEf32) {
162 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
163 // f32 and f64 cases are Legal, f80 case is not
164 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
165 } else {
166 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
167 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
170 // Handle FP_TO_UINT by promoting the destination to a larger signed
171 // conversion.
172 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
173 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
174 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
176 if (Subtarget->is64Bit()) {
177 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
178 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
179 } else {
180 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
181 // Expand FP_TO_UINT into a select.
182 // FIXME: We would like to use a Custom expander here eventually to do
183 // the optimal thing for SSE vs. the default expansion in the legalizer.
184 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
185 else
186 // With SSE3 we can use fisttpll to convert to a signed i64.
187 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
190 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
191 if (!X86ScalarSSEf64) {
192 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
193 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
196 // Scalar integer divide and remainder are lowered to use operations that
197 // produce two results, to match the available instructions. This exposes
198 // the two-result form to trivial CSE, which is able to combine x/y and x%y
199 // into a single instruction.
201 // Scalar integer multiply-high is also lowered to use two-result
202 // operations, to match the available instructions. However, plain multiply
203 // (low) operations are left as Legal, as there are single-result
204 // instructions for this in x86. Using the two-result multiply instructions
205 // when both high and low results are needed must be arranged by dagcombine.
206 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
207 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
208 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
209 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
210 setOperationAction(ISD::SREM , MVT::i8 , Expand);
211 setOperationAction(ISD::UREM , MVT::i8 , Expand);
212 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
213 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
214 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
215 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
216 setOperationAction(ISD::SREM , MVT::i16 , Expand);
217 setOperationAction(ISD::UREM , MVT::i16 , Expand);
218 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
219 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
220 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
221 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
222 setOperationAction(ISD::SREM , MVT::i32 , Expand);
223 setOperationAction(ISD::UREM , MVT::i32 , Expand);
224 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
225 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
226 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
227 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
228 setOperationAction(ISD::SREM , MVT::i64 , Expand);
229 setOperationAction(ISD::UREM , MVT::i64 , Expand);
231 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
232 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
233 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
234 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
235 if (Subtarget->is64Bit())
236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
240 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
241 setOperationAction(ISD::FREM , MVT::f32 , Expand);
242 setOperationAction(ISD::FREM , MVT::f64 , Expand);
243 setOperationAction(ISD::FREM , MVT::f80 , Expand);
244 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
246 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
247 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
248 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
249 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
250 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
251 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
252 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
253 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
254 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
255 if (Subtarget->is64Bit()) {
256 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
257 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
258 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
261 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
262 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
264 // These should be promoted to a larger select which is supported.
265 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
266 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
267 // X86 wants to expand cmov itself.
268 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
269 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
270 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
271 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
272 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
273 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
274 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
275 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
276 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
277 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
278 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
279 if (Subtarget->is64Bit()) {
280 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
281 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
283 // X86 ret instruction may pop stack.
284 setOperationAction(ISD::RET , MVT::Other, Custom);
285 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
287 // Darwin ABI issue.
288 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
289 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
290 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
291 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
292 if (Subtarget->is64Bit())
293 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
294 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
295 if (Subtarget->is64Bit()) {
296 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
297 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
298 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
299 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
301 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
302 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
303 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
304 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
305 if (Subtarget->is64Bit()) {
306 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
307 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
308 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
311 if (Subtarget->hasSSE1())
312 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
314 if (!Subtarget->hasSSE2())
315 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
317 // Expand certain atomics
318 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
319 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
320 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
321 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
328 if (!Subtarget->is64Bit()) {
329 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
330 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
331 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
332 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
333 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
334 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
335 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
338 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
339 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
340 // FIXME - use subtarget debug flags
341 if (!Subtarget->isTargetDarwin() &&
342 !Subtarget->isTargetELF() &&
343 !Subtarget->isTargetCygMing()) {
344 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
345 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
348 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
349 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
350 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
351 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
352 if (Subtarget->is64Bit()) {
353 setExceptionPointerRegister(X86::RAX);
354 setExceptionSelectorRegister(X86::RDX);
355 } else {
356 setExceptionPointerRegister(X86::EAX);
357 setExceptionSelectorRegister(X86::EDX);
359 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
360 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
362 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
364 setOperationAction(ISD::TRAP, MVT::Other, Legal);
366 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
367 setOperationAction(ISD::VASTART , MVT::Other, Custom);
368 setOperationAction(ISD::VAEND , MVT::Other, Expand);
369 if (Subtarget->is64Bit()) {
370 setOperationAction(ISD::VAARG , MVT::Other, Custom);
371 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
372 } else {
373 setOperationAction(ISD::VAARG , MVT::Other, Expand);
374 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
377 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
378 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
379 if (Subtarget->is64Bit())
380 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
381 if (Subtarget->isTargetCygMing())
382 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
383 else
384 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
386 if (!UseSoftFloat && X86ScalarSSEf64) {
387 // f32 and f64 use SSE.
388 // Set up the FP register classes.
389 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
390 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
392 // Use ANDPD to simulate FABS.
393 setOperationAction(ISD::FABS , MVT::f64, Custom);
394 setOperationAction(ISD::FABS , MVT::f32, Custom);
396 // Use XORP to simulate FNEG.
397 setOperationAction(ISD::FNEG , MVT::f64, Custom);
398 setOperationAction(ISD::FNEG , MVT::f32, Custom);
400 // Use ANDPD and ORPD to simulate FCOPYSIGN.
401 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
402 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
404 // We don't support sin/cos/fmod
405 setOperationAction(ISD::FSIN , MVT::f64, Expand);
406 setOperationAction(ISD::FCOS , MVT::f64, Expand);
407 setOperationAction(ISD::FSIN , MVT::f32, Expand);
408 setOperationAction(ISD::FCOS , MVT::f32, Expand);
410 // Expand FP immediates into loads from the stack, except for the special
411 // cases we handle.
412 addLegalFPImmediate(APFloat(+0.0)); // xorpd
413 addLegalFPImmediate(APFloat(+0.0f)); // xorps
415 // Floating truncations from f80 and extensions to f80 go through memory.
416 // If optimizing, we lie about this though and handle it in
417 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
418 if (Fast) {
419 setConvertAction(MVT::f32, MVT::f80, Expand);
420 setConvertAction(MVT::f64, MVT::f80, Expand);
421 setConvertAction(MVT::f80, MVT::f32, Expand);
422 setConvertAction(MVT::f80, MVT::f64, Expand);
424 } else if (!UseSoftFloat && X86ScalarSSEf32) {
425 // Use SSE for f32, x87 for f64.
426 // Set up the FP register classes.
427 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
428 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
430 // Use ANDPS to simulate FABS.
431 setOperationAction(ISD::FABS , MVT::f32, Custom);
433 // Use XORP to simulate FNEG.
434 setOperationAction(ISD::FNEG , MVT::f32, Custom);
436 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
438 // Use ANDPS and ORPS to simulate FCOPYSIGN.
439 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
440 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
442 // We don't support sin/cos/fmod
443 setOperationAction(ISD::FSIN , MVT::f32, Expand);
444 setOperationAction(ISD::FCOS , MVT::f32, Expand);
446 // Special cases we handle for FP constants.
447 addLegalFPImmediate(APFloat(+0.0f)); // xorps
448 addLegalFPImmediate(APFloat(+0.0)); // FLD0
449 addLegalFPImmediate(APFloat(+1.0)); // FLD1
450 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
451 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
453 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
454 // this though and handle it in InstructionSelectPreprocess so that
455 // dagcombine2 can hack on these.
456 if (Fast) {
457 setConvertAction(MVT::f32, MVT::f64, Expand);
458 setConvertAction(MVT::f32, MVT::f80, Expand);
459 setConvertAction(MVT::f80, MVT::f32, Expand);
460 setConvertAction(MVT::f64, MVT::f32, Expand);
461 // And x87->x87 truncations also.
462 setConvertAction(MVT::f80, MVT::f64, Expand);
465 if (!UnsafeFPMath) {
466 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
467 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
469 } else if (!UseSoftFloat) {
470 // f32 and f64 in x87.
471 // Set up the FP register classes.
472 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
473 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
475 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
476 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
477 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
478 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
480 // Floating truncations go through memory. If optimizing, we lie about
481 // this though and handle it in InstructionSelectPreprocess so that
482 // dagcombine2 can hack on these.
483 if (Fast) {
484 setConvertAction(MVT::f80, MVT::f32, Expand);
485 setConvertAction(MVT::f64, MVT::f32, Expand);
486 setConvertAction(MVT::f80, MVT::f64, Expand);
489 if (!UnsafeFPMath) {
490 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
491 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
493 addLegalFPImmediate(APFloat(+0.0)); // FLD0
494 addLegalFPImmediate(APFloat(+1.0)); // FLD1
495 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
496 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
497 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
498 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
499 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
500 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
503 // Long double always uses X87.
504 if (!UseSoftFloat) {
505 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
506 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
507 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
509 bool ignored;
510 APFloat TmpFlt(+0.0);
511 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
512 &ignored);
513 addLegalFPImmediate(TmpFlt); // FLD0
514 TmpFlt.changeSign();
515 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
516 APFloat TmpFlt2(+1.0);
517 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
518 &ignored);
519 addLegalFPImmediate(TmpFlt2); // FLD1
520 TmpFlt2.changeSign();
521 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
524 if (!UnsafeFPMath) {
525 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
526 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
530 // Always use a library call for pow.
531 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
532 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
533 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
535 setOperationAction(ISD::FLOG, MVT::f80, Expand);
536 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
537 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
538 setOperationAction(ISD::FEXP, MVT::f80, Expand);
539 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
541 // First set operation action for all vector types to either promote
542 // (for widening) or expand (for scalarization). Then we will selectively
543 // turn on ones that can be effectively codegen'd.
544 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
545 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
546 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
561 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
591 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
592 // with -msoft-float, disable use of MMX as well.
593 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
594 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
595 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
596 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
597 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
598 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
600 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
601 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
602 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
603 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
605 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
606 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
607 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
608 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
610 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
611 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
613 setOperationAction(ISD::AND, MVT::v8i8, Promote);
614 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
615 setOperationAction(ISD::AND, MVT::v4i16, Promote);
616 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
617 setOperationAction(ISD::AND, MVT::v2i32, Promote);
618 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
619 setOperationAction(ISD::AND, MVT::v1i64, Legal);
621 setOperationAction(ISD::OR, MVT::v8i8, Promote);
622 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
623 setOperationAction(ISD::OR, MVT::v4i16, Promote);
624 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
625 setOperationAction(ISD::OR, MVT::v2i32, Promote);
626 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
627 setOperationAction(ISD::OR, MVT::v1i64, Legal);
629 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
630 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
631 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
632 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
633 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
634 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
635 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
637 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
638 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
639 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
640 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
641 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
642 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
643 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
644 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
645 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
647 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
648 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
649 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
650 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
651 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
653 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
654 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
656 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
658 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
659 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
660 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
661 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
663 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
665 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
666 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
667 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
668 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
669 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
670 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
673 if (!UseSoftFloat && Subtarget->hasSSE1()) {
674 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
676 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
677 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
678 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
679 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
680 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
681 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
682 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
683 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
684 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
685 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
686 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
687 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
690 if (!UseSoftFloat && Subtarget->hasSSE2()) {
691 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
693 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
694 // registers cannot be used even for integer operations.
695 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
696 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
697 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
698 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
700 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
701 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
702 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
703 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
704 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
705 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
706 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
707 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
708 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
709 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
710 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
711 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
712 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
713 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
714 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
715 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
717 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
718 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
719 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
720 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
722 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
723 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
724 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
725 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
726 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
728 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
729 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
730 MVT VT = (MVT::SimpleValueType)i;
731 // Do not attempt to custom lower non-power-of-2 vectors
732 if (!isPowerOf2_32(VT.getVectorNumElements()))
733 continue;
734 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
735 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
739 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
740 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
741 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
742 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
743 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
744 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
746 if (Subtarget->is64Bit()) {
747 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
748 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
751 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
752 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
753 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
754 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
755 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
756 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
757 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
758 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
759 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
760 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
761 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
762 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
765 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
767 // Custom lower v2i64 and v2f64 selects.
768 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
769 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
770 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
771 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
775 if (Subtarget->hasSSE41()) {
776 // FIXME: Do we need to handle scalar-to-vector here?
777 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
779 // i8 and i16 vectors are custom , because the source register and source
780 // source memory operand types are not the same width. f32 vectors are
781 // custom since the immediate controlling the insert encodes additional
782 // information.
783 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
784 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
785 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
786 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
788 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
790 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
791 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
793 if (Subtarget->is64Bit()) {
794 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
799 if (Subtarget->hasSSE42()) {
800 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
803 // We want to custom lower some of our intrinsics.
804 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
806 // Add/Sub/Mul with overflow operations are custom lowered.
807 setOperationAction(ISD::SADDO, MVT::i32, Custom);
808 setOperationAction(ISD::SADDO, MVT::i64, Custom);
809 setOperationAction(ISD::UADDO, MVT::i32, Custom);
810 setOperationAction(ISD::UADDO, MVT::i64, Custom);
811 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
812 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
813 setOperationAction(ISD::USUBO, MVT::i32, Custom);
814 setOperationAction(ISD::USUBO, MVT::i64, Custom);
815 setOperationAction(ISD::SMULO, MVT::i32, Custom);
816 setOperationAction(ISD::SMULO, MVT::i64, Custom);
817 setOperationAction(ISD::UMULO, MVT::i32, Custom);
818 setOperationAction(ISD::UMULO, MVT::i64, Custom);
820 if (!Subtarget->is64Bit()) {
821 // These libcalls are not available in 32-bit.
822 setLibcallName(RTLIB::SHL_I128, 0);
823 setLibcallName(RTLIB::SRL_I128, 0);
824 setLibcallName(RTLIB::SRA_I128, 0);
827 // We have target-specific dag combine patterns for the following nodes:
828 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
829 setTargetDAGCombine(ISD::BUILD_VECTOR);
830 setTargetDAGCombine(ISD::SELECT);
831 setTargetDAGCombine(ISD::SHL);
832 setTargetDAGCombine(ISD::SRA);
833 setTargetDAGCombine(ISD::SRL);
834 setTargetDAGCombine(ISD::STORE);
835 if (Subtarget->is64Bit())
836 setTargetDAGCombine(ISD::MUL);
838 computeRegisterProperties();
840 // FIXME: These should be based on subtarget info. Plus, the values should
841 // be smaller when we are in optimizing for size mode.
842 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
843 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
844 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
845 allowUnalignedMemoryAccesses = true; // x86 supports it!
846 setPrefLoopAlignment(16);
850 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
851 return MVT::i8;
855 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
856 /// the desired ByVal argument alignment.
857 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
858 if (MaxAlign == 16)
859 return;
860 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
861 if (VTy->getBitWidth() == 128)
862 MaxAlign = 16;
863 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
864 unsigned EltAlign = 0;
865 getMaxByValAlign(ATy->getElementType(), EltAlign);
866 if (EltAlign > MaxAlign)
867 MaxAlign = EltAlign;
868 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
869 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
870 unsigned EltAlign = 0;
871 getMaxByValAlign(STy->getElementType(i), EltAlign);
872 if (EltAlign > MaxAlign)
873 MaxAlign = EltAlign;
874 if (MaxAlign == 16)
875 break;
878 return;
881 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
882 /// function arguments in the caller parameter area. For X86, aggregates
883 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
884 /// are at 4-byte boundaries.
885 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
886 if (Subtarget->is64Bit()) {
887 // Max of 8 and alignment of type.
888 unsigned TyAlign = TD->getABITypeAlignment(Ty);
889 if (TyAlign > 8)
890 return TyAlign;
891 return 8;
894 unsigned Align = 4;
895 if (Subtarget->hasSSE1())
896 getMaxByValAlign(Ty, Align);
897 return Align;
900 /// getOptimalMemOpType - Returns the target specific optimal type for load
901 /// and store operations as a result of memset, memcpy, and memmove
902 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
903 /// determining it.
905 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
906 bool isSrcConst, bool isSrcStr) const {
907 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
908 // linux. This is because the stack realignment code can't handle certain
909 // cases like PR2962. This should be removed when PR2962 is fixed.
910 if (!NoImplicitFloat && Subtarget->getStackAlignment() >= 16) {
911 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
912 return MVT::v4i32;
913 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
914 return MVT::v4f32;
916 if (Subtarget->is64Bit() && Size >= 8)
917 return MVT::i64;
918 return MVT::i32;
921 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
922 /// jumptable.
923 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
924 SelectionDAG &DAG) const {
925 if (usesGlobalOffsetTable())
926 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
927 if (!Subtarget->isPICStyleRIPRel())
928 // This doesn't have DebugLoc associated with it, but is not really the
929 // same as a Register.
930 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
931 getPointerTy());
932 return Table;
935 //===----------------------------------------------------------------------===//
936 // Return Value Calling Convention Implementation
937 //===----------------------------------------------------------------------===//
939 #include "X86GenCallingConv.inc"
941 /// LowerRET - Lower an ISD::RET node.
942 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
943 DebugLoc dl = Op.getDebugLoc();
944 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
946 SmallVector<CCValAssign, 16> RVLocs;
947 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
948 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
949 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
950 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
952 // If this is the first return lowered for this function, add the regs to the
953 // liveout set for the function.
954 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
955 for (unsigned i = 0; i != RVLocs.size(); ++i)
956 if (RVLocs[i].isRegLoc())
957 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
959 SDValue Chain = Op.getOperand(0);
961 // Handle tail call return.
962 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
963 if (Chain.getOpcode() == X86ISD::TAILCALL) {
964 SDValue TailCall = Chain;
965 SDValue TargetAddress = TailCall.getOperand(1);
966 SDValue StackAdjustment = TailCall.getOperand(2);
967 assert(((TargetAddress.getOpcode() == ISD::Register &&
968 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
969 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
970 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
971 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
972 "Expecting an global address, external symbol, or register");
973 assert(StackAdjustment.getOpcode() == ISD::Constant &&
974 "Expecting a const value");
976 SmallVector<SDValue,8> Operands;
977 Operands.push_back(Chain.getOperand(0));
978 Operands.push_back(TargetAddress);
979 Operands.push_back(StackAdjustment);
980 // Copy registers used by the call. Last operand is a flag so it is not
981 // copied.
982 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
983 Operands.push_back(Chain.getOperand(i));
985 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
986 Operands.size());
989 // Regular return.
990 SDValue Flag;
992 SmallVector<SDValue, 6> RetOps;
993 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
994 // Operand #1 = Bytes To Pop
995 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
997 // Copy the result values into the output registers.
998 for (unsigned i = 0; i != RVLocs.size(); ++i) {
999 CCValAssign &VA = RVLocs[i];
1000 assert(VA.isRegLoc() && "Can only return in registers!");
1001 SDValue ValToCopy = Op.getOperand(i*2+1);
1003 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1004 // the RET instruction and handled by the FP Stackifier.
1005 if (VA.getLocReg() == X86::ST0 ||
1006 VA.getLocReg() == X86::ST1) {
1007 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1008 // change the value to the FP stack register class.
1009 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1010 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1011 RetOps.push_back(ValToCopy);
1012 // Don't emit a copytoreg.
1013 continue;
1016 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1017 // which is returned in RAX / RDX.
1018 if (Subtarget->is64Bit()) {
1019 MVT ValVT = ValToCopy.getValueType();
1020 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1021 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1022 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1023 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1027 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1028 Flag = Chain.getValue(1);
1031 // The x86-64 ABI for returning structs by value requires that we copy
1032 // the sret argument into %rax for the return. We saved the argument into
1033 // a virtual register in the entry block, so now we copy the value out
1034 // and into %rax.
1035 if (Subtarget->is64Bit() &&
1036 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1037 MachineFunction &MF = DAG.getMachineFunction();
1038 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1039 unsigned Reg = FuncInfo->getSRetReturnReg();
1040 if (!Reg) {
1041 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1042 FuncInfo->setSRetReturnReg(Reg);
1044 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1046 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1047 Flag = Chain.getValue(1);
1050 RetOps[0] = Chain; // Update chain.
1052 // Add the flag if we have it.
1053 if (Flag.getNode())
1054 RetOps.push_back(Flag);
1056 return DAG.getNode(X86ISD::RET_FLAG, dl,
1057 MVT::Other, &RetOps[0], RetOps.size());
1061 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1062 /// appropriate copies out of appropriate physical registers. This assumes that
1063 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1064 /// being lowered. The returns a SDNode with the same number of values as the
1065 /// ISD::CALL.
1066 SDNode *X86TargetLowering::
1067 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1068 unsigned CallingConv, SelectionDAG &DAG) {
1070 DebugLoc dl = TheCall->getDebugLoc();
1071 // Assign locations to each value returned by this call.
1072 SmallVector<CCValAssign, 16> RVLocs;
1073 bool isVarArg = TheCall->isVarArg();
1074 bool Is64Bit = Subtarget->is64Bit();
1075 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1076 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1078 SmallVector<SDValue, 8> ResultVals;
1080 // Copy all of the result registers out of their specified physreg.
1081 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1082 CCValAssign &VA = RVLocs[i];
1083 MVT CopyVT = VA.getValVT();
1085 // If this is x86-64, and we disabled SSE, we can't return FP values
1086 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1087 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1088 cerr << "SSE register return with SSE disabled\n";
1089 exit(1);
1092 // If this is a call to a function that returns an fp value on the floating
1093 // point stack, but where we prefer to use the value in xmm registers, copy
1094 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1095 if ((VA.getLocReg() == X86::ST0 ||
1096 VA.getLocReg() == X86::ST1) &&
1097 isScalarFPTypeInSSEReg(VA.getValVT())) {
1098 CopyVT = MVT::f80;
1101 SDValue Val;
1102 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1103 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1104 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1105 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1106 MVT::v2i64, InFlag).getValue(1);
1107 Val = Chain.getValue(0);
1108 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1109 Val, DAG.getConstant(0, MVT::i64));
1110 } else {
1111 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1112 MVT::i64, InFlag).getValue(1);
1113 Val = Chain.getValue(0);
1115 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1116 } else {
1117 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1118 CopyVT, InFlag).getValue(1);
1119 Val = Chain.getValue(0);
1121 InFlag = Chain.getValue(2);
1123 if (CopyVT != VA.getValVT()) {
1124 // Round the F80 the right size, which also moves to the appropriate xmm
1125 // register.
1126 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1127 // This truncation won't change the value.
1128 DAG.getIntPtrConstant(1));
1131 ResultVals.push_back(Val);
1134 // Merge everything together with a MERGE_VALUES node.
1135 ResultVals.push_back(Chain);
1136 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1137 &ResultVals[0], ResultVals.size()).getNode();
1141 //===----------------------------------------------------------------------===//
1142 // C & StdCall & Fast Calling Convention implementation
1143 //===----------------------------------------------------------------------===//
1144 // StdCall calling convention seems to be standard for many Windows' API
1145 // routines and around. It differs from C calling convention just a little:
1146 // callee should clean up the stack, not caller. Symbols should be also
1147 // decorated in some fancy way :) It doesn't support any vector arguments.
1148 // For info on fast calling convention see Fast Calling Convention (tail call)
1149 // implementation LowerX86_32FastCCCallTo.
1151 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1152 /// semantics.
1153 static bool CallIsStructReturn(CallSDNode *TheCall) {
1154 unsigned NumOps = TheCall->getNumArgs();
1155 if (!NumOps)
1156 return false;
1158 return TheCall->getArgFlags(0).isSRet();
1161 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1162 /// return semantics.
1163 static bool ArgsAreStructReturn(SDValue Op) {
1164 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1165 if (!NumArgs)
1166 return false;
1168 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1171 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1172 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1173 /// calls.
1174 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1175 if (IsVarArg)
1176 return false;
1178 switch (CallingConv) {
1179 default:
1180 return false;
1181 case CallingConv::X86_StdCall:
1182 return !Subtarget->is64Bit();
1183 case CallingConv::X86_FastCall:
1184 return !Subtarget->is64Bit();
1185 case CallingConv::Fast:
1186 return PerformTailCallOpt;
1190 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1191 /// given CallingConvention value.
1192 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1193 if (Subtarget->is64Bit()) {
1194 if (Subtarget->isTargetWin64())
1195 return CC_X86_Win64_C;
1196 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1197 return CC_X86_64_TailCall;
1198 else
1199 return CC_X86_64_C;
1202 if (CC == CallingConv::X86_FastCall)
1203 return CC_X86_32_FastCall;
1204 else if (CC == CallingConv::Fast)
1205 return CC_X86_32_FastCC;
1206 else
1207 return CC_X86_32_C;
1210 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1211 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1212 NameDecorationStyle
1213 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1214 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1215 if (CC == CallingConv::X86_FastCall)
1216 return FastCall;
1217 else if (CC == CallingConv::X86_StdCall)
1218 return StdCall;
1219 return None;
1223 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1224 /// in a register before calling.
1225 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1226 return !IsTailCall && !Is64Bit &&
1227 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1228 Subtarget->isPICStyleGOT();
1231 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1232 /// address to be loaded in a register.
1233 bool
1234 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1235 return !Is64Bit && IsTailCall &&
1236 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1237 Subtarget->isPICStyleGOT();
1240 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1241 /// by "Src" to address "Dst" with size and alignment information specified by
1242 /// the specific parameter attribute. The copy will be passed as a byval
1243 /// function parameter.
1244 static SDValue
1245 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1246 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1247 DebugLoc dl) {
1248 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1249 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1250 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1253 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1254 const CCValAssign &VA,
1255 MachineFrameInfo *MFI,
1256 unsigned CC,
1257 SDValue Root, unsigned i) {
1258 // Create the nodes corresponding to a load from this parameter slot.
1259 ISD::ArgFlagsTy Flags =
1260 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1261 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1262 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1264 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1265 // changed with more analysis.
1266 // In case of tail call optimization mark all arguments mutable. Since they
1267 // could be overwritten by lowering of arguments in case of a tail call.
1268 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1269 VA.getLocMemOffset(), isImmutable);
1270 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1271 if (Flags.isByVal())
1272 return FIN;
1273 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1274 PseudoSourceValue::getFixedStack(FI), 0);
1277 SDValue
1278 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1279 MachineFunction &MF = DAG.getMachineFunction();
1280 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1281 DebugLoc dl = Op.getDebugLoc();
1283 const Function* Fn = MF.getFunction();
1284 if (Fn->hasExternalLinkage() &&
1285 Subtarget->isTargetCygMing() &&
1286 Fn->getName() == "main")
1287 FuncInfo->setForceFramePointer(true);
1289 // Decorate the function name.
1290 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1292 MachineFrameInfo *MFI = MF.getFrameInfo();
1293 SDValue Root = Op.getOperand(0);
1294 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1295 unsigned CC = MF.getFunction()->getCallingConv();
1296 bool Is64Bit = Subtarget->is64Bit();
1297 bool IsWin64 = Subtarget->isTargetWin64();
1299 assert(!(isVarArg && CC == CallingConv::Fast) &&
1300 "Var args not supported with calling convention fastcc");
1302 // Assign locations to all of the incoming arguments.
1303 SmallVector<CCValAssign, 16> ArgLocs;
1304 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1305 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1307 SmallVector<SDValue, 8> ArgValues;
1308 unsigned LastVal = ~0U;
1309 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1310 CCValAssign &VA = ArgLocs[i];
1311 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1312 // places.
1313 assert(VA.getValNo() != LastVal &&
1314 "Don't support value assigned to multiple locs yet");
1315 LastVal = VA.getValNo();
1317 if (VA.isRegLoc()) {
1318 MVT RegVT = VA.getLocVT();
1319 TargetRegisterClass *RC = NULL;
1320 if (RegVT == MVT::i32)
1321 RC = X86::GR32RegisterClass;
1322 else if (Is64Bit && RegVT == MVT::i64)
1323 RC = X86::GR64RegisterClass;
1324 else if (RegVT == MVT::f32)
1325 RC = X86::FR32RegisterClass;
1326 else if (RegVT == MVT::f64)
1327 RC = X86::FR64RegisterClass;
1328 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1329 RC = X86::VR128RegisterClass;
1330 else if (RegVT.isVector()) {
1331 assert(RegVT.getSizeInBits() == 64);
1332 if (!Is64Bit)
1333 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1334 else {
1335 // Darwin calling convention passes MMX values in either GPRs or
1336 // XMMs in x86-64. Other targets pass them in memory.
1337 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1338 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1339 RegVT = MVT::v2i64;
1340 } else {
1341 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1342 RegVT = MVT::i64;
1345 } else {
1346 assert(0 && "Unknown argument type!");
1349 unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1350 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1352 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1353 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1354 // right size.
1355 if (VA.getLocInfo() == CCValAssign::SExt)
1356 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1357 DAG.getValueType(VA.getValVT()));
1358 else if (VA.getLocInfo() == CCValAssign::ZExt)
1359 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1360 DAG.getValueType(VA.getValVT()));
1362 if (VA.getLocInfo() != CCValAssign::Full)
1363 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1365 // Handle MMX values passed in GPRs.
1366 if (Is64Bit && RegVT != VA.getLocVT()) {
1367 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1368 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1369 else if (RC == X86::VR128RegisterClass) {
1370 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1371 ArgValue, DAG.getConstant(0, MVT::i64));
1372 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1376 ArgValues.push_back(ArgValue);
1377 } else {
1378 assert(VA.isMemLoc());
1379 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1383 // The x86-64 ABI for returning structs by value requires that we copy
1384 // the sret argument into %rax for the return. Save the argument into
1385 // a virtual register so that we can access it from the return points.
1386 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1387 MachineFunction &MF = DAG.getMachineFunction();
1388 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1389 unsigned Reg = FuncInfo->getSRetReturnReg();
1390 if (!Reg) {
1391 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1392 FuncInfo->setSRetReturnReg(Reg);
1394 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1395 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1398 unsigned StackSize = CCInfo.getNextStackOffset();
1399 // align stack specially for tail calls
1400 if (PerformTailCallOpt && CC == CallingConv::Fast)
1401 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1403 // If the function takes variable number of arguments, make a frame index for
1404 // the start of the first vararg value... for expansion of llvm.va_start.
1405 if (isVarArg) {
1406 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1407 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1409 if (Is64Bit) {
1410 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1412 // FIXME: We should really autogenerate these arrays
1413 static const unsigned GPR64ArgRegsWin64[] = {
1414 X86::RCX, X86::RDX, X86::R8, X86::R9
1416 static const unsigned XMMArgRegsWin64[] = {
1417 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1419 static const unsigned GPR64ArgRegs64Bit[] = {
1420 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1422 static const unsigned XMMArgRegs64Bit[] = {
1423 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1424 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1426 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1428 if (IsWin64) {
1429 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1430 GPR64ArgRegs = GPR64ArgRegsWin64;
1431 XMMArgRegs = XMMArgRegsWin64;
1432 } else {
1433 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1434 GPR64ArgRegs = GPR64ArgRegs64Bit;
1435 XMMArgRegs = XMMArgRegs64Bit;
1437 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1438 TotalNumIntRegs);
1439 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1440 TotalNumXMMRegs);
1442 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1443 "SSE register cannot be used when SSE is disabled!");
1444 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloat) &&
1445 "SSE register cannot be used when SSE is disabled!");
1446 if (UseSoftFloat || NoImplicitFloat || !Subtarget->hasSSE1())
1447 // Kernel mode asks for SSE to be disabled, so don't push them
1448 // on the stack.
1449 TotalNumXMMRegs = 0;
1451 // For X86-64, if there are vararg parameters that are passed via
1452 // registers, then we must store them to their spots on the stack so they
1453 // may be loaded by deferencing the result of va_next.
1454 VarArgsGPOffset = NumIntRegs * 8;
1455 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1456 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1457 TotalNumXMMRegs * 16, 16);
1459 // Store the integer parameter registers.
1460 SmallVector<SDValue, 8> MemOps;
1461 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1462 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1463 DAG.getIntPtrConstant(VarArgsGPOffset));
1464 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1465 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1466 X86::GR64RegisterClass);
1467 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1468 SDValue Store =
1469 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1470 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1471 MemOps.push_back(Store);
1472 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1473 DAG.getIntPtrConstant(8));
1476 // Now store the XMM (fp + vector) parameter registers.
1477 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1478 DAG.getIntPtrConstant(VarArgsFPOffset));
1479 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1480 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1481 X86::VR128RegisterClass);
1482 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1483 SDValue Store =
1484 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1485 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1486 MemOps.push_back(Store);
1487 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1488 DAG.getIntPtrConstant(16));
1490 if (!MemOps.empty())
1491 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1492 &MemOps[0], MemOps.size());
1496 ArgValues.push_back(Root);
1498 // Some CCs need callee pop.
1499 if (IsCalleePop(isVarArg, CC)) {
1500 BytesToPopOnReturn = StackSize; // Callee pops everything.
1501 BytesCallerReserves = 0;
1502 } else {
1503 BytesToPopOnReturn = 0; // Callee pops nothing.
1504 // If this is an sret function, the return should pop the hidden pointer.
1505 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1506 BytesToPopOnReturn = 4;
1507 BytesCallerReserves = StackSize;
1510 if (!Is64Bit) {
1511 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1512 if (CC == CallingConv::X86_FastCall)
1513 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1516 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1518 // Return the new list of results.
1519 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1520 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1523 SDValue
1524 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1525 const SDValue &StackPtr,
1526 const CCValAssign &VA,
1527 SDValue Chain,
1528 SDValue Arg, ISD::ArgFlagsTy Flags) {
1529 DebugLoc dl = TheCall->getDebugLoc();
1530 unsigned LocMemOffset = VA.getLocMemOffset();
1531 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1532 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1533 if (Flags.isByVal()) {
1534 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1536 return DAG.getStore(Chain, dl, Arg, PtrOff,
1537 PseudoSourceValue::getStack(), LocMemOffset);
1540 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1541 /// optimization is performed and it is required.
1542 SDValue
1543 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1544 SDValue &OutRetAddr,
1545 SDValue Chain,
1546 bool IsTailCall,
1547 bool Is64Bit,
1548 int FPDiff,
1549 DebugLoc dl) {
1550 if (!IsTailCall || FPDiff==0) return Chain;
1552 // Adjust the Return address stack slot.
1553 MVT VT = getPointerTy();
1554 OutRetAddr = getReturnAddressFrameIndex(DAG);
1556 // Load the "old" Return address.
1557 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1558 return SDValue(OutRetAddr.getNode(), 1);
1561 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1562 /// optimization is performed and it is required (FPDiff!=0).
1563 static SDValue
1564 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1565 SDValue Chain, SDValue RetAddrFrIdx,
1566 bool Is64Bit, int FPDiff, DebugLoc dl) {
1567 // Store the return address to the appropriate stack slot.
1568 if (!FPDiff) return Chain;
1569 // Calculate the new stack slot for the return address.
1570 int SlotSize = Is64Bit ? 8 : 4;
1571 int NewReturnAddrFI =
1572 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1573 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1574 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1575 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1576 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1577 return Chain;
1580 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1581 MachineFunction &MF = DAG.getMachineFunction();
1582 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1583 SDValue Chain = TheCall->getChain();
1584 unsigned CC = TheCall->getCallingConv();
1585 bool isVarArg = TheCall->isVarArg();
1586 bool IsTailCall = TheCall->isTailCall() &&
1587 CC == CallingConv::Fast && PerformTailCallOpt;
1588 SDValue Callee = TheCall->getCallee();
1589 bool Is64Bit = Subtarget->is64Bit();
1590 bool IsStructRet = CallIsStructReturn(TheCall);
1591 DebugLoc dl = TheCall->getDebugLoc();
1593 assert(!(isVarArg && CC == CallingConv::Fast) &&
1594 "Var args not supported with calling convention fastcc");
1596 // Analyze operands of the call, assigning locations to each operand.
1597 SmallVector<CCValAssign, 16> ArgLocs;
1598 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1599 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1601 // Get a count of how many bytes are to be pushed on the stack.
1602 unsigned NumBytes = CCInfo.getNextStackOffset();
1603 if (PerformTailCallOpt && CC == CallingConv::Fast)
1604 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1606 int FPDiff = 0;
1607 if (IsTailCall) {
1608 // Lower arguments at fp - stackoffset + fpdiff.
1609 unsigned NumBytesCallerPushed =
1610 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1611 FPDiff = NumBytesCallerPushed - NumBytes;
1613 // Set the delta of movement of the returnaddr stackslot.
1614 // But only set if delta is greater than previous delta.
1615 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1616 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1619 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1621 SDValue RetAddrFrIdx;
1622 // Load return adress for tail calls.
1623 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1624 FPDiff, dl);
1626 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1627 SmallVector<SDValue, 8> MemOpChains;
1628 SDValue StackPtr;
1630 // Walk the register/memloc assignments, inserting copies/loads. In the case
1631 // of tail call optimization arguments are handle later.
1632 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1633 CCValAssign &VA = ArgLocs[i];
1634 SDValue Arg = TheCall->getArg(i);
1635 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1636 bool isByVal = Flags.isByVal();
1638 // Promote the value if needed.
1639 switch (VA.getLocInfo()) {
1640 default: assert(0 && "Unknown loc info!");
1641 case CCValAssign::Full: break;
1642 case CCValAssign::SExt:
1643 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1644 break;
1645 case CCValAssign::ZExt:
1646 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1647 break;
1648 case CCValAssign::AExt:
1649 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1650 break;
1653 if (VA.isRegLoc()) {
1654 if (Is64Bit) {
1655 MVT RegVT = VA.getLocVT();
1656 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1657 switch (VA.getLocReg()) {
1658 default:
1659 break;
1660 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1661 case X86::R8: {
1662 // Special case: passing MMX values in GPR registers.
1663 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1664 break;
1666 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1667 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1668 // Special case: passing MMX values in XMM registers.
1669 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1670 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1671 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1672 break;
1676 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1677 } else {
1678 if (!IsTailCall || (IsTailCall && isByVal)) {
1679 assert(VA.isMemLoc());
1680 if (StackPtr.getNode() == 0)
1681 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1683 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1684 Chain, Arg, Flags));
1689 if (!MemOpChains.empty())
1690 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1691 &MemOpChains[0], MemOpChains.size());
1693 // Build a sequence of copy-to-reg nodes chained together with token chain
1694 // and flag operands which copy the outgoing args into registers.
1695 SDValue InFlag;
1696 // Tail call byval lowering might overwrite argument registers so in case of
1697 // tail call optimization the copies to registers are lowered later.
1698 if (!IsTailCall)
1699 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1700 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1701 RegsToPass[i].second, InFlag);
1702 InFlag = Chain.getValue(1);
1705 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1706 // GOT pointer.
1707 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1708 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1709 DAG.getNode(X86ISD::GlobalBaseReg,
1710 DebugLoc::getUnknownLoc(),
1711 getPointerTy()),
1712 InFlag);
1713 InFlag = Chain.getValue(1);
1715 // If we are tail calling and generating PIC/GOT style code load the address
1716 // of the callee into ecx. The value in ecx is used as target of the tail
1717 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1718 // calls on PIC/GOT architectures. Normally we would just put the address of
1719 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1720 // restored (since ebx is callee saved) before jumping to the target@PLT.
1721 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1722 // Note: The actual moving to ecx is done further down.
1723 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1724 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1725 !G->getGlobal()->hasProtectedVisibility())
1726 Callee = LowerGlobalAddress(Callee, DAG);
1727 else if (isa<ExternalSymbolSDNode>(Callee))
1728 Callee = LowerExternalSymbol(Callee,DAG);
1731 if (Is64Bit && isVarArg) {
1732 // From AMD64 ABI document:
1733 // For calls that may call functions that use varargs or stdargs
1734 // (prototype-less calls or calls to functions containing ellipsis (...) in
1735 // the declaration) %al is used as hidden argument to specify the number
1736 // of SSE registers used. The contents of %al do not need to match exactly
1737 // the number of registers, but must be an ubound on the number of SSE
1738 // registers used and is in the range 0 - 8 inclusive.
1740 // FIXME: Verify this on Win64
1741 // Count the number of XMM registers allocated.
1742 static const unsigned XMMArgRegs[] = {
1743 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1744 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1746 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1747 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1748 && "SSE registers cannot be used when SSE is disabled");
1750 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1751 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1752 InFlag = Chain.getValue(1);
1756 // For tail calls lower the arguments to the 'real' stack slot.
1757 if (IsTailCall) {
1758 SmallVector<SDValue, 8> MemOpChains2;
1759 SDValue FIN;
1760 int FI = 0;
1761 // Do not flag preceeding copytoreg stuff together with the following stuff.
1762 InFlag = SDValue();
1763 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1764 CCValAssign &VA = ArgLocs[i];
1765 if (!VA.isRegLoc()) {
1766 assert(VA.isMemLoc());
1767 SDValue Arg = TheCall->getArg(i);
1768 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1769 // Create frame index.
1770 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1771 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1772 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1773 FIN = DAG.getFrameIndex(FI, getPointerTy());
1775 if (Flags.isByVal()) {
1776 // Copy relative to framepointer.
1777 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1778 if (StackPtr.getNode() == 0)
1779 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1780 getPointerTy());
1781 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1783 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1784 Flags, DAG, dl));
1785 } else {
1786 // Store relative to framepointer.
1787 MemOpChains2.push_back(
1788 DAG.getStore(Chain, dl, Arg, FIN,
1789 PseudoSourceValue::getFixedStack(FI), 0));
1794 if (!MemOpChains2.empty())
1795 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1796 &MemOpChains2[0], MemOpChains2.size());
1798 // Copy arguments to their registers.
1799 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1800 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1801 RegsToPass[i].second, InFlag);
1802 InFlag = Chain.getValue(1);
1804 InFlag =SDValue();
1806 // Store the return address to the appropriate stack slot.
1807 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1808 FPDiff, dl);
1811 // If the callee is a GlobalAddress node (quite common, every direct call is)
1812 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1813 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1814 // We should use extra load for direct calls to dllimported functions in
1815 // non-JIT mode.
1816 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1817 getTargetMachine(), true))
1818 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1819 G->getOffset());
1820 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1821 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1822 } else if (IsTailCall) {
1823 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1825 Chain = DAG.getCopyToReg(Chain, dl,
1826 DAG.getRegister(Opc, getPointerTy()),
1827 Callee,InFlag);
1828 Callee = DAG.getRegister(Opc, getPointerTy());
1829 // Add register as live out.
1830 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1833 // Returns a chain & a flag for retval copy to use.
1834 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1835 SmallVector<SDValue, 8> Ops;
1837 if (IsTailCall) {
1838 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1839 DAG.getIntPtrConstant(0, true), InFlag);
1840 InFlag = Chain.getValue(1);
1842 // Returns a chain & a flag for retval copy to use.
1843 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1844 Ops.clear();
1847 Ops.push_back(Chain);
1848 Ops.push_back(Callee);
1850 if (IsTailCall)
1851 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1853 // Add argument registers to the end of the list so that they are known live
1854 // into the call.
1855 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1856 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1857 RegsToPass[i].second.getValueType()));
1859 // Add an implicit use GOT pointer in EBX.
1860 if (!IsTailCall && !Is64Bit &&
1861 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1862 Subtarget->isPICStyleGOT())
1863 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1865 // Add an implicit use of AL for x86 vararg functions.
1866 if (Is64Bit && isVarArg)
1867 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1869 if (InFlag.getNode())
1870 Ops.push_back(InFlag);
1872 if (IsTailCall) {
1873 assert(InFlag.getNode() &&
1874 "Flag must be set. Depend on flag being set in LowerRET");
1875 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1876 TheCall->getVTList(), &Ops[0], Ops.size());
1878 return SDValue(Chain.getNode(), Op.getResNo());
1881 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1882 InFlag = Chain.getValue(1);
1884 // Create the CALLSEQ_END node.
1885 unsigned NumBytesForCalleeToPush;
1886 if (IsCalleePop(isVarArg, CC))
1887 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1888 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1889 // If this is is a call to a struct-return function, the callee
1890 // pops the hidden struct pointer, so we have to push it back.
1891 // This is common for Darwin/X86, Linux & Mingw32 targets.
1892 NumBytesForCalleeToPush = 4;
1893 else
1894 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1896 // Returns a flag for retval copy to use.
1897 Chain = DAG.getCALLSEQ_END(Chain,
1898 DAG.getIntPtrConstant(NumBytes, true),
1899 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1900 true),
1901 InFlag);
1902 InFlag = Chain.getValue(1);
1904 // Handle result values, copying them out of physregs into vregs that we
1905 // return.
1906 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1907 Op.getResNo());
1911 //===----------------------------------------------------------------------===//
1912 // Fast Calling Convention (tail call) implementation
1913 //===----------------------------------------------------------------------===//
1915 // Like std call, callee cleans arguments, convention except that ECX is
1916 // reserved for storing the tail called function address. Only 2 registers are
1917 // free for argument passing (inreg). Tail call optimization is performed
1918 // provided:
1919 // * tailcallopt is enabled
1920 // * caller/callee are fastcc
1921 // On X86_64 architecture with GOT-style position independent code only local
1922 // (within module) calls are supported at the moment.
1923 // To keep the stack aligned according to platform abi the function
1924 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1925 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1926 // If a tail called function callee has more arguments than the caller the
1927 // caller needs to make sure that there is room to move the RETADDR to. This is
1928 // achieved by reserving an area the size of the argument delta right after the
1929 // original REtADDR, but before the saved framepointer or the spilled registers
1930 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1931 // stack layout:
1932 // arg1
1933 // arg2
1934 // RETADDR
1935 // [ new RETADDR
1936 // move area ]
1937 // (possible EBP)
1938 // ESI
1939 // EDI
1940 // local1 ..
1942 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1943 /// for a 16 byte align requirement.
1944 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1945 SelectionDAG& DAG) {
1946 MachineFunction &MF = DAG.getMachineFunction();
1947 const TargetMachine &TM = MF.getTarget();
1948 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1949 unsigned StackAlignment = TFI.getStackAlignment();
1950 uint64_t AlignMask = StackAlignment - 1;
1951 int64_t Offset = StackSize;
1952 uint64_t SlotSize = TD->getPointerSize();
1953 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1954 // Number smaller than 12 so just add the difference.
1955 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1956 } else {
1957 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1958 Offset = ((~AlignMask) & Offset) + StackAlignment +
1959 (StackAlignment-SlotSize);
1961 return Offset;
1964 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1965 /// following the call is a return. A function is eligible if caller/callee
1966 /// calling conventions match, currently only fastcc supports tail calls, and
1967 /// the function CALL is immediatly followed by a RET.
1968 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1969 SDValue Ret,
1970 SelectionDAG& DAG) const {
1971 if (!PerformTailCallOpt)
1972 return false;
1974 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1975 MachineFunction &MF = DAG.getMachineFunction();
1976 unsigned CallerCC = MF.getFunction()->getCallingConv();
1977 unsigned CalleeCC= TheCall->getCallingConv();
1978 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1979 SDValue Callee = TheCall->getCallee();
1980 // On x86/32Bit PIC/GOT tail calls are supported.
1981 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1982 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1983 return true;
1985 // Can only do local tail calls (in same module, hidden or protected) on
1986 // x86_64 PIC/GOT at the moment.
1987 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1988 return G->getGlobal()->hasHiddenVisibility()
1989 || G->getGlobal()->hasProtectedVisibility();
1993 return false;
1996 FastISel *
1997 X86TargetLowering::createFastISel(MachineFunction &mf,
1998 MachineModuleInfo *mmo,
1999 DwarfWriter *dw,
2000 DenseMap<const Value *, unsigned> &vm,
2001 DenseMap<const BasicBlock *,
2002 MachineBasicBlock *> &bm,
2003 DenseMap<const AllocaInst *, int> &am
2004 #ifndef NDEBUG
2005 , SmallSet<Instruction*, 8> &cil
2006 #endif
2008 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2009 #ifndef NDEBUG
2010 , cil
2011 #endif
2016 //===----------------------------------------------------------------------===//
2017 // Other Lowering Hooks
2018 //===----------------------------------------------------------------------===//
2021 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2022 MachineFunction &MF = DAG.getMachineFunction();
2023 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2024 int ReturnAddrIndex = FuncInfo->getRAIndex();
2026 if (ReturnAddrIndex == 0) {
2027 // Set up a frame object for the return address.
2028 uint64_t SlotSize = TD->getPointerSize();
2029 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2030 FuncInfo->setRAIndex(ReturnAddrIndex);
2033 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2037 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2038 /// specific condition code, returning the condition code and the LHS/RHS of the
2039 /// comparison to make.
2040 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2041 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2042 if (!isFP) {
2043 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2044 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2045 // X > -1 -> X == 0, jump !sign.
2046 RHS = DAG.getConstant(0, RHS.getValueType());
2047 return X86::COND_NS;
2048 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2049 // X < 0 -> X == 0, jump on sign.
2050 return X86::COND_S;
2051 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2052 // X < 1 -> X <= 0
2053 RHS = DAG.getConstant(0, RHS.getValueType());
2054 return X86::COND_LE;
2058 switch (SetCCOpcode) {
2059 default: assert(0 && "Invalid integer condition!");
2060 case ISD::SETEQ: return X86::COND_E;
2061 case ISD::SETGT: return X86::COND_G;
2062 case ISD::SETGE: return X86::COND_GE;
2063 case ISD::SETLT: return X86::COND_L;
2064 case ISD::SETLE: return X86::COND_LE;
2065 case ISD::SETNE: return X86::COND_NE;
2066 case ISD::SETULT: return X86::COND_B;
2067 case ISD::SETUGT: return X86::COND_A;
2068 case ISD::SETULE: return X86::COND_BE;
2069 case ISD::SETUGE: return X86::COND_AE;
2073 // First determine if it is required or is profitable to flip the operands.
2075 // If LHS is a foldable load, but RHS is not, flip the condition.
2076 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2077 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2078 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2079 std::swap(LHS, RHS);
2082 switch (SetCCOpcode) {
2083 default: break;
2084 case ISD::SETOLT:
2085 case ISD::SETOLE:
2086 case ISD::SETUGT:
2087 case ISD::SETUGE:
2088 std::swap(LHS, RHS);
2089 break;
2092 // On a floating point condition, the flags are set as follows:
2093 // ZF PF CF op
2094 // 0 | 0 | 0 | X > Y
2095 // 0 | 0 | 1 | X < Y
2096 // 1 | 0 | 0 | X == Y
2097 // 1 | 1 | 1 | unordered
2098 switch (SetCCOpcode) {
2099 default: assert(0 && "Condcode should be pre-legalized away");
2100 case ISD::SETUEQ:
2101 case ISD::SETEQ: return X86::COND_E;
2102 case ISD::SETOLT: // flipped
2103 case ISD::SETOGT:
2104 case ISD::SETGT: return X86::COND_A;
2105 case ISD::SETOLE: // flipped
2106 case ISD::SETOGE:
2107 case ISD::SETGE: return X86::COND_AE;
2108 case ISD::SETUGT: // flipped
2109 case ISD::SETULT:
2110 case ISD::SETLT: return X86::COND_B;
2111 case ISD::SETUGE: // flipped
2112 case ISD::SETULE:
2113 case ISD::SETLE: return X86::COND_BE;
2114 case ISD::SETONE:
2115 case ISD::SETNE: return X86::COND_NE;
2116 case ISD::SETUO: return X86::COND_P;
2117 case ISD::SETO: return X86::COND_NP;
2121 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2122 /// code. Current x86 isa includes the following FP cmov instructions:
2123 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2124 static bool hasFPCMov(unsigned X86CC) {
2125 switch (X86CC) {
2126 default:
2127 return false;
2128 case X86::COND_B:
2129 case X86::COND_BE:
2130 case X86::COND_E:
2131 case X86::COND_P:
2132 case X86::COND_A:
2133 case X86::COND_AE:
2134 case X86::COND_NE:
2135 case X86::COND_NP:
2136 return true;
2140 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2141 /// the specified range (L, H].
2142 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2143 return (Val < 0) || (Val >= Low && Val < Hi);
2146 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2147 /// specified value.
2148 static bool isUndefOrEqual(int Val, int CmpVal) {
2149 if (Val < 0 || Val == CmpVal)
2150 return true;
2151 return false;
2154 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2155 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2156 /// the second operand.
2157 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2158 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2159 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2160 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2161 return (Mask[0] < 2 && Mask[1] < 2);
2162 return false;
2165 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2166 SmallVector<int, 8> M;
2167 N->getMask(M);
2168 return ::isPSHUFDMask(M, N->getValueType(0));
2171 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2172 /// is suitable for input to PSHUFHW.
2173 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2174 if (VT != MVT::v8i16)
2175 return false;
2177 // Lower quadword copied in order or undef.
2178 for (int i = 0; i != 4; ++i)
2179 if (Mask[i] >= 0 && Mask[i] != i)
2180 return false;
2182 // Upper quadword shuffled.
2183 for (int i = 4; i != 8; ++i)
2184 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2185 return false;
2187 return true;
2190 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2191 SmallVector<int, 8> M;
2192 N->getMask(M);
2193 return ::isPSHUFHWMask(M, N->getValueType(0));
2196 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2197 /// is suitable for input to PSHUFLW.
2198 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2199 if (VT != MVT::v8i16)
2200 return false;
2202 // Upper quadword copied in order.
2203 for (int i = 4; i != 8; ++i)
2204 if (Mask[i] >= 0 && Mask[i] != i)
2205 return false;
2207 // Lower quadword shuffled.
2208 for (int i = 0; i != 4; ++i)
2209 if (Mask[i] >= 4)
2210 return false;
2212 return true;
2215 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2216 SmallVector<int, 8> M;
2217 N->getMask(M);
2218 return ::isPSHUFLWMask(M, N->getValueType(0));
2221 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2222 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2223 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2224 int NumElems = VT.getVectorNumElements();
2225 if (NumElems != 2 && NumElems != 4)
2226 return false;
2228 int Half = NumElems / 2;
2229 for (int i = 0; i < Half; ++i)
2230 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2231 return false;
2232 for (int i = Half; i < NumElems; ++i)
2233 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2234 return false;
2236 return true;
2239 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2240 SmallVector<int, 8> M;
2241 N->getMask(M);
2242 return ::isSHUFPMask(M, N->getValueType(0));
2245 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2246 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2247 /// half elements to come from vector 1 (which would equal the dest.) and
2248 /// the upper half to come from vector 2.
2249 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2250 int NumElems = VT.getVectorNumElements();
2252 if (NumElems != 2 && NumElems != 4)
2253 return false;
2255 int Half = NumElems / 2;
2256 for (int i = 0; i < Half; ++i)
2257 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2258 return false;
2259 for (int i = Half; i < NumElems; ++i)
2260 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2261 return false;
2262 return true;
2265 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2266 SmallVector<int, 8> M;
2267 N->getMask(M);
2268 return isCommutedSHUFPMask(M, N->getValueType(0));
2271 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2272 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2273 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2274 if (N->getValueType(0).getVectorNumElements() != 4)
2275 return false;
2277 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2278 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2279 isUndefOrEqual(N->getMaskElt(1), 7) &&
2280 isUndefOrEqual(N->getMaskElt(2), 2) &&
2281 isUndefOrEqual(N->getMaskElt(3), 3);
2284 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2285 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2286 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2287 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2289 if (NumElems != 2 && NumElems != 4)
2290 return false;
2292 for (unsigned i = 0; i < NumElems/2; ++i)
2293 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2294 return false;
2296 for (unsigned i = NumElems/2; i < NumElems; ++i)
2297 if (!isUndefOrEqual(N->getMaskElt(i), i))
2298 return false;
2300 return true;
2303 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2304 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2305 /// and MOVLHPS.
2306 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2307 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2309 if (NumElems != 2 && NumElems != 4)
2310 return false;
2312 for (unsigned i = 0; i < NumElems/2; ++i)
2313 if (!isUndefOrEqual(N->getMaskElt(i), i))
2314 return false;
2316 for (unsigned i = 0; i < NumElems/2; ++i)
2317 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2318 return false;
2320 return true;
2323 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2324 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2325 /// <2, 3, 2, 3>
2326 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2327 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2329 if (NumElems != 4)
2330 return false;
2332 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2333 isUndefOrEqual(N->getMaskElt(1), 3) &&
2334 isUndefOrEqual(N->getMaskElt(2), 2) &&
2335 isUndefOrEqual(N->getMaskElt(3), 3);
2338 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2339 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2340 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2341 bool V2IsSplat = false) {
2342 int NumElts = VT.getVectorNumElements();
2343 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2344 return false;
2346 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2347 int BitI = Mask[i];
2348 int BitI1 = Mask[i+1];
2349 if (!isUndefOrEqual(BitI, j))
2350 return false;
2351 if (V2IsSplat) {
2352 if (!isUndefOrEqual(BitI1, NumElts))
2353 return false;
2354 } else {
2355 if (!isUndefOrEqual(BitI1, j + NumElts))
2356 return false;
2359 return true;
2362 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2363 SmallVector<int, 8> M;
2364 N->getMask(M);
2365 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2368 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2369 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2370 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2371 bool V2IsSplat = false) {
2372 int NumElts = VT.getVectorNumElements();
2373 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2374 return false;
2376 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2377 int BitI = Mask[i];
2378 int BitI1 = Mask[i+1];
2379 if (!isUndefOrEqual(BitI, j + NumElts/2))
2380 return false;
2381 if (V2IsSplat) {
2382 if (isUndefOrEqual(BitI1, NumElts))
2383 return false;
2384 } else {
2385 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2386 return false;
2389 return true;
2392 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2393 SmallVector<int, 8> M;
2394 N->getMask(M);
2395 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2398 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2399 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2400 /// <0, 0, 1, 1>
2401 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2402 int NumElems = VT.getVectorNumElements();
2403 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2404 return false;
2406 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2407 int BitI = Mask[i];
2408 int BitI1 = Mask[i+1];
2409 if (!isUndefOrEqual(BitI, j))
2410 return false;
2411 if (!isUndefOrEqual(BitI1, j))
2412 return false;
2414 return true;
2417 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2418 SmallVector<int, 8> M;
2419 N->getMask(M);
2420 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2423 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2424 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2425 /// <2, 2, 3, 3>
2426 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2427 int NumElems = VT.getVectorNumElements();
2428 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2429 return false;
2431 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2432 int BitI = Mask[i];
2433 int BitI1 = Mask[i+1];
2434 if (!isUndefOrEqual(BitI, j))
2435 return false;
2436 if (!isUndefOrEqual(BitI1, j))
2437 return false;
2439 return true;
2442 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2443 SmallVector<int, 8> M;
2444 N->getMask(M);
2445 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2448 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2449 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2450 /// MOVSD, and MOVD, i.e. setting the lowest element.
2451 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2452 int NumElts = VT.getVectorNumElements();
2453 if (NumElts != 2 && NumElts != 4)
2454 return false;
2456 if (!isUndefOrEqual(Mask[0], NumElts))
2457 return false;
2459 for (int i = 1; i < NumElts; ++i)
2460 if (!isUndefOrEqual(Mask[i], i))
2461 return false;
2463 return true;
2466 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2467 SmallVector<int, 8> M;
2468 N->getMask(M);
2469 return ::isMOVLMask(M, N->getValueType(0));
2472 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2473 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2474 /// element of vector 2 and the other elements to come from vector 1 in order.
2475 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2476 bool V2IsSplat = false, bool V2IsUndef = false) {
2477 int NumOps = VT.getVectorNumElements();
2478 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2479 return false;
2481 if (!isUndefOrEqual(Mask[0], 0))
2482 return false;
2484 for (int i = 1; i < NumOps; ++i)
2485 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2486 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2487 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2488 return false;
2490 return true;
2493 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2494 bool V2IsUndef = false) {
2495 SmallVector<int, 8> M;
2496 N->getMask(M);
2497 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2500 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2501 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2502 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2503 if (N->getValueType(0).getVectorNumElements() != 4)
2504 return false;
2506 // Expect 1, 1, 3, 3
2507 for (unsigned i = 0; i < 2; ++i) {
2508 int Elt = N->getMaskElt(i);
2509 if (Elt >= 0 && Elt != 1)
2510 return false;
2513 bool HasHi = false;
2514 for (unsigned i = 2; i < 4; ++i) {
2515 int Elt = N->getMaskElt(i);
2516 if (Elt >= 0 && Elt != 3)
2517 return false;
2518 if (Elt == 3)
2519 HasHi = true;
2521 // Don't use movshdup if it can be done with a shufps.
2522 // FIXME: verify that matching u, u, 3, 3 is what we want.
2523 return HasHi;
2526 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2527 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2528 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2529 if (N->getValueType(0).getVectorNumElements() != 4)
2530 return false;
2532 // Expect 0, 0, 2, 2
2533 for (unsigned i = 0; i < 2; ++i)
2534 if (N->getMaskElt(i) > 0)
2535 return false;
2537 bool HasHi = false;
2538 for (unsigned i = 2; i < 4; ++i) {
2539 int Elt = N->getMaskElt(i);
2540 if (Elt >= 0 && Elt != 2)
2541 return false;
2542 if (Elt == 2)
2543 HasHi = true;
2545 // Don't use movsldup if it can be done with a shufps.
2546 return HasHi;
2549 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2550 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2551 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2552 int e = N->getValueType(0).getVectorNumElements() / 2;
2554 for (int i = 0; i < e; ++i)
2555 if (!isUndefOrEqual(N->getMaskElt(i), i))
2556 return false;
2557 for (int i = 0; i < e; ++i)
2558 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2559 return false;
2560 return true;
2563 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2564 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2565 /// instructions.
2566 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2567 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2568 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2570 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2571 unsigned Mask = 0;
2572 for (int i = 0; i < NumOperands; ++i) {
2573 int Val = SVOp->getMaskElt(NumOperands-i-1);
2574 if (Val < 0) Val = 0;
2575 if (Val >= NumOperands) Val -= NumOperands;
2576 Mask |= Val;
2577 if (i != NumOperands - 1)
2578 Mask <<= Shift;
2580 return Mask;
2583 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2584 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2585 /// instructions.
2586 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2587 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2588 unsigned Mask = 0;
2589 // 8 nodes, but we only care about the last 4.
2590 for (unsigned i = 7; i >= 4; --i) {
2591 int Val = SVOp->getMaskElt(i);
2592 if (Val >= 0)
2593 Mask |= (Val - 4);
2594 if (i != 4)
2595 Mask <<= 2;
2597 return Mask;
2600 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2601 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2602 /// instructions.
2603 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2604 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2605 unsigned Mask = 0;
2606 // 8 nodes, but we only care about the first 4.
2607 for (int i = 3; i >= 0; --i) {
2608 int Val = SVOp->getMaskElt(i);
2609 if (Val >= 0)
2610 Mask |= Val;
2611 if (i != 0)
2612 Mask <<= 2;
2614 return Mask;
2617 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2618 /// their permute mask.
2619 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2620 SelectionDAG &DAG) {
2621 MVT VT = SVOp->getValueType(0);
2622 unsigned NumElems = VT.getVectorNumElements();
2623 SmallVector<int, 8> MaskVec;
2625 for (unsigned i = 0; i != NumElems; ++i) {
2626 int idx = SVOp->getMaskElt(i);
2627 if (idx < 0)
2628 MaskVec.push_back(idx);
2629 else if (idx < (int)NumElems)
2630 MaskVec.push_back(idx + NumElems);
2631 else
2632 MaskVec.push_back(idx - NumElems);
2634 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2635 SVOp->getOperand(0), &MaskVec[0]);
2638 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2639 /// the two vector operands have swapped position.
2640 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2641 unsigned NumElems = VT.getVectorNumElements();
2642 for (unsigned i = 0; i != NumElems; ++i) {
2643 int idx = Mask[i];
2644 if (idx < 0)
2645 continue;
2646 else if (idx < (int)NumElems)
2647 Mask[i] = idx + NumElems;
2648 else
2649 Mask[i] = idx - NumElems;
2653 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2654 /// match movhlps. The lower half elements should come from upper half of
2655 /// V1 (and in order), and the upper half elements should come from the upper
2656 /// half of V2 (and in order).
2657 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2658 if (Op->getValueType(0).getVectorNumElements() != 4)
2659 return false;
2660 for (unsigned i = 0, e = 2; i != e; ++i)
2661 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2662 return false;
2663 for (unsigned i = 2; i != 4; ++i)
2664 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2665 return false;
2666 return true;
2669 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2670 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2671 /// required.
2672 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2673 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2674 return false;
2675 N = N->getOperand(0).getNode();
2676 if (!ISD::isNON_EXTLoad(N))
2677 return false;
2678 if (LD)
2679 *LD = cast<LoadSDNode>(N);
2680 return true;
2683 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2684 /// match movlp{s|d}. The lower half elements should come from lower half of
2685 /// V1 (and in order), and the upper half elements should come from the upper
2686 /// half of V2 (and in order). And since V1 will become the source of the
2687 /// MOVLP, it must be either a vector load or a scalar load to vector.
2688 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2689 ShuffleVectorSDNode *Op) {
2690 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2691 return false;
2692 // Is V2 is a vector load, don't do this transformation. We will try to use
2693 // load folding shufps op.
2694 if (ISD::isNON_EXTLoad(V2))
2695 return false;
2697 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2699 if (NumElems != 2 && NumElems != 4)
2700 return false;
2701 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2702 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2703 return false;
2704 for (unsigned i = NumElems/2; i != NumElems; ++i)
2705 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2706 return false;
2707 return true;
2710 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2711 /// all the same.
2712 static bool isSplatVector(SDNode *N) {
2713 if (N->getOpcode() != ISD::BUILD_VECTOR)
2714 return false;
2716 SDValue SplatValue = N->getOperand(0);
2717 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2718 if (N->getOperand(i) != SplatValue)
2719 return false;
2720 return true;
2723 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2724 /// constant +0.0.
2725 static inline bool isZeroNode(SDValue Elt) {
2726 return ((isa<ConstantSDNode>(Elt) &&
2727 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2728 (isa<ConstantFPSDNode>(Elt) &&
2729 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2732 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2733 /// to an zero vector.
2734 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2735 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2736 SDValue V1 = N->getOperand(0);
2737 SDValue V2 = N->getOperand(1);
2738 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2739 for (unsigned i = 0; i != NumElems; ++i) {
2740 int Idx = N->getMaskElt(i);
2741 if (Idx >= (int)NumElems) {
2742 unsigned Opc = V2.getOpcode();
2743 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2744 continue;
2745 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2746 return false;
2747 } else if (Idx >= 0) {
2748 unsigned Opc = V1.getOpcode();
2749 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2750 continue;
2751 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2752 return false;
2755 return true;
2758 /// getZeroVector - Returns a vector of specified type with all zero elements.
2760 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2761 DebugLoc dl) {
2762 assert(VT.isVector() && "Expected a vector type");
2764 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2765 // type. This ensures they get CSE'd.
2766 SDValue Vec;
2767 if (VT.getSizeInBits() == 64) { // MMX
2768 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2769 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2770 } else if (HasSSE2) { // SSE2
2771 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2772 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2773 } else { // SSE1
2774 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2775 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2777 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2780 /// getOnesVector - Returns a vector of specified type with all bits set.
2782 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2783 assert(VT.isVector() && "Expected a vector type");
2785 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2786 // type. This ensures they get CSE'd.
2787 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2788 SDValue Vec;
2789 if (VT.getSizeInBits() == 64) // MMX
2790 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2791 else // SSE
2792 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2793 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2797 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2798 /// that point to V2 points to its first element.
2799 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2800 MVT VT = SVOp->getValueType(0);
2801 unsigned NumElems = VT.getVectorNumElements();
2803 bool Changed = false;
2804 SmallVector<int, 8> MaskVec;
2805 SVOp->getMask(MaskVec);
2807 for (unsigned i = 0; i != NumElems; ++i) {
2808 if (MaskVec[i] > (int)NumElems) {
2809 MaskVec[i] = NumElems;
2810 Changed = true;
2813 if (Changed)
2814 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2815 SVOp->getOperand(1), &MaskVec[0]);
2816 return SDValue(SVOp, 0);
2819 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2820 /// operation of specified width.
2821 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2822 SDValue V2) {
2823 unsigned NumElems = VT.getVectorNumElements();
2824 SmallVector<int, 8> Mask;
2825 Mask.push_back(NumElems);
2826 for (unsigned i = 1; i != NumElems; ++i)
2827 Mask.push_back(i);
2828 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2831 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2832 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2833 SDValue V2) {
2834 unsigned NumElems = VT.getVectorNumElements();
2835 SmallVector<int, 8> Mask;
2836 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2837 Mask.push_back(i);
2838 Mask.push_back(i + NumElems);
2840 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2843 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2844 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2845 SDValue V2) {
2846 unsigned NumElems = VT.getVectorNumElements();
2847 unsigned Half = NumElems/2;
2848 SmallVector<int, 8> Mask;
2849 for (unsigned i = 0; i != Half; ++i) {
2850 Mask.push_back(i + Half);
2851 Mask.push_back(i + NumElems + Half);
2853 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2856 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2857 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2858 bool HasSSE2) {
2859 if (SV->getValueType(0).getVectorNumElements() <= 4)
2860 return SDValue(SV, 0);
2862 MVT PVT = MVT::v4f32;
2863 MVT VT = SV->getValueType(0);
2864 DebugLoc dl = SV->getDebugLoc();
2865 SDValue V1 = SV->getOperand(0);
2866 int NumElems = VT.getVectorNumElements();
2867 int EltNo = SV->getSplatIndex();
2869 // unpack elements to the correct location
2870 while (NumElems > 4) {
2871 if (EltNo < NumElems/2) {
2872 V1 = getUnpackl(DAG, dl, VT, V1, V1);
2873 } else {
2874 V1 = getUnpackh(DAG, dl, VT, V1, V1);
2875 EltNo -= NumElems/2;
2877 NumElems >>= 1;
2880 // Perform the splat.
2881 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2882 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2883 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2884 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2887 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2888 /// vector of zero or undef vector. This produces a shuffle where the low
2889 /// element of V2 is swizzled into the zero/undef vector, landing at element
2890 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2891 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2892 bool isZero, bool HasSSE2,
2893 SelectionDAG &DAG) {
2894 MVT VT = V2.getValueType();
2895 SDValue V1 = isZero
2896 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2897 unsigned NumElems = VT.getVectorNumElements();
2898 SmallVector<int, 16> MaskVec;
2899 for (unsigned i = 0; i != NumElems; ++i)
2900 // If this is the insertion idx, put the low elt of V2 here.
2901 MaskVec.push_back(i == Idx ? NumElems : i);
2902 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
2905 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2906 /// a shuffle that is zero.
2907 static
2908 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
2909 bool Low, SelectionDAG &DAG) {
2910 unsigned NumZeros = 0;
2911 for (int i = 0; i < NumElems; ++i) {
2912 unsigned Index = Low ? i : NumElems-i-1;
2913 int Idx = SVOp->getMaskElt(Index);
2914 if (Idx < 0) {
2915 ++NumZeros;
2916 continue;
2918 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
2919 if (Elt.getNode() && isZeroNode(Elt))
2920 ++NumZeros;
2921 else
2922 break;
2924 return NumZeros;
2927 /// isVectorShift - Returns true if the shuffle can be implemented as a
2928 /// logical left or right shift of a vector.
2929 /// FIXME: split into pslldqi, psrldqi, palignr variants.
2930 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
2931 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2932 int NumElems = SVOp->getValueType(0).getVectorNumElements();
2934 isLeft = true;
2935 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
2936 if (!NumZeros) {
2937 isLeft = false;
2938 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
2939 if (!NumZeros)
2940 return false;
2942 bool SeenV1 = false;
2943 bool SeenV2 = false;
2944 for (int i = NumZeros; i < NumElems; ++i) {
2945 int Val = isLeft ? (i - NumZeros) : i;
2946 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
2947 if (Idx < 0)
2948 continue;
2949 if (Idx < NumElems)
2950 SeenV1 = true;
2951 else {
2952 Idx -= NumElems;
2953 SeenV2 = true;
2955 if (Idx != Val)
2956 return false;
2958 if (SeenV1 && SeenV2)
2959 return false;
2961 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
2962 ShAmt = NumZeros;
2963 return true;
2967 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2969 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2970 unsigned NumNonZero, unsigned NumZero,
2971 SelectionDAG &DAG, TargetLowering &TLI) {
2972 if (NumNonZero > 8)
2973 return SDValue();
2975 DebugLoc dl = Op.getDebugLoc();
2976 SDValue V(0, 0);
2977 bool First = true;
2978 for (unsigned i = 0; i < 16; ++i) {
2979 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2980 if (ThisIsNonZero && First) {
2981 if (NumZero)
2982 V = getZeroVector(MVT::v8i16, true, DAG, dl);
2983 else
2984 V = DAG.getUNDEF(MVT::v8i16);
2985 First = false;
2988 if ((i & 1) != 0) {
2989 SDValue ThisElt(0, 0), LastElt(0, 0);
2990 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2991 if (LastIsNonZero) {
2992 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
2993 MVT::i16, Op.getOperand(i-1));
2995 if (ThisIsNonZero) {
2996 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
2997 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
2998 ThisElt, DAG.getConstant(8, MVT::i8));
2999 if (LastIsNonZero)
3000 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3001 } else
3002 ThisElt = LastElt;
3004 if (ThisElt.getNode())
3005 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3006 DAG.getIntPtrConstant(i/2));
3010 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3013 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3015 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3016 unsigned NumNonZero, unsigned NumZero,
3017 SelectionDAG &DAG, TargetLowering &TLI) {
3018 if (NumNonZero > 4)
3019 return SDValue();
3021 DebugLoc dl = Op.getDebugLoc();
3022 SDValue V(0, 0);
3023 bool First = true;
3024 for (unsigned i = 0; i < 8; ++i) {
3025 bool isNonZero = (NonZeros & (1 << i)) != 0;
3026 if (isNonZero) {
3027 if (First) {
3028 if (NumZero)
3029 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3030 else
3031 V = DAG.getUNDEF(MVT::v8i16);
3032 First = false;
3034 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3035 MVT::v8i16, V, Op.getOperand(i),
3036 DAG.getIntPtrConstant(i));
3040 return V;
3043 /// getVShift - Return a vector logical shift node.
3045 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3046 unsigned NumBits, SelectionDAG &DAG,
3047 const TargetLowering &TLI, DebugLoc dl) {
3048 bool isMMX = VT.getSizeInBits() == 64;
3049 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3050 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3051 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3052 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3053 DAG.getNode(Opc, dl, ShVT, SrcOp,
3054 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3057 SDValue
3058 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3059 DebugLoc dl = Op.getDebugLoc();
3060 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3061 if (ISD::isBuildVectorAllZeros(Op.getNode())
3062 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3063 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3064 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3065 // eliminated on x86-32 hosts.
3066 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3067 return Op;
3069 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3070 return getOnesVector(Op.getValueType(), DAG, dl);
3071 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3074 MVT VT = Op.getValueType();
3075 MVT EVT = VT.getVectorElementType();
3076 unsigned EVTBits = EVT.getSizeInBits();
3078 unsigned NumElems = Op.getNumOperands();
3079 unsigned NumZero = 0;
3080 unsigned NumNonZero = 0;
3081 unsigned NonZeros = 0;
3082 bool IsAllConstants = true;
3083 SmallSet<SDValue, 8> Values;
3084 for (unsigned i = 0; i < NumElems; ++i) {
3085 SDValue Elt = Op.getOperand(i);
3086 if (Elt.getOpcode() == ISD::UNDEF)
3087 continue;
3088 Values.insert(Elt);
3089 if (Elt.getOpcode() != ISD::Constant &&
3090 Elt.getOpcode() != ISD::ConstantFP)
3091 IsAllConstants = false;
3092 if (isZeroNode(Elt))
3093 NumZero++;
3094 else {
3095 NonZeros |= (1 << i);
3096 NumNonZero++;
3100 if (NumNonZero == 0) {
3101 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3102 return DAG.getUNDEF(VT);
3105 // Special case for single non-zero, non-undef, element.
3106 if (NumNonZero == 1 && NumElems <= 4) {
3107 unsigned Idx = CountTrailingZeros_32(NonZeros);
3108 SDValue Item = Op.getOperand(Idx);
3110 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3111 // the value are obviously zero, truncate the value to i32 and do the
3112 // insertion that way. Only do this if the value is non-constant or if the
3113 // value is a constant being inserted into element 0. It is cheaper to do
3114 // a constant pool load than it is to do a movd + shuffle.
3115 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3116 (!IsAllConstants || Idx == 0)) {
3117 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3118 // Handle MMX and SSE both.
3119 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3120 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3122 // Truncate the value (which may itself be a constant) to i32, and
3123 // convert it to a vector with movd (S2V+shuffle to zero extend).
3124 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3125 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3126 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3127 Subtarget->hasSSE2(), DAG);
3129 // Now we have our 32-bit value zero extended in the low element of
3130 // a vector. If Idx != 0, swizzle it into place.
3131 if (Idx != 0) {
3132 SmallVector<int, 4> Mask;
3133 Mask.push_back(Idx);
3134 for (unsigned i = 1; i != VecElts; ++i)
3135 Mask.push_back(i);
3136 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3137 DAG.getUNDEF(Item.getValueType()),
3138 &Mask[0]);
3140 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3144 // If we have a constant or non-constant insertion into the low element of
3145 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3146 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3147 // depending on what the source datatype is. Because we can only get here
3148 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3149 if (Idx == 0 &&
3150 // Don't do this for i64 values on x86-32.
3151 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3152 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3153 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3154 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3155 Subtarget->hasSSE2(), DAG);
3158 // Is it a vector logical left shift?
3159 if (NumElems == 2 && Idx == 1 &&
3160 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3161 unsigned NumBits = VT.getSizeInBits();
3162 return getVShift(true, VT,
3163 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3164 VT, Op.getOperand(1)),
3165 NumBits/2, DAG, *this, dl);
3168 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3169 return SDValue();
3171 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3172 // is a non-constant being inserted into an element other than the low one,
3173 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3174 // movd/movss) to move this into the low element, then shuffle it into
3175 // place.
3176 if (EVTBits == 32) {
3177 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3179 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3180 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3181 Subtarget->hasSSE2(), DAG);
3182 SmallVector<int, 8> MaskVec;
3183 for (unsigned i = 0; i < NumElems; i++)
3184 MaskVec.push_back(i == Idx ? 0 : 1);
3185 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3189 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3190 if (Values.size() == 1)
3191 return SDValue();
3193 // A vector full of immediates; various special cases are already
3194 // handled, so this is best done with a single constant-pool load.
3195 if (IsAllConstants)
3196 return SDValue();
3198 // Let legalizer expand 2-wide build_vectors.
3199 if (EVTBits == 64) {
3200 if (NumNonZero == 1) {
3201 // One half is zero or undef.
3202 unsigned Idx = CountTrailingZeros_32(NonZeros);
3203 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3204 Op.getOperand(Idx));
3205 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3206 Subtarget->hasSSE2(), DAG);
3208 return SDValue();
3211 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3212 if (EVTBits == 8 && NumElems == 16) {
3213 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3214 *this);
3215 if (V.getNode()) return V;
3218 if (EVTBits == 16 && NumElems == 8) {
3219 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3220 *this);
3221 if (V.getNode()) return V;
3224 // If element VT is == 32 bits, turn it into a number of shuffles.
3225 SmallVector<SDValue, 8> V;
3226 V.resize(NumElems);
3227 if (NumElems == 4 && NumZero > 0) {
3228 for (unsigned i = 0; i < 4; ++i) {
3229 bool isZero = !(NonZeros & (1 << i));
3230 if (isZero)
3231 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3232 else
3233 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3236 for (unsigned i = 0; i < 2; ++i) {
3237 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3238 default: break;
3239 case 0:
3240 V[i] = V[i*2]; // Must be a zero vector.
3241 break;
3242 case 1:
3243 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3244 break;
3245 case 2:
3246 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3247 break;
3248 case 3:
3249 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3250 break;
3254 SmallVector<int, 8> MaskVec;
3255 bool Reverse = (NonZeros & 0x3) == 2;
3256 for (unsigned i = 0; i < 2; ++i)
3257 MaskVec.push_back(Reverse ? 1-i : i);
3258 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3259 for (unsigned i = 0; i < 2; ++i)
3260 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3261 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3264 if (Values.size() > 2) {
3265 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3266 // values to be inserted is equal to the number of elements, in which case
3267 // use the unpack code below in the hopes of matching the consecutive elts
3268 // load merge pattern for shuffles.
3269 // FIXME: We could probably just check that here directly.
3270 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3271 getSubtarget()->hasSSE41()) {
3272 V[0] = DAG.getUNDEF(VT);
3273 for (unsigned i = 0; i < NumElems; ++i)
3274 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3275 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3276 Op.getOperand(i), DAG.getIntPtrConstant(i));
3277 return V[0];
3279 // Expand into a number of unpckl*.
3280 // e.g. for v4f32
3281 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3282 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3283 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3284 for (unsigned i = 0; i < NumElems; ++i)
3285 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3286 NumElems >>= 1;
3287 while (NumElems != 0) {
3288 for (unsigned i = 0; i < NumElems; ++i)
3289 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3290 NumElems >>= 1;
3292 return V[0];
3295 return SDValue();
3298 // v8i16 shuffles - Prefer shuffles in the following order:
3299 // 1. [all] pshuflw, pshufhw, optional move
3300 // 2. [ssse3] 1 x pshufb
3301 // 3. [ssse3] 2 x pshufb + 1 x por
3302 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3303 static
3304 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3305 SelectionDAG &DAG, X86TargetLowering &TLI) {
3306 SDValue V1 = SVOp->getOperand(0);
3307 SDValue V2 = SVOp->getOperand(1);
3308 DebugLoc dl = SVOp->getDebugLoc();
3309 SmallVector<int, 8> MaskVals;
3311 // Determine if more than 1 of the words in each of the low and high quadwords
3312 // of the result come from the same quadword of one of the two inputs. Undef
3313 // mask values count as coming from any quadword, for better codegen.
3314 SmallVector<unsigned, 4> LoQuad(4);
3315 SmallVector<unsigned, 4> HiQuad(4);
3316 BitVector InputQuads(4);
3317 for (unsigned i = 0; i < 8; ++i) {
3318 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3319 int EltIdx = SVOp->getMaskElt(i);
3320 MaskVals.push_back(EltIdx);
3321 if (EltIdx < 0) {
3322 ++Quad[0];
3323 ++Quad[1];
3324 ++Quad[2];
3325 ++Quad[3];
3326 continue;
3328 ++Quad[EltIdx / 4];
3329 InputQuads.set(EltIdx / 4);
3332 int BestLoQuad = -1;
3333 unsigned MaxQuad = 1;
3334 for (unsigned i = 0; i < 4; ++i) {
3335 if (LoQuad[i] > MaxQuad) {
3336 BestLoQuad = i;
3337 MaxQuad = LoQuad[i];
3341 int BestHiQuad = -1;
3342 MaxQuad = 1;
3343 for (unsigned i = 0; i < 4; ++i) {
3344 if (HiQuad[i] > MaxQuad) {
3345 BestHiQuad = i;
3346 MaxQuad = HiQuad[i];
3350 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3351 // of the two input vectors, shuffle them into one input vector so only a
3352 // single pshufb instruction is necessary. If There are more than 2 input
3353 // quads, disable the next transformation since it does not help SSSE3.
3354 bool V1Used = InputQuads[0] || InputQuads[1];
3355 bool V2Used = InputQuads[2] || InputQuads[3];
3356 if (TLI.getSubtarget()->hasSSSE3()) {
3357 if (InputQuads.count() == 2 && V1Used && V2Used) {
3358 BestLoQuad = InputQuads.find_first();
3359 BestHiQuad = InputQuads.find_next(BestLoQuad);
3361 if (InputQuads.count() > 2) {
3362 BestLoQuad = -1;
3363 BestHiQuad = -1;
3367 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3368 // the shuffle mask. If a quad is scored as -1, that means that it contains
3369 // words from all 4 input quadwords.
3370 SDValue NewV;
3371 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3372 SmallVector<int, 8> MaskV;
3373 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3374 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3375 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3376 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3377 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3378 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3380 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3381 // source words for the shuffle, to aid later transformations.
3382 bool AllWordsInNewV = true;
3383 bool InOrder[2] = { true, true };
3384 for (unsigned i = 0; i != 8; ++i) {
3385 int idx = MaskVals[i];
3386 if (idx != (int)i)
3387 InOrder[i/4] = false;
3388 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3389 continue;
3390 AllWordsInNewV = false;
3391 break;
3394 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3395 if (AllWordsInNewV) {
3396 for (int i = 0; i != 8; ++i) {
3397 int idx = MaskVals[i];
3398 if (idx < 0)
3399 continue;
3400 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3401 if ((idx != i) && idx < 4)
3402 pshufhw = false;
3403 if ((idx != i) && idx > 3)
3404 pshuflw = false;
3406 V1 = NewV;
3407 V2Used = false;
3408 BestLoQuad = 0;
3409 BestHiQuad = 1;
3412 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3413 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3414 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3415 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3416 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3420 // If we have SSSE3, and all words of the result are from 1 input vector,
3421 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3422 // is present, fall back to case 4.
3423 if (TLI.getSubtarget()->hasSSSE3()) {
3424 SmallVector<SDValue,16> pshufbMask;
3426 // If we have elements from both input vectors, set the high bit of the
3427 // shuffle mask element to zero out elements that come from V2 in the V1
3428 // mask, and elements that come from V1 in the V2 mask, so that the two
3429 // results can be OR'd together.
3430 bool TwoInputs = V1Used && V2Used;
3431 for (unsigned i = 0; i != 8; ++i) {
3432 int EltIdx = MaskVals[i] * 2;
3433 if (TwoInputs && (EltIdx >= 16)) {
3434 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3435 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3436 continue;
3438 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3439 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3441 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3442 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3443 DAG.getNode(ISD::BUILD_VECTOR, dl,
3444 MVT::v16i8, &pshufbMask[0], 16));
3445 if (!TwoInputs)
3446 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3448 // Calculate the shuffle mask for the second input, shuffle it, and
3449 // OR it with the first shuffled input.
3450 pshufbMask.clear();
3451 for (unsigned i = 0; i != 8; ++i) {
3452 int EltIdx = MaskVals[i] * 2;
3453 if (EltIdx < 16) {
3454 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3455 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3456 continue;
3458 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3459 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3461 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3462 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3463 DAG.getNode(ISD::BUILD_VECTOR, dl,
3464 MVT::v16i8, &pshufbMask[0], 16));
3465 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3466 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3469 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3470 // and update MaskVals with new element order.
3471 BitVector InOrder(8);
3472 if (BestLoQuad >= 0) {
3473 SmallVector<int, 8> MaskV;
3474 for (int i = 0; i != 4; ++i) {
3475 int idx = MaskVals[i];
3476 if (idx < 0) {
3477 MaskV.push_back(-1);
3478 InOrder.set(i);
3479 } else if ((idx / 4) == BestLoQuad) {
3480 MaskV.push_back(idx & 3);
3481 InOrder.set(i);
3482 } else {
3483 MaskV.push_back(-1);
3486 for (unsigned i = 4; i != 8; ++i)
3487 MaskV.push_back(i);
3488 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3489 &MaskV[0]);
3492 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3493 // and update MaskVals with the new element order.
3494 if (BestHiQuad >= 0) {
3495 SmallVector<int, 8> MaskV;
3496 for (unsigned i = 0; i != 4; ++i)
3497 MaskV.push_back(i);
3498 for (unsigned i = 4; i != 8; ++i) {
3499 int idx = MaskVals[i];
3500 if (idx < 0) {
3501 MaskV.push_back(-1);
3502 InOrder.set(i);
3503 } else if ((idx / 4) == BestHiQuad) {
3504 MaskV.push_back((idx & 3) + 4);
3505 InOrder.set(i);
3506 } else {
3507 MaskV.push_back(-1);
3510 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3511 &MaskV[0]);
3514 // In case BestHi & BestLo were both -1, which means each quadword has a word
3515 // from each of the four input quadwords, calculate the InOrder bitvector now
3516 // before falling through to the insert/extract cleanup.
3517 if (BestLoQuad == -1 && BestHiQuad == -1) {
3518 NewV = V1;
3519 for (int i = 0; i != 8; ++i)
3520 if (MaskVals[i] < 0 || MaskVals[i] == i)
3521 InOrder.set(i);
3524 // The other elements are put in the right place using pextrw and pinsrw.
3525 for (unsigned i = 0; i != 8; ++i) {
3526 if (InOrder[i])
3527 continue;
3528 int EltIdx = MaskVals[i];
3529 if (EltIdx < 0)
3530 continue;
3531 SDValue ExtOp = (EltIdx < 8)
3532 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3533 DAG.getIntPtrConstant(EltIdx))
3534 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3535 DAG.getIntPtrConstant(EltIdx - 8));
3536 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3537 DAG.getIntPtrConstant(i));
3539 return NewV;
3542 // v16i8 shuffles - Prefer shuffles in the following order:
3543 // 1. [ssse3] 1 x pshufb
3544 // 2. [ssse3] 2 x pshufb + 1 x por
3545 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3546 static
3547 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3548 SelectionDAG &DAG, X86TargetLowering &TLI) {
3549 SDValue V1 = SVOp->getOperand(0);
3550 SDValue V2 = SVOp->getOperand(1);
3551 DebugLoc dl = SVOp->getDebugLoc();
3552 SmallVector<int, 16> MaskVals;
3553 SVOp->getMask(MaskVals);
3555 // If we have SSSE3, case 1 is generated when all result bytes come from
3556 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3557 // present, fall back to case 3.
3558 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3559 bool V1Only = true;
3560 bool V2Only = true;
3561 for (unsigned i = 0; i < 16; ++i) {
3562 int EltIdx = MaskVals[i];
3563 if (EltIdx < 0)
3564 continue;
3565 if (EltIdx < 16)
3566 V2Only = false;
3567 else
3568 V1Only = false;
3571 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3572 if (TLI.getSubtarget()->hasSSSE3()) {
3573 SmallVector<SDValue,16> pshufbMask;
3575 // If all result elements are from one input vector, then only translate
3576 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3578 // Otherwise, we have elements from both input vectors, and must zero out
3579 // elements that come from V2 in the first mask, and V1 in the second mask
3580 // so that we can OR them together.
3581 bool TwoInputs = !(V1Only || V2Only);
3582 for (unsigned i = 0; i != 16; ++i) {
3583 int EltIdx = MaskVals[i];
3584 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3585 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3586 continue;
3588 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3590 // If all the elements are from V2, assign it to V1 and return after
3591 // building the first pshufb.
3592 if (V2Only)
3593 V1 = V2;
3594 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3595 DAG.getNode(ISD::BUILD_VECTOR, dl,
3596 MVT::v16i8, &pshufbMask[0], 16));
3597 if (!TwoInputs)
3598 return V1;
3600 // Calculate the shuffle mask for the second input, shuffle it, and
3601 // OR it with the first shuffled input.
3602 pshufbMask.clear();
3603 for (unsigned i = 0; i != 16; ++i) {
3604 int EltIdx = MaskVals[i];
3605 if (EltIdx < 16) {
3606 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3607 continue;
3609 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3611 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3612 DAG.getNode(ISD::BUILD_VECTOR, dl,
3613 MVT::v16i8, &pshufbMask[0], 16));
3614 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3617 // No SSSE3 - Calculate in place words and then fix all out of place words
3618 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3619 // the 16 different words that comprise the two doublequadword input vectors.
3620 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3621 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3622 SDValue NewV = V2Only ? V2 : V1;
3623 for (int i = 0; i != 8; ++i) {
3624 int Elt0 = MaskVals[i*2];
3625 int Elt1 = MaskVals[i*2+1];
3627 // This word of the result is all undef, skip it.
3628 if (Elt0 < 0 && Elt1 < 0)
3629 continue;
3631 // This word of the result is already in the correct place, skip it.
3632 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3633 continue;
3634 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3635 continue;
3637 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3638 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3639 SDValue InsElt;
3641 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3642 // using a single extract together, load it and store it.
3643 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3644 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3645 DAG.getIntPtrConstant(Elt1 / 2));
3646 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3647 DAG.getIntPtrConstant(i));
3648 continue;
3651 // If Elt1 is defined, extract it from the appropriate source. If the
3652 // source byte is not also odd, shift the extracted word left 8 bits
3653 // otherwise clear the bottom 8 bits if we need to do an or.
3654 if (Elt1 >= 0) {
3655 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3656 DAG.getIntPtrConstant(Elt1 / 2));
3657 if ((Elt1 & 1) == 0)
3658 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3659 DAG.getConstant(8, TLI.getShiftAmountTy()));
3660 else if (Elt0 >= 0)
3661 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3662 DAG.getConstant(0xFF00, MVT::i16));
3664 // If Elt0 is defined, extract it from the appropriate source. If the
3665 // source byte is not also even, shift the extracted word right 8 bits. If
3666 // Elt1 was also defined, OR the extracted values together before
3667 // inserting them in the result.
3668 if (Elt0 >= 0) {
3669 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3670 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3671 if ((Elt0 & 1) != 0)
3672 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3673 DAG.getConstant(8, TLI.getShiftAmountTy()));
3674 else if (Elt1 >= 0)
3675 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3676 DAG.getConstant(0x00FF, MVT::i16));
3677 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3678 : InsElt0;
3680 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3681 DAG.getIntPtrConstant(i));
3683 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3686 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3687 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3688 /// done when every pair / quad of shuffle mask elements point to elements in
3689 /// the right sequence. e.g.
3690 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3691 static
3692 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3693 SelectionDAG &DAG,
3694 TargetLowering &TLI, DebugLoc dl) {
3695 MVT VT = SVOp->getValueType(0);
3696 SDValue V1 = SVOp->getOperand(0);
3697 SDValue V2 = SVOp->getOperand(1);
3698 unsigned NumElems = VT.getVectorNumElements();
3699 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3700 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3701 MVT MaskEltVT = MaskVT.getVectorElementType();
3702 MVT NewVT = MaskVT;
3703 switch (VT.getSimpleVT()) {
3704 default: assert(false && "Unexpected!");
3705 case MVT::v4f32: NewVT = MVT::v2f64; break;
3706 case MVT::v4i32: NewVT = MVT::v2i64; break;
3707 case MVT::v8i16: NewVT = MVT::v4i32; break;
3708 case MVT::v16i8: NewVT = MVT::v4i32; break;
3711 if (NewWidth == 2) {
3712 if (VT.isInteger())
3713 NewVT = MVT::v2i64;
3714 else
3715 NewVT = MVT::v2f64;
3717 int Scale = NumElems / NewWidth;
3718 SmallVector<int, 8> MaskVec;
3719 for (unsigned i = 0; i < NumElems; i += Scale) {
3720 int StartIdx = -1;
3721 for (int j = 0; j < Scale; ++j) {
3722 int EltIdx = SVOp->getMaskElt(i+j);
3723 if (EltIdx < 0)
3724 continue;
3725 if (StartIdx == -1)
3726 StartIdx = EltIdx - (EltIdx % Scale);
3727 if (EltIdx != StartIdx + j)
3728 return SDValue();
3730 if (StartIdx == -1)
3731 MaskVec.push_back(-1);
3732 else
3733 MaskVec.push_back(StartIdx / Scale);
3736 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3737 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3738 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3741 /// getVZextMovL - Return a zero-extending vector move low node.
3743 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3744 SDValue SrcOp, SelectionDAG &DAG,
3745 const X86Subtarget *Subtarget, DebugLoc dl) {
3746 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3747 LoadSDNode *LD = NULL;
3748 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3749 LD = dyn_cast<LoadSDNode>(SrcOp);
3750 if (!LD) {
3751 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3752 // instead.
3753 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3754 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3755 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3756 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3757 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3758 // PR2108
3759 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3760 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3761 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3762 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3763 OpVT,
3764 SrcOp.getOperand(0)
3765 .getOperand(0))));
3770 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3771 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3772 DAG.getNode(ISD::BIT_CONVERT, dl,
3773 OpVT, SrcOp)));
3776 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3777 /// shuffles.
3778 static SDValue
3779 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3780 SDValue V1 = SVOp->getOperand(0);
3781 SDValue V2 = SVOp->getOperand(1);
3782 DebugLoc dl = SVOp->getDebugLoc();
3783 MVT VT = SVOp->getValueType(0);
3785 SmallVector<std::pair<int, int>, 8> Locs;
3786 Locs.resize(4);
3787 SmallVector<int, 8> Mask1(4U, -1);
3788 SmallVector<int, 8> PermMask;
3789 SVOp->getMask(PermMask);
3791 unsigned NumHi = 0;
3792 unsigned NumLo = 0;
3793 for (unsigned i = 0; i != 4; ++i) {
3794 int Idx = PermMask[i];
3795 if (Idx < 0) {
3796 Locs[i] = std::make_pair(-1, -1);
3797 } else {
3798 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3799 if (Idx < 4) {
3800 Locs[i] = std::make_pair(0, NumLo);
3801 Mask1[NumLo] = Idx;
3802 NumLo++;
3803 } else {
3804 Locs[i] = std::make_pair(1, NumHi);
3805 if (2+NumHi < 4)
3806 Mask1[2+NumHi] = Idx;
3807 NumHi++;
3812 if (NumLo <= 2 && NumHi <= 2) {
3813 // If no more than two elements come from either vector. This can be
3814 // implemented with two shuffles. First shuffle gather the elements.
3815 // The second shuffle, which takes the first shuffle as both of its
3816 // vector operands, put the elements into the right order.
3817 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3819 SmallVector<int, 8> Mask2(4U, -1);
3821 for (unsigned i = 0; i != 4; ++i) {
3822 if (Locs[i].first == -1)
3823 continue;
3824 else {
3825 unsigned Idx = (i < 2) ? 0 : 4;
3826 Idx += Locs[i].first * 2 + Locs[i].second;
3827 Mask2[i] = Idx;
3831 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3832 } else if (NumLo == 3 || NumHi == 3) {
3833 // Otherwise, we must have three elements from one vector, call it X, and
3834 // one element from the other, call it Y. First, use a shufps to build an
3835 // intermediate vector with the one element from Y and the element from X
3836 // that will be in the same half in the final destination (the indexes don't
3837 // matter). Then, use a shufps to build the final vector, taking the half
3838 // containing the element from Y from the intermediate, and the other half
3839 // from X.
3840 if (NumHi == 3) {
3841 // Normalize it so the 3 elements come from V1.
3842 CommuteVectorShuffleMask(PermMask, VT);
3843 std::swap(V1, V2);
3846 // Find the element from V2.
3847 unsigned HiIndex;
3848 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3849 int Val = PermMask[HiIndex];
3850 if (Val < 0)
3851 continue;
3852 if (Val >= 4)
3853 break;
3856 Mask1[0] = PermMask[HiIndex];
3857 Mask1[1] = -1;
3858 Mask1[2] = PermMask[HiIndex^1];
3859 Mask1[3] = -1;
3860 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3862 if (HiIndex >= 2) {
3863 Mask1[0] = PermMask[0];
3864 Mask1[1] = PermMask[1];
3865 Mask1[2] = HiIndex & 1 ? 6 : 4;
3866 Mask1[3] = HiIndex & 1 ? 4 : 6;
3867 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3868 } else {
3869 Mask1[0] = HiIndex & 1 ? 2 : 0;
3870 Mask1[1] = HiIndex & 1 ? 0 : 2;
3871 Mask1[2] = PermMask[2];
3872 Mask1[3] = PermMask[3];
3873 if (Mask1[2] >= 0)
3874 Mask1[2] += 4;
3875 if (Mask1[3] >= 0)
3876 Mask1[3] += 4;
3877 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3881 // Break it into (shuffle shuffle_hi, shuffle_lo).
3882 Locs.clear();
3883 SmallVector<int,8> LoMask(4U, -1);
3884 SmallVector<int,8> HiMask(4U, -1);
3886 SmallVector<int,8> *MaskPtr = &LoMask;
3887 unsigned MaskIdx = 0;
3888 unsigned LoIdx = 0;
3889 unsigned HiIdx = 2;
3890 for (unsigned i = 0; i != 4; ++i) {
3891 if (i == 2) {
3892 MaskPtr = &HiMask;
3893 MaskIdx = 1;
3894 LoIdx = 0;
3895 HiIdx = 2;
3897 int Idx = PermMask[i];
3898 if (Idx < 0) {
3899 Locs[i] = std::make_pair(-1, -1);
3900 } else if (Idx < 4) {
3901 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3902 (*MaskPtr)[LoIdx] = Idx;
3903 LoIdx++;
3904 } else {
3905 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3906 (*MaskPtr)[HiIdx] = Idx;
3907 HiIdx++;
3911 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
3912 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
3913 SmallVector<int, 8> MaskOps;
3914 for (unsigned i = 0; i != 4; ++i) {
3915 if (Locs[i].first == -1) {
3916 MaskOps.push_back(-1);
3917 } else {
3918 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3919 MaskOps.push_back(Idx);
3922 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
3925 SDValue
3926 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3927 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3928 SDValue V1 = Op.getOperand(0);
3929 SDValue V2 = Op.getOperand(1);
3930 MVT VT = Op.getValueType();
3931 DebugLoc dl = Op.getDebugLoc();
3932 unsigned NumElems = VT.getVectorNumElements();
3933 bool isMMX = VT.getSizeInBits() == 64;
3934 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3935 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3936 bool V1IsSplat = false;
3937 bool V2IsSplat = false;
3939 if (isZeroShuffle(SVOp))
3940 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3942 // Promote splats to v4f32.
3943 if (SVOp->isSplat()) {
3944 if (isMMX || NumElems < 4)
3945 return Op;
3946 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
3949 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3950 // do it!
3951 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3952 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3953 if (NewOp.getNode())
3954 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3955 LowerVECTOR_SHUFFLE(NewOp, DAG));
3956 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3957 // FIXME: Figure out a cleaner way to do this.
3958 // Try to make use of movq to zero out the top part.
3959 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3960 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3961 if (NewOp.getNode()) {
3962 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
3963 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
3964 DAG, Subtarget, dl);
3966 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3967 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3968 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
3969 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3970 DAG, Subtarget, dl);
3974 if (X86::isPSHUFDMask(SVOp))
3975 return Op;
3977 // Check if this can be converted into a logical shift.
3978 bool isLeft = false;
3979 unsigned ShAmt = 0;
3980 SDValue ShVal;
3981 bool isShift = getSubtarget()->hasSSE2() &&
3982 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
3983 if (isShift && ShVal.hasOneUse()) {
3984 // If the shifted value has multiple uses, it may be cheaper to use
3985 // v_set0 + movlhps or movhlps, etc.
3986 MVT EVT = VT.getVectorElementType();
3987 ShAmt *= EVT.getSizeInBits();
3988 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3991 if (X86::isMOVLMask(SVOp)) {
3992 if (V1IsUndef)
3993 return V2;
3994 if (ISD::isBuildVectorAllZeros(V1.getNode()))
3995 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
3996 if (!isMMX)
3997 return Op;
4000 // FIXME: fold these into legal mask.
4001 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4002 X86::isMOVSLDUPMask(SVOp) ||
4003 X86::isMOVHLPSMask(SVOp) ||
4004 X86::isMOVHPMask(SVOp) ||
4005 X86::isMOVLPMask(SVOp)))
4006 return Op;
4008 if (ShouldXformToMOVHLPS(SVOp) ||
4009 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4010 return CommuteVectorShuffle(SVOp, DAG);
4012 if (isShift) {
4013 // No better options. Use a vshl / vsrl.
4014 MVT EVT = VT.getVectorElementType();
4015 ShAmt *= EVT.getSizeInBits();
4016 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4019 bool Commuted = false;
4020 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4021 // 1,1,1,1 -> v8i16 though.
4022 V1IsSplat = isSplatVector(V1.getNode());
4023 V2IsSplat = isSplatVector(V2.getNode());
4025 // Canonicalize the splat or undef, if present, to be on the RHS.
4026 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4027 Op = CommuteVectorShuffle(SVOp, DAG);
4028 SVOp = cast<ShuffleVectorSDNode>(Op);
4029 V1 = SVOp->getOperand(0);
4030 V2 = SVOp->getOperand(1);
4031 std::swap(V1IsSplat, V2IsSplat);
4032 std::swap(V1IsUndef, V2IsUndef);
4033 Commuted = true;
4036 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4037 // Shuffling low element of v1 into undef, just return v1.
4038 if (V2IsUndef)
4039 return V1;
4040 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4041 // the instruction selector will not match, so get a canonical MOVL with
4042 // swapped operands to undo the commute.
4043 return getMOVL(DAG, dl, VT, V2, V1);
4046 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4047 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4048 X86::isUNPCKLMask(SVOp) ||
4049 X86::isUNPCKHMask(SVOp))
4050 return Op;
4052 if (V2IsSplat) {
4053 // Normalize mask so all entries that point to V2 points to its first
4054 // element then try to match unpck{h|l} again. If match, return a
4055 // new vector_shuffle with the corrected mask.
4056 SDValue NewMask = NormalizeMask(SVOp, DAG);
4057 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4058 if (NSVOp != SVOp) {
4059 if (X86::isUNPCKLMask(NSVOp, true)) {
4060 return NewMask;
4061 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4062 return NewMask;
4067 if (Commuted) {
4068 // Commute is back and try unpck* again.
4069 // FIXME: this seems wrong.
4070 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4071 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4072 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4073 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4074 X86::isUNPCKLMask(NewSVOp) ||
4075 X86::isUNPCKHMask(NewSVOp))
4076 return NewOp;
4079 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4081 // Normalize the node to match x86 shuffle ops if needed
4082 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4083 return CommuteVectorShuffle(SVOp, DAG);
4085 // Check for legal shuffle and return?
4086 SmallVector<int, 16> PermMask;
4087 SVOp->getMask(PermMask);
4088 if (isShuffleMaskLegal(PermMask, VT))
4089 return Op;
4091 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4092 if (VT == MVT::v8i16) {
4093 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4094 if (NewOp.getNode())
4095 return NewOp;
4098 if (VT == MVT::v16i8) {
4099 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4100 if (NewOp.getNode())
4101 return NewOp;
4104 // Handle all 4 wide cases with a number of shuffles except for MMX.
4105 if (NumElems == 4 && !isMMX)
4106 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4108 return SDValue();
4111 SDValue
4112 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4113 SelectionDAG &DAG) {
4114 MVT VT = Op.getValueType();
4115 DebugLoc dl = Op.getDebugLoc();
4116 if (VT.getSizeInBits() == 8) {
4117 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4118 Op.getOperand(0), Op.getOperand(1));
4119 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4120 DAG.getValueType(VT));
4121 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4122 } else if (VT.getSizeInBits() == 16) {
4123 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4124 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4125 if (Idx == 0)
4126 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4127 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4128 DAG.getNode(ISD::BIT_CONVERT, dl,
4129 MVT::v4i32,
4130 Op.getOperand(0)),
4131 Op.getOperand(1)));
4132 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4133 Op.getOperand(0), Op.getOperand(1));
4134 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4135 DAG.getValueType(VT));
4136 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4137 } else if (VT == MVT::f32) {
4138 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4139 // the result back to FR32 register. It's only worth matching if the
4140 // result has a single use which is a store or a bitcast to i32. And in
4141 // the case of a store, it's not worth it if the index is a constant 0,
4142 // because a MOVSSmr can be used instead, which is smaller and faster.
4143 if (!Op.hasOneUse())
4144 return SDValue();
4145 SDNode *User = *Op.getNode()->use_begin();
4146 if ((User->getOpcode() != ISD::STORE ||
4147 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4148 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4149 (User->getOpcode() != ISD::BIT_CONVERT ||
4150 User->getValueType(0) != MVT::i32))
4151 return SDValue();
4152 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4153 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4154 Op.getOperand(0)),
4155 Op.getOperand(1));
4156 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4157 } else if (VT == MVT::i32) {
4158 // ExtractPS works with constant index.
4159 if (isa<ConstantSDNode>(Op.getOperand(1)))
4160 return Op;
4162 return SDValue();
4166 SDValue
4167 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4168 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4169 return SDValue();
4171 if (Subtarget->hasSSE41()) {
4172 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4173 if (Res.getNode())
4174 return Res;
4177 MVT VT = Op.getValueType();
4178 DebugLoc dl = Op.getDebugLoc();
4179 // TODO: handle v16i8.
4180 if (VT.getSizeInBits() == 16) {
4181 SDValue Vec = Op.getOperand(0);
4182 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4183 if (Idx == 0)
4184 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4185 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4186 DAG.getNode(ISD::BIT_CONVERT, dl,
4187 MVT::v4i32, Vec),
4188 Op.getOperand(1)));
4189 // Transform it so it match pextrw which produces a 32-bit result.
4190 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4191 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4192 Op.getOperand(0), Op.getOperand(1));
4193 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4194 DAG.getValueType(VT));
4195 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4196 } else if (VT.getSizeInBits() == 32) {
4197 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4198 if (Idx == 0)
4199 return Op;
4201 // SHUFPS the element to the lowest double word, then movss.
4202 int Mask[4] = { Idx, -1, -1, -1 };
4203 MVT VVT = Op.getOperand(0).getValueType();
4204 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4205 DAG.getUNDEF(VVT), Mask);
4206 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4207 DAG.getIntPtrConstant(0));
4208 } else if (VT.getSizeInBits() == 64) {
4209 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4210 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4211 // to match extract_elt for f64.
4212 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4213 if (Idx == 0)
4214 return Op;
4216 // UNPCKHPD the element to the lowest double word, then movsd.
4217 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4218 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4219 int Mask[2] = { 1, -1 };
4220 MVT VVT = Op.getOperand(0).getValueType();
4221 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4222 DAG.getUNDEF(VVT), Mask);
4223 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4224 DAG.getIntPtrConstant(0));
4227 return SDValue();
4230 SDValue
4231 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4232 MVT VT = Op.getValueType();
4233 MVT EVT = VT.getVectorElementType();
4234 DebugLoc dl = Op.getDebugLoc();
4236 SDValue N0 = Op.getOperand(0);
4237 SDValue N1 = Op.getOperand(1);
4238 SDValue N2 = Op.getOperand(2);
4240 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4241 isa<ConstantSDNode>(N2)) {
4242 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4243 : X86ISD::PINSRW;
4244 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4245 // argument.
4246 if (N1.getValueType() != MVT::i32)
4247 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4248 if (N2.getValueType() != MVT::i32)
4249 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4250 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4251 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4252 // Bits [7:6] of the constant are the source select. This will always be
4253 // zero here. The DAG Combiner may combine an extract_elt index into these
4254 // bits. For example (insert (extract, 3), 2) could be matched by putting
4255 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4256 // Bits [5:4] of the constant are the destination select. This is the
4257 // value of the incoming immediate.
4258 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4259 // combine either bitwise AND or insert of float 0.0 to set these bits.
4260 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4261 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4262 } else if (EVT == MVT::i32) {
4263 // InsertPS works with constant index.
4264 if (isa<ConstantSDNode>(N2))
4265 return Op;
4267 return SDValue();
4270 SDValue
4271 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4272 MVT VT = Op.getValueType();
4273 MVT EVT = VT.getVectorElementType();
4275 if (Subtarget->hasSSE41())
4276 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4278 if (EVT == MVT::i8)
4279 return SDValue();
4281 DebugLoc dl = Op.getDebugLoc();
4282 SDValue N0 = Op.getOperand(0);
4283 SDValue N1 = Op.getOperand(1);
4284 SDValue N2 = Op.getOperand(2);
4286 if (EVT.getSizeInBits() == 16) {
4287 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4288 // as its second argument.
4289 if (N1.getValueType() != MVT::i32)
4290 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4291 if (N2.getValueType() != MVT::i32)
4292 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4293 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4295 return SDValue();
4298 SDValue
4299 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4300 DebugLoc dl = Op.getDebugLoc();
4301 if (Op.getValueType() == MVT::v2f32)
4302 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4303 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4304 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4305 Op.getOperand(0))));
4307 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4308 MVT VT = MVT::v2i32;
4309 switch (Op.getValueType().getSimpleVT()) {
4310 default: break;
4311 case MVT::v16i8:
4312 case MVT::v8i16:
4313 VT = MVT::v4i32;
4314 break;
4316 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4317 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4320 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4321 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4322 // one of the above mentioned nodes. It has to be wrapped because otherwise
4323 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4324 // be used to form addressing mode. These wrapped nodes will be selected
4325 // into MOV32ri.
4326 SDValue
4327 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4328 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4329 // FIXME there isn't really any debug info here, should come from the parent
4330 DebugLoc dl = CP->getDebugLoc();
4331 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4332 CP->getAlignment());
4333 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4334 // With PIC, the address is actually $g + Offset.
4335 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4336 !Subtarget->isPICStyleRIPRel()) {
4337 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4338 DAG.getNode(X86ISD::GlobalBaseReg,
4339 DebugLoc::getUnknownLoc(),
4340 getPointerTy()),
4341 Result);
4344 return Result;
4347 SDValue
4348 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4349 int64_t Offset,
4350 SelectionDAG &DAG) const {
4351 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4352 bool ExtraLoadRequired =
4353 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4355 // Create the TargetGlobalAddress node, folding in the constant
4356 // offset if it is legal.
4357 SDValue Result;
4358 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4359 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4360 Offset = 0;
4361 } else
4362 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4363 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4365 // With PIC, the address is actually $g + Offset.
4366 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4367 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4368 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4369 Result);
4372 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4373 // load the value at address GV, not the value of GV itself. This means that
4374 // the GlobalAddress must be in the base or index register of the address, not
4375 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4376 // The same applies for external symbols during PIC codegen
4377 if (ExtraLoadRequired)
4378 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4379 PseudoSourceValue::getGOT(), 0);
4381 // If there was a non-zero offset that we didn't fold, create an explicit
4382 // addition for it.
4383 if (Offset != 0)
4384 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4385 DAG.getConstant(Offset, getPointerTy()));
4387 return Result;
4390 SDValue
4391 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4392 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4393 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4394 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4397 static SDValue
4398 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4399 SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg) {
4400 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4401 DebugLoc dl = GA->getDebugLoc();
4402 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4403 GA->getValueType(0),
4404 GA->getOffset());
4405 if (InFlag) {
4406 SDValue Ops[] = { Chain, TGA, *InFlag };
4407 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4408 } else {
4409 SDValue Ops[] = { Chain, TGA };
4410 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4412 SDValue Flag = Chain.getValue(1);
4413 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4416 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4417 static SDValue
4418 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4419 const MVT PtrVT) {
4420 SDValue InFlag;
4421 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4422 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4423 DAG.getNode(X86ISD::GlobalBaseReg,
4424 DebugLoc::getUnknownLoc(),
4425 PtrVT), InFlag);
4426 InFlag = Chain.getValue(1);
4428 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX);
4431 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4432 static SDValue
4433 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4434 const MVT PtrVT) {
4435 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX);
4438 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4439 // "local exec" model.
4440 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4441 const MVT PtrVT, TLSModel::Model model,
4442 bool is64Bit) {
4443 DebugLoc dl = GA->getDebugLoc();
4444 // Get the Thread Pointer
4445 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4446 DebugLoc::getUnknownLoc(), PtrVT,
4447 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4448 MVT::i32));
4450 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4451 NULL, 0);
4453 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4454 // exec)
4455 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4456 GA->getValueType(0),
4457 GA->getOffset());
4458 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4460 if (model == TLSModel::InitialExec)
4461 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4462 PseudoSourceValue::getGOT(), 0);
4464 // The address of the thread local variable is the add of the thread
4465 // pointer with the offset of the variable.
4466 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4469 SDValue
4470 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4471 // TODO: implement the "local dynamic" model
4472 // TODO: implement the "initial exec"model for pic executables
4473 assert(Subtarget->isTargetELF() &&
4474 "TLS not implemented for non-ELF targets");
4475 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4476 GlobalValue *GV = GA->getGlobal();
4477 TLSModel::Model model =
4478 getTLSModel (GV, getTargetMachine().getRelocationModel());
4479 if (Subtarget->is64Bit()) {
4480 switch (model) {
4481 case TLSModel::GeneralDynamic:
4482 case TLSModel::LocalDynamic: // not implemented
4483 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4485 case TLSModel::InitialExec:
4486 case TLSModel::LocalExec:
4487 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, true);
4489 } else {
4490 switch (model) {
4491 case TLSModel::GeneralDynamic:
4492 case TLSModel::LocalDynamic: // not implemented
4493 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4495 case TLSModel::InitialExec:
4496 case TLSModel::LocalExec:
4497 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, false);
4500 assert(0 && "Unreachable");
4501 return SDValue();
4504 SDValue
4505 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4506 // FIXME there isn't really any debug info here
4507 DebugLoc dl = Op.getDebugLoc();
4508 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4509 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4510 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4511 // With PIC, the address is actually $g + Offset.
4512 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4513 !Subtarget->isPICStyleRIPRel()) {
4514 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4515 DAG.getNode(X86ISD::GlobalBaseReg,
4516 DebugLoc::getUnknownLoc(),
4517 getPointerTy()),
4518 Result);
4521 return Result;
4524 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4525 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4526 // FIXME there isn't really any debug into here
4527 DebugLoc dl = JT->getDebugLoc();
4528 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4529 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4530 // With PIC, the address is actually $g + Offset.
4531 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4532 !Subtarget->isPICStyleRIPRel()) {
4533 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4534 DAG.getNode(X86ISD::GlobalBaseReg,
4535 DebugLoc::getUnknownLoc(),
4536 getPointerTy()),
4537 Result);
4540 return Result;
4543 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4544 /// take a 2 x i32 value to shift plus a shift amount.
4545 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4546 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4547 MVT VT = Op.getValueType();
4548 unsigned VTBits = VT.getSizeInBits();
4549 DebugLoc dl = Op.getDebugLoc();
4550 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4551 SDValue ShOpLo = Op.getOperand(0);
4552 SDValue ShOpHi = Op.getOperand(1);
4553 SDValue ShAmt = Op.getOperand(2);
4554 SDValue Tmp1 = isSRA ?
4555 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4556 DAG.getConstant(VTBits - 1, MVT::i8)) :
4557 DAG.getConstant(0, VT);
4559 SDValue Tmp2, Tmp3;
4560 if (Op.getOpcode() == ISD::SHL_PARTS) {
4561 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4562 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4563 } else {
4564 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4565 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4568 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4569 DAG.getConstant(VTBits, MVT::i8));
4570 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4571 AndNode, DAG.getConstant(0, MVT::i8));
4573 SDValue Hi, Lo;
4574 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4575 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4576 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4578 if (Op.getOpcode() == ISD::SHL_PARTS) {
4579 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4580 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4581 } else {
4582 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4583 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4586 SDValue Ops[2] = { Lo, Hi };
4587 return DAG.getMergeValues(Ops, 2, dl);
4590 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4591 MVT SrcVT = Op.getOperand(0).getValueType();
4592 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4593 "Unknown SINT_TO_FP to lower!");
4595 // These are really Legal; caller falls through into that case.
4596 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4597 return SDValue();
4598 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4599 Subtarget->is64Bit())
4600 return SDValue();
4602 DebugLoc dl = Op.getDebugLoc();
4603 unsigned Size = SrcVT.getSizeInBits()/8;
4604 MachineFunction &MF = DAG.getMachineFunction();
4605 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4606 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4607 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4608 StackSlot,
4609 PseudoSourceValue::getFixedStack(SSFI), 0);
4611 // Build the FILD
4612 SDVTList Tys;
4613 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4614 if (useSSE)
4615 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4616 else
4617 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4618 SmallVector<SDValue, 8> Ops;
4619 Ops.push_back(Chain);
4620 Ops.push_back(StackSlot);
4621 Ops.push_back(DAG.getValueType(SrcVT));
4622 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4623 Tys, &Ops[0], Ops.size());
4625 if (useSSE) {
4626 Chain = Result.getValue(1);
4627 SDValue InFlag = Result.getValue(2);
4629 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4630 // shouldn't be necessary except that RFP cannot be live across
4631 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4632 MachineFunction &MF = DAG.getMachineFunction();
4633 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4634 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4635 Tys = DAG.getVTList(MVT::Other);
4636 SmallVector<SDValue, 8> Ops;
4637 Ops.push_back(Chain);
4638 Ops.push_back(Result);
4639 Ops.push_back(StackSlot);
4640 Ops.push_back(DAG.getValueType(Op.getValueType()));
4641 Ops.push_back(InFlag);
4642 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4643 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4644 PseudoSourceValue::getFixedStack(SSFI), 0);
4647 return Result;
4650 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4651 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4652 // This algorithm is not obvious. Here it is in C code, more or less:
4654 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4655 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4656 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4658 // Copy ints to xmm registers.
4659 __m128i xh = _mm_cvtsi32_si128( hi );
4660 __m128i xl = _mm_cvtsi32_si128( lo );
4662 // Combine into low half of a single xmm register.
4663 __m128i x = _mm_unpacklo_epi32( xh, xl );
4664 __m128d d;
4665 double sd;
4667 // Merge in appropriate exponents to give the integer bits the right
4668 // magnitude.
4669 x = _mm_unpacklo_epi32( x, exp );
4671 // Subtract away the biases to deal with the IEEE-754 double precision
4672 // implicit 1.
4673 d = _mm_sub_pd( (__m128d) x, bias );
4675 // All conversions up to here are exact. The correctly rounded result is
4676 // calculated using the current rounding mode using the following
4677 // horizontal add.
4678 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4679 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4680 // store doesn't really need to be here (except
4681 // maybe to zero the other double)
4682 return sd;
4686 DebugLoc dl = Op.getDebugLoc();
4688 // Build some magic constants.
4689 std::vector<Constant*> CV0;
4690 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4691 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4692 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4693 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4694 Constant *C0 = ConstantVector::get(CV0);
4695 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4697 std::vector<Constant*> CV1;
4698 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4699 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4700 Constant *C1 = ConstantVector::get(CV1);
4701 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4703 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4704 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4705 Op.getOperand(0),
4706 DAG.getIntPtrConstant(1)));
4707 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4708 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4709 Op.getOperand(0),
4710 DAG.getIntPtrConstant(0)));
4711 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4712 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4713 PseudoSourceValue::getConstantPool(), 0,
4714 false, 16);
4715 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4716 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4717 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4718 PseudoSourceValue::getConstantPool(), 0,
4719 false, 16);
4720 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4722 // Add the halves; easiest way is to swap them into another reg first.
4723 int ShufMask[2] = { 1, -1 };
4724 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4725 DAG.getUNDEF(MVT::v2f64), ShufMask);
4726 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4727 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4728 DAG.getIntPtrConstant(0));
4731 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4732 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4733 DebugLoc dl = Op.getDebugLoc();
4734 // FP constant to bias correct the final result.
4735 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4736 MVT::f64);
4738 // Load the 32-bit value into an XMM register.
4739 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4740 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4741 Op.getOperand(0),
4742 DAG.getIntPtrConstant(0)));
4744 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4745 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4746 DAG.getIntPtrConstant(0));
4748 // Or the load with the bias.
4749 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4750 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4751 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4752 MVT::v2f64, Load)),
4753 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4754 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4755 MVT::v2f64, Bias)));
4756 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4757 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4758 DAG.getIntPtrConstant(0));
4760 // Subtract the bias.
4761 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4763 // Handle final rounding.
4764 MVT DestVT = Op.getValueType();
4766 if (DestVT.bitsLT(MVT::f64)) {
4767 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4768 DAG.getIntPtrConstant(0));
4769 } else if (DestVT.bitsGT(MVT::f64)) {
4770 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4773 // Handle final rounding.
4774 return Sub;
4777 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4778 SDValue N0 = Op.getOperand(0);
4779 DebugLoc dl = Op.getDebugLoc();
4781 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4782 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4783 // the optimization here.
4784 if (DAG.SignBitIsZero(N0))
4785 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4787 MVT SrcVT = N0.getValueType();
4788 if (SrcVT == MVT::i64) {
4789 // We only handle SSE2 f64 target here; caller can handle the rest.
4790 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4791 return SDValue();
4793 return LowerUINT_TO_FP_i64(Op, DAG);
4794 } else if (SrcVT == MVT::i32) {
4795 return LowerUINT_TO_FP_i32(Op, DAG);
4798 assert(0 && "Unknown UINT_TO_FP to lower!");
4799 return SDValue();
4802 std::pair<SDValue,SDValue> X86TargetLowering::
4803 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4804 DebugLoc dl = Op.getDebugLoc();
4805 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4806 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4807 "Unknown FP_TO_SINT to lower!");
4809 // These are really Legal.
4810 if (Op.getValueType() == MVT::i32 &&
4811 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4812 return std::make_pair(SDValue(), SDValue());
4813 if (Subtarget->is64Bit() &&
4814 Op.getValueType() == MVT::i64 &&
4815 Op.getOperand(0).getValueType() != MVT::f80)
4816 return std::make_pair(SDValue(), SDValue());
4818 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4819 // stack slot.
4820 MachineFunction &MF = DAG.getMachineFunction();
4821 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4822 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4823 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4824 unsigned Opc;
4825 switch (Op.getValueType().getSimpleVT()) {
4826 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4827 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4828 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4829 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4832 SDValue Chain = DAG.getEntryNode();
4833 SDValue Value = Op.getOperand(0);
4834 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4835 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4836 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
4837 PseudoSourceValue::getFixedStack(SSFI), 0);
4838 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4839 SDValue Ops[] = {
4840 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4842 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
4843 Chain = Value.getValue(1);
4844 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4845 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4848 // Build the FP_TO_INT*_IN_MEM
4849 SDValue Ops[] = { Chain, Value, StackSlot };
4850 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
4852 return std::make_pair(FIST, StackSlot);
4855 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4856 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4857 SDValue FIST = Vals.first, StackSlot = Vals.second;
4858 if (FIST.getNode() == 0) return SDValue();
4860 // Load the result.
4861 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4862 FIST, StackSlot, NULL, 0);
4865 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4866 DebugLoc dl = Op.getDebugLoc();
4867 MVT VT = Op.getValueType();
4868 MVT EltVT = VT;
4869 if (VT.isVector())
4870 EltVT = VT.getVectorElementType();
4871 std::vector<Constant*> CV;
4872 if (EltVT == MVT::f64) {
4873 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4874 CV.push_back(C);
4875 CV.push_back(C);
4876 } else {
4877 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4878 CV.push_back(C);
4879 CV.push_back(C);
4880 CV.push_back(C);
4881 CV.push_back(C);
4883 Constant *C = ConstantVector::get(CV);
4884 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4885 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4886 PseudoSourceValue::getConstantPool(), 0,
4887 false, 16);
4888 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
4891 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4892 DebugLoc dl = Op.getDebugLoc();
4893 MVT VT = Op.getValueType();
4894 MVT EltVT = VT;
4895 unsigned EltNum = 1;
4896 if (VT.isVector()) {
4897 EltVT = VT.getVectorElementType();
4898 EltNum = VT.getVectorNumElements();
4900 std::vector<Constant*> CV;
4901 if (EltVT == MVT::f64) {
4902 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4903 CV.push_back(C);
4904 CV.push_back(C);
4905 } else {
4906 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4907 CV.push_back(C);
4908 CV.push_back(C);
4909 CV.push_back(C);
4910 CV.push_back(C);
4912 Constant *C = ConstantVector::get(CV);
4913 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4914 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4915 PseudoSourceValue::getConstantPool(), 0,
4916 false, 16);
4917 if (VT.isVector()) {
4918 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4919 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
4920 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4921 Op.getOperand(0)),
4922 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
4923 } else {
4924 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
4928 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4929 SDValue Op0 = Op.getOperand(0);
4930 SDValue Op1 = Op.getOperand(1);
4931 DebugLoc dl = Op.getDebugLoc();
4932 MVT VT = Op.getValueType();
4933 MVT SrcVT = Op1.getValueType();
4935 // If second operand is smaller, extend it first.
4936 if (SrcVT.bitsLT(VT)) {
4937 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
4938 SrcVT = VT;
4940 // And if it is bigger, shrink it first.
4941 if (SrcVT.bitsGT(VT)) {
4942 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
4943 SrcVT = VT;
4946 // At this point the operands and the result should have the same
4947 // type, and that won't be f80 since that is not custom lowered.
4949 // First get the sign bit of second operand.
4950 std::vector<Constant*> CV;
4951 if (SrcVT == MVT::f64) {
4952 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4953 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4954 } else {
4955 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4956 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4957 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4958 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4960 Constant *C = ConstantVector::get(CV);
4961 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4962 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
4963 PseudoSourceValue::getConstantPool(), 0,
4964 false, 16);
4965 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
4967 // Shift sign bit right or left if the two operands have different types.
4968 if (SrcVT.bitsGT(VT)) {
4969 // Op0 is MVT::f32, Op1 is MVT::f64.
4970 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
4971 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
4972 DAG.getConstant(32, MVT::i32));
4973 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
4974 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
4975 DAG.getIntPtrConstant(0));
4978 // Clear first operand sign bit.
4979 CV.clear();
4980 if (VT == MVT::f64) {
4981 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4982 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4983 } else {
4984 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4985 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4986 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4987 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4989 C = ConstantVector::get(CV);
4990 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4991 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4992 PseudoSourceValue::getConstantPool(), 0,
4993 false, 16);
4994 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
4996 // Or the value with the sign bit.
4997 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5000 /// Emit nodes that will be selected as "test Op0,Op0", or something
5001 /// equivalent.
5002 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5003 SelectionDAG &DAG) {
5004 DebugLoc dl = Op.getDebugLoc();
5006 // CF and OF aren't always set the way we want. Determine which
5007 // of these we need.
5008 bool NeedCF = false;
5009 bool NeedOF = false;
5010 switch (X86CC) {
5011 case X86::COND_A: case X86::COND_AE:
5012 case X86::COND_B: case X86::COND_BE:
5013 NeedCF = true;
5014 break;
5015 case X86::COND_G: case X86::COND_GE:
5016 case X86::COND_L: case X86::COND_LE:
5017 case X86::COND_O: case X86::COND_NO:
5018 NeedOF = true;
5019 break;
5020 default: break;
5023 // See if we can use the EFLAGS value from the operand instead of
5024 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5025 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5026 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5027 unsigned Opcode = 0;
5028 unsigned NumOperands = 0;
5029 switch (Op.getNode()->getOpcode()) {
5030 case ISD::ADD:
5031 // Due to an isel shortcoming, be conservative if this add is likely to
5032 // be selected as part of a load-modify-store instruction. When the root
5033 // node in a match is a store, isel doesn't know how to remap non-chain
5034 // non-flag uses of other nodes in the match, such as the ADD in this
5035 // case. This leads to the ADD being left around and reselected, with
5036 // the result being two adds in the output.
5037 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5038 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5039 if (UI->getOpcode() == ISD::STORE)
5040 goto default_case;
5041 if (ConstantSDNode *C =
5042 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5043 // An add of one will be selected as an INC.
5044 if (C->getAPIntValue() == 1) {
5045 Opcode = X86ISD::INC;
5046 NumOperands = 1;
5047 break;
5049 // An add of negative one (subtract of one) will be selected as a DEC.
5050 if (C->getAPIntValue().isAllOnesValue()) {
5051 Opcode = X86ISD::DEC;
5052 NumOperands = 1;
5053 break;
5056 // Otherwise use a regular EFLAGS-setting add.
5057 Opcode = X86ISD::ADD;
5058 NumOperands = 2;
5059 break;
5060 case ISD::SUB:
5061 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5062 // likely to be selected as part of a load-modify-store instruction.
5063 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5064 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5065 if (UI->getOpcode() == ISD::STORE)
5066 goto default_case;
5067 // Otherwise use a regular EFLAGS-setting sub.
5068 Opcode = X86ISD::SUB;
5069 NumOperands = 2;
5070 break;
5071 case X86ISD::ADD:
5072 case X86ISD::SUB:
5073 case X86ISD::INC:
5074 case X86ISD::DEC:
5075 return SDValue(Op.getNode(), 1);
5076 default:
5077 default_case:
5078 break;
5080 if (Opcode != 0) {
5081 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5082 SmallVector<SDValue, 4> Ops;
5083 for (unsigned i = 0; i != NumOperands; ++i)
5084 Ops.push_back(Op.getOperand(i));
5085 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5086 DAG.ReplaceAllUsesWith(Op, New);
5087 return SDValue(New.getNode(), 1);
5091 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5092 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5093 DAG.getConstant(0, Op.getValueType()));
5096 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5097 /// equivalent.
5098 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5099 SelectionDAG &DAG) {
5100 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5101 if (C->getAPIntValue() == 0)
5102 return EmitTest(Op0, X86CC, DAG);
5104 DebugLoc dl = Op0.getDebugLoc();
5105 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5108 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5109 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5110 SDValue Op0 = Op.getOperand(0);
5111 SDValue Op1 = Op.getOperand(1);
5112 DebugLoc dl = Op.getDebugLoc();
5113 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5115 // Lower (X & (1 << N)) == 0 to BT(X, N).
5116 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5117 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5118 if (Op0.getOpcode() == ISD::AND &&
5119 Op0.hasOneUse() &&
5120 Op1.getOpcode() == ISD::Constant &&
5121 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5122 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5123 SDValue LHS, RHS;
5124 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5125 if (ConstantSDNode *Op010C =
5126 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5127 if (Op010C->getZExtValue() == 1) {
5128 LHS = Op0.getOperand(0);
5129 RHS = Op0.getOperand(1).getOperand(1);
5131 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5132 if (ConstantSDNode *Op000C =
5133 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5134 if (Op000C->getZExtValue() == 1) {
5135 LHS = Op0.getOperand(1);
5136 RHS = Op0.getOperand(0).getOperand(1);
5138 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5139 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5140 SDValue AndLHS = Op0.getOperand(0);
5141 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5142 LHS = AndLHS.getOperand(0);
5143 RHS = AndLHS.getOperand(1);
5147 if (LHS.getNode()) {
5148 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5149 // instruction. Since the shift amount is in-range-or-undefined, we know
5150 // that doing a bittest on the i16 value is ok. We extend to i32 because
5151 // the encoding for the i16 version is larger than the i32 version.
5152 if (LHS.getValueType() == MVT::i8)
5153 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5155 // If the operand types disagree, extend the shift amount to match. Since
5156 // BT ignores high bits (like shifts) we can use anyextend.
5157 if (LHS.getValueType() != RHS.getValueType())
5158 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5160 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5161 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5162 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5163 DAG.getConstant(Cond, MVT::i8), BT);
5167 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5168 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5170 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5171 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5172 DAG.getConstant(X86CC, MVT::i8), Cond);
5175 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5176 SDValue Cond;
5177 SDValue Op0 = Op.getOperand(0);
5178 SDValue Op1 = Op.getOperand(1);
5179 SDValue CC = Op.getOperand(2);
5180 MVT VT = Op.getValueType();
5181 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5182 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5183 DebugLoc dl = Op.getDebugLoc();
5185 if (isFP) {
5186 unsigned SSECC = 8;
5187 MVT VT0 = Op0.getValueType();
5188 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5189 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5190 bool Swap = false;
5192 switch (SetCCOpcode) {
5193 default: break;
5194 case ISD::SETOEQ:
5195 case ISD::SETEQ: SSECC = 0; break;
5196 case ISD::SETOGT:
5197 case ISD::SETGT: Swap = true; // Fallthrough
5198 case ISD::SETLT:
5199 case ISD::SETOLT: SSECC = 1; break;
5200 case ISD::SETOGE:
5201 case ISD::SETGE: Swap = true; // Fallthrough
5202 case ISD::SETLE:
5203 case ISD::SETOLE: SSECC = 2; break;
5204 case ISD::SETUO: SSECC = 3; break;
5205 case ISD::SETUNE:
5206 case ISD::SETNE: SSECC = 4; break;
5207 case ISD::SETULE: Swap = true;
5208 case ISD::SETUGE: SSECC = 5; break;
5209 case ISD::SETULT: Swap = true;
5210 case ISD::SETUGT: SSECC = 6; break;
5211 case ISD::SETO: SSECC = 7; break;
5213 if (Swap)
5214 std::swap(Op0, Op1);
5216 // In the two special cases we can't handle, emit two comparisons.
5217 if (SSECC == 8) {
5218 if (SetCCOpcode == ISD::SETUEQ) {
5219 SDValue UNORD, EQ;
5220 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5221 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5222 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5224 else if (SetCCOpcode == ISD::SETONE) {
5225 SDValue ORD, NEQ;
5226 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5227 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5228 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5230 assert(0 && "Illegal FP comparison");
5232 // Handle all other FP comparisons here.
5233 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5236 // We are handling one of the integer comparisons here. Since SSE only has
5237 // GT and EQ comparisons for integer, swapping operands and multiple
5238 // operations may be required for some comparisons.
5239 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5240 bool Swap = false, Invert = false, FlipSigns = false;
5242 switch (VT.getSimpleVT()) {
5243 default: break;
5244 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5245 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5246 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5247 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5250 switch (SetCCOpcode) {
5251 default: break;
5252 case ISD::SETNE: Invert = true;
5253 case ISD::SETEQ: Opc = EQOpc; break;
5254 case ISD::SETLT: Swap = true;
5255 case ISD::SETGT: Opc = GTOpc; break;
5256 case ISD::SETGE: Swap = true;
5257 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5258 case ISD::SETULT: Swap = true;
5259 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5260 case ISD::SETUGE: Swap = true;
5261 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5263 if (Swap)
5264 std::swap(Op0, Op1);
5266 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5267 // bits of the inputs before performing those operations.
5268 if (FlipSigns) {
5269 MVT EltVT = VT.getVectorElementType();
5270 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5271 EltVT);
5272 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5273 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5274 SignBits.size());
5275 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5276 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5279 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5281 // If the logical-not of the result is required, perform that now.
5282 if (Invert)
5283 Result = DAG.getNOT(dl, Result, VT);
5285 return Result;
5288 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5289 static bool isX86LogicalCmp(SDValue Op) {
5290 unsigned Opc = Op.getNode()->getOpcode();
5291 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5292 return true;
5293 if (Op.getResNo() == 1 &&
5294 (Opc == X86ISD::ADD ||
5295 Opc == X86ISD::SUB ||
5296 Opc == X86ISD::SMUL ||
5297 Opc == X86ISD::UMUL ||
5298 Opc == X86ISD::INC ||
5299 Opc == X86ISD::DEC))
5300 return true;
5302 return false;
5305 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5306 bool addTest = true;
5307 SDValue Cond = Op.getOperand(0);
5308 DebugLoc dl = Op.getDebugLoc();
5309 SDValue CC;
5311 if (Cond.getOpcode() == ISD::SETCC)
5312 Cond = LowerSETCC(Cond, DAG);
5314 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5315 // setting operand in place of the X86ISD::SETCC.
5316 if (Cond.getOpcode() == X86ISD::SETCC) {
5317 CC = Cond.getOperand(0);
5319 SDValue Cmp = Cond.getOperand(1);
5320 unsigned Opc = Cmp.getOpcode();
5321 MVT VT = Op.getValueType();
5323 bool IllegalFPCMov = false;
5324 if (VT.isFloatingPoint() && !VT.isVector() &&
5325 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5326 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5328 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5329 Opc == X86ISD::BT) { // FIXME
5330 Cond = Cmp;
5331 addTest = false;
5335 if (addTest) {
5336 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5337 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5340 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5341 SmallVector<SDValue, 4> Ops;
5342 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5343 // condition is true.
5344 Ops.push_back(Op.getOperand(2));
5345 Ops.push_back(Op.getOperand(1));
5346 Ops.push_back(CC);
5347 Ops.push_back(Cond);
5348 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5351 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5352 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5353 // from the AND / OR.
5354 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5355 Opc = Op.getOpcode();
5356 if (Opc != ISD::OR && Opc != ISD::AND)
5357 return false;
5358 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5359 Op.getOperand(0).hasOneUse() &&
5360 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5361 Op.getOperand(1).hasOneUse());
5364 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5365 // 1 and that the SETCC node has a single use.
5366 static bool isXor1OfSetCC(SDValue Op) {
5367 if (Op.getOpcode() != ISD::XOR)
5368 return false;
5369 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5370 if (N1C && N1C->getAPIntValue() == 1) {
5371 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5372 Op.getOperand(0).hasOneUse();
5374 return false;
5377 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5378 bool addTest = true;
5379 SDValue Chain = Op.getOperand(0);
5380 SDValue Cond = Op.getOperand(1);
5381 SDValue Dest = Op.getOperand(2);
5382 DebugLoc dl = Op.getDebugLoc();
5383 SDValue CC;
5385 if (Cond.getOpcode() == ISD::SETCC)
5386 Cond = LowerSETCC(Cond, DAG);
5387 #if 0
5388 // FIXME: LowerXALUO doesn't handle these!!
5389 else if (Cond.getOpcode() == X86ISD::ADD ||
5390 Cond.getOpcode() == X86ISD::SUB ||
5391 Cond.getOpcode() == X86ISD::SMUL ||
5392 Cond.getOpcode() == X86ISD::UMUL)
5393 Cond = LowerXALUO(Cond, DAG);
5394 #endif
5396 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5397 // setting operand in place of the X86ISD::SETCC.
5398 if (Cond.getOpcode() == X86ISD::SETCC) {
5399 CC = Cond.getOperand(0);
5401 SDValue Cmp = Cond.getOperand(1);
5402 unsigned Opc = Cmp.getOpcode();
5403 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5404 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5405 Cond = Cmp;
5406 addTest = false;
5407 } else {
5408 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5409 default: break;
5410 case X86::COND_O:
5411 case X86::COND_B:
5412 // These can only come from an arithmetic instruction with overflow,
5413 // e.g. SADDO, UADDO.
5414 Cond = Cond.getNode()->getOperand(1);
5415 addTest = false;
5416 break;
5419 } else {
5420 unsigned CondOpc;
5421 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5422 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5423 if (CondOpc == ISD::OR) {
5424 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5425 // two branches instead of an explicit OR instruction with a
5426 // separate test.
5427 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5428 isX86LogicalCmp(Cmp)) {
5429 CC = Cond.getOperand(0).getOperand(0);
5430 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5431 Chain, Dest, CC, Cmp);
5432 CC = Cond.getOperand(1).getOperand(0);
5433 Cond = Cmp;
5434 addTest = false;
5436 } else { // ISD::AND
5437 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5438 // two branches instead of an explicit AND instruction with a
5439 // separate test. However, we only do this if this block doesn't
5440 // have a fall-through edge, because this requires an explicit
5441 // jmp when the condition is false.
5442 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5443 isX86LogicalCmp(Cmp) &&
5444 Op.getNode()->hasOneUse()) {
5445 X86::CondCode CCode =
5446 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5447 CCode = X86::GetOppositeBranchCondition(CCode);
5448 CC = DAG.getConstant(CCode, MVT::i8);
5449 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5450 // Look for an unconditional branch following this conditional branch.
5451 // We need this because we need to reverse the successors in order
5452 // to implement FCMP_OEQ.
5453 if (User.getOpcode() == ISD::BR) {
5454 SDValue FalseBB = User.getOperand(1);
5455 SDValue NewBR =
5456 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5457 assert(NewBR == User);
5458 Dest = FalseBB;
5460 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5461 Chain, Dest, CC, Cmp);
5462 X86::CondCode CCode =
5463 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5464 CCode = X86::GetOppositeBranchCondition(CCode);
5465 CC = DAG.getConstant(CCode, MVT::i8);
5466 Cond = Cmp;
5467 addTest = false;
5471 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5472 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5473 // It should be transformed during dag combiner except when the condition
5474 // is set by a arithmetics with overflow node.
5475 X86::CondCode CCode =
5476 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5477 CCode = X86::GetOppositeBranchCondition(CCode);
5478 CC = DAG.getConstant(CCode, MVT::i8);
5479 Cond = Cond.getOperand(0).getOperand(1);
5480 addTest = false;
5484 if (addTest) {
5485 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5486 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5488 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5489 Chain, Dest, CC, Cond);
5493 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5494 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5495 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5496 // that the guard pages used by the OS virtual memory manager are allocated in
5497 // correct sequence.
5498 SDValue
5499 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5500 SelectionDAG &DAG) {
5501 assert(Subtarget->isTargetCygMing() &&
5502 "This should be used only on Cygwin/Mingw targets");
5503 DebugLoc dl = Op.getDebugLoc();
5505 // Get the inputs.
5506 SDValue Chain = Op.getOperand(0);
5507 SDValue Size = Op.getOperand(1);
5508 // FIXME: Ensure alignment here
5510 SDValue Flag;
5512 MVT IntPtr = getPointerTy();
5513 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5515 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5517 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5518 Flag = Chain.getValue(1);
5520 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5521 SDValue Ops[] = { Chain,
5522 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5523 DAG.getRegister(X86::EAX, IntPtr),
5524 DAG.getRegister(X86StackPtr, SPTy),
5525 Flag };
5526 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5527 Flag = Chain.getValue(1);
5529 Chain = DAG.getCALLSEQ_END(Chain,
5530 DAG.getIntPtrConstant(0, true),
5531 DAG.getIntPtrConstant(0, true),
5532 Flag);
5534 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5536 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5537 return DAG.getMergeValues(Ops1, 2, dl);
5540 SDValue
5541 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5542 SDValue Chain,
5543 SDValue Dst, SDValue Src,
5544 SDValue Size, unsigned Align,
5545 const Value *DstSV,
5546 uint64_t DstSVOff) {
5547 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5549 // If not DWORD aligned or size is more than the threshold, call the library.
5550 // The libc version is likely to be faster for these cases. It can use the
5551 // address value and run time information about the CPU.
5552 if ((Align & 3) != 0 ||
5553 !ConstantSize ||
5554 ConstantSize->getZExtValue() >
5555 getSubtarget()->getMaxInlineSizeThreshold()) {
5556 SDValue InFlag(0, 0);
5558 // Check to see if there is a specialized entry-point for memory zeroing.
5559 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5561 if (const char *bzeroEntry = V &&
5562 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5563 MVT IntPtr = getPointerTy();
5564 const Type *IntPtrTy = TD->getIntPtrType();
5565 TargetLowering::ArgListTy Args;
5566 TargetLowering::ArgListEntry Entry;
5567 Entry.Node = Dst;
5568 Entry.Ty = IntPtrTy;
5569 Args.push_back(Entry);
5570 Entry.Node = Size;
5571 Args.push_back(Entry);
5572 std::pair<SDValue,SDValue> CallResult =
5573 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5574 CallingConv::C, false,
5575 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5576 return CallResult.second;
5579 // Otherwise have the target-independent code call memset.
5580 return SDValue();
5583 uint64_t SizeVal = ConstantSize->getZExtValue();
5584 SDValue InFlag(0, 0);
5585 MVT AVT;
5586 SDValue Count;
5587 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5588 unsigned BytesLeft = 0;
5589 bool TwoRepStos = false;
5590 if (ValC) {
5591 unsigned ValReg;
5592 uint64_t Val = ValC->getZExtValue() & 255;
5594 // If the value is a constant, then we can potentially use larger sets.
5595 switch (Align & 3) {
5596 case 2: // WORD aligned
5597 AVT = MVT::i16;
5598 ValReg = X86::AX;
5599 Val = (Val << 8) | Val;
5600 break;
5601 case 0: // DWORD aligned
5602 AVT = MVT::i32;
5603 ValReg = X86::EAX;
5604 Val = (Val << 8) | Val;
5605 Val = (Val << 16) | Val;
5606 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5607 AVT = MVT::i64;
5608 ValReg = X86::RAX;
5609 Val = (Val << 32) | Val;
5611 break;
5612 default: // Byte aligned
5613 AVT = MVT::i8;
5614 ValReg = X86::AL;
5615 Count = DAG.getIntPtrConstant(SizeVal);
5616 break;
5619 if (AVT.bitsGT(MVT::i8)) {
5620 unsigned UBytes = AVT.getSizeInBits() / 8;
5621 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5622 BytesLeft = SizeVal % UBytes;
5625 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5626 InFlag);
5627 InFlag = Chain.getValue(1);
5628 } else {
5629 AVT = MVT::i8;
5630 Count = DAG.getIntPtrConstant(SizeVal);
5631 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5632 InFlag = Chain.getValue(1);
5635 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5636 X86::ECX,
5637 Count, InFlag);
5638 InFlag = Chain.getValue(1);
5639 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5640 X86::EDI,
5641 Dst, InFlag);
5642 InFlag = Chain.getValue(1);
5644 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5645 SmallVector<SDValue, 8> Ops;
5646 Ops.push_back(Chain);
5647 Ops.push_back(DAG.getValueType(AVT));
5648 Ops.push_back(InFlag);
5649 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5651 if (TwoRepStos) {
5652 InFlag = Chain.getValue(1);
5653 Count = Size;
5654 MVT CVT = Count.getValueType();
5655 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5656 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5657 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5658 X86::ECX,
5659 Left, InFlag);
5660 InFlag = Chain.getValue(1);
5661 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5662 Ops.clear();
5663 Ops.push_back(Chain);
5664 Ops.push_back(DAG.getValueType(MVT::i8));
5665 Ops.push_back(InFlag);
5666 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5667 } else if (BytesLeft) {
5668 // Handle the last 1 - 7 bytes.
5669 unsigned Offset = SizeVal - BytesLeft;
5670 MVT AddrVT = Dst.getValueType();
5671 MVT SizeVT = Size.getValueType();
5673 Chain = DAG.getMemset(Chain, dl,
5674 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5675 DAG.getConstant(Offset, AddrVT)),
5676 Src,
5677 DAG.getConstant(BytesLeft, SizeVT),
5678 Align, DstSV, DstSVOff + Offset);
5681 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5682 return Chain;
5685 SDValue
5686 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5687 SDValue Chain, SDValue Dst, SDValue Src,
5688 SDValue Size, unsigned Align,
5689 bool AlwaysInline,
5690 const Value *DstSV, uint64_t DstSVOff,
5691 const Value *SrcSV, uint64_t SrcSVOff) {
5692 // This requires the copy size to be a constant, preferrably
5693 // within a subtarget-specific limit.
5694 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5695 if (!ConstantSize)
5696 return SDValue();
5697 uint64_t SizeVal = ConstantSize->getZExtValue();
5698 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5699 return SDValue();
5701 /// If not DWORD aligned, call the library.
5702 if ((Align & 3) != 0)
5703 return SDValue();
5705 // DWORD aligned
5706 MVT AVT = MVT::i32;
5707 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5708 AVT = MVT::i64;
5710 unsigned UBytes = AVT.getSizeInBits() / 8;
5711 unsigned CountVal = SizeVal / UBytes;
5712 SDValue Count = DAG.getIntPtrConstant(CountVal);
5713 unsigned BytesLeft = SizeVal % UBytes;
5715 SDValue InFlag(0, 0);
5716 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5717 X86::ECX,
5718 Count, InFlag);
5719 InFlag = Chain.getValue(1);
5720 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5721 X86::EDI,
5722 Dst, InFlag);
5723 InFlag = Chain.getValue(1);
5724 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5725 X86::ESI,
5726 Src, InFlag);
5727 InFlag = Chain.getValue(1);
5729 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5730 SmallVector<SDValue, 8> Ops;
5731 Ops.push_back(Chain);
5732 Ops.push_back(DAG.getValueType(AVT));
5733 Ops.push_back(InFlag);
5734 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5736 SmallVector<SDValue, 4> Results;
5737 Results.push_back(RepMovs);
5738 if (BytesLeft) {
5739 // Handle the last 1 - 7 bytes.
5740 unsigned Offset = SizeVal - BytesLeft;
5741 MVT DstVT = Dst.getValueType();
5742 MVT SrcVT = Src.getValueType();
5743 MVT SizeVT = Size.getValueType();
5744 Results.push_back(DAG.getMemcpy(Chain, dl,
5745 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5746 DAG.getConstant(Offset, DstVT)),
5747 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5748 DAG.getConstant(Offset, SrcVT)),
5749 DAG.getConstant(BytesLeft, SizeVT),
5750 Align, AlwaysInline,
5751 DstSV, DstSVOff + Offset,
5752 SrcSV, SrcSVOff + Offset));
5755 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5756 &Results[0], Results.size());
5759 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5760 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5761 DebugLoc dl = Op.getDebugLoc();
5763 if (!Subtarget->is64Bit()) {
5764 // vastart just stores the address of the VarArgsFrameIndex slot into the
5765 // memory location argument.
5766 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5767 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5770 // __va_list_tag:
5771 // gp_offset (0 - 6 * 8)
5772 // fp_offset (48 - 48 + 8 * 16)
5773 // overflow_arg_area (point to parameters coming in memory).
5774 // reg_save_area
5775 SmallVector<SDValue, 8> MemOps;
5776 SDValue FIN = Op.getOperand(1);
5777 // Store gp_offset
5778 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5779 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5780 FIN, SV, 0);
5781 MemOps.push_back(Store);
5783 // Store fp_offset
5784 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5785 FIN, DAG.getIntPtrConstant(4));
5786 Store = DAG.getStore(Op.getOperand(0), dl,
5787 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5788 FIN, SV, 0);
5789 MemOps.push_back(Store);
5791 // Store ptr to overflow_arg_area
5792 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5793 FIN, DAG.getIntPtrConstant(4));
5794 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5795 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5796 MemOps.push_back(Store);
5798 // Store ptr to reg_save_area.
5799 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5800 FIN, DAG.getIntPtrConstant(8));
5801 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5802 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5803 MemOps.push_back(Store);
5804 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5805 &MemOps[0], MemOps.size());
5808 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5809 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5810 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5811 SDValue Chain = Op.getOperand(0);
5812 SDValue SrcPtr = Op.getOperand(1);
5813 SDValue SrcSV = Op.getOperand(2);
5815 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5816 abort();
5817 return SDValue();
5820 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5821 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5822 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5823 SDValue Chain = Op.getOperand(0);
5824 SDValue DstPtr = Op.getOperand(1);
5825 SDValue SrcPtr = Op.getOperand(2);
5826 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5827 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5828 DebugLoc dl = Op.getDebugLoc();
5830 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5831 DAG.getIntPtrConstant(24), 8, false,
5832 DstSV, 0, SrcSV, 0);
5835 SDValue
5836 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5837 DebugLoc dl = Op.getDebugLoc();
5838 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5839 switch (IntNo) {
5840 default: return SDValue(); // Don't custom lower most intrinsics.
5841 // Comparison intrinsics.
5842 case Intrinsic::x86_sse_comieq_ss:
5843 case Intrinsic::x86_sse_comilt_ss:
5844 case Intrinsic::x86_sse_comile_ss:
5845 case Intrinsic::x86_sse_comigt_ss:
5846 case Intrinsic::x86_sse_comige_ss:
5847 case Intrinsic::x86_sse_comineq_ss:
5848 case Intrinsic::x86_sse_ucomieq_ss:
5849 case Intrinsic::x86_sse_ucomilt_ss:
5850 case Intrinsic::x86_sse_ucomile_ss:
5851 case Intrinsic::x86_sse_ucomigt_ss:
5852 case Intrinsic::x86_sse_ucomige_ss:
5853 case Intrinsic::x86_sse_ucomineq_ss:
5854 case Intrinsic::x86_sse2_comieq_sd:
5855 case Intrinsic::x86_sse2_comilt_sd:
5856 case Intrinsic::x86_sse2_comile_sd:
5857 case Intrinsic::x86_sse2_comigt_sd:
5858 case Intrinsic::x86_sse2_comige_sd:
5859 case Intrinsic::x86_sse2_comineq_sd:
5860 case Intrinsic::x86_sse2_ucomieq_sd:
5861 case Intrinsic::x86_sse2_ucomilt_sd:
5862 case Intrinsic::x86_sse2_ucomile_sd:
5863 case Intrinsic::x86_sse2_ucomigt_sd:
5864 case Intrinsic::x86_sse2_ucomige_sd:
5865 case Intrinsic::x86_sse2_ucomineq_sd: {
5866 unsigned Opc = 0;
5867 ISD::CondCode CC = ISD::SETCC_INVALID;
5868 switch (IntNo) {
5869 default: break;
5870 case Intrinsic::x86_sse_comieq_ss:
5871 case Intrinsic::x86_sse2_comieq_sd:
5872 Opc = X86ISD::COMI;
5873 CC = ISD::SETEQ;
5874 break;
5875 case Intrinsic::x86_sse_comilt_ss:
5876 case Intrinsic::x86_sse2_comilt_sd:
5877 Opc = X86ISD::COMI;
5878 CC = ISD::SETLT;
5879 break;
5880 case Intrinsic::x86_sse_comile_ss:
5881 case Intrinsic::x86_sse2_comile_sd:
5882 Opc = X86ISD::COMI;
5883 CC = ISD::SETLE;
5884 break;
5885 case Intrinsic::x86_sse_comigt_ss:
5886 case Intrinsic::x86_sse2_comigt_sd:
5887 Opc = X86ISD::COMI;
5888 CC = ISD::SETGT;
5889 break;
5890 case Intrinsic::x86_sse_comige_ss:
5891 case Intrinsic::x86_sse2_comige_sd:
5892 Opc = X86ISD::COMI;
5893 CC = ISD::SETGE;
5894 break;
5895 case Intrinsic::x86_sse_comineq_ss:
5896 case Intrinsic::x86_sse2_comineq_sd:
5897 Opc = X86ISD::COMI;
5898 CC = ISD::SETNE;
5899 break;
5900 case Intrinsic::x86_sse_ucomieq_ss:
5901 case Intrinsic::x86_sse2_ucomieq_sd:
5902 Opc = X86ISD::UCOMI;
5903 CC = ISD::SETEQ;
5904 break;
5905 case Intrinsic::x86_sse_ucomilt_ss:
5906 case Intrinsic::x86_sse2_ucomilt_sd:
5907 Opc = X86ISD::UCOMI;
5908 CC = ISD::SETLT;
5909 break;
5910 case Intrinsic::x86_sse_ucomile_ss:
5911 case Intrinsic::x86_sse2_ucomile_sd:
5912 Opc = X86ISD::UCOMI;
5913 CC = ISD::SETLE;
5914 break;
5915 case Intrinsic::x86_sse_ucomigt_ss:
5916 case Intrinsic::x86_sse2_ucomigt_sd:
5917 Opc = X86ISD::UCOMI;
5918 CC = ISD::SETGT;
5919 break;
5920 case Intrinsic::x86_sse_ucomige_ss:
5921 case Intrinsic::x86_sse2_ucomige_sd:
5922 Opc = X86ISD::UCOMI;
5923 CC = ISD::SETGE;
5924 break;
5925 case Intrinsic::x86_sse_ucomineq_ss:
5926 case Intrinsic::x86_sse2_ucomineq_sd:
5927 Opc = X86ISD::UCOMI;
5928 CC = ISD::SETNE;
5929 break;
5932 SDValue LHS = Op.getOperand(1);
5933 SDValue RHS = Op.getOperand(2);
5934 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5935 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
5936 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5937 DAG.getConstant(X86CC, MVT::i8), Cond);
5938 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
5941 // Fix vector shift instructions where the last operand is a non-immediate
5942 // i32 value.
5943 case Intrinsic::x86_sse2_pslli_w:
5944 case Intrinsic::x86_sse2_pslli_d:
5945 case Intrinsic::x86_sse2_pslli_q:
5946 case Intrinsic::x86_sse2_psrli_w:
5947 case Intrinsic::x86_sse2_psrli_d:
5948 case Intrinsic::x86_sse2_psrli_q:
5949 case Intrinsic::x86_sse2_psrai_w:
5950 case Intrinsic::x86_sse2_psrai_d:
5951 case Intrinsic::x86_mmx_pslli_w:
5952 case Intrinsic::x86_mmx_pslli_d:
5953 case Intrinsic::x86_mmx_pslli_q:
5954 case Intrinsic::x86_mmx_psrli_w:
5955 case Intrinsic::x86_mmx_psrli_d:
5956 case Intrinsic::x86_mmx_psrli_q:
5957 case Intrinsic::x86_mmx_psrai_w:
5958 case Intrinsic::x86_mmx_psrai_d: {
5959 SDValue ShAmt = Op.getOperand(2);
5960 if (isa<ConstantSDNode>(ShAmt))
5961 return SDValue();
5963 unsigned NewIntNo = 0;
5964 MVT ShAmtVT = MVT::v4i32;
5965 switch (IntNo) {
5966 case Intrinsic::x86_sse2_pslli_w:
5967 NewIntNo = Intrinsic::x86_sse2_psll_w;
5968 break;
5969 case Intrinsic::x86_sse2_pslli_d:
5970 NewIntNo = Intrinsic::x86_sse2_psll_d;
5971 break;
5972 case Intrinsic::x86_sse2_pslli_q:
5973 NewIntNo = Intrinsic::x86_sse2_psll_q;
5974 break;
5975 case Intrinsic::x86_sse2_psrli_w:
5976 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5977 break;
5978 case Intrinsic::x86_sse2_psrli_d:
5979 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5980 break;
5981 case Intrinsic::x86_sse2_psrli_q:
5982 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5983 break;
5984 case Intrinsic::x86_sse2_psrai_w:
5985 NewIntNo = Intrinsic::x86_sse2_psra_w;
5986 break;
5987 case Intrinsic::x86_sse2_psrai_d:
5988 NewIntNo = Intrinsic::x86_sse2_psra_d;
5989 break;
5990 default: {
5991 ShAmtVT = MVT::v2i32;
5992 switch (IntNo) {
5993 case Intrinsic::x86_mmx_pslli_w:
5994 NewIntNo = Intrinsic::x86_mmx_psll_w;
5995 break;
5996 case Intrinsic::x86_mmx_pslli_d:
5997 NewIntNo = Intrinsic::x86_mmx_psll_d;
5998 break;
5999 case Intrinsic::x86_mmx_pslli_q:
6000 NewIntNo = Intrinsic::x86_mmx_psll_q;
6001 break;
6002 case Intrinsic::x86_mmx_psrli_w:
6003 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6004 break;
6005 case Intrinsic::x86_mmx_psrli_d:
6006 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6007 break;
6008 case Intrinsic::x86_mmx_psrli_q:
6009 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6010 break;
6011 case Intrinsic::x86_mmx_psrai_w:
6012 NewIntNo = Intrinsic::x86_mmx_psra_w;
6013 break;
6014 case Intrinsic::x86_mmx_psrai_d:
6015 NewIntNo = Intrinsic::x86_mmx_psra_d;
6016 break;
6017 default: abort(); // Can't reach here.
6019 break;
6022 MVT VT = Op.getValueType();
6023 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6024 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6025 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6026 DAG.getConstant(NewIntNo, MVT::i32),
6027 Op.getOperand(1), ShAmt);
6032 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6033 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6034 DebugLoc dl = Op.getDebugLoc();
6036 if (Depth > 0) {
6037 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6038 SDValue Offset =
6039 DAG.getConstant(TD->getPointerSize(),
6040 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6041 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6042 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6043 FrameAddr, Offset),
6044 NULL, 0);
6047 // Just load the return address.
6048 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6049 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6050 RetAddrFI, NULL, 0);
6053 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6054 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6055 MFI->setFrameAddressIsTaken(true);
6056 MVT VT = Op.getValueType();
6057 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6058 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6059 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6060 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6061 while (Depth--)
6062 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6063 return FrameAddr;
6066 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6067 SelectionDAG &DAG) {
6068 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6071 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6073 MachineFunction &MF = DAG.getMachineFunction();
6074 SDValue Chain = Op.getOperand(0);
6075 SDValue Offset = Op.getOperand(1);
6076 SDValue Handler = Op.getOperand(2);
6077 DebugLoc dl = Op.getDebugLoc();
6079 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6080 getPointerTy());
6081 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6083 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6084 DAG.getIntPtrConstant(-TD->getPointerSize()));
6085 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6086 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6087 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6088 MF.getRegInfo().addLiveOut(StoreAddrReg);
6090 return DAG.getNode(X86ISD::EH_RETURN, dl,
6091 MVT::Other,
6092 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6095 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6096 SelectionDAG &DAG) {
6097 SDValue Root = Op.getOperand(0);
6098 SDValue Trmp = Op.getOperand(1); // trampoline
6099 SDValue FPtr = Op.getOperand(2); // nested function
6100 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6101 DebugLoc dl = Op.getDebugLoc();
6103 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6105 const X86InstrInfo *TII =
6106 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6108 if (Subtarget->is64Bit()) {
6109 SDValue OutChains[6];
6111 // Large code-model.
6113 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6114 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6116 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6117 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6119 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6121 // Load the pointer to the nested function into R11.
6122 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6123 SDValue Addr = Trmp;
6124 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6125 Addr, TrmpAddr, 0);
6127 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6128 DAG.getConstant(2, MVT::i64));
6129 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6131 // Load the 'nest' parameter value into R10.
6132 // R10 is specified in X86CallingConv.td
6133 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6134 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6135 DAG.getConstant(10, MVT::i64));
6136 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6137 Addr, TrmpAddr, 10);
6139 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6140 DAG.getConstant(12, MVT::i64));
6141 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6143 // Jump to the nested function.
6144 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6145 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6146 DAG.getConstant(20, MVT::i64));
6147 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6148 Addr, TrmpAddr, 20);
6150 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6151 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6152 DAG.getConstant(22, MVT::i64));
6153 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6154 TrmpAddr, 22);
6156 SDValue Ops[] =
6157 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6158 return DAG.getMergeValues(Ops, 2, dl);
6159 } else {
6160 const Function *Func =
6161 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6162 unsigned CC = Func->getCallingConv();
6163 unsigned NestReg;
6165 switch (CC) {
6166 default:
6167 assert(0 && "Unsupported calling convention");
6168 case CallingConv::C:
6169 case CallingConv::X86_StdCall: {
6170 // Pass 'nest' parameter in ECX.
6171 // Must be kept in sync with X86CallingConv.td
6172 NestReg = X86::ECX;
6174 // Check that ECX wasn't needed by an 'inreg' parameter.
6175 const FunctionType *FTy = Func->getFunctionType();
6176 const AttrListPtr &Attrs = Func->getAttributes();
6178 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6179 unsigned InRegCount = 0;
6180 unsigned Idx = 1;
6182 for (FunctionType::param_iterator I = FTy->param_begin(),
6183 E = FTy->param_end(); I != E; ++I, ++Idx)
6184 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6185 // FIXME: should only count parameters that are lowered to integers.
6186 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6188 if (InRegCount > 2) {
6189 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6190 abort();
6193 break;
6195 case CallingConv::X86_FastCall:
6196 case CallingConv::Fast:
6197 // Pass 'nest' parameter in EAX.
6198 // Must be kept in sync with X86CallingConv.td
6199 NestReg = X86::EAX;
6200 break;
6203 SDValue OutChains[4];
6204 SDValue Addr, Disp;
6206 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6207 DAG.getConstant(10, MVT::i32));
6208 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6210 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6211 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6212 OutChains[0] = DAG.getStore(Root, dl,
6213 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6214 Trmp, TrmpAddr, 0);
6216 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6217 DAG.getConstant(1, MVT::i32));
6218 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6220 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6221 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6222 DAG.getConstant(5, MVT::i32));
6223 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6224 TrmpAddr, 5, false, 1);
6226 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6227 DAG.getConstant(6, MVT::i32));
6228 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6230 SDValue Ops[] =
6231 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6232 return DAG.getMergeValues(Ops, 2, dl);
6236 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6238 The rounding mode is in bits 11:10 of FPSR, and has the following
6239 settings:
6240 00 Round to nearest
6241 01 Round to -inf
6242 10 Round to +inf
6243 11 Round to 0
6245 FLT_ROUNDS, on the other hand, expects the following:
6246 -1 Undefined
6247 0 Round to 0
6248 1 Round to nearest
6249 2 Round to +inf
6250 3 Round to -inf
6252 To perform the conversion, we do:
6253 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6256 MachineFunction &MF = DAG.getMachineFunction();
6257 const TargetMachine &TM = MF.getTarget();
6258 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6259 unsigned StackAlignment = TFI.getStackAlignment();
6260 MVT VT = Op.getValueType();
6261 DebugLoc dl = Op.getDebugLoc();
6263 // Save FP Control Word to stack slot
6264 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6265 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6267 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6268 DAG.getEntryNode(), StackSlot);
6270 // Load FP Control Word from stack slot
6271 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6273 // Transform as necessary
6274 SDValue CWD1 =
6275 DAG.getNode(ISD::SRL, dl, MVT::i16,
6276 DAG.getNode(ISD::AND, dl, MVT::i16,
6277 CWD, DAG.getConstant(0x800, MVT::i16)),
6278 DAG.getConstant(11, MVT::i8));
6279 SDValue CWD2 =
6280 DAG.getNode(ISD::SRL, dl, MVT::i16,
6281 DAG.getNode(ISD::AND, dl, MVT::i16,
6282 CWD, DAG.getConstant(0x400, MVT::i16)),
6283 DAG.getConstant(9, MVT::i8));
6285 SDValue RetVal =
6286 DAG.getNode(ISD::AND, dl, MVT::i16,
6287 DAG.getNode(ISD::ADD, dl, MVT::i16,
6288 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6289 DAG.getConstant(1, MVT::i16)),
6290 DAG.getConstant(3, MVT::i16));
6293 return DAG.getNode((VT.getSizeInBits() < 16 ?
6294 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6297 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6298 MVT VT = Op.getValueType();
6299 MVT OpVT = VT;
6300 unsigned NumBits = VT.getSizeInBits();
6301 DebugLoc dl = Op.getDebugLoc();
6303 Op = Op.getOperand(0);
6304 if (VT == MVT::i8) {
6305 // Zero extend to i32 since there is not an i8 bsr.
6306 OpVT = MVT::i32;
6307 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6310 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6311 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6312 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6314 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6315 SmallVector<SDValue, 4> Ops;
6316 Ops.push_back(Op);
6317 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6318 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6319 Ops.push_back(Op.getValue(1));
6320 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6322 // Finally xor with NumBits-1.
6323 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6325 if (VT == MVT::i8)
6326 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6327 return Op;
6330 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6331 MVT VT = Op.getValueType();
6332 MVT OpVT = VT;
6333 unsigned NumBits = VT.getSizeInBits();
6334 DebugLoc dl = Op.getDebugLoc();
6336 Op = Op.getOperand(0);
6337 if (VT == MVT::i8) {
6338 OpVT = MVT::i32;
6339 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6342 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6343 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6344 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6346 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6347 SmallVector<SDValue, 4> Ops;
6348 Ops.push_back(Op);
6349 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6350 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6351 Ops.push_back(Op.getValue(1));
6352 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6354 if (VT == MVT::i8)
6355 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6356 return Op;
6359 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6360 MVT VT = Op.getValueType();
6361 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6362 DebugLoc dl = Op.getDebugLoc();
6364 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6365 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6366 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6367 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6368 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6370 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6371 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6372 // return AloBlo + AloBhi + AhiBlo;
6374 SDValue A = Op.getOperand(0);
6375 SDValue B = Op.getOperand(1);
6377 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6378 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6379 A, DAG.getConstant(32, MVT::i32));
6380 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6381 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6382 B, DAG.getConstant(32, MVT::i32));
6383 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6384 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6385 A, B);
6386 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6387 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6388 A, Bhi);
6389 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6390 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6391 Ahi, B);
6392 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6393 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6394 AloBhi, DAG.getConstant(32, MVT::i32));
6395 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6396 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6397 AhiBlo, DAG.getConstant(32, MVT::i32));
6398 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6399 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6400 return Res;
6404 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6405 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6406 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6407 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6408 // has only one use.
6409 SDNode *N = Op.getNode();
6410 SDValue LHS = N->getOperand(0);
6411 SDValue RHS = N->getOperand(1);
6412 unsigned BaseOp = 0;
6413 unsigned Cond = 0;
6414 DebugLoc dl = Op.getDebugLoc();
6416 switch (Op.getOpcode()) {
6417 default: assert(0 && "Unknown ovf instruction!");
6418 case ISD::SADDO:
6419 // A subtract of one will be selected as a INC. Note that INC doesn't
6420 // set CF, so we can't do this for UADDO.
6421 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6422 if (C->getAPIntValue() == 1) {
6423 BaseOp = X86ISD::INC;
6424 Cond = X86::COND_O;
6425 break;
6427 BaseOp = X86ISD::ADD;
6428 Cond = X86::COND_O;
6429 break;
6430 case ISD::UADDO:
6431 BaseOp = X86ISD::ADD;
6432 Cond = X86::COND_B;
6433 break;
6434 case ISD::SSUBO:
6435 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6436 // set CF, so we can't do this for USUBO.
6437 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6438 if (C->getAPIntValue() == 1) {
6439 BaseOp = X86ISD::DEC;
6440 Cond = X86::COND_O;
6441 break;
6443 BaseOp = X86ISD::SUB;
6444 Cond = X86::COND_O;
6445 break;
6446 case ISD::USUBO:
6447 BaseOp = X86ISD::SUB;
6448 Cond = X86::COND_B;
6449 break;
6450 case ISD::SMULO:
6451 BaseOp = X86ISD::SMUL;
6452 Cond = X86::COND_O;
6453 break;
6454 case ISD::UMULO:
6455 BaseOp = X86ISD::UMUL;
6456 Cond = X86::COND_B;
6457 break;
6460 // Also sets EFLAGS.
6461 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6462 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6464 SDValue SetCC =
6465 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6466 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6468 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6469 return Sum;
6472 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6473 MVT T = Op.getValueType();
6474 DebugLoc dl = Op.getDebugLoc();
6475 unsigned Reg = 0;
6476 unsigned size = 0;
6477 switch(T.getSimpleVT()) {
6478 default:
6479 assert(false && "Invalid value type!");
6480 case MVT::i8: Reg = X86::AL; size = 1; break;
6481 case MVT::i16: Reg = X86::AX; size = 2; break;
6482 case MVT::i32: Reg = X86::EAX; size = 4; break;
6483 case MVT::i64:
6484 assert(Subtarget->is64Bit() && "Node not type legal!");
6485 Reg = X86::RAX; size = 8;
6486 break;
6488 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6489 Op.getOperand(2), SDValue());
6490 SDValue Ops[] = { cpIn.getValue(0),
6491 Op.getOperand(1),
6492 Op.getOperand(3),
6493 DAG.getTargetConstant(size, MVT::i8),
6494 cpIn.getValue(1) };
6495 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6496 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6497 SDValue cpOut =
6498 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6499 return cpOut;
6502 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6503 SelectionDAG &DAG) {
6504 assert(Subtarget->is64Bit() && "Result not type legalized?");
6505 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6506 SDValue TheChain = Op.getOperand(0);
6507 DebugLoc dl = Op.getDebugLoc();
6508 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6509 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6510 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6511 rax.getValue(2));
6512 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6513 DAG.getConstant(32, MVT::i8));
6514 SDValue Ops[] = {
6515 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6516 rdx.getValue(1)
6518 return DAG.getMergeValues(Ops, 2, dl);
6521 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6522 SDNode *Node = Op.getNode();
6523 DebugLoc dl = Node->getDebugLoc();
6524 MVT T = Node->getValueType(0);
6525 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6526 DAG.getConstant(0, T), Node->getOperand(2));
6527 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6528 cast<AtomicSDNode>(Node)->getMemoryVT(),
6529 Node->getOperand(0),
6530 Node->getOperand(1), negOp,
6531 cast<AtomicSDNode>(Node)->getSrcValue(),
6532 cast<AtomicSDNode>(Node)->getAlignment());
6535 /// LowerOperation - Provide custom lowering hooks for some operations.
6537 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6538 switch (Op.getOpcode()) {
6539 default: assert(0 && "Should not custom lower this!");
6540 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6541 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6542 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6543 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6544 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6545 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6546 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6547 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6548 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6549 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6550 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6551 case ISD::SHL_PARTS:
6552 case ISD::SRA_PARTS:
6553 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6554 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6555 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6556 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6557 case ISD::FABS: return LowerFABS(Op, DAG);
6558 case ISD::FNEG: return LowerFNEG(Op, DAG);
6559 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6560 case ISD::SETCC: return LowerSETCC(Op, DAG);
6561 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6562 case ISD::SELECT: return LowerSELECT(Op, DAG);
6563 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6564 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6565 case ISD::CALL: return LowerCALL(Op, DAG);
6566 case ISD::RET: return LowerRET(Op, DAG);
6567 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6568 case ISD::VASTART: return LowerVASTART(Op, DAG);
6569 case ISD::VAARG: return LowerVAARG(Op, DAG);
6570 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6571 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6572 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6573 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6574 case ISD::FRAME_TO_ARGS_OFFSET:
6575 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6576 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6577 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6578 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6579 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6580 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6581 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6582 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6583 case ISD::SADDO:
6584 case ISD::UADDO:
6585 case ISD::SSUBO:
6586 case ISD::USUBO:
6587 case ISD::SMULO:
6588 case ISD::UMULO: return LowerXALUO(Op, DAG);
6589 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6593 void X86TargetLowering::
6594 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6595 SelectionDAG &DAG, unsigned NewOp) {
6596 MVT T = Node->getValueType(0);
6597 DebugLoc dl = Node->getDebugLoc();
6598 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6600 SDValue Chain = Node->getOperand(0);
6601 SDValue In1 = Node->getOperand(1);
6602 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6603 Node->getOperand(2), DAG.getIntPtrConstant(0));
6604 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6605 Node->getOperand(2), DAG.getIntPtrConstant(1));
6606 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6607 // have a MemOperand. Pass the info through as a normal operand.
6608 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6609 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6610 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6611 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6612 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6613 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6614 Results.push_back(Result.getValue(2));
6617 /// ReplaceNodeResults - Replace a node with an illegal result type
6618 /// with a new node built out of custom code.
6619 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6620 SmallVectorImpl<SDValue>&Results,
6621 SelectionDAG &DAG) {
6622 DebugLoc dl = N->getDebugLoc();
6623 switch (N->getOpcode()) {
6624 default:
6625 assert(false && "Do not know how to custom type legalize this operation!");
6626 return;
6627 case ISD::FP_TO_SINT: {
6628 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6629 SDValue FIST = Vals.first, StackSlot = Vals.second;
6630 if (FIST.getNode() != 0) {
6631 MVT VT = N->getValueType(0);
6632 // Return a load from the stack slot.
6633 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6635 return;
6637 case ISD::READCYCLECOUNTER: {
6638 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6639 SDValue TheChain = N->getOperand(0);
6640 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6641 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6642 rd.getValue(1));
6643 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6644 eax.getValue(2));
6645 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6646 SDValue Ops[] = { eax, edx };
6647 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6648 Results.push_back(edx.getValue(1));
6649 return;
6651 case ISD::ATOMIC_CMP_SWAP: {
6652 MVT T = N->getValueType(0);
6653 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6654 SDValue cpInL, cpInH;
6655 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6656 DAG.getConstant(0, MVT::i32));
6657 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6658 DAG.getConstant(1, MVT::i32));
6659 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6660 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6661 cpInL.getValue(1));
6662 SDValue swapInL, swapInH;
6663 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6664 DAG.getConstant(0, MVT::i32));
6665 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6666 DAG.getConstant(1, MVT::i32));
6667 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6668 cpInH.getValue(1));
6669 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6670 swapInL.getValue(1));
6671 SDValue Ops[] = { swapInH.getValue(0),
6672 N->getOperand(1),
6673 swapInH.getValue(1) };
6674 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6675 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6676 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6677 MVT::i32, Result.getValue(1));
6678 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6679 MVT::i32, cpOutL.getValue(2));
6680 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6681 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6682 Results.push_back(cpOutH.getValue(1));
6683 return;
6685 case ISD::ATOMIC_LOAD_ADD:
6686 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6687 return;
6688 case ISD::ATOMIC_LOAD_AND:
6689 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6690 return;
6691 case ISD::ATOMIC_LOAD_NAND:
6692 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6693 return;
6694 case ISD::ATOMIC_LOAD_OR:
6695 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6696 return;
6697 case ISD::ATOMIC_LOAD_SUB:
6698 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6699 return;
6700 case ISD::ATOMIC_LOAD_XOR:
6701 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6702 return;
6703 case ISD::ATOMIC_SWAP:
6704 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6705 return;
6709 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6710 switch (Opcode) {
6711 default: return NULL;
6712 case X86ISD::BSF: return "X86ISD::BSF";
6713 case X86ISD::BSR: return "X86ISD::BSR";
6714 case X86ISD::SHLD: return "X86ISD::SHLD";
6715 case X86ISD::SHRD: return "X86ISD::SHRD";
6716 case X86ISD::FAND: return "X86ISD::FAND";
6717 case X86ISD::FOR: return "X86ISD::FOR";
6718 case X86ISD::FXOR: return "X86ISD::FXOR";
6719 case X86ISD::FSRL: return "X86ISD::FSRL";
6720 case X86ISD::FILD: return "X86ISD::FILD";
6721 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6722 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6723 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6724 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6725 case X86ISD::FLD: return "X86ISD::FLD";
6726 case X86ISD::FST: return "X86ISD::FST";
6727 case X86ISD::CALL: return "X86ISD::CALL";
6728 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6729 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6730 case X86ISD::BT: return "X86ISD::BT";
6731 case X86ISD::CMP: return "X86ISD::CMP";
6732 case X86ISD::COMI: return "X86ISD::COMI";
6733 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6734 case X86ISD::SETCC: return "X86ISD::SETCC";
6735 case X86ISD::CMOV: return "X86ISD::CMOV";
6736 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6737 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6738 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6739 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6740 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6741 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6742 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6743 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6744 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6745 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6746 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6747 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
6748 case X86ISD::FMAX: return "X86ISD::FMAX";
6749 case X86ISD::FMIN: return "X86ISD::FMIN";
6750 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6751 case X86ISD::FRCP: return "X86ISD::FRCP";
6752 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6753 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6754 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6755 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6756 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6757 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6758 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6759 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6760 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6761 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6762 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6763 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6764 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6765 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6766 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6767 case X86ISD::VSHL: return "X86ISD::VSHL";
6768 case X86ISD::VSRL: return "X86ISD::VSRL";
6769 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6770 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6771 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6772 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6773 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6774 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6775 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6776 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6777 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6778 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6779 case X86ISD::ADD: return "X86ISD::ADD";
6780 case X86ISD::SUB: return "X86ISD::SUB";
6781 case X86ISD::SMUL: return "X86ISD::SMUL";
6782 case X86ISD::UMUL: return "X86ISD::UMUL";
6783 case X86ISD::INC: return "X86ISD::INC";
6784 case X86ISD::DEC: return "X86ISD::DEC";
6785 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
6789 // isLegalAddressingMode - Return true if the addressing mode represented
6790 // by AM is legal for this target, for a load/store of the specified type.
6791 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6792 const Type *Ty) const {
6793 // X86 supports extremely general addressing modes.
6795 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6796 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6797 return false;
6799 if (AM.BaseGV) {
6800 // We can only fold this if we don't need an extra load.
6801 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6802 return false;
6803 // If BaseGV requires a register, we cannot also have a BaseReg.
6804 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6805 AM.HasBaseReg)
6806 return false;
6808 // X86-64 only supports addr of globals in small code model.
6809 if (Subtarget->is64Bit()) {
6810 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6811 return false;
6812 // If lower 4G is not available, then we must use rip-relative addressing.
6813 if (AM.BaseOffs || AM.Scale > 1)
6814 return false;
6818 switch (AM.Scale) {
6819 case 0:
6820 case 1:
6821 case 2:
6822 case 4:
6823 case 8:
6824 // These scales always work.
6825 break;
6826 case 3:
6827 case 5:
6828 case 9:
6829 // These scales are formed with basereg+scalereg. Only accept if there is
6830 // no basereg yet.
6831 if (AM.HasBaseReg)
6832 return false;
6833 break;
6834 default: // Other stuff never works.
6835 return false;
6838 return true;
6842 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6843 if (!Ty1->isInteger() || !Ty2->isInteger())
6844 return false;
6845 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6846 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6847 if (NumBits1 <= NumBits2)
6848 return false;
6849 return Subtarget->is64Bit() || NumBits1 < 64;
6852 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6853 if (!VT1.isInteger() || !VT2.isInteger())
6854 return false;
6855 unsigned NumBits1 = VT1.getSizeInBits();
6856 unsigned NumBits2 = VT2.getSizeInBits();
6857 if (NumBits1 <= NumBits2)
6858 return false;
6859 return Subtarget->is64Bit() || NumBits1 < 64;
6862 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
6863 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6864 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
6867 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
6868 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6869 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
6872 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6873 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6874 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6875 /// are assumed to be legal.
6876 bool
6877 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6878 MVT VT) const {
6879 // Only do shuffles on 128-bit vector types for now.
6880 if (VT.getSizeInBits() == 64)
6881 return false;
6883 // FIXME: pshufb, blends, palignr, shifts.
6884 return (VT.getVectorNumElements() == 2 ||
6885 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6886 isMOVLMask(M, VT) ||
6887 isSHUFPMask(M, VT) ||
6888 isPSHUFDMask(M, VT) ||
6889 isPSHUFHWMask(M, VT) ||
6890 isPSHUFLWMask(M, VT) ||
6891 isUNPCKLMask(M, VT) ||
6892 isUNPCKHMask(M, VT) ||
6893 isUNPCKL_v_undef_Mask(M, VT) ||
6894 isUNPCKH_v_undef_Mask(M, VT));
6897 bool
6898 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
6899 MVT VT) const {
6900 unsigned NumElts = VT.getVectorNumElements();
6901 // FIXME: This collection of masks seems suspect.
6902 if (NumElts == 2)
6903 return true;
6904 if (NumElts == 4 && VT.getSizeInBits() == 128) {
6905 return (isMOVLMask(Mask, VT) ||
6906 isCommutedMOVLMask(Mask, VT, true) ||
6907 isSHUFPMask(Mask, VT) ||
6908 isCommutedSHUFPMask(Mask, VT));
6910 return false;
6913 //===----------------------------------------------------------------------===//
6914 // X86 Scheduler Hooks
6915 //===----------------------------------------------------------------------===//
6917 // private utility function
6918 MachineBasicBlock *
6919 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6920 MachineBasicBlock *MBB,
6921 unsigned regOpc,
6922 unsigned immOpc,
6923 unsigned LoadOpc,
6924 unsigned CXchgOpc,
6925 unsigned copyOpc,
6926 unsigned notOpc,
6927 unsigned EAXreg,
6928 TargetRegisterClass *RC,
6929 bool invSrc) const {
6930 // For the atomic bitwise operator, we generate
6931 // thisMBB:
6932 // newMBB:
6933 // ld t1 = [bitinstr.addr]
6934 // op t2 = t1, [bitinstr.val]
6935 // mov EAX = t1
6936 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6937 // bz newMBB
6938 // fallthrough -->nextMBB
6939 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6940 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6941 MachineFunction::iterator MBBIter = MBB;
6942 ++MBBIter;
6944 /// First build the CFG
6945 MachineFunction *F = MBB->getParent();
6946 MachineBasicBlock *thisMBB = MBB;
6947 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6948 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6949 F->insert(MBBIter, newMBB);
6950 F->insert(MBBIter, nextMBB);
6952 // Move all successors to thisMBB to nextMBB
6953 nextMBB->transferSuccessors(thisMBB);
6955 // Update thisMBB to fall through to newMBB
6956 thisMBB->addSuccessor(newMBB);
6958 // newMBB jumps to itself and fall through to nextMBB
6959 newMBB->addSuccessor(nextMBB);
6960 newMBB->addSuccessor(newMBB);
6962 // Insert instructions into newMBB based on incoming instruction
6963 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
6964 "unexpected number of operands");
6965 DebugLoc dl = bInstr->getDebugLoc();
6966 MachineOperand& destOper = bInstr->getOperand(0);
6967 MachineOperand* argOpers[2 + X86AddrNumOperands];
6968 int numArgs = bInstr->getNumOperands() - 1;
6969 for (int i=0; i < numArgs; ++i)
6970 argOpers[i] = &bInstr->getOperand(i+1);
6972 // x86 address has 4 operands: base, index, scale, and displacement
6973 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
6974 int valArgIndx = lastAddrIndx + 1;
6976 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6977 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
6978 for (int i=0; i <= lastAddrIndx; ++i)
6979 (*MIB).addOperand(*argOpers[i]);
6981 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6982 if (invSrc) {
6983 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
6985 else
6986 tt = t1;
6988 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6989 assert((argOpers[valArgIndx]->isReg() ||
6990 argOpers[valArgIndx]->isImm()) &&
6991 "invalid operand");
6992 if (argOpers[valArgIndx]->isReg())
6993 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
6994 else
6995 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
6996 MIB.addReg(tt);
6997 (*MIB).addOperand(*argOpers[valArgIndx]);
6999 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7000 MIB.addReg(t1);
7002 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7003 for (int i=0; i <= lastAddrIndx; ++i)
7004 (*MIB).addOperand(*argOpers[i]);
7005 MIB.addReg(t2);
7006 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7007 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7009 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7010 MIB.addReg(EAXreg);
7012 // insert branch
7013 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7015 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7016 return nextMBB;
7019 // private utility function: 64 bit atomics on 32 bit host.
7020 MachineBasicBlock *
7021 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7022 MachineBasicBlock *MBB,
7023 unsigned regOpcL,
7024 unsigned regOpcH,
7025 unsigned immOpcL,
7026 unsigned immOpcH,
7027 bool invSrc) const {
7028 // For the atomic bitwise operator, we generate
7029 // thisMBB (instructions are in pairs, except cmpxchg8b)
7030 // ld t1,t2 = [bitinstr.addr]
7031 // newMBB:
7032 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7033 // op t5, t6 <- out1, out2, [bitinstr.val]
7034 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7035 // mov ECX, EBX <- t5, t6
7036 // mov EAX, EDX <- t1, t2
7037 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7038 // mov t3, t4 <- EAX, EDX
7039 // bz newMBB
7040 // result in out1, out2
7041 // fallthrough -->nextMBB
7043 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7044 const unsigned LoadOpc = X86::MOV32rm;
7045 const unsigned copyOpc = X86::MOV32rr;
7046 const unsigned NotOpc = X86::NOT32r;
7047 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7048 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7049 MachineFunction::iterator MBBIter = MBB;
7050 ++MBBIter;
7052 /// First build the CFG
7053 MachineFunction *F = MBB->getParent();
7054 MachineBasicBlock *thisMBB = MBB;
7055 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7056 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7057 F->insert(MBBIter, newMBB);
7058 F->insert(MBBIter, nextMBB);
7060 // Move all successors to thisMBB to nextMBB
7061 nextMBB->transferSuccessors(thisMBB);
7063 // Update thisMBB to fall through to newMBB
7064 thisMBB->addSuccessor(newMBB);
7066 // newMBB jumps to itself and fall through to nextMBB
7067 newMBB->addSuccessor(nextMBB);
7068 newMBB->addSuccessor(newMBB);
7070 DebugLoc dl = bInstr->getDebugLoc();
7071 // Insert instructions into newMBB based on incoming instruction
7072 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7073 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7074 "unexpected number of operands");
7075 MachineOperand& dest1Oper = bInstr->getOperand(0);
7076 MachineOperand& dest2Oper = bInstr->getOperand(1);
7077 MachineOperand* argOpers[2 + X86AddrNumOperands];
7078 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7079 argOpers[i] = &bInstr->getOperand(i+2);
7081 // x86 address has 4 operands: base, index, scale, and displacement
7082 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7084 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7085 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7086 for (int i=0; i <= lastAddrIndx; ++i)
7087 (*MIB).addOperand(*argOpers[i]);
7088 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7089 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7090 // add 4 to displacement.
7091 for (int i=0; i <= lastAddrIndx-2; ++i)
7092 (*MIB).addOperand(*argOpers[i]);
7093 MachineOperand newOp3 = *(argOpers[3]);
7094 if (newOp3.isImm())
7095 newOp3.setImm(newOp3.getImm()+4);
7096 else
7097 newOp3.setOffset(newOp3.getOffset()+4);
7098 (*MIB).addOperand(newOp3);
7099 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7101 // t3/4 are defined later, at the bottom of the loop
7102 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7103 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7104 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7105 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7106 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7107 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7109 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7110 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7111 if (invSrc) {
7112 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7113 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7114 } else {
7115 tt1 = t1;
7116 tt2 = t2;
7119 int valArgIndx = lastAddrIndx + 1;
7120 assert((argOpers[valArgIndx]->isReg() ||
7121 argOpers[valArgIndx]->isImm()) &&
7122 "invalid operand");
7123 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7124 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7125 if (argOpers[valArgIndx]->isReg())
7126 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7127 else
7128 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7129 if (regOpcL != X86::MOV32rr)
7130 MIB.addReg(tt1);
7131 (*MIB).addOperand(*argOpers[valArgIndx]);
7132 assert(argOpers[valArgIndx + 1]->isReg() ==
7133 argOpers[valArgIndx]->isReg());
7134 assert(argOpers[valArgIndx + 1]->isImm() ==
7135 argOpers[valArgIndx]->isImm());
7136 if (argOpers[valArgIndx + 1]->isReg())
7137 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7138 else
7139 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7140 if (regOpcH != X86::MOV32rr)
7141 MIB.addReg(tt2);
7142 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7144 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7145 MIB.addReg(t1);
7146 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7147 MIB.addReg(t2);
7149 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7150 MIB.addReg(t5);
7151 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7152 MIB.addReg(t6);
7154 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7155 for (int i=0; i <= lastAddrIndx; ++i)
7156 (*MIB).addOperand(*argOpers[i]);
7158 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7159 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7161 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7162 MIB.addReg(X86::EAX);
7163 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7164 MIB.addReg(X86::EDX);
7166 // insert branch
7167 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7169 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7170 return nextMBB;
7173 // private utility function
7174 MachineBasicBlock *
7175 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7176 MachineBasicBlock *MBB,
7177 unsigned cmovOpc) const {
7178 // For the atomic min/max operator, we generate
7179 // thisMBB:
7180 // newMBB:
7181 // ld t1 = [min/max.addr]
7182 // mov t2 = [min/max.val]
7183 // cmp t1, t2
7184 // cmov[cond] t2 = t1
7185 // mov EAX = t1
7186 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7187 // bz newMBB
7188 // fallthrough -->nextMBB
7190 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7191 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7192 MachineFunction::iterator MBBIter = MBB;
7193 ++MBBIter;
7195 /// First build the CFG
7196 MachineFunction *F = MBB->getParent();
7197 MachineBasicBlock *thisMBB = MBB;
7198 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7199 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7200 F->insert(MBBIter, newMBB);
7201 F->insert(MBBIter, nextMBB);
7203 // Move all successors to thisMBB to nextMBB
7204 nextMBB->transferSuccessors(thisMBB);
7206 // Update thisMBB to fall through to newMBB
7207 thisMBB->addSuccessor(newMBB);
7209 // newMBB jumps to newMBB and fall through to nextMBB
7210 newMBB->addSuccessor(nextMBB);
7211 newMBB->addSuccessor(newMBB);
7213 DebugLoc dl = mInstr->getDebugLoc();
7214 // Insert instructions into newMBB based on incoming instruction
7215 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7216 "unexpected number of operands");
7217 MachineOperand& destOper = mInstr->getOperand(0);
7218 MachineOperand* argOpers[2 + X86AddrNumOperands];
7219 int numArgs = mInstr->getNumOperands() - 1;
7220 for (int i=0; i < numArgs; ++i)
7221 argOpers[i] = &mInstr->getOperand(i+1);
7223 // x86 address has 4 operands: base, index, scale, and displacement
7224 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7225 int valArgIndx = lastAddrIndx + 1;
7227 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7228 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7229 for (int i=0; i <= lastAddrIndx; ++i)
7230 (*MIB).addOperand(*argOpers[i]);
7232 // We only support register and immediate values
7233 assert((argOpers[valArgIndx]->isReg() ||
7234 argOpers[valArgIndx]->isImm()) &&
7235 "invalid operand");
7237 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7238 if (argOpers[valArgIndx]->isReg())
7239 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7240 else
7241 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7242 (*MIB).addOperand(*argOpers[valArgIndx]);
7244 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7245 MIB.addReg(t1);
7247 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7248 MIB.addReg(t1);
7249 MIB.addReg(t2);
7251 // Generate movc
7252 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7253 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7254 MIB.addReg(t2);
7255 MIB.addReg(t1);
7257 // Cmp and exchange if none has modified the memory location
7258 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7259 for (int i=0; i <= lastAddrIndx; ++i)
7260 (*MIB).addOperand(*argOpers[i]);
7261 MIB.addReg(t3);
7262 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7263 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7265 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7266 MIB.addReg(X86::EAX);
7268 // insert branch
7269 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7271 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7272 return nextMBB;
7276 MachineBasicBlock *
7277 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7278 MachineBasicBlock *BB) const {
7279 DebugLoc dl = MI->getDebugLoc();
7280 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7281 switch (MI->getOpcode()) {
7282 default: assert(false && "Unexpected instr type to insert");
7283 case X86::CMOV_V1I64:
7284 case X86::CMOV_FR32:
7285 case X86::CMOV_FR64:
7286 case X86::CMOV_V4F32:
7287 case X86::CMOV_V2F64:
7288 case X86::CMOV_V2I64: {
7289 // To "insert" a SELECT_CC instruction, we actually have to insert the
7290 // diamond control-flow pattern. The incoming instruction knows the
7291 // destination vreg to set, the condition code register to branch on, the
7292 // true/false values to select between, and a branch opcode to use.
7293 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7294 MachineFunction::iterator It = BB;
7295 ++It;
7297 // thisMBB:
7298 // ...
7299 // TrueVal = ...
7300 // cmpTY ccX, r1, r2
7301 // bCC copy1MBB
7302 // fallthrough --> copy0MBB
7303 MachineBasicBlock *thisMBB = BB;
7304 MachineFunction *F = BB->getParent();
7305 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7306 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7307 unsigned Opc =
7308 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7309 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7310 F->insert(It, copy0MBB);
7311 F->insert(It, sinkMBB);
7312 // Update machine-CFG edges by transferring all successors of the current
7313 // block to the new block which will contain the Phi node for the select.
7314 sinkMBB->transferSuccessors(BB);
7316 // Add the true and fallthrough blocks as its successors.
7317 BB->addSuccessor(copy0MBB);
7318 BB->addSuccessor(sinkMBB);
7320 // copy0MBB:
7321 // %FalseValue = ...
7322 // # fallthrough to sinkMBB
7323 BB = copy0MBB;
7325 // Update machine-CFG edges
7326 BB->addSuccessor(sinkMBB);
7328 // sinkMBB:
7329 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7330 // ...
7331 BB = sinkMBB;
7332 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7333 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7334 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7336 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7337 return BB;
7340 case X86::FP32_TO_INT16_IN_MEM:
7341 case X86::FP32_TO_INT32_IN_MEM:
7342 case X86::FP32_TO_INT64_IN_MEM:
7343 case X86::FP64_TO_INT16_IN_MEM:
7344 case X86::FP64_TO_INT32_IN_MEM:
7345 case X86::FP64_TO_INT64_IN_MEM:
7346 case X86::FP80_TO_INT16_IN_MEM:
7347 case X86::FP80_TO_INT32_IN_MEM:
7348 case X86::FP80_TO_INT64_IN_MEM: {
7349 // Change the floating point control register to use "round towards zero"
7350 // mode when truncating to an integer value.
7351 MachineFunction *F = BB->getParent();
7352 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7353 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7355 // Load the old value of the high byte of the control word...
7356 unsigned OldCW =
7357 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7358 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7359 CWFrameIdx);
7361 // Set the high part to be round to zero...
7362 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7363 .addImm(0xC7F);
7365 // Reload the modified control word now...
7366 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7368 // Restore the memory image of control word to original value
7369 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7370 .addReg(OldCW);
7372 // Get the X86 opcode to use.
7373 unsigned Opc;
7374 switch (MI->getOpcode()) {
7375 default: assert(0 && "illegal opcode!");
7376 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7377 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7378 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7379 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7380 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7381 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7382 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7383 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7384 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7387 X86AddressMode AM;
7388 MachineOperand &Op = MI->getOperand(0);
7389 if (Op.isReg()) {
7390 AM.BaseType = X86AddressMode::RegBase;
7391 AM.Base.Reg = Op.getReg();
7392 } else {
7393 AM.BaseType = X86AddressMode::FrameIndexBase;
7394 AM.Base.FrameIndex = Op.getIndex();
7396 Op = MI->getOperand(1);
7397 if (Op.isImm())
7398 AM.Scale = Op.getImm();
7399 Op = MI->getOperand(2);
7400 if (Op.isImm())
7401 AM.IndexReg = Op.getImm();
7402 Op = MI->getOperand(3);
7403 if (Op.isGlobal()) {
7404 AM.GV = Op.getGlobal();
7405 } else {
7406 AM.Disp = Op.getImm();
7408 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7409 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7411 // Reload the original control word now.
7412 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7414 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7415 return BB;
7417 case X86::ATOMAND32:
7418 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7419 X86::AND32ri, X86::MOV32rm,
7420 X86::LCMPXCHG32, X86::MOV32rr,
7421 X86::NOT32r, X86::EAX,
7422 X86::GR32RegisterClass);
7423 case X86::ATOMOR32:
7424 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7425 X86::OR32ri, X86::MOV32rm,
7426 X86::LCMPXCHG32, X86::MOV32rr,
7427 X86::NOT32r, X86::EAX,
7428 X86::GR32RegisterClass);
7429 case X86::ATOMXOR32:
7430 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7431 X86::XOR32ri, X86::MOV32rm,
7432 X86::LCMPXCHG32, X86::MOV32rr,
7433 X86::NOT32r, X86::EAX,
7434 X86::GR32RegisterClass);
7435 case X86::ATOMNAND32:
7436 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7437 X86::AND32ri, X86::MOV32rm,
7438 X86::LCMPXCHG32, X86::MOV32rr,
7439 X86::NOT32r, X86::EAX,
7440 X86::GR32RegisterClass, true);
7441 case X86::ATOMMIN32:
7442 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7443 case X86::ATOMMAX32:
7444 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7445 case X86::ATOMUMIN32:
7446 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7447 case X86::ATOMUMAX32:
7448 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7450 case X86::ATOMAND16:
7451 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7452 X86::AND16ri, X86::MOV16rm,
7453 X86::LCMPXCHG16, X86::MOV16rr,
7454 X86::NOT16r, X86::AX,
7455 X86::GR16RegisterClass);
7456 case X86::ATOMOR16:
7457 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7458 X86::OR16ri, X86::MOV16rm,
7459 X86::LCMPXCHG16, X86::MOV16rr,
7460 X86::NOT16r, X86::AX,
7461 X86::GR16RegisterClass);
7462 case X86::ATOMXOR16:
7463 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7464 X86::XOR16ri, X86::MOV16rm,
7465 X86::LCMPXCHG16, X86::MOV16rr,
7466 X86::NOT16r, X86::AX,
7467 X86::GR16RegisterClass);
7468 case X86::ATOMNAND16:
7469 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7470 X86::AND16ri, X86::MOV16rm,
7471 X86::LCMPXCHG16, X86::MOV16rr,
7472 X86::NOT16r, X86::AX,
7473 X86::GR16RegisterClass, true);
7474 case X86::ATOMMIN16:
7475 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7476 case X86::ATOMMAX16:
7477 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7478 case X86::ATOMUMIN16:
7479 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7480 case X86::ATOMUMAX16:
7481 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7483 case X86::ATOMAND8:
7484 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7485 X86::AND8ri, X86::MOV8rm,
7486 X86::LCMPXCHG8, X86::MOV8rr,
7487 X86::NOT8r, X86::AL,
7488 X86::GR8RegisterClass);
7489 case X86::ATOMOR8:
7490 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7491 X86::OR8ri, X86::MOV8rm,
7492 X86::LCMPXCHG8, X86::MOV8rr,
7493 X86::NOT8r, X86::AL,
7494 X86::GR8RegisterClass);
7495 case X86::ATOMXOR8:
7496 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7497 X86::XOR8ri, X86::MOV8rm,
7498 X86::LCMPXCHG8, X86::MOV8rr,
7499 X86::NOT8r, X86::AL,
7500 X86::GR8RegisterClass);
7501 case X86::ATOMNAND8:
7502 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7503 X86::AND8ri, X86::MOV8rm,
7504 X86::LCMPXCHG8, X86::MOV8rr,
7505 X86::NOT8r, X86::AL,
7506 X86::GR8RegisterClass, true);
7507 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7508 // This group is for 64-bit host.
7509 case X86::ATOMAND64:
7510 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7511 X86::AND64ri32, X86::MOV64rm,
7512 X86::LCMPXCHG64, X86::MOV64rr,
7513 X86::NOT64r, X86::RAX,
7514 X86::GR64RegisterClass);
7515 case X86::ATOMOR64:
7516 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7517 X86::OR64ri32, X86::MOV64rm,
7518 X86::LCMPXCHG64, X86::MOV64rr,
7519 X86::NOT64r, X86::RAX,
7520 X86::GR64RegisterClass);
7521 case X86::ATOMXOR64:
7522 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7523 X86::XOR64ri32, X86::MOV64rm,
7524 X86::LCMPXCHG64, X86::MOV64rr,
7525 X86::NOT64r, X86::RAX,
7526 X86::GR64RegisterClass);
7527 case X86::ATOMNAND64:
7528 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7529 X86::AND64ri32, X86::MOV64rm,
7530 X86::LCMPXCHG64, X86::MOV64rr,
7531 X86::NOT64r, X86::RAX,
7532 X86::GR64RegisterClass, true);
7533 case X86::ATOMMIN64:
7534 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7535 case X86::ATOMMAX64:
7536 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7537 case X86::ATOMUMIN64:
7538 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7539 case X86::ATOMUMAX64:
7540 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7542 // This group does 64-bit operations on a 32-bit host.
7543 case X86::ATOMAND6432:
7544 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7545 X86::AND32rr, X86::AND32rr,
7546 X86::AND32ri, X86::AND32ri,
7547 false);
7548 case X86::ATOMOR6432:
7549 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7550 X86::OR32rr, X86::OR32rr,
7551 X86::OR32ri, X86::OR32ri,
7552 false);
7553 case X86::ATOMXOR6432:
7554 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7555 X86::XOR32rr, X86::XOR32rr,
7556 X86::XOR32ri, X86::XOR32ri,
7557 false);
7558 case X86::ATOMNAND6432:
7559 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7560 X86::AND32rr, X86::AND32rr,
7561 X86::AND32ri, X86::AND32ri,
7562 true);
7563 case X86::ATOMADD6432:
7564 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7565 X86::ADD32rr, X86::ADC32rr,
7566 X86::ADD32ri, X86::ADC32ri,
7567 false);
7568 case X86::ATOMSUB6432:
7569 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7570 X86::SUB32rr, X86::SBB32rr,
7571 X86::SUB32ri, X86::SBB32ri,
7572 false);
7573 case X86::ATOMSWAP6432:
7574 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7575 X86::MOV32rr, X86::MOV32rr,
7576 X86::MOV32ri, X86::MOV32ri,
7577 false);
7581 //===----------------------------------------------------------------------===//
7582 // X86 Optimization Hooks
7583 //===----------------------------------------------------------------------===//
7585 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7586 const APInt &Mask,
7587 APInt &KnownZero,
7588 APInt &KnownOne,
7589 const SelectionDAG &DAG,
7590 unsigned Depth) const {
7591 unsigned Opc = Op.getOpcode();
7592 assert((Opc >= ISD::BUILTIN_OP_END ||
7593 Opc == ISD::INTRINSIC_WO_CHAIN ||
7594 Opc == ISD::INTRINSIC_W_CHAIN ||
7595 Opc == ISD::INTRINSIC_VOID) &&
7596 "Should use MaskedValueIsZero if you don't know whether Op"
7597 " is a target node!");
7599 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7600 switch (Opc) {
7601 default: break;
7602 case X86ISD::ADD:
7603 case X86ISD::SUB:
7604 case X86ISD::SMUL:
7605 case X86ISD::UMUL:
7606 case X86ISD::INC:
7607 case X86ISD::DEC:
7608 // These nodes' second result is a boolean.
7609 if (Op.getResNo() == 0)
7610 break;
7611 // Fallthrough
7612 case X86ISD::SETCC:
7613 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7614 Mask.getBitWidth() - 1);
7615 break;
7619 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7620 /// node is a GlobalAddress + offset.
7621 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7622 GlobalValue* &GA, int64_t &Offset) const{
7623 if (N->getOpcode() == X86ISD::Wrapper) {
7624 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7625 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7626 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7627 return true;
7630 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7633 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7634 const TargetLowering &TLI) {
7635 GlobalValue *GV;
7636 int64_t Offset = 0;
7637 if (TLI.isGAPlusOffset(Base, GV, Offset))
7638 return (GV->getAlignment() >= N && (Offset % N) == 0);
7639 // DAG combine handles the stack object case.
7640 return false;
7643 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7644 MVT EVT, SDNode *&Base,
7645 SelectionDAG &DAG, MachineFrameInfo *MFI,
7646 const TargetLowering &TLI) {
7647 Base = NULL;
7648 for (unsigned i = 0; i < NumElems; ++i) {
7649 if (N->getMaskElt(i) < 0) {
7650 if (!Base)
7651 return false;
7652 continue;
7655 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7656 if (!Elt.getNode() ||
7657 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7658 return false;
7659 if (!Base) {
7660 Base = Elt.getNode();
7661 if (Base->getOpcode() == ISD::UNDEF)
7662 return false;
7663 continue;
7665 if (Elt.getOpcode() == ISD::UNDEF)
7666 continue;
7668 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7669 EVT.getSizeInBits()/8, i, MFI))
7670 return false;
7672 return true;
7675 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7676 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7677 /// if the load addresses are consecutive, non-overlapping, and in the right
7678 /// order. In the case of v2i64, it will see if it can rewrite the
7679 /// shuffle to be an appropriate build vector so it can take advantage of
7680 // performBuildVectorCombine.
7681 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7682 const TargetLowering &TLI) {
7683 DebugLoc dl = N->getDebugLoc();
7684 MVT VT = N->getValueType(0);
7685 MVT EVT = VT.getVectorElementType();
7686 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7687 unsigned NumElems = VT.getVectorNumElements();
7689 // For x86-32 machines, if we see an insert and then a shuffle in a v2i64
7690 // where the upper half is 0, it is advantageous to rewrite it as a build
7691 // vector of (0, val) so it can use movq.
7692 if (VT == MVT::v2i64) {
7693 SDValue In[2];
7694 In[0] = N->getOperand(0);
7695 In[1] = N->getOperand(1);
7696 int Idx0 = SVN->getMaskElt(0);
7697 int Idx1 = SVN->getMaskElt(1);
7698 // FIXME: can we take advantage of undef index?
7699 if (Idx0 >= 0 && Idx1 >= 0 &&
7700 In[Idx0/2].getOpcode() == ISD::INSERT_VECTOR_ELT &&
7701 In[Idx1/2].getOpcode() == ISD::BUILD_VECTOR) {
7702 ConstantSDNode* InsertVecIdx =
7703 dyn_cast<ConstantSDNode>(In[Idx0/2].getOperand(2));
7704 if (InsertVecIdx &&
7705 InsertVecIdx->getZExtValue() == (unsigned)(Idx0 % 2) &&
7706 isZeroNode(In[Idx1/2].getOperand(Idx1 % 2))) {
7707 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7708 In[Idx0/2].getOperand(1),
7709 In[Idx1/2].getOperand(Idx1 % 2));
7714 // Try to combine a vector_shuffle into a 128-bit load.
7715 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7716 SDNode *Base = NULL;
7717 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, Base, DAG, MFI, TLI))
7718 return SDValue();
7720 LoadSDNode *LD = cast<LoadSDNode>(Base);
7721 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7722 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7723 LD->getSrcValue(), LD->getSrcValueOffset(),
7724 LD->isVolatile());
7725 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7726 LD->getSrcValue(), LD->getSrcValueOffset(),
7727 LD->isVolatile(), LD->getAlignment());
7730 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7731 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7732 TargetLowering::DAGCombinerInfo &DCI,
7733 const X86Subtarget *Subtarget,
7734 const TargetLowering &TLI) {
7735 unsigned NumOps = N->getNumOperands();
7736 DebugLoc dl = N->getDebugLoc();
7738 // Ignore single operand BUILD_VECTOR.
7739 if (NumOps == 1)
7740 return SDValue();
7742 MVT VT = N->getValueType(0);
7743 MVT EVT = VT.getVectorElementType();
7744 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7745 // We are looking for load i64 and zero extend. We want to transform
7746 // it before legalizer has a chance to expand it. Also look for i64
7747 // BUILD_PAIR bit casted to f64.
7748 return SDValue();
7749 // This must be an insertion into a zero vector.
7750 SDValue HighElt = N->getOperand(1);
7751 if (!isZeroNode(HighElt))
7752 return SDValue();
7754 // Value must be a load.
7755 SDNode *Base = N->getOperand(0).getNode();
7756 if (!isa<LoadSDNode>(Base)) {
7757 if (Base->getOpcode() != ISD::BIT_CONVERT)
7758 return SDValue();
7759 Base = Base->getOperand(0).getNode();
7760 if (!isa<LoadSDNode>(Base))
7761 return SDValue();
7764 // Transform it into VZEXT_LOAD addr.
7765 LoadSDNode *LD = cast<LoadSDNode>(Base);
7767 // Load must not be an extload.
7768 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7769 return SDValue();
7771 // Load type should legal type so we don't have to legalize it.
7772 if (!TLI.isTypeLegal(VT))
7773 return SDValue();
7775 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7776 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7777 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7778 TargetLowering::TargetLoweringOpt TLO(DAG);
7779 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7780 DCI.CommitTargetLoweringOpt(TLO);
7781 return ResNode;
7784 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7785 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7786 const X86Subtarget *Subtarget) {
7787 DebugLoc DL = N->getDebugLoc();
7788 SDValue Cond = N->getOperand(0);
7789 // Get the LHS/RHS of the select.
7790 SDValue LHS = N->getOperand(1);
7791 SDValue RHS = N->getOperand(2);
7793 // If we have SSE[12] support, try to form min/max nodes.
7794 if (Subtarget->hasSSE2() &&
7795 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7796 Cond.getOpcode() == ISD::SETCC) {
7797 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7799 unsigned Opcode = 0;
7800 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7801 switch (CC) {
7802 default: break;
7803 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7804 case ISD::SETULE:
7805 case ISD::SETLE:
7806 if (!UnsafeFPMath) break;
7807 // FALL THROUGH.
7808 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7809 case ISD::SETLT:
7810 Opcode = X86ISD::FMIN;
7811 break;
7813 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7814 case ISD::SETUGT:
7815 case ISD::SETGT:
7816 if (!UnsafeFPMath) break;
7817 // FALL THROUGH.
7818 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7819 case ISD::SETGE:
7820 Opcode = X86ISD::FMAX;
7821 break;
7823 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7824 switch (CC) {
7825 default: break;
7826 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7827 case ISD::SETUGT:
7828 case ISD::SETGT:
7829 if (!UnsafeFPMath) break;
7830 // FALL THROUGH.
7831 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7832 case ISD::SETGE:
7833 Opcode = X86ISD::FMIN;
7834 break;
7836 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7837 case ISD::SETULE:
7838 case ISD::SETLE:
7839 if (!UnsafeFPMath) break;
7840 // FALL THROUGH.
7841 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7842 case ISD::SETLT:
7843 Opcode = X86ISD::FMAX;
7844 break;
7848 if (Opcode)
7849 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
7852 // If this is a select between two integer constants, try to do some
7853 // optimizations.
7854 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
7855 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
7856 // Don't do this for crazy integer types.
7857 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
7858 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
7859 // so that TrueC (the true value) is larger than FalseC.
7860 bool NeedsCondInvert = false;
7862 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
7863 // Efficiently invertible.
7864 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
7865 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
7866 isa<ConstantSDNode>(Cond.getOperand(1))))) {
7867 NeedsCondInvert = true;
7868 std::swap(TrueC, FalseC);
7871 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
7872 if (FalseC->getAPIntValue() == 0 &&
7873 TrueC->getAPIntValue().isPowerOf2()) {
7874 if (NeedsCondInvert) // Invert the condition if needed.
7875 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7876 DAG.getConstant(1, Cond.getValueType()));
7878 // Zero extend the condition if needed.
7879 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
7881 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7882 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
7883 DAG.getConstant(ShAmt, MVT::i8));
7886 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
7887 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7888 if (NeedsCondInvert) // Invert the condition if needed.
7889 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7890 DAG.getConstant(1, Cond.getValueType()));
7892 // Zero extend the condition if needed.
7893 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7894 FalseC->getValueType(0), Cond);
7895 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7896 SDValue(FalseC, 0));
7899 // Optimize cases that will turn into an LEA instruction. This requires
7900 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
7901 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
7902 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
7903 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
7905 bool isFastMultiplier = false;
7906 if (Diff < 10) {
7907 switch ((unsigned char)Diff) {
7908 default: break;
7909 case 1: // result = add base, cond
7910 case 2: // result = lea base( , cond*2)
7911 case 3: // result = lea base(cond, cond*2)
7912 case 4: // result = lea base( , cond*4)
7913 case 5: // result = lea base(cond, cond*4)
7914 case 8: // result = lea base( , cond*8)
7915 case 9: // result = lea base(cond, cond*8)
7916 isFastMultiplier = true;
7917 break;
7921 if (isFastMultiplier) {
7922 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
7923 if (NeedsCondInvert) // Invert the condition if needed.
7924 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7925 DAG.getConstant(1, Cond.getValueType()));
7927 // Zero extend the condition if needed.
7928 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
7929 Cond);
7930 // Scale the condition by the difference.
7931 if (Diff != 1)
7932 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
7933 DAG.getConstant(Diff, Cond.getValueType()));
7935 // Add the base if non-zero.
7936 if (FalseC->getAPIntValue() != 0)
7937 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7938 SDValue(FalseC, 0));
7939 return Cond;
7945 return SDValue();
7948 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
7949 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
7950 TargetLowering::DAGCombinerInfo &DCI) {
7951 DebugLoc DL = N->getDebugLoc();
7953 // If the flag operand isn't dead, don't touch this CMOV.
7954 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
7955 return SDValue();
7957 // If this is a select between two integer constants, try to do some
7958 // optimizations. Note that the operands are ordered the opposite of SELECT
7959 // operands.
7960 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7961 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7962 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
7963 // larger than FalseC (the false value).
7964 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
7966 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
7967 CC = X86::GetOppositeBranchCondition(CC);
7968 std::swap(TrueC, FalseC);
7971 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
7972 // This is efficient for any integer data type (including i8/i16) and
7973 // shift amount.
7974 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
7975 SDValue Cond = N->getOperand(3);
7976 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
7977 DAG.getConstant(CC, MVT::i8), Cond);
7979 // Zero extend the condition if needed.
7980 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
7982 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7983 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
7984 DAG.getConstant(ShAmt, MVT::i8));
7985 if (N->getNumValues() == 2) // Dead flag value?
7986 return DCI.CombineTo(N, Cond, SDValue());
7987 return Cond;
7990 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
7991 // for any integer data type, including i8/i16.
7992 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7993 SDValue Cond = N->getOperand(3);
7994 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
7995 DAG.getConstant(CC, MVT::i8), Cond);
7997 // Zero extend the condition if needed.
7998 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7999 FalseC->getValueType(0), Cond);
8000 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8001 SDValue(FalseC, 0));
8003 if (N->getNumValues() == 2) // Dead flag value?
8004 return DCI.CombineTo(N, Cond, SDValue());
8005 return Cond;
8008 // Optimize cases that will turn into an LEA instruction. This requires
8009 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8010 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8011 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8012 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8014 bool isFastMultiplier = false;
8015 if (Diff < 10) {
8016 switch ((unsigned char)Diff) {
8017 default: break;
8018 case 1: // result = add base, cond
8019 case 2: // result = lea base( , cond*2)
8020 case 3: // result = lea base(cond, cond*2)
8021 case 4: // result = lea base( , cond*4)
8022 case 5: // result = lea base(cond, cond*4)
8023 case 8: // result = lea base( , cond*8)
8024 case 9: // result = lea base(cond, cond*8)
8025 isFastMultiplier = true;
8026 break;
8030 if (isFastMultiplier) {
8031 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8032 SDValue Cond = N->getOperand(3);
8033 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8034 DAG.getConstant(CC, MVT::i8), Cond);
8035 // Zero extend the condition if needed.
8036 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8037 Cond);
8038 // Scale the condition by the difference.
8039 if (Diff != 1)
8040 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8041 DAG.getConstant(Diff, Cond.getValueType()));
8043 // Add the base if non-zero.
8044 if (FalseC->getAPIntValue() != 0)
8045 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8046 SDValue(FalseC, 0));
8047 if (N->getNumValues() == 2) // Dead flag value?
8048 return DCI.CombineTo(N, Cond, SDValue());
8049 return Cond;
8054 return SDValue();
8058 /// PerformMulCombine - Optimize a single multiply with constant into two
8059 /// in order to implement it with two cheaper instructions, e.g.
8060 /// LEA + SHL, LEA + LEA.
8061 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8062 TargetLowering::DAGCombinerInfo &DCI) {
8063 if (DAG.getMachineFunction().
8064 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8065 return SDValue();
8067 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8068 return SDValue();
8070 MVT VT = N->getValueType(0);
8071 if (VT != MVT::i64)
8072 return SDValue();
8074 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8075 if (!C)
8076 return SDValue();
8077 uint64_t MulAmt = C->getZExtValue();
8078 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8079 return SDValue();
8081 uint64_t MulAmt1 = 0;
8082 uint64_t MulAmt2 = 0;
8083 if ((MulAmt % 9) == 0) {
8084 MulAmt1 = 9;
8085 MulAmt2 = MulAmt / 9;
8086 } else if ((MulAmt % 5) == 0) {
8087 MulAmt1 = 5;
8088 MulAmt2 = MulAmt / 5;
8089 } else if ((MulAmt % 3) == 0) {
8090 MulAmt1 = 3;
8091 MulAmt2 = MulAmt / 3;
8093 if (MulAmt2 &&
8094 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8095 DebugLoc DL = N->getDebugLoc();
8097 if (isPowerOf2_64(MulAmt2) &&
8098 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8099 // If second multiplifer is pow2, issue it first. We want the multiply by
8100 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8101 // is an add.
8102 std::swap(MulAmt1, MulAmt2);
8104 SDValue NewMul;
8105 if (isPowerOf2_64(MulAmt1))
8106 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8107 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8108 else
8109 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8110 DAG.getConstant(MulAmt1, VT));
8112 if (isPowerOf2_64(MulAmt2))
8113 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8114 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8115 else
8116 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8117 DAG.getConstant(MulAmt2, VT));
8119 // Do not add new nodes to DAG combiner worklist.
8120 DCI.CombineTo(N, NewMul, false);
8122 return SDValue();
8126 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8127 /// when possible.
8128 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8129 const X86Subtarget *Subtarget) {
8130 // On X86 with SSE2 support, we can transform this to a vector shift if
8131 // all elements are shifted by the same amount. We can't do this in legalize
8132 // because the a constant vector is typically transformed to a constant pool
8133 // so we have no knowledge of the shift amount.
8134 if (!Subtarget->hasSSE2())
8135 return SDValue();
8137 MVT VT = N->getValueType(0);
8138 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8139 return SDValue();
8141 SDValue ShAmtOp = N->getOperand(1);
8142 MVT EltVT = VT.getVectorElementType();
8143 DebugLoc DL = N->getDebugLoc();
8144 SDValue BaseShAmt;
8145 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8146 unsigned NumElts = VT.getVectorNumElements();
8147 unsigned i = 0;
8148 for (; i != NumElts; ++i) {
8149 SDValue Arg = ShAmtOp.getOperand(i);
8150 if (Arg.getOpcode() == ISD::UNDEF) continue;
8151 BaseShAmt = Arg;
8152 break;
8154 for (; i != NumElts; ++i) {
8155 SDValue Arg = ShAmtOp.getOperand(i);
8156 if (Arg.getOpcode() == ISD::UNDEF) continue;
8157 if (Arg != BaseShAmt) {
8158 return SDValue();
8161 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8162 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8163 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8164 DAG.getIntPtrConstant(0));
8165 } else
8166 return SDValue();
8168 if (EltVT.bitsGT(MVT::i32))
8169 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8170 else if (EltVT.bitsLT(MVT::i32))
8171 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8173 // The shift amount is identical so we can do a vector shift.
8174 SDValue ValOp = N->getOperand(0);
8175 switch (N->getOpcode()) {
8176 default:
8177 assert(0 && "Unknown shift opcode!");
8178 break;
8179 case ISD::SHL:
8180 if (VT == MVT::v2i64)
8181 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8182 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8183 ValOp, BaseShAmt);
8184 if (VT == MVT::v4i32)
8185 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8186 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8187 ValOp, BaseShAmt);
8188 if (VT == MVT::v8i16)
8189 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8190 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8191 ValOp, BaseShAmt);
8192 break;
8193 case ISD::SRA:
8194 if (VT == MVT::v4i32)
8195 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8196 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8197 ValOp, BaseShAmt);
8198 if (VT == MVT::v8i16)
8199 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8200 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8201 ValOp, BaseShAmt);
8202 break;
8203 case ISD::SRL:
8204 if (VT == MVT::v2i64)
8205 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8206 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8207 ValOp, BaseShAmt);
8208 if (VT == MVT::v4i32)
8209 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8210 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8211 ValOp, BaseShAmt);
8212 if (VT == MVT::v8i16)
8213 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8214 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8215 ValOp, BaseShAmt);
8216 break;
8218 return SDValue();
8221 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8222 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8223 const X86Subtarget *Subtarget) {
8224 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8225 // the FP state in cases where an emms may be missing.
8226 // A preferable solution to the general problem is to figure out the right
8227 // places to insert EMMS. This qualifies as a quick hack.
8229 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8230 StoreSDNode *St = cast<StoreSDNode>(N);
8231 MVT VT = St->getValue().getValueType();
8232 if (VT.getSizeInBits() != 64)
8233 return SDValue();
8235 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloat && Subtarget->hasSSE2();
8236 if ((VT.isVector() ||
8237 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8238 isa<LoadSDNode>(St->getValue()) &&
8239 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8240 St->getChain().hasOneUse() && !St->isVolatile()) {
8241 SDNode* LdVal = St->getValue().getNode();
8242 LoadSDNode *Ld = 0;
8243 int TokenFactorIndex = -1;
8244 SmallVector<SDValue, 8> Ops;
8245 SDNode* ChainVal = St->getChain().getNode();
8246 // Must be a store of a load. We currently handle two cases: the load
8247 // is a direct child, and it's under an intervening TokenFactor. It is
8248 // possible to dig deeper under nested TokenFactors.
8249 if (ChainVal == LdVal)
8250 Ld = cast<LoadSDNode>(St->getChain());
8251 else if (St->getValue().hasOneUse() &&
8252 ChainVal->getOpcode() == ISD::TokenFactor) {
8253 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8254 if (ChainVal->getOperand(i).getNode() == LdVal) {
8255 TokenFactorIndex = i;
8256 Ld = cast<LoadSDNode>(St->getValue());
8257 } else
8258 Ops.push_back(ChainVal->getOperand(i));
8262 if (!Ld || !ISD::isNormalLoad(Ld))
8263 return SDValue();
8265 // If this is not the MMX case, i.e. we are just turning i64 load/store
8266 // into f64 load/store, avoid the transformation if there are multiple
8267 // uses of the loaded value.
8268 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8269 return SDValue();
8271 DebugLoc LdDL = Ld->getDebugLoc();
8272 DebugLoc StDL = N->getDebugLoc();
8273 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8274 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8275 // pair instead.
8276 if (Subtarget->is64Bit() || F64IsLegal) {
8277 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8278 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8279 Ld->getBasePtr(), Ld->getSrcValue(),
8280 Ld->getSrcValueOffset(), Ld->isVolatile(),
8281 Ld->getAlignment());
8282 SDValue NewChain = NewLd.getValue(1);
8283 if (TokenFactorIndex != -1) {
8284 Ops.push_back(NewChain);
8285 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8286 Ops.size());
8288 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8289 St->getSrcValue(), St->getSrcValueOffset(),
8290 St->isVolatile(), St->getAlignment());
8293 // Otherwise, lower to two pairs of 32-bit loads / stores.
8294 SDValue LoAddr = Ld->getBasePtr();
8295 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8296 DAG.getConstant(4, MVT::i32));
8298 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8299 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8300 Ld->isVolatile(), Ld->getAlignment());
8301 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8302 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8303 Ld->isVolatile(),
8304 MinAlign(Ld->getAlignment(), 4));
8306 SDValue NewChain = LoLd.getValue(1);
8307 if (TokenFactorIndex != -1) {
8308 Ops.push_back(LoLd);
8309 Ops.push_back(HiLd);
8310 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8311 Ops.size());
8314 LoAddr = St->getBasePtr();
8315 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8316 DAG.getConstant(4, MVT::i32));
8318 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8319 St->getSrcValue(), St->getSrcValueOffset(),
8320 St->isVolatile(), St->getAlignment());
8321 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8322 St->getSrcValue(),
8323 St->getSrcValueOffset() + 4,
8324 St->isVolatile(),
8325 MinAlign(St->getAlignment(), 4));
8326 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8328 return SDValue();
8331 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8332 /// X86ISD::FXOR nodes.
8333 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8334 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8335 // F[X]OR(0.0, x) -> x
8336 // F[X]OR(x, 0.0) -> x
8337 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8338 if (C->getValueAPF().isPosZero())
8339 return N->getOperand(1);
8340 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8341 if (C->getValueAPF().isPosZero())
8342 return N->getOperand(0);
8343 return SDValue();
8346 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8347 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8348 // FAND(0.0, x) -> 0.0
8349 // FAND(x, 0.0) -> 0.0
8350 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8351 if (C->getValueAPF().isPosZero())
8352 return N->getOperand(0);
8353 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8354 if (C->getValueAPF().isPosZero())
8355 return N->getOperand(1);
8356 return SDValue();
8359 static SDValue PerformBTCombine(SDNode *N,
8360 SelectionDAG &DAG,
8361 TargetLowering::DAGCombinerInfo &DCI) {
8362 // BT ignores high bits in the bit index operand.
8363 SDValue Op1 = N->getOperand(1);
8364 if (Op1.hasOneUse()) {
8365 unsigned BitWidth = Op1.getValueSizeInBits();
8366 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8367 APInt KnownZero, KnownOne;
8368 TargetLowering::TargetLoweringOpt TLO(DAG);
8369 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8370 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8371 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8372 DCI.CommitTargetLoweringOpt(TLO);
8374 return SDValue();
8377 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8378 DAGCombinerInfo &DCI) const {
8379 SelectionDAG &DAG = DCI.DAG;
8380 switch (N->getOpcode()) {
8381 default: break;
8382 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8383 case ISD::BUILD_VECTOR:
8384 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8385 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8386 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8387 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8388 case ISD::SHL:
8389 case ISD::SRA:
8390 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8391 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8392 case X86ISD::FXOR:
8393 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8394 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8395 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8398 return SDValue();
8401 //===----------------------------------------------------------------------===//
8402 // X86 Inline Assembly Support
8403 //===----------------------------------------------------------------------===//
8405 /// getConstraintType - Given a constraint letter, return the type of
8406 /// constraint it is for this target.
8407 X86TargetLowering::ConstraintType
8408 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8409 if (Constraint.size() == 1) {
8410 switch (Constraint[0]) {
8411 case 'A':
8412 return C_Register;
8413 case 'f':
8414 case 'r':
8415 case 'R':
8416 case 'l':
8417 case 'q':
8418 case 'Q':
8419 case 'x':
8420 case 'y':
8421 case 'Y':
8422 return C_RegisterClass;
8423 case 'e':
8424 case 'Z':
8425 return C_Other;
8426 default:
8427 break;
8430 return TargetLowering::getConstraintType(Constraint);
8433 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8434 /// with another that has more specific requirements based on the type of the
8435 /// corresponding operand.
8436 const char *X86TargetLowering::
8437 LowerXConstraint(MVT ConstraintVT) const {
8438 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8439 // 'f' like normal targets.
8440 if (ConstraintVT.isFloatingPoint()) {
8441 if (Subtarget->hasSSE2())
8442 return "Y";
8443 if (Subtarget->hasSSE1())
8444 return "x";
8447 return TargetLowering::LowerXConstraint(ConstraintVT);
8450 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8451 /// vector. If it is invalid, don't add anything to Ops.
8452 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8453 char Constraint,
8454 bool hasMemory,
8455 std::vector<SDValue>&Ops,
8456 SelectionDAG &DAG) const {
8457 SDValue Result(0, 0);
8459 switch (Constraint) {
8460 default: break;
8461 case 'I':
8462 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8463 if (C->getZExtValue() <= 31) {
8464 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8465 break;
8468 return;
8469 case 'J':
8470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8471 if (C->getZExtValue() <= 63) {
8472 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8473 break;
8476 return;
8477 case 'N':
8478 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8479 if (C->getZExtValue() <= 255) {
8480 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8481 break;
8484 return;
8485 case 'e': {
8486 // 32-bit signed value
8487 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8488 const ConstantInt *CI = C->getConstantIntValue();
8489 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8490 // Widen to 64 bits here to get it sign extended.
8491 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8492 break;
8494 // FIXME gcc accepts some relocatable values here too, but only in certain
8495 // memory models; it's complicated.
8497 return;
8499 case 'Z': {
8500 // 32-bit unsigned value
8501 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8502 const ConstantInt *CI = C->getConstantIntValue();
8503 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8504 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8505 break;
8508 // FIXME gcc accepts some relocatable values here too, but only in certain
8509 // memory models; it's complicated.
8510 return;
8512 case 'i': {
8513 // Literal immediates are always ok.
8514 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8515 // Widen to 64 bits here to get it sign extended.
8516 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8517 break;
8520 // If we are in non-pic codegen mode, we allow the address of a global (with
8521 // an optional displacement) to be used with 'i'.
8522 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8523 int64_t Offset = 0;
8525 // Match either (GA) or (GA+C)
8526 if (GA) {
8527 Offset = GA->getOffset();
8528 } else if (Op.getOpcode() == ISD::ADD) {
8529 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8530 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8531 if (C && GA) {
8532 Offset = GA->getOffset()+C->getZExtValue();
8533 } else {
8534 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8535 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8536 if (C && GA)
8537 Offset = GA->getOffset()+C->getZExtValue();
8538 else
8539 C = 0, GA = 0;
8543 if (GA) {
8544 if (hasMemory)
8545 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(),
8546 Offset, DAG);
8547 else
8548 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8549 Offset);
8550 Result = Op;
8551 break;
8554 // Otherwise, not valid for this mode.
8555 return;
8559 if (Result.getNode()) {
8560 Ops.push_back(Result);
8561 return;
8563 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8564 Ops, DAG);
8567 std::vector<unsigned> X86TargetLowering::
8568 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8569 MVT VT) const {
8570 if (Constraint.size() == 1) {
8571 // FIXME: not handling fp-stack yet!
8572 switch (Constraint[0]) { // GCC X86 Constraint Letters
8573 default: break; // Unknown constraint letter
8574 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8575 case 'Q': // Q_REGS
8576 if (VT == MVT::i32)
8577 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8578 else if (VT == MVT::i16)
8579 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8580 else if (VT == MVT::i8)
8581 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8582 else if (VT == MVT::i64)
8583 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8584 break;
8588 return std::vector<unsigned>();
8591 std::pair<unsigned, const TargetRegisterClass*>
8592 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8593 MVT VT) const {
8594 // First, see if this is a constraint that directly corresponds to an LLVM
8595 // register class.
8596 if (Constraint.size() == 1) {
8597 // GCC Constraint Letters
8598 switch (Constraint[0]) {
8599 default: break;
8600 case 'r': // GENERAL_REGS
8601 case 'R': // LEGACY_REGS
8602 case 'l': // INDEX_REGS
8603 if (VT == MVT::i8)
8604 return std::make_pair(0U, X86::GR8RegisterClass);
8605 if (VT == MVT::i16)
8606 return std::make_pair(0U, X86::GR16RegisterClass);
8607 if (VT == MVT::i32 || !Subtarget->is64Bit())
8608 return std::make_pair(0U, X86::GR32RegisterClass);
8609 return std::make_pair(0U, X86::GR64RegisterClass);
8610 case 'f': // FP Stack registers.
8611 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8612 // value to the correct fpstack register class.
8613 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8614 return std::make_pair(0U, X86::RFP32RegisterClass);
8615 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8616 return std::make_pair(0U, X86::RFP64RegisterClass);
8617 return std::make_pair(0U, X86::RFP80RegisterClass);
8618 case 'y': // MMX_REGS if MMX allowed.
8619 if (!Subtarget->hasMMX()) break;
8620 return std::make_pair(0U, X86::VR64RegisterClass);
8621 case 'Y': // SSE_REGS if SSE2 allowed
8622 if (!Subtarget->hasSSE2()) break;
8623 // FALL THROUGH.
8624 case 'x': // SSE_REGS if SSE1 allowed
8625 if (!Subtarget->hasSSE1()) break;
8627 switch (VT.getSimpleVT()) {
8628 default: break;
8629 // Scalar SSE types.
8630 case MVT::f32:
8631 case MVT::i32:
8632 return std::make_pair(0U, X86::FR32RegisterClass);
8633 case MVT::f64:
8634 case MVT::i64:
8635 return std::make_pair(0U, X86::FR64RegisterClass);
8636 // Vector types.
8637 case MVT::v16i8:
8638 case MVT::v8i16:
8639 case MVT::v4i32:
8640 case MVT::v2i64:
8641 case MVT::v4f32:
8642 case MVT::v2f64:
8643 return std::make_pair(0U, X86::VR128RegisterClass);
8645 break;
8649 // Use the default implementation in TargetLowering to convert the register
8650 // constraint into a member of a register class.
8651 std::pair<unsigned, const TargetRegisterClass*> Res;
8652 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8654 // Not found as a standard register?
8655 if (Res.second == 0) {
8656 // GCC calls "st(0)" just plain "st".
8657 if (StringsEqualNoCase("{st}", Constraint)) {
8658 Res.first = X86::ST0;
8659 Res.second = X86::RFP80RegisterClass;
8661 // 'A' means EAX + EDX.
8662 if (Constraint == "A") {
8663 Res.first = X86::EAX;
8664 Res.second = X86::GRADRegisterClass;
8666 return Res;
8669 // Otherwise, check to see if this is a register class of the wrong value
8670 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8671 // turn into {ax},{dx}.
8672 if (Res.second->hasType(VT))
8673 return Res; // Correct type already, nothing to do.
8675 // All of the single-register GCC register classes map their values onto
8676 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8677 // really want an 8-bit or 32-bit register, map to the appropriate register
8678 // class and return the appropriate register.
8679 if (Res.second == X86::GR16RegisterClass) {
8680 if (VT == MVT::i8) {
8681 unsigned DestReg = 0;
8682 switch (Res.first) {
8683 default: break;
8684 case X86::AX: DestReg = X86::AL; break;
8685 case X86::DX: DestReg = X86::DL; break;
8686 case X86::CX: DestReg = X86::CL; break;
8687 case X86::BX: DestReg = X86::BL; break;
8689 if (DestReg) {
8690 Res.first = DestReg;
8691 Res.second = X86::GR8RegisterClass;
8693 } else if (VT == MVT::i32) {
8694 unsigned DestReg = 0;
8695 switch (Res.first) {
8696 default: break;
8697 case X86::AX: DestReg = X86::EAX; break;
8698 case X86::DX: DestReg = X86::EDX; break;
8699 case X86::CX: DestReg = X86::ECX; break;
8700 case X86::BX: DestReg = X86::EBX; break;
8701 case X86::SI: DestReg = X86::ESI; break;
8702 case X86::DI: DestReg = X86::EDI; break;
8703 case X86::BP: DestReg = X86::EBP; break;
8704 case X86::SP: DestReg = X86::ESP; break;
8706 if (DestReg) {
8707 Res.first = DestReg;
8708 Res.second = X86::GR32RegisterClass;
8710 } else if (VT == MVT::i64) {
8711 unsigned DestReg = 0;
8712 switch (Res.first) {
8713 default: break;
8714 case X86::AX: DestReg = X86::RAX; break;
8715 case X86::DX: DestReg = X86::RDX; break;
8716 case X86::CX: DestReg = X86::RCX; break;
8717 case X86::BX: DestReg = X86::RBX; break;
8718 case X86::SI: DestReg = X86::RSI; break;
8719 case X86::DI: DestReg = X86::RDI; break;
8720 case X86::BP: DestReg = X86::RBP; break;
8721 case X86::SP: DestReg = X86::RSP; break;
8723 if (DestReg) {
8724 Res.first = DestReg;
8725 Res.second = X86::GR64RegisterClass;
8728 } else if (Res.second == X86::FR32RegisterClass ||
8729 Res.second == X86::FR64RegisterClass ||
8730 Res.second == X86::VR128RegisterClass) {
8731 // Handle references to XMM physical registers that got mapped into the
8732 // wrong class. This can happen with constraints like {xmm0} where the
8733 // target independent register mapper will just pick the first match it can
8734 // find, ignoring the required type.
8735 if (VT == MVT::f32)
8736 Res.second = X86::FR32RegisterClass;
8737 else if (VT == MVT::f64)
8738 Res.second = X86::FR64RegisterClass;
8739 else if (X86::VR128RegisterClass->hasType(VT))
8740 Res.second = X86::VR128RegisterClass;
8743 return Res;
8746 //===----------------------------------------------------------------------===//
8747 // X86 Widen vector type
8748 //===----------------------------------------------------------------------===//
8750 /// getWidenVectorType: given a vector type, returns the type to widen
8751 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8752 /// If there is no vector type that we want to widen to, returns MVT::Other
8753 /// When and where to widen is target dependent based on the cost of
8754 /// scalarizing vs using the wider vector type.
8756 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8757 assert(VT.isVector());
8758 if (isTypeLegal(VT))
8759 return VT;
8761 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8762 // type based on element type. This would speed up our search (though
8763 // it may not be worth it since the size of the list is relatively
8764 // small).
8765 MVT EltVT = VT.getVectorElementType();
8766 unsigned NElts = VT.getVectorNumElements();
8768 // On X86, it make sense to widen any vector wider than 1
8769 if (NElts <= 1)
8770 return MVT::Other;
8772 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8773 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8774 MVT SVT = (MVT::SimpleValueType)nVT;
8776 if (isTypeLegal(SVT) &&
8777 SVT.getVectorElementType() == EltVT &&
8778 SVT.getVectorNumElements() > NElts)
8779 return SVT;
8781 return MVT::Other;