blob: 7b683e3ee3ab992b60e63d434ae76bf1fa9a5088 [file] [log] [blame]
Arnold Schwaighofera70fe792007-10-12 21:53:12 +00001//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
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"
Evan Cheng75184a92007-12-11 01:46:18 +000026#include "llvm/ADT/BitVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/ADT/VectorExtras.h"
28#include "llvm/Analysis/ScalarEvolutionExpressions.h"
29#include "llvm/CodeGen/CallingConvLower.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner1b989192007-12-31 04:13:23 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/Support/MathExtras.h"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000036#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/Target/TargetOptions.h"
Evan Cheng75184a92007-12-11 01:46:18 +000038#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/ADT/StringExtras.h"
Duncan Sandsd8455ca2007-07-27 20:02:49 +000040#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041using namespace llvm;
42
43X86TargetLowering::X86TargetLowering(TargetMachine &TM)
44 : TargetLowering(TM) {
45 Subtarget = &TM.getSubtarget<X86Subtarget>();
Dale Johannesene0e0fd02007-09-23 14:52:20 +000046 X86ScalarSSEf64 = Subtarget->hasSSE2();
47 X86ScalarSSEf32 = Subtarget->hasSSE1();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +000049
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050
51 RegInfo = TM.getRegisterInfo();
52
53 // Set up the TargetLowering object.
54
55 // X86 is weird, it always uses i8 for shift amounts and setcc results.
56 setShiftAmountType(MVT::i8);
57 setSetCCResultType(MVT::i8);
58 setSetCCResultContents(ZeroOrOneSetCCResult);
59 setSchedulingPreference(SchedulingForRegPressure);
60 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
61 setStackPointerRegisterToSaveRestore(X86StackPtr);
62
63 if (Subtarget->isTargetDarwin()) {
64 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
65 setUseUnderscoreSetJmp(false);
66 setUseUnderscoreLongJmp(false);
67 } else if (Subtarget->isTargetMingw()) {
68 // MS runtime is weird: it exports _setjmp, but longjmp!
69 setUseUnderscoreSetJmp(true);
70 setUseUnderscoreLongJmp(false);
71 } else {
72 setUseUnderscoreSetJmp(true);
73 setUseUnderscoreLongJmp(true);
74 }
75
76 // Set up the register classes.
77 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
78 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
79 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
80 if (Subtarget->is64Bit())
81 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
82
83 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
84
85 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
86 // operation.
87 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
88 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
89 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
90
91 if (Subtarget->is64Bit()) {
92 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
93 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
94 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +000095 if (X86ScalarSSEf64)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
97 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
98 else
99 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
100 }
101
102 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
103 // this operation.
104 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
105 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
106 // SSE has no i16 to fp conversion, only i32
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000107 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000109 // f32 and f64 cases are Legal, f80 case is not
110 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
111 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000112 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
113 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
114 }
115
Dale Johannesen958b08b2007-09-19 23:55:34 +0000116 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
117 // are Legal, f80 is custom lowered.
118 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
119 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120
121 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
122 // this operation.
123 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
124 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
125
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000126 if (X86ScalarSSEf32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000128 // f32 and f64 cases are Legal, f80 case is not
129 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 } else {
131 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
132 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
133 }
134
135 // Handle FP_TO_UINT by promoting the destination to a larger signed
136 // conversion.
137 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
138 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
139 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
140
141 if (Subtarget->is64Bit()) {
142 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
143 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
144 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000145 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 // Expand FP_TO_UINT into a select.
147 // FIXME: We would like to use a Custom expander here eventually to do
148 // the optimal thing for SSE vs. the default expansion in the legalizer.
149 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
150 else
151 // With SSE3 we can use fisttpll to convert to a signed i64.
152 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
153 }
154
155 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000156 if (!X86ScalarSSEf64) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
158 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
159 }
160
Dan Gohman5a199552007-10-08 18:33:35 +0000161 // Scalar integer multiply, multiply-high, divide, and remainder are
162 // lowered to use operations that produce two results, to match the
163 // available instructions. This exposes the two-result form to trivial
164 // CSE, which is able to combine x/y and x%y into a single instruction,
165 // for example. The single-result multiply instructions are introduced
166 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
167 // is not needed.
168 setOperationAction(ISD::MUL , MVT::i8 , Expand);
169 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
170 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
171 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
172 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
173 setOperationAction(ISD::SREM , MVT::i8 , Expand);
174 setOperationAction(ISD::UREM , MVT::i8 , Expand);
175 setOperationAction(ISD::MUL , MVT::i16 , Expand);
176 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
177 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
178 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
179 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
180 setOperationAction(ISD::SREM , MVT::i16 , Expand);
181 setOperationAction(ISD::UREM , MVT::i16 , Expand);
182 setOperationAction(ISD::MUL , MVT::i32 , Expand);
183 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
184 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
185 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
186 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
187 setOperationAction(ISD::SREM , MVT::i32 , Expand);
188 setOperationAction(ISD::UREM , MVT::i32 , Expand);
189 setOperationAction(ISD::MUL , MVT::i64 , Expand);
190 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
191 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
192 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
193 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
194 setOperationAction(ISD::SREM , MVT::i64 , Expand);
195 setOperationAction(ISD::UREM , MVT::i64 , Expand);
Dan Gohman242a5ba2007-09-25 18:23:27 +0000196
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
198 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
199 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
200 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
201 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
202 if (Subtarget->is64Bit())
Christopher Lamb0a7c8662007-08-10 21:48:46 +0000203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
207 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
208 setOperationAction(ISD::FREM , MVT::f64 , Expand);
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +0000209 setOperationAction(ISD::FLT_ROUNDS , MVT::i32 , Custom);
210
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
Evan Cheng48679f42007-12-14 02:13:44 +0000212 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
213 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
Evan Cheng48679f42007-12-14 02:13:44 +0000215 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
216 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
Evan Cheng48679f42007-12-14 02:13:44 +0000218 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
219 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 if (Subtarget->is64Bit()) {
221 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
Evan Cheng48679f42007-12-14 02:13:44 +0000222 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
223 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 }
225
226 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
227 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
228
229 // These should be promoted to a larger select which is supported.
230 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
231 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
232 // X86 wants to expand cmov itself.
233 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
234 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
235 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
236 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000237 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
239 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
240 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
241 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
242 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000243 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244 if (Subtarget->is64Bit()) {
245 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
246 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
247 }
248 // X86 ret instruction may pop stack.
249 setOperationAction(ISD::RET , MVT::Other, Custom);
250 if (!Subtarget->is64Bit())
251 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
252
253 // Darwin ABI issue.
254 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
255 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
256 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
257 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
258 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
259 if (Subtarget->is64Bit()) {
260 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
261 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
262 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
263 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
264 }
265 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
266 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
267 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
268 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
269 // X86 wants to expand memset / memcpy itself.
270 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
271 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
272
Dan Gohman21442852007-09-25 15:10:49 +0000273 // Use the default ISD::LOCATION expansion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 // FIXME - use subtarget debug flags
276 if (!Subtarget->isTargetDarwin() &&
277 !Subtarget->isTargetELF() &&
278 !Subtarget->isTargetCygMing())
279 setOperationAction(ISD::LABEL, MVT::Other, Expand);
280
281 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
282 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
283 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
284 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
285 if (Subtarget->is64Bit()) {
286 // FIXME: Verify
287 setExceptionPointerRegister(X86::RAX);
288 setExceptionSelectorRegister(X86::RDX);
289 } else {
290 setExceptionPointerRegister(X86::EAX);
291 setExceptionSelectorRegister(X86::EDX);
292 }
Anton Korobeynikov23ca9c52007-09-03 00:36:06 +0000293 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294
Duncan Sands7407a9f2007-09-11 14:10:23 +0000295 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
Duncan Sandsd8455ca2007-07-27 20:02:49 +0000296
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
298 setOperationAction(ISD::VASTART , MVT::Other, Custom);
299 setOperationAction(ISD::VAARG , MVT::Other, Expand);
300 setOperationAction(ISD::VAEND , MVT::Other, Expand);
301 if (Subtarget->is64Bit())
302 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
303 else
304 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
305
306 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
307 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
308 if (Subtarget->is64Bit())
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
310 if (Subtarget->isTargetCygMing())
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
312 else
313 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
314
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000315 if (X86ScalarSSEf64) {
316 // f32 and f64 use SSE.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 // Set up the FP register classes.
318 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
319 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
320
321 // Use ANDPD to simulate FABS.
322 setOperationAction(ISD::FABS , MVT::f64, Custom);
323 setOperationAction(ISD::FABS , MVT::f32, Custom);
324
325 // Use XORP to simulate FNEG.
326 setOperationAction(ISD::FNEG , MVT::f64, Custom);
327 setOperationAction(ISD::FNEG , MVT::f32, Custom);
328
329 // Use ANDPD and ORPD to simulate FCOPYSIGN.
330 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
331 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
332
333 // We don't support sin/cos/fmod
334 setOperationAction(ISD::FSIN , MVT::f64, Expand);
335 setOperationAction(ISD::FCOS , MVT::f64, Expand);
336 setOperationAction(ISD::FREM , MVT::f64, Expand);
337 setOperationAction(ISD::FSIN , MVT::f32, Expand);
338 setOperationAction(ISD::FCOS , MVT::f32, Expand);
339 setOperationAction(ISD::FREM , MVT::f32, Expand);
340
341 // Expand FP immediates into loads from the stack, except for the special
342 // cases we handle.
343 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
344 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000345 addLegalFPImmediate(APFloat(+0.0)); // xorpd
346 addLegalFPImmediate(APFloat(+0.0f)); // xorps
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000347
348 // Conversions to long double (in X87) go through memory.
349 setConvertAction(MVT::f32, MVT::f80, Expand);
350 setConvertAction(MVT::f64, MVT::f80, Expand);
351
352 // Conversions from long double (in X87) go through memory.
353 setConvertAction(MVT::f80, MVT::f32, Expand);
354 setConvertAction(MVT::f80, MVT::f64, Expand);
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000355 } else if (X86ScalarSSEf32) {
356 // Use SSE for f32, x87 for f64.
357 // Set up the FP register classes.
358 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
359 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
360
361 // Use ANDPS to simulate FABS.
362 setOperationAction(ISD::FABS , MVT::f32, Custom);
363
364 // Use XORP to simulate FNEG.
365 setOperationAction(ISD::FNEG , MVT::f32, Custom);
366
367 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
368
369 // Use ANDPS and ORPS to simulate FCOPYSIGN.
370 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
371 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
372
373 // We don't support sin/cos/fmod
374 setOperationAction(ISD::FSIN , MVT::f32, Expand);
375 setOperationAction(ISD::FCOS , MVT::f32, Expand);
376 setOperationAction(ISD::FREM , MVT::f32, Expand);
377
378 // Expand FP immediates into loads from the stack, except for the special
379 // cases we handle.
380 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
381 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
382 addLegalFPImmediate(APFloat(+0.0f)); // xorps
383 addLegalFPImmediate(APFloat(+0.0)); // FLD0
384 addLegalFPImmediate(APFloat(+1.0)); // FLD1
385 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
386 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
387
388 // SSE->x87 conversions go through memory.
389 setConvertAction(MVT::f32, MVT::f64, Expand);
390 setConvertAction(MVT::f32, MVT::f80, Expand);
391
392 // x87->SSE truncations need to go through memory.
393 setConvertAction(MVT::f80, MVT::f32, Expand);
394 setConvertAction(MVT::f64, MVT::f32, Expand);
395 // And x87->x87 truncations also.
396 setConvertAction(MVT::f80, MVT::f64, Expand);
397
398 if (!UnsafeFPMath) {
399 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
400 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
401 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 } else {
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000403 // f32 and f64 in x87.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 // Set up the FP register classes.
405 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
406 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
407
408 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
409 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
410 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
411 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
Dale Johannesen8f83a6b2007-08-09 01:04:01 +0000412
413 // Floating truncations need to go through memory.
414 setConvertAction(MVT::f80, MVT::f32, Expand);
415 setConvertAction(MVT::f64, MVT::f32, Expand);
416 setConvertAction(MVT::f80, MVT::f64, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417
418 if (!UnsafeFPMath) {
419 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
420 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
421 }
422
423 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
424 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
Dale Johannesenbbe2b702007-08-30 00:23:21 +0000425 addLegalFPImmediate(APFloat(+0.0)); // FLD0
426 addLegalFPImmediate(APFloat(+1.0)); // FLD1
427 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
428 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000429 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
430 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
431 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
432 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 }
434
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000435 // Long double always uses X87.
436 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
Dale Johannesen2fc20782007-09-14 22:26:36 +0000437 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
438 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
439 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
Dale Johannesen7f1076b2007-09-26 21:10:55 +0000440 if (!UnsafeFPMath) {
441 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
442 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
443 }
Dale Johannesen4ab00bd2007-08-05 18:49:15 +0000444
Dan Gohman2f7b1982007-10-11 23:21:31 +0000445 // Always use a library call for pow.
446 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
447 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
448 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
449
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450 // First set operation action for all vector types to expand. Then we
451 // will selectively turn on ones that can be effectively codegen'd.
452 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
453 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
454 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
455 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
456 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
457 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
458 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
459 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
460 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
461 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
462 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
463 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
464 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
465 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
466 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
467 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
468 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
469 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
470 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
471 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
472 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
473 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
474 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
475 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
476 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
Dan Gohman5a199552007-10-08 18:33:35 +0000477 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
478 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
479 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
480 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
Dan Gohman2f7b1982007-10-11 23:21:31 +0000481 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
Dan Gohman1d2dc2c2007-10-12 14:09:42 +0000482 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
483 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
484 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
Dan Gohman5b9d6412007-12-12 22:21:26 +0000485 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
486 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
487 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
488 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
489 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
490 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 }
492
493 if (Subtarget->hasMMX()) {
494 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
495 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
496 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
497 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
498
499 // FIXME: add MMX packed arithmetics
500
501 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
502 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
503 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
504 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
505
506 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
507 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
508 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
Dale Johannesen6b65c332007-10-30 01:18:38 +0000509 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510
511 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
512 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
513
514 setOperationAction(ISD::AND, MVT::v8i8, Promote);
515 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
516 setOperationAction(ISD::AND, MVT::v4i16, Promote);
517 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
518 setOperationAction(ISD::AND, MVT::v2i32, Promote);
519 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
520 setOperationAction(ISD::AND, MVT::v1i64, Legal);
521
522 setOperationAction(ISD::OR, MVT::v8i8, Promote);
523 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
524 setOperationAction(ISD::OR, MVT::v4i16, Promote);
525 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
526 setOperationAction(ISD::OR, MVT::v2i32, Promote);
527 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
528 setOperationAction(ISD::OR, MVT::v1i64, Legal);
529
530 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
531 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
532 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
533 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
534 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
535 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
536 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
537
538 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
539 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
540 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
541 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
542 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
543 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
544 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
545
546 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
547 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
548 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
549 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
550
551 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
552 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
553 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
554 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
555
556 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
557 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
558 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
559 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
560 }
561
562 if (Subtarget->hasSSE1()) {
563 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
564
565 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
566 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
567 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
568 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
569 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
570 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000571 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
572 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
573 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
574 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
575 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
576 }
577
578 if (Subtarget->hasSSE2()) {
579 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
580 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
581 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
582 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
583 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
584
585 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
586 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
587 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
588 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
589 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
590 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
591 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
592 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
593 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
594 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
595 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
596 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
597 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
598 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
599 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600
601 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
602 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
603 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
604 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
605 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
606 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
607
608 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
609 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
Nate Begemanc16406d2007-12-11 01:41:33 +0000610 // Do not attempt to custom lower non-power-of-2 vectors
611 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
612 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
614 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
615 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
616 }
617 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
619 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
620 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
621 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
Dale Johannesen2ff963d2007-10-31 00:32:36 +0000622 if (Subtarget->is64Bit())
623 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624
625 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
626 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
627 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
628 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
629 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
630 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
631 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
632 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
633 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
634 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
635 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
636 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
637 }
638
639 // Custom lower v2i64 and v2f64 selects.
640 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
641 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
642 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
643 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
644 }
645
646 // We want to custom lower some of our intrinsics.
647 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
648
649 // We have target-specific dag combine patterns for the following nodes:
650 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
651 setTargetDAGCombine(ISD::SELECT);
652
653 computeRegisterProperties();
654
655 // FIXME: These should be based on subtarget info. Plus, the values should
656 // be smaller when we are in optimizing for size mode.
657 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
658 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
659 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
660 allowUnalignedMemoryAccesses = true; // x86 supports it!
661}
662
663
Evan Cheng6fb06762007-11-09 01:32:10 +0000664/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
665/// jumptable.
666SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
667 SelectionDAG &DAG) const {
668 if (usesGlobalOffsetTable())
669 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
670 if (!Subtarget->isPICStyleRIPRel())
671 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
672 return Table;
673}
674
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675//===----------------------------------------------------------------------===//
676// Return Value Calling Convention Implementation
677//===----------------------------------------------------------------------===//
678
679#include "X86GenCallingConv.inc"
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000680
681/// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
682/// exists skip possible ISD:TokenFactor.
683static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
684 if (Chain.getOpcode()==X86ISD::TAILCALL) {
685 return Chain;
686 } else if (Chain.getOpcode()==ISD::TokenFactor) {
687 if (Chain.getNumOperands() &&
688 Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
689 return Chain.getOperand(0);
690 }
691 return Chain;
692}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693
694/// LowerRET - Lower an ISD::RET node.
695SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
696 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
697
698 SmallVector<CCValAssign, 16> RVLocs;
699 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
700 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
701 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
702 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000703
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 // If this is the first return lowered for this function, add the regs to the
705 // liveout set for the function.
Chris Lattner1b989192007-12-31 04:13:23 +0000706 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 for (unsigned i = 0; i != RVLocs.size(); ++i)
708 if (RVLocs[i].isRegLoc())
Chris Lattner1b989192007-12-31 04:13:23 +0000709 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711 SDOperand Chain = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000713 // Handle tail call return.
714 Chain = GetPossiblePreceedingTailCall(Chain);
715 if (Chain.getOpcode() == X86ISD::TAILCALL) {
716 SDOperand TailCall = Chain;
717 SDOperand TargetAddress = TailCall.getOperand(1);
718 SDOperand StackAdjustment = TailCall.getOperand(2);
719 assert ( ((TargetAddress.getOpcode() == ISD::Register &&
720 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
721 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
722 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
723 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
724 "Expecting an global address, external symbol, or register");
725 assert( StackAdjustment.getOpcode() == ISD::Constant &&
726 "Expecting a const value");
727
728 SmallVector<SDOperand,8> Operands;
729 Operands.push_back(Chain.getOperand(0));
730 Operands.push_back(TargetAddress);
731 Operands.push_back(StackAdjustment);
732 // Copy registers used by the call. Last operand is a flag so it is not
733 // copied.
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000734 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000735 Operands.push_back(Chain.getOperand(i));
736 }
Arnold Schwaighofer10202b32007-10-16 09:05:00 +0000737 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
738 Operands.size());
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000739 }
740
741 // Regular return.
742 SDOperand Flag;
743
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000744 // Copy the result values into the output registers.
745 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
746 RVLocs[0].getLocReg() != X86::ST0) {
747 for (unsigned i = 0; i != RVLocs.size(); ++i) {
748 CCValAssign &VA = RVLocs[i];
749 assert(VA.isRegLoc() && "Can only return in registers!");
750 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
751 Flag);
752 Flag = Chain.getValue(1);
753 }
754 } else {
755 // We need to handle a destination of ST0 specially, because it isn't really
756 // a register.
757 SDOperand Value = Op.getOperand(1);
758
759 // If this is an FP return with ScalarSSE, we need to move the value from
760 // an XMM register onto the fp-stack.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000761 if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
762 (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 SDOperand MemLoc;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000764
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 // If this is a load into a scalarsse value, don't store the loaded value
766 // back to the stack, only to reload it: just replace the scalar-sse load.
767 if (ISD::isNON_EXTLoad(Value.Val) &&
768 (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
769 Chain = Value.getOperand(0);
770 MemLoc = Value.getOperand(1);
771 } else {
772 // Spill the value to memory and reload it into top of stack.
773 unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
774 MachineFunction &MF = DAG.getMachineFunction();
775 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
776 MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
777 Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
778 }
779 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
780 SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
781 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
782 Chain = Value.getValue(1);
783 }
784
785 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
786 SDOperand Ops[] = { Chain, Value };
787 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
788 Flag = Chain.getValue(1);
789 }
790
791 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
792 if (Flag.Val)
793 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
794 else
795 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
796}
797
798
799/// LowerCallResult - Lower the result values of an ISD::CALL into the
800/// appropriate copies out of appropriate physical registers. This assumes that
801/// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
802/// being lowered. The returns a SDNode with the same number of values as the
803/// ISD::CALL.
804SDNode *X86TargetLowering::
805LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
806 unsigned CallingConv, SelectionDAG &DAG) {
807
808 // Assign locations to each value returned by this call.
809 SmallVector<CCValAssign, 16> RVLocs;
810 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
811 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
812 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
813
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 SmallVector<SDOperand, 8> ResultVals;
815
816 // Copy all of the result registers out of their specified physreg.
817 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
818 for (unsigned i = 0; i != RVLocs.size(); ++i) {
819 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
820 RVLocs[i].getValVT(), InFlag).getValue(1);
821 InFlag = Chain.getValue(2);
822 ResultVals.push_back(Chain.getValue(0));
823 }
824 } else {
825 // Copies from the FP stack are special, as ST0 isn't a valid register
826 // before the fp stackifier runs.
827
828 // Copy ST0 into an RFP register with FP_GET_RESULT.
829 SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
830 SDOperand GROps[] = { Chain, InFlag };
831 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
832 Chain = RetVal.getValue(1);
833 InFlag = RetVal.getValue(2);
834
835 // If we are using ScalarSSE, store ST(0) to the stack and reload it into
836 // an XMM register.
Dale Johannesene0e0fd02007-09-23 14:52:20 +0000837 if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
838 (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
Chris Lattner40758732007-12-29 06:41:28 +0000839 SDOperand StoreLoc;
840 const Value *SrcVal = 0;
841 int SrcValOffset = 0;
Chris Lattner8b815c22007-12-29 06:57:38 +0000842 MVT::ValueType RetStoreVT = RVLocs[0].getValVT();
Chris Lattner40758732007-12-29 06:41:28 +0000843
844 // Determine where to store the value. If the call result is directly
845 // used by a store, see if we can store directly into the location. In
846 // this case, we'll end up producing a fst + movss[load] + movss[store] to
847 // the same location, and the two movss's will be nuked as dead. This
848 // optimizes common things like "*D = atof(..)" to not need an
849 // intermediate stack slot.
850 if (SDOperand(TheCall, 0).hasOneUse() &&
851 SDOperand(TheCall, 1).hasOneUse()) {
Chris Lattner8b815c22007-12-29 06:57:38 +0000852 // In addition to direct uses, we also support a FP_ROUND that uses the
853 // value, if it is directly stored somewhere.
854 SDNode *User = *TheCall->use_begin();
855 if (User->getOpcode() == ISD::FP_ROUND && User->hasOneUse())
856 User = *User->use_begin();
857
Chris Lattner40758732007-12-29 06:41:28 +0000858 // Ok, we have one use of the value and one use of the chain. See if
859 // they are the same node: a store.
Chris Lattner8b815c22007-12-29 06:57:38 +0000860 if (StoreSDNode *N = dyn_cast<StoreSDNode>(User)) {
861 // Verify that the value being stored is either the call or a
862 // truncation of the call.
863 SDNode *StoreVal = N->getValue().Val;
864 if (StoreVal == TheCall)
865 ; // ok.
866 else if (StoreVal->getOpcode() == ISD::FP_ROUND &&
867 StoreVal->hasOneUse() &&
868 StoreVal->getOperand(0).Val == TheCall)
869 ; // ok.
870 else
871 N = 0; // not ok.
872
873 if (N && N->getChain().Val == TheCall &&
Chris Lattner40758732007-12-29 06:41:28 +0000874 !N->isVolatile() && !N->isTruncatingStore() &&
875 N->getAddressingMode() == ISD::UNINDEXED) {
876 StoreLoc = N->getBasePtr();
877 SrcVal = N->getSrcValue();
878 SrcValOffset = N->getSrcValueOffset();
Chris Lattner8b815c22007-12-29 06:57:38 +0000879 RetStoreVT = N->getValue().getValueType();
Chris Lattner40758732007-12-29 06:41:28 +0000880 }
881 }
882 }
883
884 // If we weren't able to optimize the result, just create a temporary
885 // stack slot.
886 if (StoreLoc.Val == 0) {
887 MachineFunction &MF = DAG.getMachineFunction();
888 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
889 StoreLoc = DAG.getFrameIndex(SSFI, getPointerTy());
890 }
891
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
893 // shouldn't be necessary except that RFP cannot be live across
Chris Lattner40758732007-12-29 06:41:28 +0000894 // multiple blocks (which could happen if a select gets lowered into
895 // multiple blocks and scheduled in between them). When stackifier is
896 // fixed, they can be uncoupled.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 SDOperand Ops[] = {
Chris Lattner8b815c22007-12-29 06:57:38 +0000898 Chain, RetVal, StoreLoc, DAG.getValueType(RetStoreVT), InFlag
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 };
900 Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
Chris Lattner8b815c22007-12-29 06:57:38 +0000901 RetVal = DAG.getLoad(RetStoreVT, Chain,
Chris Lattner40758732007-12-29 06:41:28 +0000902 StoreLoc, SrcVal, SrcValOffset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 Chain = RetVal.getValue(1);
Chris Lattner8b815c22007-12-29 06:57:38 +0000904
905 // If we optimized a truncate, then extend the result back to its desired
906 // type.
907 if (RVLocs[0].getValVT() != RetStoreVT)
908 RetVal = DAG.getNode(ISD::FP_EXTEND, RVLocs[0].getValVT(), RetVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909 }
910 ResultVals.push_back(RetVal);
911 }
912
913 // Merge everything together with a MERGE_VALUES node.
914 ResultVals.push_back(Chain);
915 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
916 &ResultVals[0], ResultVals.size()).Val;
917}
918
919
920//===----------------------------------------------------------------------===//
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000921// C & StdCall & Fast Calling Convention implementation
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922//===----------------------------------------------------------------------===//
923// StdCall calling convention seems to be standard for many Windows' API
924// routines and around. It differs from C calling convention just a little:
925// callee should clean up the stack, not caller. Symbols should be also
926// decorated in some fancy way :) It doesn't support any vector arguments.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000927// For info on fast calling convention see Fast Calling Convention (tail call)
928// implementation LowerX86_32FastCCCallTo.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929
930/// AddLiveIn - This helper function adds the specified physical register to the
931/// MachineFunction as a live in value. It also creates a corresponding virtual
932/// register for it.
933static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
934 const TargetRegisterClass *RC) {
935 assert(RC->contains(PReg) && "Not the correct regclass!");
Chris Lattner1b989192007-12-31 04:13:23 +0000936 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
937 MF.getRegInfo().addLiveIn(PReg, VReg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 return VReg;
939}
940
Rafael Espindola03cbeb72007-09-14 15:48:13 +0000941SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
942 const CCValAssign &VA,
943 MachineFrameInfo *MFI,
944 SDOperand Root, unsigned i) {
945 // Create the nodes corresponding to a load from this parameter slot.
946 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
947 VA.getLocMemOffset());
948 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
949
950 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
951
952 if (Flags & ISD::ParamFlags::ByVal)
953 return FIN;
954 else
955 return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
956}
957
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
959 bool isStdCall) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960 MachineFunction &MF = DAG.getMachineFunction();
961 MachineFrameInfo *MFI = MF.getFrameInfo();
962 SDOperand Root = Op.getOperand(0);
963 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000964 unsigned CC = MF.getFunction()->getCallingConv();
Gordon Henriksen6bbcc672008-01-03 16:47:34 +0000965
966 assert(!(isVarArg && CC == CallingConv::Fast) &&
967 "Var args not supported with calling convention fastcc");
968
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 // Assign locations to all of the incoming arguments.
970 SmallVector<CCValAssign, 16> ArgLocs;
Gordon Henriksen6bbcc672008-01-03 16:47:34 +0000971 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +0000972 // Check for possible tail call calling convention.
973 if (CC == CallingConv::Fast && PerformTailCallOpt)
974 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
975 else
976 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
977
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 SmallVector<SDOperand, 8> ArgValues;
979 unsigned LastVal = ~0U;
980 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
981 CCValAssign &VA = ArgLocs[i];
982 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
983 // places.
984 assert(VA.getValNo() != LastVal &&
985 "Don't support value assigned to multiple locs yet");
986 LastVal = VA.getValNo();
987
988 if (VA.isRegLoc()) {
989 MVT::ValueType RegVT = VA.getLocVT();
990 TargetRegisterClass *RC;
991 if (RegVT == MVT::i32)
992 RC = X86::GR32RegisterClass;
993 else {
994 assert(MVT::isVector(RegVT));
995 RC = X86::VR128RegisterClass;
996 }
Gordon Henriksen6bbcc672008-01-03 16:47:34 +0000997
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000998 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
999 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1000
1001 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1002 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1003 // right size.
1004 if (VA.getLocInfo() == CCValAssign::SExt)
1005 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1006 DAG.getValueType(VA.getValVT()));
1007 else if (VA.getLocInfo() == CCValAssign::ZExt)
1008 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1009 DAG.getValueType(VA.getValVT()));
1010
1011 if (VA.getLocInfo() != CCValAssign::Full)
1012 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1013
1014 ArgValues.push_back(ArgValue);
1015 } else {
1016 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +00001017 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 }
1019 }
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001020
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 unsigned StackSize = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001022 // align stack specially for tail calls
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001023 if (CC == CallingConv::Fast)
1024 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025
1026 // If the function takes variable number of arguments, make a frame index for
1027 // the start of the first vararg value... for expansion of llvm.va_start.
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001028 if (isVarArg) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001030 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001032 ArgValues.push_back(Root);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001033
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001034 // Tail call convention (fastcc) needs callee pop.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001035 if (isStdCall && !isVarArg &&
1036 (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001037 BytesToPopOnReturn = StackSize; // Callee pops everything..
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 BytesCallerReserves = 0;
1039 } else {
1040 BytesToPopOnReturn = 0; // Callee pops nothing.
1041
1042 // If this is an sret function, the return should pop the hidden pointer.
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001043 unsigned NumArgs = Op.Val->getNumValues() - 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 if (NumArgs &&
1045 (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
1046 ISD::ParamFlags::StructReturn))
1047 BytesToPopOnReturn = 4;
1048
1049 BytesCallerReserves = StackSize;
1050 }
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001051
1052 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053
Anton Korobeynikove844e472007-08-15 17:12:32 +00001054 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1055 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056
1057 // Return the new list of results.
1058 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1059 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1060}
1061
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001062SDOperand
1063X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
1064 unsigned CC) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 SDOperand Chain = Op.getOperand(0);
1066 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067 SDOperand Callee = Op.getOperand(4);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001068
1069 assert(!(isVarArg && CC == CallingConv::Fast) &&
1070 "Var args not supported with calling convention fastcc");
1071
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 // Analyze operands of the call, assigning locations to each operand.
1073 SmallVector<CCValAssign, 16> ArgLocs;
1074 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001075 if (CC==CallingConv::Fast && PerformTailCallOpt)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001076 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1077 else
1078 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079
1080 // Get a count of how many bytes are to be pushed on the stack.
1081 unsigned NumBytes = CCInfo.getNextStackOffset();
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001082 if (CC == CallingConv::Fast)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001083 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084
1085 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1086
1087 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1088 SmallVector<SDOperand, 8> MemOpChains;
1089
1090 SDOperand StackPtr;
1091
1092 // Walk the register/memloc assignments, inserting copies/loads.
1093 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1094 CCValAssign &VA = ArgLocs[i];
1095 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1096
1097 // Promote the value if needed.
1098 switch (VA.getLocInfo()) {
1099 default: assert(0 && "Unknown loc info!");
1100 case CCValAssign::Full: break;
1101 case CCValAssign::SExt:
1102 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1103 break;
1104 case CCValAssign::ZExt:
1105 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1106 break;
1107 case CCValAssign::AExt:
1108 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1109 break;
1110 }
1111
1112 if (VA.isRegLoc()) {
1113 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1114 } else {
1115 assert(VA.isMemLoc());
1116 if (StackPtr.Val == 0)
1117 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001118
1119 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1120 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 }
1122 }
1123
1124 // If the first argument is an sret pointer, remember it.
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001125 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 bool isSRet = NumOps &&
1127 (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1128 ISD::ParamFlags::StructReturn);
1129
1130 if (!MemOpChains.empty())
1131 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1132 &MemOpChains[0], MemOpChains.size());
1133
1134 // Build a sequence of copy-to-reg nodes chained together with token chain
1135 // and flag operands which copy the outgoing args into registers.
1136 SDOperand InFlag;
1137 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1138 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1139 InFlag);
1140 InFlag = Chain.getValue(1);
1141 }
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001142
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1144 // GOT pointer.
1145 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1146 Subtarget->isPICStyleGOT()) {
1147 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1148 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1149 InFlag);
1150 InFlag = Chain.getValue(1);
1151 }
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001152
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153 // If the callee is a GlobalAddress node (quite common, every direct call is)
1154 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1155 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1156 // We should use extra load for direct calls to dllimported functions in
1157 // non-JIT mode.
1158 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1159 getTargetMachine(), true))
1160 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001161 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001163 }
1164
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 // Returns a chain & a flag for retval copy to use.
1166 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1167 SmallVector<SDOperand, 8> Ops;
1168 Ops.push_back(Chain);
1169 Ops.push_back(Callee);
1170
1171 // Add argument registers to the end of the list so that they are known live
1172 // into the call.
1173 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1174 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1175 RegsToPass[i].second.getValueType()));
1176
1177 // Add an implicit use GOT pointer in EBX.
1178 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1179 Subtarget->isPICStyleGOT())
1180 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001181
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 if (InFlag.Val)
1183 Ops.push_back(InFlag);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001184
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001185 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 InFlag = Chain.getValue(1);
1187
1188 // Create the CALLSEQ_END node.
1189 unsigned NumBytesForCalleeToPush = 0;
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001190 if (!isVarArg && (CC == CallingConv::X86_StdCall
1191 || CC == CallingConv::Fast && PerformTailCallOpt)) {
1192 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1193 } else if (isSRet) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 // If this is is a call to a struct-return function, the callee
1195 // pops the hidden struct pointer, so we have to push it back.
1196 // This is common for Darwin/X86, Linux & Mingw32 targets.
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001197 NumBytesForCalleeToPush = 4;
1198 } else {
1199 NumBytesForCalleeToPush = 0; // Callee pops nothing.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 }
Bill Wendling22f8deb2007-11-13 00:44:25 +00001201
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001202 // Returns a flag for retval copy to use.
Bill Wendling22f8deb2007-11-13 00:44:25 +00001203 Chain = DAG.getCALLSEQ_END(Chain,
1204 DAG.getConstant(NumBytes, getPointerTy()),
1205 DAG.getConstant(NumBytesForCalleeToPush,
1206 getPointerTy()),
1207 InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 InFlag = Chain.getValue(1);
1209
1210 // Handle result values, copying them out of physregs into vregs that we
1211 // return.
1212 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1213}
1214
1215
1216//===----------------------------------------------------------------------===//
1217// FastCall Calling Convention implementation
1218//===----------------------------------------------------------------------===//
1219//
1220// The X86 'fastcall' calling convention passes up to two integer arguments in
1221// registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1222// and requires that the callee pop its arguments off the stack (allowing proper
1223// tail calls), and has the same return value conventions as C calling convs.
1224//
1225// This calling convention always arranges for the callee pop value to be 8n+4
1226// bytes, which is needed for tail recursion elimination and stack alignment
1227// reasons.
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001228
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229SDOperand
1230X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1231 MachineFunction &MF = DAG.getMachineFunction();
1232 MachineFrameInfo *MFI = MF.getFrameInfo();
1233 SDOperand Root = Op.getOperand(0);
1234 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001235 unsigned CC = MF.getFunction()->getCallingConv();
1236
1237 assert(!(isVarArg && CC == CallingConv::Fast) &&
1238 "Var args not supported with calling convention fastcc");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239
1240 // Assign locations to all of the incoming arguments.
1241 SmallVector<CCValAssign, 16> ArgLocs;
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001242 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1244
1245 SmallVector<SDOperand, 8> ArgValues;
1246 unsigned LastVal = ~0U;
1247 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1248 CCValAssign &VA = ArgLocs[i];
1249 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1250 // places.
1251 assert(VA.getValNo() != LastVal &&
1252 "Don't support value assigned to multiple locs yet");
1253 LastVal = VA.getValNo();
1254
1255 if (VA.isRegLoc()) {
1256 MVT::ValueType RegVT = VA.getLocVT();
1257 TargetRegisterClass *RC;
1258 if (RegVT == MVT::i32)
1259 RC = X86::GR32RegisterClass;
1260 else {
1261 assert(MVT::isVector(RegVT));
1262 RC = X86::VR128RegisterClass;
1263 }
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001264
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1266 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1267
1268 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1269 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1270 // right size.
1271 if (VA.getLocInfo() == CCValAssign::SExt)
1272 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1273 DAG.getValueType(VA.getValVT()));
1274 else if (VA.getLocInfo() == CCValAssign::ZExt)
1275 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1276 DAG.getValueType(VA.getValVT()));
1277
1278 if (VA.getLocInfo() != CCValAssign::Full)
1279 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1280
1281 ArgValues.push_back(ArgValue);
1282 } else {
1283 assert(VA.isMemLoc());
Rafael Espindolab53ef122007-09-21 14:55:38 +00001284 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 }
1286 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287
1288 unsigned StackSize = CCInfo.getNextStackOffset();
1289
1290 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1291 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001292 // arguments and the arguments after the retaddr has been pushed are
1293 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 if ((StackSize & 7) == 0)
1295 StackSize += 4;
1296 }
1297
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001298 ArgValues.push_back(Root);
1299
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300 RegSaveFrameIndex = 0xAAAAAAA; // X86-64 only.
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001301 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 BytesToPopOnReturn = StackSize; // Callee pops all stack arguments.
1303 BytesCallerReserves = 0;
1304
Anton Korobeynikove844e472007-08-15 17:12:32 +00001305 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1306 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307
1308 // Return the new list of results.
1309 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1310 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1311}
1312
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001313SDOperand
1314X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1315 const SDOperand &StackPtr,
1316 const CCValAssign &VA,
1317 SDOperand Chain,
1318 SDOperand Arg) {
1319 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1320 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1321 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1322 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1323 if (Flags & ISD::ParamFlags::ByVal) {
1324 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1325 ISD::ParamFlags::ByValAlignOffs);
1326
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001327 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1328 ISD::ParamFlags::ByValSizeOffs;
1329
1330 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1331 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00001332 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001333
Rafael Espindola80825902007-10-19 10:41:11 +00001334 return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1335 AlwaysInline);
Rafael Espindoladdb88da2007-08-31 15:06:30 +00001336 } else {
1337 return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1338 }
1339}
1340
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001341SDOperand
1342X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1343 unsigned CC) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 SDOperand Chain = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1346 SDOperand Callee = Op.getOperand(4);
1347
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001348 assert(!cast<ConstantSDNode>(Op.getOperand(3))->getValue() &&
1349 "Tail calls should not reach here.");
1350
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 // Analyze operands of the call, assigning locations to each operand.
1352 SmallVector<CCValAssign, 16> ArgLocs;
1353 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1354 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1355
1356 // Get a count of how many bytes are to be pushed on the stack.
1357 unsigned NumBytes = CCInfo.getNextStackOffset();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1359 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001360 // arguments and the arguments after the retaddr has been pushed are
1361 // aligned.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362 if ((NumBytes & 7) == 0)
1363 NumBytes += 4;
1364 }
1365
1366 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001367
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1369 SmallVector<SDOperand, 8> MemOpChains;
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001370
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 SDOperand StackPtr;
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001372
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 // Walk the register/memloc assignments, inserting copies/loads.
1374 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1375 CCValAssign &VA = ArgLocs[i];
1376 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1377
1378 // Promote the value if needed.
1379 switch (VA.getLocInfo()) {
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001380 default: assert(0 && "Unknown loc info!");
1381 case CCValAssign::Full: break;
1382 case CCValAssign::SExt:
1383 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1384 break;
1385 case CCValAssign::ZExt:
1386 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1387 break;
1388 case CCValAssign::AExt:
1389 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1390 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 }
1392
1393 if (VA.isRegLoc()) {
1394 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1395 } else {
1396 assert(VA.isMemLoc());
1397 if (StackPtr.Val == 0)
1398 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindola007b7142007-09-21 15:50:22 +00001399
1400 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1401 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001402 }
1403 }
1404
1405 if (!MemOpChains.empty())
1406 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1407 &MemOpChains[0], MemOpChains.size());
1408
1409 // Build a sequence of copy-to-reg nodes chained together with token chain
1410 // and flag operands which copy the outgoing args into registers.
1411 SDOperand InFlag;
1412 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1413 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1414 InFlag);
1415 InFlag = Chain.getValue(1);
1416 }
1417
1418 // If the callee is a GlobalAddress node (quite common, every direct call is)
1419 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1420 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1421 // We should use extra load for direct calls to dllimported functions in
1422 // non-JIT mode.
1423 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1424 getTargetMachine(), true))
1425 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001426 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001428 }
1429
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001430 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1431 // GOT pointer.
1432 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1433 Subtarget->isPICStyleGOT()) {
1434 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1435 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1436 InFlag);
1437 InFlag = Chain.getValue(1);
1438 }
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001439
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440 // Returns a chain & a flag for retval copy to use.
1441 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1442 SmallVector<SDOperand, 8> Ops;
1443 Ops.push_back(Chain);
1444 Ops.push_back(Callee);
1445
1446 // Add argument registers to the end of the list so that they are known live
1447 // into the call.
1448 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1449 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1450 RegsToPass[i].second.getValueType()));
1451
1452 // Add an implicit use GOT pointer in EBX.
1453 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1454 Subtarget->isPICStyleGOT())
1455 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1456
1457 if (InFlag.Val)
1458 Ops.push_back(InFlag);
1459
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001460 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001461 InFlag = Chain.getValue(1);
1462
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001463 // Create the CALLSEQ_END node.
1464 unsigned NumBytesForCalleeToPush = NumBytes;
1465
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001466 // Returns a flag for retval copy to use.
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001467 Chain = DAG.getCALLSEQ_END(Chain,
1468 DAG.getConstant(NumBytes, getPointerTy()),
1469 DAG.getConstant(NumBytesForCalleeToPush,
1470 getPointerTy()),
1471 InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 InFlag = Chain.getValue(1);
1473
1474 // Handle result values, copying them out of physregs into vregs that we
1475 // return.
1476 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1477}
1478
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001479//===----------------------------------------------------------------------===//
1480// Fast Calling Convention (tail call) implementation
1481//===----------------------------------------------------------------------===//
1482
1483// Like std call, callee cleans arguments, convention except that ECX is
1484// reserved for storing the tail called function address. Only 2 registers are
1485// free for argument passing (inreg). Tail call optimization is performed
1486// provided:
1487// * tailcallopt is enabled
1488// * caller/callee are fastcc
1489// * elf/pic is disabled OR
1490// * elf/pic enabled + callee is in module + callee has
1491// visibility protected or hidden
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001492// To keep the stack aligned according to platform abi the function
1493// GetAlignedArgumentStackSize ensures that argument delta is always multiples
1494// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001495// If a tail called function callee has more arguments than the caller the
1496// caller needs to make sure that there is room to move the RETADDR to. This is
Arnold Schwaighofer373e8652007-10-12 21:30:57 +00001497// achieved by reserving an area the size of the argument delta right after the
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001498// original REtADDR, but before the saved framepointer or the spilled registers
1499// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1500// stack layout:
1501// arg1
1502// arg2
1503// RETADDR
1504// [ new RETADDR
1505// move area ]
1506// (possible EBP)
1507// ESI
1508// EDI
1509// local1 ..
1510
1511/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1512/// for a 16 byte align requirement.
1513unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1514 SelectionDAG& DAG) {
1515 if (PerformTailCallOpt) {
1516 MachineFunction &MF = DAG.getMachineFunction();
1517 const TargetMachine &TM = MF.getTarget();
1518 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1519 unsigned StackAlignment = TFI.getStackAlignment();
1520 uint64_t AlignMask = StackAlignment - 1;
1521 int64_t Offset = StackSize;
1522 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1523 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1524 // Number smaller than 12 so just add the difference.
1525 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1526 } else {
1527 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1528 Offset = ((~AlignMask) & Offset) + StackAlignment +
1529 (StackAlignment-SlotSize);
1530 }
1531 StackSize = Offset;
1532 }
1533 return StackSize;
1534}
1535
1536/// IsEligibleForTailCallElimination - Check to see whether the next instruction
Evan Chenge7a87392007-11-02 01:26:22 +00001537/// following the call is a return. A function is eligible if caller/callee
1538/// calling conventions match, currently only fastcc supports tail calls, and
1539/// the function CALL is immediatly followed by a RET.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001540bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1541 SDOperand Ret,
1542 SelectionDAG& DAG) const {
Evan Chenge7a87392007-11-02 01:26:22 +00001543 if (!PerformTailCallOpt)
1544 return false;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001545
1546 // Check whether CALL node immediatly preceeds the RET node and whether the
1547 // return uses the result of the node or is a void return.
Evan Chenge7a87392007-11-02 01:26:22 +00001548 unsigned NumOps = Ret.getNumOperands();
1549 if ((NumOps == 1 &&
1550 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1551 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
Evan Cheng26c0e982007-11-02 17:45:40 +00001552 (NumOps > 1 &&
Evan Chenge7a87392007-11-02 01:26:22 +00001553 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1554 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001555 MachineFunction &MF = DAG.getMachineFunction();
1556 unsigned CallerCC = MF.getFunction()->getCallingConv();
1557 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1558 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1559 SDOperand Callee = Call.getOperand(4);
1560 // On elf/pic %ebx needs to be livein.
Evan Chenge7a87392007-11-02 01:26:22 +00001561 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1562 !Subtarget->isPICStyleGOT())
1563 return true;
1564
1565 // Can only do local tail calls with PIC.
1566 GlobalValue * GV = 0;
1567 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1568 if(G != 0 &&
1569 (GV = G->getGlobal()) &&
1570 (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1571 return true;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001572 }
1573 }
Evan Chenge7a87392007-11-02 01:26:22 +00001574
1575 return false;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001576}
1577
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001578SDOperand
1579X86TargetLowering::LowerX86_TailCallTo(SDOperand Op, SelectionDAG &DAG,
1580 unsigned CC) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001581 SDOperand Chain = Op.getOperand(0);
1582 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001583 SDOperand Callee = Op.getOperand(4);
1584 bool is64Bit = Subtarget->is64Bit();
1585
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001586 assert(cast<ConstantSDNode>(Op.getOperand(3))->getValue() &&PerformTailCallOpt
1587 && "Should only emit tail calls.");
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001588
1589 // Analyze operands of the call, assigning locations to each operand.
1590 SmallVector<CCValAssign, 16> ArgLocs;
1591 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1592 if (is64Bit)
1593 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1594 else
1595 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1596
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001597 // Lower arguments at fp - stackoffset + fpdiff.
1598 MachineFunction &MF = DAG.getMachineFunction();
1599
1600 unsigned NumBytesToBePushed =
1601 GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1602
1603 unsigned NumBytesCallerPushed =
1604 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1605 int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1606
1607 // Set the delta of movement of the returnaddr stackslot.
1608 // But only set if delta is greater than previous delta.
1609 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1610 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1611
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001612 Chain = DAG.
1613 getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1614
1615 // Adjust the Return address stack slot.
1616 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001617 if (FPDiff) {
1618 MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001619 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1620 // Load the "old" Return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001621 RetAddrFrIdx =
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001622 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1623 // Calculate the new stack slot for the return address.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001624 int SlotSize = is64Bit ? 8 : 4;
1625 int NewReturnAddrFI =
1626 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001627 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1628 Chain = SDOperand(RetAddrFrIdx.Val, 1);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001629 }
1630
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001631 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1632 SmallVector<SDOperand, 8> MemOpChains;
1633 SmallVector<SDOperand, 8> MemOpChains2;
1634 SDOperand FramePtr, StackPtr;
1635 SDOperand PtrOff;
1636 SDOperand FIN;
1637 int FI = 0;
1638
1639 // Walk the register/memloc assignments, inserting copies/loads. Lower
1640 // arguments first to the stack slot where they would normally - in case of a
1641 // normal function call - be.
1642 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1643 CCValAssign &VA = ArgLocs[i];
1644 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1645
1646 // Promote the value if needed.
1647 switch (VA.getLocInfo()) {
1648 default: assert(0 && "Unknown loc info!");
1649 case CCValAssign::Full: break;
1650 case CCValAssign::SExt:
1651 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1652 break;
1653 case CCValAssign::ZExt:
1654 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1655 break;
1656 case CCValAssign::AExt:
1657 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1658 break;
1659 }
1660
1661 if (VA.isRegLoc()) {
1662 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1663 } else {
1664 assert(VA.isMemLoc());
1665 if (StackPtr.Val == 0)
1666 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1667
1668 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1669 Arg));
1670 }
1671 }
1672
1673 if (!MemOpChains.empty())
1674 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1675 &MemOpChains[0], MemOpChains.size());
1676
1677 // Build a sequence of copy-to-reg nodes chained together with token chain
1678 // and flag operands which copy the outgoing args into registers.
1679 SDOperand InFlag;
1680 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1681 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1682 InFlag);
1683 InFlag = Chain.getValue(1);
1684 }
1685 InFlag = SDOperand();
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001686
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001687 // Copy from stack slots to stack slot of a tail called function. This needs
1688 // to be done because if we would lower the arguments directly to their real
1689 // stack slot we might end up overwriting each other.
1690 // TODO: To make this more efficient (sometimes saving a store/load) we could
1691 // analyse the arguments and emit this store/load/store sequence only for
1692 // arguments which would be overwritten otherwise.
1693 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1694 CCValAssign &VA = ArgLocs[i];
1695 if (!VA.isRegLoc()) {
1696 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1697 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1698
1699 // Get source stack slot.
1700 SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1701 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1702 // Create frame index.
1703 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1704 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1705 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1706 FIN = DAG.getFrameIndex(FI, MVT::i32);
1707 if (Flags & ISD::ParamFlags::ByVal) {
1708 // Copy relative to framepointer.
1709 unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1710 ISD::ParamFlags::ByValAlignOffs);
1711
1712 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1713 ISD::ParamFlags::ByValSizeOffs;
1714
1715 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1716 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
Arnold Schwaighofer97794942007-11-10 10:48:01 +00001717 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
1718
1719 MemOpChains2.push_back(DAG.getMemcpy(Chain, FIN, PtrOff, SizeNode,
1720 AlignNode,AlwaysInline));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001721 } else {
1722 SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1723 // Store relative to framepointer.
1724 MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1725 }
1726 }
1727 }
1728
1729 if (!MemOpChains2.empty())
1730 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1731 &MemOpChains2[0], MemOpChains.size());
1732
Arnold Schwaighofer10202b32007-10-16 09:05:00 +00001733 // Store the return address to the appropriate stack slot.
1734 if (FPDiff)
1735 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1736
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001737 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1738 // GOT pointer.
1739 // Does not work with tail call since ebx is not restored correctly by
1740 // tailcaller. TODO: at least for x86 - verify for x86-64
1741
1742 // If the callee is a GlobalAddress node (quite common, every direct call is)
1743 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1744 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1745 // We should use extra load for direct calls to dllimported functions in
1746 // non-JIT mode.
1747 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1748 getTargetMachine(), true))
1749 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1750 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1751 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1752 else {
1753 assert(Callee.getOpcode() == ISD::LOAD &&
1754 "Function destination must be loaded into virtual register");
1755 unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1756
1757 Chain = DAG.getCopyToReg(Chain,
1758 DAG.getRegister(Opc, getPointerTy()) ,
1759 Callee,InFlag);
1760 Callee = DAG.getRegister(Opc, getPointerTy());
1761 // Add register as live out.
Chris Lattner1b989192007-12-31 04:13:23 +00001762 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001763 }
1764
1765 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1766 SmallVector<SDOperand, 8> Ops;
1767
1768 Ops.push_back(Chain);
1769 Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1770 Ops.push_back(DAG.getConstant(0, getPointerTy()));
1771 if (InFlag.Val)
1772 Ops.push_back(InFlag);
1773 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1774 InFlag = Chain.getValue(1);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001775
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001776 // Returns a chain & a flag for retval copy to use.
1777 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1778 Ops.clear();
1779 Ops.push_back(Chain);
1780 Ops.push_back(Callee);
1781 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1782 // Add argument registers to the end of the list so that they are known live
1783 // into the call.
1784 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1785 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1786 RegsToPass[i].second.getValueType()));
1787 if (InFlag.Val)
1788 Ops.push_back(InFlag);
1789 assert(InFlag.Val &&
1790 "Flag must be set. Depend on flag being set in LowerRET");
1791 Chain = DAG.getNode(X86ISD::TAILCALL,
1792 Op.Val->getVTList(), &Ops[0], Ops.size());
1793
1794 return SDOperand(Chain.Val, Op.ResNo);
1795}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796
1797//===----------------------------------------------------------------------===//
1798// X86-64 C Calling Convention implementation
1799//===----------------------------------------------------------------------===//
1800
1801SDOperand
1802X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1803 MachineFunction &MF = DAG.getMachineFunction();
1804 MachineFrameInfo *MFI = MF.getFrameInfo();
1805 SDOperand Root = Op.getOperand(0);
1806 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001807 unsigned CC = MF.getFunction()->getCallingConv();
1808
1809 assert(!(isVarArg && CC == CallingConv::Fast) &&
1810 "Var args not supported with calling convention fastcc");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001811
1812 static const unsigned GPR64ArgRegs[] = {
1813 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1814 };
1815 static const unsigned XMMArgRegs[] = {
1816 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1817 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1818 };
1819
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001820 // Assign locations to all of the incoming arguments.
1821 SmallVector<CCValAssign, 16> ArgLocs;
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001822 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1823 // Check for possible tail call calling convention.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001824 if (CC == CallingConv::Fast && PerformTailCallOpt)
1825 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1826 else
1827 CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001828
1829 SmallVector<SDOperand, 8> ArgValues;
1830 unsigned LastVal = ~0U;
1831 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1832 CCValAssign &VA = ArgLocs[i];
1833 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1834 // places.
1835 assert(VA.getValNo() != LastVal &&
1836 "Don't support value assigned to multiple locs yet");
1837 LastVal = VA.getValNo();
1838
1839 if (VA.isRegLoc()) {
1840 MVT::ValueType RegVT = VA.getLocVT();
1841 TargetRegisterClass *RC;
1842 if (RegVT == MVT::i32)
1843 RC = X86::GR32RegisterClass;
1844 else if (RegVT == MVT::i64)
1845 RC = X86::GR64RegisterClass;
1846 else if (RegVT == MVT::f32)
1847 RC = X86::FR32RegisterClass;
1848 else if (RegVT == MVT::f64)
1849 RC = X86::FR64RegisterClass;
1850 else {
1851 assert(MVT::isVector(RegVT));
1852 if (MVT::getSizeInBits(RegVT) == 64) {
1853 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1854 RegVT = MVT::i64;
1855 } else
1856 RC = X86::VR128RegisterClass;
1857 }
1858
1859 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1860 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1861
1862 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1863 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1864 // right size.
1865 if (VA.getLocInfo() == CCValAssign::SExt)
1866 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1867 DAG.getValueType(VA.getValVT()));
1868 else if (VA.getLocInfo() == CCValAssign::ZExt)
1869 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1870 DAG.getValueType(VA.getValVT()));
1871
1872 if (VA.getLocInfo() != CCValAssign::Full)
1873 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1874
1875 // Handle MMX values passed in GPRs.
1876 if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1877 MVT::getSizeInBits(RegVT) == 64)
1878 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1879
1880 ArgValues.push_back(ArgValue);
1881 } else {
1882 assert(VA.isMemLoc());
Rafael Espindola03cbeb72007-09-14 15:48:13 +00001883 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001884 }
1885 }
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001886
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001887 unsigned StackSize = CCInfo.getNextStackOffset();
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001888 // align stack specially for tail calls
1889 if (CC == CallingConv::Fast)
1890 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1891
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892 // If the function takes variable number of arguments, make a frame index for
1893 // the start of the first vararg value... for expansion of llvm.va_start.
1894 if (isVarArg) {
1895 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1896 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1897
1898 // For X86-64, if there are vararg parameters that are passed via
1899 // registers, then we must store them to their spots on the stack so they
1900 // may be loaded by deferencing the result of va_next.
1901 VarArgsGPOffset = NumIntRegs * 8;
1902 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1903 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1904 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1905
1906 // Store the integer parameter registers.
1907 SmallVector<SDOperand, 8> MemOps;
1908 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1909 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1910 DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1911 for (; NumIntRegs != 6; ++NumIntRegs) {
1912 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1913 X86::GR64RegisterClass);
1914 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1915 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1916 MemOps.push_back(Store);
1917 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1918 DAG.getConstant(8, getPointerTy()));
1919 }
1920
1921 // Now store the XMM (fp + vector) parameter registers.
1922 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1923 DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1924 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1925 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1926 X86::VR128RegisterClass);
1927 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1928 SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1929 MemOps.push_back(Store);
1930 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1931 DAG.getConstant(16, getPointerTy()));
1932 }
1933 if (!MemOps.empty())
1934 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1935 &MemOps[0], MemOps.size());
1936 }
1937
1938 ArgValues.push_back(Root);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001939
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001940 // Tail call convention (fastcc) needs callee pop.
Evan Cheng778fa0f2007-10-14 10:09:39 +00001941 if (CC == CallingConv::Fast && PerformTailCallOpt) {
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001942 BytesToPopOnReturn = StackSize; // Callee pops everything.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001943 BytesCallerReserves = 0;
1944 } else {
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001945 BytesToPopOnReturn = 0; // Callee pops nothing.
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001946 BytesCallerReserves = StackSize;
1947 }
Anton Korobeynikove844e472007-08-15 17:12:32 +00001948 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1949 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1950
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001951 // Return the new list of results.
1952 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1953 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1954}
1955
1956SDOperand
1957X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1958 unsigned CC) {
1959 SDOperand Chain = Op.getOperand(0);
1960 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001961 SDOperand Callee = Op.getOperand(4);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001962
1963 assert(!(isVarArg && CC == CallingConv::Fast) &&
1964 "Var args not supported with calling convention fastcc");
1965
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001966 // Analyze operands of the call, assigning locations to each operand.
1967 SmallVector<CCValAssign, 16> ArgLocs;
1968 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
Evan Cheng778fa0f2007-10-14 10:09:39 +00001969 if (CC==CallingConv::Fast && PerformTailCallOpt)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001970 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1971 else
1972 CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001973
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001974 // Get a count of how many bytes are to be pushed on the stack.
1975 unsigned NumBytes = CCInfo.getNextStackOffset();
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001976 if (CC == CallingConv::Fast)
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001977 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00001978
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001979 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1980
1981 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1982 SmallVector<SDOperand, 8> MemOpChains;
1983
1984 SDOperand StackPtr;
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00001985
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001986 // Walk the register/memloc assignments, inserting copies/loads.
1987 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1988 CCValAssign &VA = ArgLocs[i];
1989 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1990
1991 // Promote the value if needed.
1992 switch (VA.getLocInfo()) {
1993 default: assert(0 && "Unknown loc info!");
1994 case CCValAssign::Full: break;
1995 case CCValAssign::SExt:
1996 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1997 break;
1998 case CCValAssign::ZExt:
1999 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
2000 break;
2001 case CCValAssign::AExt:
2002 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
2003 break;
2004 }
2005
2006 if (VA.isRegLoc()) {
2007 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2008 } else {
2009 assert(VA.isMemLoc());
2010 if (StackPtr.Val == 0)
2011 StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00002012
Rafael Espindoladdb88da2007-08-31 15:06:30 +00002013 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
2014 Arg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002015 }
2016 }
2017
2018 if (!MemOpChains.empty())
2019 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2020 &MemOpChains[0], MemOpChains.size());
2021
2022 // Build a sequence of copy-to-reg nodes chained together with token chain
2023 // and flag operands which copy the outgoing args into registers.
2024 SDOperand InFlag;
2025 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2026 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
2027 InFlag);
2028 InFlag = Chain.getValue(1);
2029 }
2030
2031 if (isVarArg) {
2032 // From AMD64 ABI document:
2033 // For calls that may call functions that use varargs or stdargs
2034 // (prototype-less calls or calls to functions containing ellipsis (...) in
2035 // the declaration) %al is used as hidden argument to specify the number
2036 // of SSE registers used. The contents of %al do not need to match exactly
2037 // the number of registers, but must be an ubound on the number of SSE
2038 // registers used and is in the range 0 - 8 inclusive.
2039
2040 // Count the number of XMM registers allocated.
2041 static const unsigned XMMArgRegs[] = {
2042 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2043 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2044 };
2045 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2046
2047 Chain = DAG.getCopyToReg(Chain, X86::AL,
2048 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2049 InFlag = Chain.getValue(1);
2050 }
2051
2052 // If the callee is a GlobalAddress node (quite common, every direct call is)
2053 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
2054 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2055 // We should use extra load for direct calls to dllimported functions in
2056 // non-JIT mode.
2057 if (getTargetMachine().getCodeModel() != CodeModel::Large
2058 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
2059 getTargetMachine(), true))
2060 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00002061 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002062 if (getTargetMachine().getCodeModel() != CodeModel::Large)
2063 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00002064 }
2065
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002066 // Returns a chain & a flag for retval copy to use.
2067 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2068 SmallVector<SDOperand, 8> Ops;
2069 Ops.push_back(Chain);
2070 Ops.push_back(Callee);
2071
2072 // Add argument registers to the end of the list so that they are known live
2073 // into the call.
2074 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2075 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2076 RegsToPass[i].second.getValueType()));
2077
2078 if (InFlag.Val)
2079 Ops.push_back(InFlag);
2080
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00002081 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002082 InFlag = Chain.getValue(1);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00002083
2084 // Create the CALLSEQ_END node.
2085 unsigned NumBytesForCalleeToPush = 0;
2086 if (CC == CallingConv::Fast && PerformTailCallOpt) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002087 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00002088 } else {
2089 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2090 }
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00002091
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002092 // Returns a flag for retval copy to use.
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00002093 Chain = DAG.getCALLSEQ_END(Chain,
2094 DAG.getConstant(NumBytes, getPointerTy()),
2095 DAG.getConstant(NumBytesForCalleeToPush,
2096 getPointerTy()),
2097 InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098 InFlag = Chain.getValue(1);
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00002099
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002100 // Handle result values, copying them out of physregs into vregs that we
2101 // return.
2102 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2103}
2104
2105
2106//===----------------------------------------------------------------------===//
2107// Other Lowering Hooks
2108//===----------------------------------------------------------------------===//
2109
2110
2111SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
Anton Korobeynikove844e472007-08-15 17:12:32 +00002112 MachineFunction &MF = DAG.getMachineFunction();
2113 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2114 int ReturnAddrIndex = FuncInfo->getRAIndex();
2115
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002116 if (ReturnAddrIndex == 0) {
2117 // Set up a frame object for the return address.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002118 if (Subtarget->is64Bit())
2119 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2120 else
2121 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
Anton Korobeynikove844e472007-08-15 17:12:32 +00002122
2123 FuncInfo->setRAIndex(ReturnAddrIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002124 }
2125
2126 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2127}
2128
2129
2130
2131/// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2132/// specific condition code. It returns a false if it cannot do a direct
2133/// translation. X86CC is the translated CondCode. LHS/RHS are modified as
2134/// needed.
2135static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2136 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2137 SelectionDAG &DAG) {
2138 X86CC = X86::COND_INVALID;
2139 if (!isFP) {
2140 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2141 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2142 // X > -1 -> X == 0, jump !sign.
2143 RHS = DAG.getConstant(0, RHS.getValueType());
2144 X86CC = X86::COND_NS;
2145 return true;
2146 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2147 // X < 0 -> X == 0, jump on sign.
2148 X86CC = X86::COND_S;
2149 return true;
Dan Gohman37b34262007-09-17 14:49:27 +00002150 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2151 // X < 1 -> X <= 0
2152 RHS = DAG.getConstant(0, RHS.getValueType());
2153 X86CC = X86::COND_LE;
2154 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155 }
2156 }
2157
2158 switch (SetCCOpcode) {
2159 default: break;
2160 case ISD::SETEQ: X86CC = X86::COND_E; break;
2161 case ISD::SETGT: X86CC = X86::COND_G; break;
2162 case ISD::SETGE: X86CC = X86::COND_GE; break;
2163 case ISD::SETLT: X86CC = X86::COND_L; break;
2164 case ISD::SETLE: X86CC = X86::COND_LE; break;
2165 case ISD::SETNE: X86CC = X86::COND_NE; break;
2166 case ISD::SETULT: X86CC = X86::COND_B; break;
2167 case ISD::SETUGT: X86CC = X86::COND_A; break;
2168 case ISD::SETULE: X86CC = X86::COND_BE; break;
2169 case ISD::SETUGE: X86CC = X86::COND_AE; break;
2170 }
2171 } else {
2172 // On a floating point condition, the flags are set as follows:
2173 // ZF PF CF op
2174 // 0 | 0 | 0 | X > Y
2175 // 0 | 0 | 1 | X < Y
2176 // 1 | 0 | 0 | X == Y
2177 // 1 | 1 | 1 | unordered
2178 bool Flip = false;
2179 switch (SetCCOpcode) {
2180 default: break;
2181 case ISD::SETUEQ:
2182 case ISD::SETEQ: X86CC = X86::COND_E; break;
2183 case ISD::SETOLT: Flip = true; // Fallthrough
2184 case ISD::SETOGT:
2185 case ISD::SETGT: X86CC = X86::COND_A; break;
2186 case ISD::SETOLE: Flip = true; // Fallthrough
2187 case ISD::SETOGE:
2188 case ISD::SETGE: X86CC = X86::COND_AE; break;
2189 case ISD::SETUGT: Flip = true; // Fallthrough
2190 case ISD::SETULT:
2191 case ISD::SETLT: X86CC = X86::COND_B; break;
2192 case ISD::SETUGE: Flip = true; // Fallthrough
2193 case ISD::SETULE:
2194 case ISD::SETLE: X86CC = X86::COND_BE; break;
2195 case ISD::SETONE:
2196 case ISD::SETNE: X86CC = X86::COND_NE; break;
2197 case ISD::SETUO: X86CC = X86::COND_P; break;
2198 case ISD::SETO: X86CC = X86::COND_NP; break;
2199 }
2200 if (Flip)
2201 std::swap(LHS, RHS);
2202 }
2203
2204 return X86CC != X86::COND_INVALID;
2205}
2206
2207/// hasFPCMov - is there a floating point cmov for the specific X86 condition
2208/// code. Current x86 isa includes the following FP cmov instructions:
2209/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2210static bool hasFPCMov(unsigned X86CC) {
2211 switch (X86CC) {
2212 default:
2213 return false;
2214 case X86::COND_B:
2215 case X86::COND_BE:
2216 case X86::COND_E:
2217 case X86::COND_P:
2218 case X86::COND_A:
2219 case X86::COND_AE:
2220 case X86::COND_NE:
2221 case X86::COND_NP:
2222 return true;
2223 }
2224}
2225
2226/// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2227/// true if Op is undef or if its value falls within the specified range (L, H].
2228static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2229 if (Op.getOpcode() == ISD::UNDEF)
2230 return true;
2231
2232 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2233 return (Val >= Low && Val < Hi);
2234}
2235
2236/// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2237/// true if Op is undef or if its value equal to the specified value.
2238static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2239 if (Op.getOpcode() == ISD::UNDEF)
2240 return true;
2241 return cast<ConstantSDNode>(Op)->getValue() == Val;
2242}
2243
2244/// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2245/// specifies a shuffle of elements that is suitable for input to PSHUFD.
2246bool X86::isPSHUFDMask(SDNode *N) {
2247 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2248
Dan Gohman7dc19012007-08-02 21:17:01 +00002249 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002250 return false;
2251
2252 // Check if the value doesn't reference the second vector.
2253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2254 SDOperand Arg = N->getOperand(i);
2255 if (Arg.getOpcode() == ISD::UNDEF) continue;
2256 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Dan Gohman7dc19012007-08-02 21:17:01 +00002257 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258 return false;
2259 }
2260
2261 return true;
2262}
2263
2264/// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2265/// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2266bool X86::isPSHUFHWMask(SDNode *N) {
2267 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2268
2269 if (N->getNumOperands() != 8)
2270 return false;
2271
2272 // Lower quadword copied in order.
2273 for (unsigned i = 0; i != 4; ++i) {
2274 SDOperand Arg = N->getOperand(i);
2275 if (Arg.getOpcode() == ISD::UNDEF) continue;
2276 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2277 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2278 return false;
2279 }
2280
2281 // Upper quadword shuffled.
2282 for (unsigned i = 4; i != 8; ++i) {
2283 SDOperand Arg = N->getOperand(i);
2284 if (Arg.getOpcode() == ISD::UNDEF) continue;
2285 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2286 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2287 if (Val < 4 || Val > 7)
2288 return false;
2289 }
2290
2291 return true;
2292}
2293
2294/// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2295/// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2296bool X86::isPSHUFLWMask(SDNode *N) {
2297 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2298
2299 if (N->getNumOperands() != 8)
2300 return false;
2301
2302 // Upper quadword copied in order.
2303 for (unsigned i = 4; i != 8; ++i)
2304 if (!isUndefOrEqual(N->getOperand(i), i))
2305 return false;
2306
2307 // Lower quadword shuffled.
2308 for (unsigned i = 0; i != 4; ++i)
2309 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2310 return false;
2311
2312 return true;
2313}
2314
2315/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2316/// specifies a shuffle of elements that is suitable for input to SHUFP*.
2317static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2318 if (NumElems != 2 && NumElems != 4) return false;
2319
2320 unsigned Half = NumElems / 2;
2321 for (unsigned i = 0; i < Half; ++i)
2322 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2323 return false;
2324 for (unsigned i = Half; i < NumElems; ++i)
2325 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2326 return false;
2327
2328 return true;
2329}
2330
2331bool X86::isSHUFPMask(SDNode *N) {
2332 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2333 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2334}
2335
2336/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2337/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2338/// half elements to come from vector 1 (which would equal the dest.) and
2339/// the upper half to come from vector 2.
2340static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2341 if (NumOps != 2 && NumOps != 4) return false;
2342
2343 unsigned Half = NumOps / 2;
2344 for (unsigned i = 0; i < Half; ++i)
2345 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2346 return false;
2347 for (unsigned i = Half; i < NumOps; ++i)
2348 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2349 return false;
2350 return true;
2351}
2352
2353static bool isCommutedSHUFP(SDNode *N) {
2354 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2355 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2356}
2357
2358/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2359/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2360bool X86::isMOVHLPSMask(SDNode *N) {
2361 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2362
2363 if (N->getNumOperands() != 4)
2364 return false;
2365
2366 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2367 return isUndefOrEqual(N->getOperand(0), 6) &&
2368 isUndefOrEqual(N->getOperand(1), 7) &&
2369 isUndefOrEqual(N->getOperand(2), 2) &&
2370 isUndefOrEqual(N->getOperand(3), 3);
2371}
2372
2373/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2374/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2375/// <2, 3, 2, 3>
2376bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2377 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2378
2379 if (N->getNumOperands() != 4)
2380 return false;
2381
2382 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2383 return isUndefOrEqual(N->getOperand(0), 2) &&
2384 isUndefOrEqual(N->getOperand(1), 3) &&
2385 isUndefOrEqual(N->getOperand(2), 2) &&
2386 isUndefOrEqual(N->getOperand(3), 3);
2387}
2388
2389/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2390/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2391bool X86::isMOVLPMask(SDNode *N) {
2392 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2393
2394 unsigned NumElems = N->getNumOperands();
2395 if (NumElems != 2 && NumElems != 4)
2396 return false;
2397
2398 for (unsigned i = 0; i < NumElems/2; ++i)
2399 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2400 return false;
2401
2402 for (unsigned i = NumElems/2; i < NumElems; ++i)
2403 if (!isUndefOrEqual(N->getOperand(i), i))
2404 return false;
2405
2406 return true;
2407}
2408
2409/// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2410/// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2411/// and MOVLHPS.
2412bool X86::isMOVHPMask(SDNode *N) {
2413 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2414
2415 unsigned NumElems = N->getNumOperands();
2416 if (NumElems != 2 && NumElems != 4)
2417 return false;
2418
2419 for (unsigned i = 0; i < NumElems/2; ++i)
2420 if (!isUndefOrEqual(N->getOperand(i), i))
2421 return false;
2422
2423 for (unsigned i = 0; i < NumElems/2; ++i) {
2424 SDOperand Arg = N->getOperand(i + NumElems/2);
2425 if (!isUndefOrEqual(Arg, i + NumElems))
2426 return false;
2427 }
2428
2429 return true;
2430}
2431
2432/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2433/// specifies a shuffle of elements that is suitable for input to UNPCKL.
2434bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2435 bool V2IsSplat = false) {
2436 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2437 return false;
2438
2439 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2440 SDOperand BitI = Elts[i];
2441 SDOperand BitI1 = Elts[i+1];
2442 if (!isUndefOrEqual(BitI, j))
2443 return false;
2444 if (V2IsSplat) {
2445 if (isUndefOrEqual(BitI1, NumElts))
2446 return false;
2447 } else {
2448 if (!isUndefOrEqual(BitI1, j + NumElts))
2449 return false;
2450 }
2451 }
2452
2453 return true;
2454}
2455
2456bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2457 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2458 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2459}
2460
2461/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2462/// specifies a shuffle of elements that is suitable for input to UNPCKH.
2463bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2464 bool V2IsSplat = false) {
2465 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2466 return false;
2467
2468 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2469 SDOperand BitI = Elts[i];
2470 SDOperand BitI1 = Elts[i+1];
2471 if (!isUndefOrEqual(BitI, j + NumElts/2))
2472 return false;
2473 if (V2IsSplat) {
2474 if (isUndefOrEqual(BitI1, NumElts))
2475 return false;
2476 } else {
2477 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2478 return false;
2479 }
2480 }
2481
2482 return true;
2483}
2484
2485bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2486 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2487 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2488}
2489
2490/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2491/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2492/// <0, 0, 1, 1>
2493bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2494 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2495
2496 unsigned NumElems = N->getNumOperands();
2497 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2498 return false;
2499
2500 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2501 SDOperand BitI = N->getOperand(i);
2502 SDOperand BitI1 = N->getOperand(i+1);
2503
2504 if (!isUndefOrEqual(BitI, j))
2505 return false;
2506 if (!isUndefOrEqual(BitI1, j))
2507 return false;
2508 }
2509
2510 return true;
2511}
2512
2513/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2514/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2515/// <2, 2, 3, 3>
2516bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2517 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2518
2519 unsigned NumElems = N->getNumOperands();
2520 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2521 return false;
2522
2523 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2524 SDOperand BitI = N->getOperand(i);
2525 SDOperand BitI1 = N->getOperand(i + 1);
2526
2527 if (!isUndefOrEqual(BitI, j))
2528 return false;
2529 if (!isUndefOrEqual(BitI1, j))
2530 return false;
2531 }
2532
2533 return true;
2534}
2535
2536/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2537/// specifies a shuffle of elements that is suitable for input to MOVSS,
2538/// MOVSD, and MOVD, i.e. setting the lowest element.
2539static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
Evan Cheng62cdc642007-12-06 22:14:22 +00002540 if (NumElts != 2 && NumElts != 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002541 return false;
2542
2543 if (!isUndefOrEqual(Elts[0], NumElts))
2544 return false;
2545
2546 for (unsigned i = 1; i < NumElts; ++i) {
2547 if (!isUndefOrEqual(Elts[i], i))
2548 return false;
2549 }
2550
2551 return true;
2552}
2553
2554bool X86::isMOVLMask(SDNode *N) {
2555 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2556 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2557}
2558
2559/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2560/// of what x86 movss want. X86 movs requires the lowest element to be lowest
2561/// element of vector 2 and the other elements to come from vector 1 in order.
2562static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2563 bool V2IsSplat = false,
2564 bool V2IsUndef = false) {
2565 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2566 return false;
2567
2568 if (!isUndefOrEqual(Ops[0], 0))
2569 return false;
2570
2571 for (unsigned i = 1; i < NumOps; ++i) {
2572 SDOperand Arg = Ops[i];
2573 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2574 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2575 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2576 return false;
2577 }
2578
2579 return true;
2580}
2581
2582static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2583 bool V2IsUndef = false) {
2584 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2585 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2586 V2IsSplat, V2IsUndef);
2587}
2588
2589/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2590/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2591bool X86::isMOVSHDUPMask(SDNode *N) {
2592 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2593
2594 if (N->getNumOperands() != 4)
2595 return false;
2596
2597 // Expect 1, 1, 3, 3
2598 for (unsigned i = 0; i < 2; ++i) {
2599 SDOperand Arg = N->getOperand(i);
2600 if (Arg.getOpcode() == ISD::UNDEF) continue;
2601 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2602 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2603 if (Val != 1) return false;
2604 }
2605
2606 bool HasHi = false;
2607 for (unsigned i = 2; i < 4; ++i) {
2608 SDOperand Arg = N->getOperand(i);
2609 if (Arg.getOpcode() == ISD::UNDEF) continue;
2610 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2611 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2612 if (Val != 3) return false;
2613 HasHi = true;
2614 }
2615
2616 // Don't use movshdup if it can be done with a shufps.
2617 return HasHi;
2618}
2619
2620/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2621/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2622bool X86::isMOVSLDUPMask(SDNode *N) {
2623 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2624
2625 if (N->getNumOperands() != 4)
2626 return false;
2627
2628 // Expect 0, 0, 2, 2
2629 for (unsigned i = 0; i < 2; ++i) {
2630 SDOperand Arg = N->getOperand(i);
2631 if (Arg.getOpcode() == ISD::UNDEF) continue;
2632 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2633 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2634 if (Val != 0) return false;
2635 }
2636
2637 bool HasHi = false;
2638 for (unsigned i = 2; i < 4; ++i) {
2639 SDOperand Arg = N->getOperand(i);
2640 if (Arg.getOpcode() == ISD::UNDEF) continue;
2641 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2642 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2643 if (Val != 2) return false;
2644 HasHi = true;
2645 }
2646
2647 // Don't use movshdup if it can be done with a shufps.
2648 return HasHi;
2649}
2650
2651/// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2652/// specifies a identity operation on the LHS or RHS.
2653static bool isIdentityMask(SDNode *N, bool RHS = false) {
2654 unsigned NumElems = N->getNumOperands();
2655 for (unsigned i = 0; i < NumElems; ++i)
2656 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2657 return false;
2658 return true;
2659}
2660
2661/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2662/// a splat of a single element.
2663static bool isSplatMask(SDNode *N) {
2664 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2665
2666 // This is a splat operation if each element of the permute is the same, and
2667 // if the value doesn't reference the second vector.
2668 unsigned NumElems = N->getNumOperands();
2669 SDOperand ElementBase;
2670 unsigned i = 0;
2671 for (; i != NumElems; ++i) {
2672 SDOperand Elt = N->getOperand(i);
2673 if (isa<ConstantSDNode>(Elt)) {
2674 ElementBase = Elt;
2675 break;
2676 }
2677 }
2678
2679 if (!ElementBase.Val)
2680 return false;
2681
2682 for (; i != NumElems; ++i) {
2683 SDOperand Arg = N->getOperand(i);
2684 if (Arg.getOpcode() == ISD::UNDEF) continue;
2685 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2686 if (Arg != ElementBase) return false;
2687 }
2688
2689 // Make sure it is a splat of the first vector operand.
2690 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2691}
2692
2693/// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2694/// a splat of a single element and it's a 2 or 4 element mask.
2695bool X86::isSplatMask(SDNode *N) {
2696 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2697
2698 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2699 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2700 return false;
2701 return ::isSplatMask(N);
2702}
2703
2704/// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2705/// specifies a splat of zero element.
2706bool X86::isSplatLoMask(SDNode *N) {
2707 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2708
2709 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2710 if (!isUndefOrEqual(N->getOperand(i), 0))
2711 return false;
2712 return true;
2713}
2714
2715/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2716/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2717/// instructions.
2718unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2719 unsigned NumOperands = N->getNumOperands();
2720 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2721 unsigned Mask = 0;
2722 for (unsigned i = 0; i < NumOperands; ++i) {
2723 unsigned Val = 0;
2724 SDOperand Arg = N->getOperand(NumOperands-i-1);
2725 if (Arg.getOpcode() != ISD::UNDEF)
2726 Val = cast<ConstantSDNode>(Arg)->getValue();
2727 if (Val >= NumOperands) Val -= NumOperands;
2728 Mask |= Val;
2729 if (i != NumOperands - 1)
2730 Mask <<= Shift;
2731 }
2732
2733 return Mask;
2734}
2735
2736/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2737/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2738/// instructions.
2739unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2740 unsigned Mask = 0;
2741 // 8 nodes, but we only care about the last 4.
2742 for (unsigned i = 7; i >= 4; --i) {
2743 unsigned Val = 0;
2744 SDOperand Arg = N->getOperand(i);
2745 if (Arg.getOpcode() != ISD::UNDEF)
2746 Val = cast<ConstantSDNode>(Arg)->getValue();
2747 Mask |= (Val - 4);
2748 if (i != 4)
2749 Mask <<= 2;
2750 }
2751
2752 return Mask;
2753}
2754
2755/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2756/// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2757/// instructions.
2758unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2759 unsigned Mask = 0;
2760 // 8 nodes, but we only care about the first 4.
2761 for (int i = 3; i >= 0; --i) {
2762 unsigned Val = 0;
2763 SDOperand Arg = N->getOperand(i);
2764 if (Arg.getOpcode() != ISD::UNDEF)
2765 Val = cast<ConstantSDNode>(Arg)->getValue();
2766 Mask |= Val;
2767 if (i != 0)
2768 Mask <<= 2;
2769 }
2770
2771 return Mask;
2772}
2773
2774/// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2775/// specifies a 8 element shuffle that can be broken into a pair of
2776/// PSHUFHW and PSHUFLW.
2777static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2778 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2779
2780 if (N->getNumOperands() != 8)
2781 return false;
2782
2783 // Lower quadword shuffled.
2784 for (unsigned i = 0; i != 4; ++i) {
2785 SDOperand Arg = N->getOperand(i);
2786 if (Arg.getOpcode() == ISD::UNDEF) continue;
2787 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2788 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
Evan Cheng75184a92007-12-11 01:46:18 +00002789 if (Val >= 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002790 return false;
2791 }
2792
2793 // Upper quadword shuffled.
2794 for (unsigned i = 4; i != 8; ++i) {
2795 SDOperand Arg = N->getOperand(i);
2796 if (Arg.getOpcode() == ISD::UNDEF) continue;
2797 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2798 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2799 if (Val < 4 || Val > 7)
2800 return false;
2801 }
2802
2803 return true;
2804}
2805
Chris Lattnere6aa3862007-11-25 00:24:49 +00002806/// CommuteVectorShuffle - Swap vector_shuffle operands as well as
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807/// values in ther permute mask.
2808static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2809 SDOperand &V2, SDOperand &Mask,
2810 SelectionDAG &DAG) {
2811 MVT::ValueType VT = Op.getValueType();
2812 MVT::ValueType MaskVT = Mask.getValueType();
2813 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2814 unsigned NumElems = Mask.getNumOperands();
2815 SmallVector<SDOperand, 8> MaskVec;
2816
2817 for (unsigned i = 0; i != NumElems; ++i) {
2818 SDOperand Arg = Mask.getOperand(i);
2819 if (Arg.getOpcode() == ISD::UNDEF) {
2820 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2821 continue;
2822 }
2823 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2824 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2825 if (Val < NumElems)
2826 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2827 else
2828 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2829 }
2830
2831 std::swap(V1, V2);
Evan Chengfca29242007-12-07 08:07:39 +00002832 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002833 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2834}
2835
Evan Chenga6769df2007-12-07 21:30:01 +00002836/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2837/// the two vector operands have swapped position.
Evan Chengfca29242007-12-07 08:07:39 +00002838static
2839SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2840 MVT::ValueType MaskVT = Mask.getValueType();
2841 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2842 unsigned NumElems = Mask.getNumOperands();
2843 SmallVector<SDOperand, 8> MaskVec;
2844 for (unsigned i = 0; i != NumElems; ++i) {
2845 SDOperand Arg = Mask.getOperand(i);
2846 if (Arg.getOpcode() == ISD::UNDEF) {
2847 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2848 continue;
2849 }
2850 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2851 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2852 if (Val < NumElems)
2853 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2854 else
2855 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2856 }
2857 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2858}
2859
2860
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002861/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2862/// match movhlps. The lower half elements should come from upper half of
2863/// V1 (and in order), and the upper half elements should come from the upper
2864/// half of V2 (and in order).
2865static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2866 unsigned NumElems = Mask->getNumOperands();
2867 if (NumElems != 4)
2868 return false;
2869 for (unsigned i = 0, e = 2; i != e; ++i)
2870 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2871 return false;
2872 for (unsigned i = 2; i != 4; ++i)
2873 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2874 return false;
2875 return true;
2876}
2877
2878/// isScalarLoadToVector - Returns true if the node is a scalar load that
2879/// is promoted to a vector.
2880static inline bool isScalarLoadToVector(SDNode *N) {
2881 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2882 N = N->getOperand(0).Val;
2883 return ISD::isNON_EXTLoad(N);
2884 }
2885 return false;
2886}
2887
2888/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2889/// match movlp{s|d}. The lower half elements should come from lower half of
2890/// V1 (and in order), and the upper half elements should come from the upper
2891/// half of V2 (and in order). And since V1 will become the source of the
2892/// MOVLP, it must be either a vector load or a scalar load to vector.
2893static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2894 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2895 return false;
2896 // Is V2 is a vector load, don't do this transformation. We will try to use
2897 // load folding shufps op.
2898 if (ISD::isNON_EXTLoad(V2))
2899 return false;
2900
2901 unsigned NumElems = Mask->getNumOperands();
2902 if (NumElems != 2 && NumElems != 4)
2903 return false;
2904 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2905 if (!isUndefOrEqual(Mask->getOperand(i), i))
2906 return false;
2907 for (unsigned i = NumElems/2; i != NumElems; ++i)
2908 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2909 return false;
2910 return true;
2911}
2912
2913/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2914/// all the same.
2915static bool isSplatVector(SDNode *N) {
2916 if (N->getOpcode() != ISD::BUILD_VECTOR)
2917 return false;
2918
2919 SDOperand SplatValue = N->getOperand(0);
2920 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2921 if (N->getOperand(i) != SplatValue)
2922 return false;
2923 return true;
2924}
2925
2926/// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2927/// to an undef.
2928static bool isUndefShuffle(SDNode *N) {
2929 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2930 return false;
2931
2932 SDOperand V1 = N->getOperand(0);
2933 SDOperand V2 = N->getOperand(1);
2934 SDOperand Mask = N->getOperand(2);
2935 unsigned NumElems = Mask.getNumOperands();
2936 for (unsigned i = 0; i != NumElems; ++i) {
2937 SDOperand Arg = Mask.getOperand(i);
2938 if (Arg.getOpcode() != ISD::UNDEF) {
2939 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2940 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2941 return false;
2942 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2943 return false;
2944 }
2945 }
2946 return true;
2947}
2948
2949/// isZeroNode - Returns true if Elt is a constant zero or a floating point
2950/// constant +0.0.
2951static inline bool isZeroNode(SDOperand Elt) {
2952 return ((isa<ConstantSDNode>(Elt) &&
2953 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2954 (isa<ConstantFPSDNode>(Elt) &&
Dale Johannesendf8a8312007-08-31 04:03:46 +00002955 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002956}
2957
2958/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2959/// to an zero vector.
2960static bool isZeroShuffle(SDNode *N) {
2961 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2962 return false;
2963
2964 SDOperand V1 = N->getOperand(0);
2965 SDOperand V2 = N->getOperand(1);
2966 SDOperand Mask = N->getOperand(2);
2967 unsigned NumElems = Mask.getNumOperands();
2968 for (unsigned i = 0; i != NumElems; ++i) {
2969 SDOperand Arg = Mask.getOperand(i);
Chris Lattnere6aa3862007-11-25 00:24:49 +00002970 if (Arg.getOpcode() == ISD::UNDEF)
2971 continue;
2972
2973 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2974 if (Idx < NumElems) {
2975 unsigned Opc = V1.Val->getOpcode();
2976 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2977 continue;
2978 if (Opc != ISD::BUILD_VECTOR ||
2979 !isZeroNode(V1.Val->getOperand(Idx)))
2980 return false;
2981 } else if (Idx >= NumElems) {
2982 unsigned Opc = V2.Val->getOpcode();
2983 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2984 continue;
2985 if (Opc != ISD::BUILD_VECTOR ||
2986 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2987 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002988 }
2989 }
2990 return true;
2991}
2992
2993/// getZeroVector - Returns a vector of specified type with all zero elements.
2994///
2995static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2996 assert(MVT::isVector(VT) && "Expected a vector type");
Chris Lattnere6aa3862007-11-25 00:24:49 +00002997
2998 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2999 // type. This ensures they get CSE'd.
3000 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
3001 SDOperand Vec;
3002 if (MVT::getSizeInBits(VT) == 64) // MMX
3003 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3004 else // SSE
3005 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
3006 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003007}
3008
Chris Lattnere6aa3862007-11-25 00:24:49 +00003009/// getOnesVector - Returns a vector of specified type with all bits set.
3010///
3011static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
3012 assert(MVT::isVector(VT) && "Expected a vector type");
3013
3014 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3015 // type. This ensures they get CSE'd.
3016 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
3017 SDOperand Vec;
3018 if (MVT::getSizeInBits(VT) == 64) // MMX
3019 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3020 else // SSE
3021 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
3022 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
3023}
3024
3025
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003026/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3027/// that point to V2 points to its first element.
3028static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
3029 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
3030
3031 bool Changed = false;
3032 SmallVector<SDOperand, 8> MaskVec;
3033 unsigned NumElems = Mask.getNumOperands();
3034 for (unsigned i = 0; i != NumElems; ++i) {
3035 SDOperand Arg = Mask.getOperand(i);
3036 if (Arg.getOpcode() != ISD::UNDEF) {
3037 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
3038 if (Val > NumElems) {
3039 Arg = DAG.getConstant(NumElems, Arg.getValueType());
3040 Changed = true;
3041 }
3042 }
3043 MaskVec.push_back(Arg);
3044 }
3045
3046 if (Changed)
3047 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
3048 &MaskVec[0], MaskVec.size());
3049 return Mask;
3050}
3051
3052/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3053/// operation of specified width.
3054static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
3055 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3056 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3057
3058 SmallVector<SDOperand, 8> MaskVec;
3059 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
3060 for (unsigned i = 1; i != NumElems; ++i)
3061 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3062 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3063}
3064
3065/// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
3066/// of specified width.
3067static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
3068 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3069 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3070 SmallVector<SDOperand, 8> MaskVec;
3071 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3072 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3073 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3074 }
3075 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3076}
3077
3078/// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3079/// of specified width.
3080static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
3081 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3082 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3083 unsigned Half = NumElems/2;
3084 SmallVector<SDOperand, 8> MaskVec;
3085 for (unsigned i = 0; i != Half; ++i) {
3086 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3087 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3088 }
3089 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3090}
3091
3092/// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
3093///
3094static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
3095 SDOperand V1 = Op.getOperand(0);
3096 SDOperand Mask = Op.getOperand(2);
3097 MVT::ValueType VT = Op.getValueType();
3098 unsigned NumElems = Mask.getNumOperands();
3099 Mask = getUnpacklMask(NumElems, DAG);
3100 while (NumElems != 4) {
3101 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3102 NumElems >>= 1;
3103 }
3104 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3105
Chris Lattnere6aa3862007-11-25 00:24:49 +00003106 Mask = getZeroVector(MVT::v4i32, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
3108 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
3109 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3110}
3111
3112/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
Chris Lattnere6aa3862007-11-25 00:24:49 +00003113/// vector of zero or undef vector. This produces a shuffle where the low
3114/// element of V2 is swizzled into the zero/undef vector, landing at element
3115/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003116static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
3117 unsigned NumElems, unsigned Idx,
3118 bool isZero, SelectionDAG &DAG) {
3119 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
3120 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3121 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
Chris Lattnere6aa3862007-11-25 00:24:49 +00003122 SmallVector<SDOperand, 16> MaskVec;
3123 for (unsigned i = 0; i != NumElems; ++i)
3124 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3125 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3126 else
3127 MaskVec.push_back(DAG.getConstant(i, EVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003128 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3129 &MaskVec[0], MaskVec.size());
3130 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3131}
3132
3133/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3134///
3135static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
3136 unsigned NumNonZero, unsigned NumZero,
3137 SelectionDAG &DAG, TargetLowering &TLI) {
3138 if (NumNonZero > 8)
3139 return SDOperand();
3140
3141 SDOperand V(0, 0);
3142 bool First = true;
3143 for (unsigned i = 0; i < 16; ++i) {
3144 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3145 if (ThisIsNonZero && First) {
3146 if (NumZero)
3147 V = getZeroVector(MVT::v8i16, DAG);
3148 else
3149 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3150 First = false;
3151 }
3152
3153 if ((i & 1) != 0) {
3154 SDOperand ThisElt(0, 0), LastElt(0, 0);
3155 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3156 if (LastIsNonZero) {
3157 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3158 }
3159 if (ThisIsNonZero) {
3160 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3161 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3162 ThisElt, DAG.getConstant(8, MVT::i8));
3163 if (LastIsNonZero)
3164 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3165 } else
3166 ThisElt = LastElt;
3167
3168 if (ThisElt.Val)
3169 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3170 DAG.getConstant(i/2, TLI.getPointerTy()));
3171 }
3172 }
3173
3174 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3175}
3176
3177/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3178///
3179static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3180 unsigned NumNonZero, unsigned NumZero,
3181 SelectionDAG &DAG, TargetLowering &TLI) {
3182 if (NumNonZero > 4)
3183 return SDOperand();
3184
3185 SDOperand V(0, 0);
3186 bool First = true;
3187 for (unsigned i = 0; i < 8; ++i) {
3188 bool isNonZero = (NonZeros & (1 << i)) != 0;
3189 if (isNonZero) {
3190 if (First) {
3191 if (NumZero)
3192 V = getZeroVector(MVT::v8i16, DAG);
3193 else
3194 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3195 First = false;
3196 }
3197 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3198 DAG.getConstant(i, TLI.getPointerTy()));
3199 }
3200 }
3201
3202 return V;
3203}
3204
3205SDOperand
3206X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
Chris Lattnere6aa3862007-11-25 00:24:49 +00003207 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3208 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3209 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3210 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3211 // eliminated on x86-32 hosts.
3212 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3213 return Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214
Chris Lattnere6aa3862007-11-25 00:24:49 +00003215 if (ISD::isBuildVectorAllOnes(Op.Val))
3216 return getOnesVector(Op.getValueType(), DAG);
3217 return getZeroVector(Op.getValueType(), DAG);
3218 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219
3220 MVT::ValueType VT = Op.getValueType();
3221 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3222 unsigned EVTBits = MVT::getSizeInBits(EVT);
3223
3224 unsigned NumElems = Op.getNumOperands();
3225 unsigned NumZero = 0;
3226 unsigned NumNonZero = 0;
3227 unsigned NonZeros = 0;
Evan Chengc1073492007-12-12 06:45:40 +00003228 bool HasNonImms = false;
Evan Cheng75184a92007-12-11 01:46:18 +00003229 SmallSet<SDOperand, 8> Values;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003230 for (unsigned i = 0; i < NumElems; ++i) {
3231 SDOperand Elt = Op.getOperand(i);
Evan Chengc1073492007-12-12 06:45:40 +00003232 if (Elt.getOpcode() == ISD::UNDEF)
3233 continue;
3234 Values.insert(Elt);
3235 if (Elt.getOpcode() != ISD::Constant &&
3236 Elt.getOpcode() != ISD::ConstantFP)
3237 HasNonImms = true;
3238 if (isZeroNode(Elt))
3239 NumZero++;
3240 else {
3241 NonZeros |= (1 << i);
3242 NumNonZero++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003243 }
3244 }
3245
3246 if (NumNonZero == 0) {
Chris Lattnere6aa3862007-11-25 00:24:49 +00003247 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3248 return DAG.getNode(ISD::UNDEF, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003249 }
3250
3251 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3252 if (Values.size() == 1)
3253 return SDOperand();
3254
3255 // Special case for single non-zero element.
Evan Chengc1073492007-12-12 06:45:40 +00003256 if (NumNonZero == 1 && NumElems <= 4) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003257 unsigned Idx = CountTrailingZeros_32(NonZeros);
3258 SDOperand Item = Op.getOperand(Idx);
3259 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3260 if (Idx == 0)
3261 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3262 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3263 NumZero > 0, DAG);
Evan Chengc1073492007-12-12 06:45:40 +00003264 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
3265 return SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003266
3267 if (EVTBits == 32) {
3268 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3269 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3270 DAG);
3271 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3272 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3273 SmallVector<SDOperand, 8> MaskVec;
3274 for (unsigned i = 0; i < NumElems; i++)
3275 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3276 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3277 &MaskVec[0], MaskVec.size());
3278 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3279 DAG.getNode(ISD::UNDEF, VT), Mask);
3280 }
3281 }
3282
Dan Gohman21463242007-07-24 22:55:08 +00003283 // A vector full of immediates; various special cases are already
3284 // handled, so this is best done with a single constant-pool load.
Evan Chengc1073492007-12-12 06:45:40 +00003285 if (!HasNonImms)
Dan Gohman21463242007-07-24 22:55:08 +00003286 return SDOperand();
3287
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003288 // Let legalizer expand 2-wide build_vectors.
3289 if (EVTBits == 64)
3290 return SDOperand();
3291
3292 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3293 if (EVTBits == 8 && NumElems == 16) {
3294 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3295 *this);
3296 if (V.Val) return V;
3297 }
3298
3299 if (EVTBits == 16 && NumElems == 8) {
3300 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3301 *this);
3302 if (V.Val) return V;
3303 }
3304
3305 // If element VT is == 32 bits, turn it into a number of shuffles.
3306 SmallVector<SDOperand, 8> V;
3307 V.resize(NumElems);
3308 if (NumElems == 4 && NumZero > 0) {
3309 for (unsigned i = 0; i < 4; ++i) {
3310 bool isZero = !(NonZeros & (1 << i));
3311 if (isZero)
3312 V[i] = getZeroVector(VT, DAG);
3313 else
3314 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3315 }
3316
3317 for (unsigned i = 0; i < 2; ++i) {
3318 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3319 default: break;
3320 case 0:
3321 V[i] = V[i*2]; // Must be a zero vector.
3322 break;
3323 case 1:
3324 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3325 getMOVLMask(NumElems, DAG));
3326 break;
3327 case 2:
3328 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3329 getMOVLMask(NumElems, DAG));
3330 break;
3331 case 3:
3332 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3333 getUnpacklMask(NumElems, DAG));
3334 break;
3335 }
3336 }
3337
3338 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3339 // clears the upper bits.
3340 // FIXME: we can do the same for v4f32 case when we know both parts of
3341 // the lower half come from scalar_to_vector (loadf32). We should do
3342 // that in post legalizer dag combiner with target specific hooks.
3343 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3344 return V[0];
3345 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3346 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3347 SmallVector<SDOperand, 8> MaskVec;
3348 bool Reverse = (NonZeros & 0x3) == 2;
3349 for (unsigned i = 0; i < 2; ++i)
3350 if (Reverse)
3351 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3352 else
3353 MaskVec.push_back(DAG.getConstant(i, EVT));
3354 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3355 for (unsigned i = 0; i < 2; ++i)
3356 if (Reverse)
3357 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3358 else
3359 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3360 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3361 &MaskVec[0], MaskVec.size());
3362 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3363 }
3364
3365 if (Values.size() > 2) {
3366 // Expand into a number of unpckl*.
3367 // e.g. for v4f32
3368 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3369 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3370 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3371 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3372 for (unsigned i = 0; i < NumElems; ++i)
3373 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3374 NumElems >>= 1;
3375 while (NumElems != 0) {
3376 for (unsigned i = 0; i < NumElems; ++i)
3377 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3378 UnpckMask);
3379 NumElems >>= 1;
3380 }
3381 return V[0];
3382 }
3383
3384 return SDOperand();
3385}
3386
Evan Chengfca29242007-12-07 08:07:39 +00003387static
3388SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3389 SDOperand PermMask, SelectionDAG &DAG,
3390 TargetLowering &TLI) {
Evan Cheng75184a92007-12-11 01:46:18 +00003391 SDOperand NewV;
Evan Chengfca29242007-12-07 08:07:39 +00003392 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3393 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
Evan Cheng75184a92007-12-11 01:46:18 +00003394 MVT::ValueType PtrVT = TLI.getPointerTy();
3395 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3396 PermMask.Val->op_end());
3397
3398 // First record which half of which vector the low elements come from.
3399 SmallVector<unsigned, 4> LowQuad(4);
3400 for (unsigned i = 0; i < 4; ++i) {
3401 SDOperand Elt = MaskElts[i];
3402 if (Elt.getOpcode() == ISD::UNDEF)
3403 continue;
3404 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3405 int QuadIdx = EltIdx / 4;
3406 ++LowQuad[QuadIdx];
3407 }
3408 int BestLowQuad = -1;
3409 unsigned MaxQuad = 1;
3410 for (unsigned i = 0; i < 4; ++i) {
3411 if (LowQuad[i] > MaxQuad) {
3412 BestLowQuad = i;
3413 MaxQuad = LowQuad[i];
3414 }
Evan Chengfca29242007-12-07 08:07:39 +00003415 }
3416
Evan Cheng75184a92007-12-11 01:46:18 +00003417 // Record which half of which vector the high elements come from.
3418 SmallVector<unsigned, 4> HighQuad(4);
3419 for (unsigned i = 4; i < 8; ++i) {
3420 SDOperand Elt = MaskElts[i];
3421 if (Elt.getOpcode() == ISD::UNDEF)
3422 continue;
3423 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3424 int QuadIdx = EltIdx / 4;
3425 ++HighQuad[QuadIdx];
3426 }
3427 int BestHighQuad = -1;
3428 MaxQuad = 1;
3429 for (unsigned i = 0; i < 4; ++i) {
3430 if (HighQuad[i] > MaxQuad) {
3431 BestHighQuad = i;
3432 MaxQuad = HighQuad[i];
3433 }
3434 }
3435
3436 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3437 if (BestLowQuad != -1 || BestHighQuad != -1) {
3438 // First sort the 4 chunks in order using shufpd.
3439 SmallVector<SDOperand, 8> MaskVec;
3440 if (BestLowQuad != -1)
3441 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3442 else
3443 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3444 if (BestHighQuad != -1)
3445 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3446 else
3447 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3448 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3449 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3450 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3451 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3452 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3453
3454 // Now sort high and low parts separately.
3455 BitVector InOrder(8);
3456 if (BestLowQuad != -1) {
3457 // Sort lower half in order using PSHUFLW.
3458 MaskVec.clear();
3459 bool AnyOutOrder = false;
3460 for (unsigned i = 0; i != 4; ++i) {
3461 SDOperand Elt = MaskElts[i];
3462 if (Elt.getOpcode() == ISD::UNDEF) {
3463 MaskVec.push_back(Elt);
3464 InOrder.set(i);
3465 } else {
3466 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3467 if (EltIdx != i)
3468 AnyOutOrder = true;
3469 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3470 // If this element is in the right place after this shuffle, then
3471 // remember it.
3472 if ((int)(EltIdx / 4) == BestLowQuad)
3473 InOrder.set(i);
3474 }
3475 }
3476 if (AnyOutOrder) {
3477 for (unsigned i = 4; i != 8; ++i)
3478 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3479 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3480 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3481 }
3482 }
3483
3484 if (BestHighQuad != -1) {
3485 // Sort high half in order using PSHUFHW if possible.
3486 MaskVec.clear();
3487 for (unsigned i = 0; i != 4; ++i)
3488 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3489 bool AnyOutOrder = false;
3490 for (unsigned i = 4; i != 8; ++i) {
3491 SDOperand Elt = MaskElts[i];
3492 if (Elt.getOpcode() == ISD::UNDEF) {
3493 MaskVec.push_back(Elt);
3494 InOrder.set(i);
3495 } else {
3496 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3497 if (EltIdx != i)
3498 AnyOutOrder = true;
3499 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3500 // If this element is in the right place after this shuffle, then
3501 // remember it.
3502 if ((int)(EltIdx / 4) == BestHighQuad)
3503 InOrder.set(i);
3504 }
3505 }
3506 if (AnyOutOrder) {
3507 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3508 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3509 }
3510 }
3511
3512 // The other elements are put in the right place using pextrw and pinsrw.
3513 for (unsigned i = 0; i != 8; ++i) {
3514 if (InOrder[i])
3515 continue;
3516 SDOperand Elt = MaskElts[i];
3517 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3518 if (EltIdx == i)
3519 continue;
3520 SDOperand ExtOp = (EltIdx < 8)
3521 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3522 DAG.getConstant(EltIdx, PtrVT))
3523 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3524 DAG.getConstant(EltIdx - 8, PtrVT));
3525 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3526 DAG.getConstant(i, PtrVT));
3527 }
3528 return NewV;
3529 }
3530
3531 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3532 ///as few as possible.
Evan Chengfca29242007-12-07 08:07:39 +00003533 // First, let's find out how many elements are already in the right order.
3534 unsigned V1InOrder = 0;
3535 unsigned V1FromV1 = 0;
3536 unsigned V2InOrder = 0;
3537 unsigned V2FromV2 = 0;
Evan Cheng75184a92007-12-11 01:46:18 +00003538 SmallVector<SDOperand, 8> V1Elts;
3539 SmallVector<SDOperand, 8> V2Elts;
Evan Chengfca29242007-12-07 08:07:39 +00003540 for (unsigned i = 0; i < 8; ++i) {
Evan Cheng75184a92007-12-11 01:46:18 +00003541 SDOperand Elt = MaskElts[i];
Evan Chengfca29242007-12-07 08:07:39 +00003542 if (Elt.getOpcode() == ISD::UNDEF) {
Evan Cheng75184a92007-12-11 01:46:18 +00003543 V1Elts.push_back(Elt);
3544 V2Elts.push_back(Elt);
Evan Chengfca29242007-12-07 08:07:39 +00003545 ++V1InOrder;
3546 ++V2InOrder;
Evan Cheng75184a92007-12-11 01:46:18 +00003547 continue;
3548 }
3549 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3550 if (EltIdx == i) {
3551 V1Elts.push_back(Elt);
3552 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3553 ++V1InOrder;
3554 } else if (EltIdx == i+8) {
3555 V1Elts.push_back(Elt);
3556 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3557 ++V2InOrder;
3558 } else if (EltIdx < 8) {
3559 V1Elts.push_back(Elt);
3560 ++V1FromV1;
Evan Chengfca29242007-12-07 08:07:39 +00003561 } else {
Evan Cheng75184a92007-12-11 01:46:18 +00003562 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3563 ++V2FromV2;
Evan Chengfca29242007-12-07 08:07:39 +00003564 }
3565 }
3566
3567 if (V2InOrder > V1InOrder) {
3568 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3569 std::swap(V1, V2);
3570 std::swap(V1Elts, V2Elts);
3571 std::swap(V1FromV1, V2FromV2);
3572 }
3573
Evan Cheng75184a92007-12-11 01:46:18 +00003574 if ((V1FromV1 + V1InOrder) != 8) {
3575 // Some elements are from V2.
3576 if (V1FromV1) {
3577 // If there are elements that are from V1 but out of place,
3578 // then first sort them in place
3579 SmallVector<SDOperand, 8> MaskVec;
3580 for (unsigned i = 0; i < 8; ++i) {
3581 SDOperand Elt = V1Elts[i];
3582 if (Elt.getOpcode() == ISD::UNDEF) {
3583 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3584 continue;
3585 }
3586 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3587 if (EltIdx >= 8)
3588 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3589 else
3590 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3591 }
3592 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3593 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
Evan Chengfca29242007-12-07 08:07:39 +00003594 }
Evan Cheng75184a92007-12-11 01:46:18 +00003595
3596 NewV = V1;
3597 for (unsigned i = 0; i < 8; ++i) {
3598 SDOperand Elt = V1Elts[i];
3599 if (Elt.getOpcode() == ISD::UNDEF)
3600 continue;
3601 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3602 if (EltIdx < 8)
3603 continue;
3604 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3605 DAG.getConstant(EltIdx - 8, PtrVT));
3606 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3607 DAG.getConstant(i, PtrVT));
3608 }
3609 return NewV;
3610 } else {
3611 // All elements are from V1.
3612 NewV = V1;
3613 for (unsigned i = 0; i < 8; ++i) {
3614 SDOperand Elt = V1Elts[i];
3615 if (Elt.getOpcode() == ISD::UNDEF)
3616 continue;
3617 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3618 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3619 DAG.getConstant(EltIdx, PtrVT));
3620 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3621 DAG.getConstant(i, PtrVT));
3622 }
3623 return NewV;
3624 }
3625}
3626
Evan Cheng15e8f5a2007-12-15 03:00:47 +00003627/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3628/// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3629/// done when every pair / quad of shuffle mask elements point to elements in
3630/// the right sequence. e.g.
Evan Cheng75184a92007-12-11 01:46:18 +00003631/// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3632static
Evan Cheng15e8f5a2007-12-15 03:00:47 +00003633SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3634 MVT::ValueType VT,
Evan Cheng75184a92007-12-11 01:46:18 +00003635 SDOperand PermMask, SelectionDAG &DAG,
3636 TargetLowering &TLI) {
3637 unsigned NumElems = PermMask.getNumOperands();
Evan Cheng15e8f5a2007-12-15 03:00:47 +00003638 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3639 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3640 MVT::ValueType NewVT = MaskVT;
3641 switch (VT) {
3642 case MVT::v4f32: NewVT = MVT::v2f64; break;
3643 case MVT::v4i32: NewVT = MVT::v2i64; break;
3644 case MVT::v8i16: NewVT = MVT::v4i32; break;
3645 case MVT::v16i8: NewVT = MVT::v4i32; break;
3646 default: assert(false && "Unexpected!");
3647 }
3648
3649 if (NewWidth == 2)
3650 if (MVT::isInteger(VT))
3651 NewVT = MVT::v2i64;
3652 else
3653 NewVT = MVT::v2f64;
3654 unsigned Scale = NumElems / NewWidth;
3655 SmallVector<SDOperand, 8> MaskVec;
Evan Cheng75184a92007-12-11 01:46:18 +00003656 for (unsigned i = 0; i < NumElems; i += Scale) {
3657 unsigned StartIdx = ~0U;
3658 for (unsigned j = 0; j < Scale; ++j) {
3659 SDOperand Elt = PermMask.getOperand(i+j);
3660 if (Elt.getOpcode() == ISD::UNDEF)
3661 continue;
3662 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3663 if (StartIdx == ~0U)
3664 StartIdx = EltIdx - (EltIdx % Scale);
3665 if (EltIdx != StartIdx + j)
3666 return SDOperand();
3667 }
3668 if (StartIdx == ~0U)
3669 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3670 else
3671 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
Evan Chengfca29242007-12-07 08:07:39 +00003672 }
3673
Evan Cheng15e8f5a2007-12-15 03:00:47 +00003674 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3675 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3676 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3677 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3678 &MaskVec[0], MaskVec.size()));
Evan Chengfca29242007-12-07 08:07:39 +00003679}
3680
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003681SDOperand
3682X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3683 SDOperand V1 = Op.getOperand(0);
3684 SDOperand V2 = Op.getOperand(1);
3685 SDOperand PermMask = Op.getOperand(2);
3686 MVT::ValueType VT = Op.getValueType();
3687 unsigned NumElems = PermMask.getNumOperands();
3688 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3689 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3690 bool V1IsSplat = false;
3691 bool V2IsSplat = false;
3692
3693 if (isUndefShuffle(Op.Val))
3694 return DAG.getNode(ISD::UNDEF, VT);
3695
3696 if (isZeroShuffle(Op.Val))
3697 return getZeroVector(VT, DAG);
3698
3699 if (isIdentityMask(PermMask.Val))
3700 return V1;
3701 else if (isIdentityMask(PermMask.Val, true))
3702 return V2;
3703
3704 if (isSplatMask(PermMask.Val)) {
3705 if (NumElems <= 4) return Op;
3706 // Promote it to a v4i32 splat.
3707 return PromoteSplat(Op, DAG);
3708 }
3709
Evan Cheng15e8f5a2007-12-15 03:00:47 +00003710 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3711 // do it!
3712 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3713 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3714 if (NewOp.Val)
3715 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3716 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3717 // FIXME: Figure out a cleaner way to do this.
3718 // Try to make use of movq to zero out the top part.
3719 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3720 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3721 if (NewOp.Val) {
3722 SDOperand NewV1 = NewOp.getOperand(0);
3723 SDOperand NewV2 = NewOp.getOperand(1);
3724 SDOperand NewMask = NewOp.getOperand(2);
3725 if (isCommutedMOVL(NewMask.Val, true, false)) {
3726 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3727 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3728 NewV1, NewV2, getMOVLMask(2, DAG));
3729 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3730 }
3731 }
3732 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3733 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3734 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3735 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3736 }
3737 }
3738
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003739 if (X86::isMOVLMask(PermMask.Val))
3740 return (V1IsUndef) ? V2 : Op;
3741
3742 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3743 X86::isMOVSLDUPMask(PermMask.Val) ||
3744 X86::isMOVHLPSMask(PermMask.Val) ||
3745 X86::isMOVHPMask(PermMask.Val) ||
3746 X86::isMOVLPMask(PermMask.Val))
3747 return Op;
3748
3749 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3750 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3751 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3752
3753 bool Commuted = false;
Chris Lattnere6aa3862007-11-25 00:24:49 +00003754 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3755 // 1,1,1,1 -> v8i16 though.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003756 V1IsSplat = isSplatVector(V1.Val);
3757 V2IsSplat = isSplatVector(V2.Val);
Chris Lattnere6aa3862007-11-25 00:24:49 +00003758
3759 // Canonicalize the splat or undef, if present, to be on the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003760 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3761 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3762 std::swap(V1IsSplat, V2IsSplat);
3763 std::swap(V1IsUndef, V2IsUndef);
3764 Commuted = true;
3765 }
3766
Evan Cheng15e8f5a2007-12-15 03:00:47 +00003767 // FIXME: Figure out a cleaner way to do this.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003768 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3769 if (V2IsUndef) return V1;
3770 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3771 if (V2IsSplat) {
3772 // V2 is a splat, so the mask may be malformed. That is, it may point
3773 // to any V2 element. The instruction selectior won't like this. Get
3774 // a corrected mask and commute to form a proper MOVS{S|D}.
3775 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3776 if (NewMask.Val != PermMask.Val)
3777 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3778 }
3779 return Op;
3780 }
3781
3782 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3783 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3784 X86::isUNPCKLMask(PermMask.Val) ||
3785 X86::isUNPCKHMask(PermMask.Val))
3786 return Op;
3787
3788 if (V2IsSplat) {
3789 // Normalize mask so all entries that point to V2 points to its first
3790 // element then try to match unpck{h|l} again. If match, return a
3791 // new vector_shuffle with the corrected mask.
3792 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3793 if (NewMask.Val != PermMask.Val) {
3794 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3795 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3796 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3797 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3798 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3799 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3800 }
3801 }
3802 }
3803
3804 // Normalize the node to match x86 shuffle ops if needed
3805 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3806 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3807
3808 if (Commuted) {
3809 // Commute is back and try unpck* again.
3810 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3811 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3812 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3813 X86::isUNPCKLMask(PermMask.Val) ||
3814 X86::isUNPCKHMask(PermMask.Val))
3815 return Op;
3816 }
3817
3818 // If VT is integer, try PSHUF* first, then SHUFP*.
3819 if (MVT::isInteger(VT)) {
Dan Gohman7dc19012007-08-02 21:17:01 +00003820 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3821 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3822 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3823 X86::isPSHUFDMask(PermMask.Val)) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003824 X86::isPSHUFHWMask(PermMask.Val) ||
3825 X86::isPSHUFLWMask(PermMask.Val)) {
3826 if (V2.getOpcode() != ISD::UNDEF)
3827 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3828 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3829 return Op;
3830 }
3831
3832 if (X86::isSHUFPMask(PermMask.Val) &&
3833 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3834 return Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003835 } else {
3836 // Floating point cases in the other order.
3837 if (X86::isSHUFPMask(PermMask.Val))
3838 return Op;
3839 if (X86::isPSHUFDMask(PermMask.Val) ||
3840 X86::isPSHUFHWMask(PermMask.Val) ||
3841 X86::isPSHUFLWMask(PermMask.Val)) {
3842 if (V2.getOpcode() != ISD::UNDEF)
3843 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3844 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3845 return Op;
3846 }
3847 }
3848
Evan Cheng75184a92007-12-11 01:46:18 +00003849 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3850 if (VT == MVT::v8i16) {
3851 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3852 if (NewOp.Val)
3853 return NewOp;
3854 }
3855
3856 // Handle all 4 wide cases with a number of shuffles.
3857 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
Evan Chengfca29242007-12-07 08:07:39 +00003858 // Don't do this for MMX.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003859 MVT::ValueType MaskVT = PermMask.getValueType();
3860 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3861 SmallVector<std::pair<int, int>, 8> Locs;
3862 Locs.reserve(NumElems);
Evan Cheng75184a92007-12-11 01:46:18 +00003863 SmallVector<SDOperand, 8> Mask1(NumElems,
3864 DAG.getNode(ISD::UNDEF, MaskEVT));
3865 SmallVector<SDOperand, 8> Mask2(NumElems,
3866 DAG.getNode(ISD::UNDEF, MaskEVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003867 unsigned NumHi = 0;
3868 unsigned NumLo = 0;
3869 // If no more than two elements come from either vector. This can be
3870 // implemented with two shuffles. First shuffle gather the elements.
3871 // The second shuffle, which takes the first shuffle as both of its
3872 // vector operands, put the elements into the right order.
3873 for (unsigned i = 0; i != NumElems; ++i) {
3874 SDOperand Elt = PermMask.getOperand(i);
3875 if (Elt.getOpcode() == ISD::UNDEF) {
3876 Locs[i] = std::make_pair(-1, -1);
3877 } else {
3878 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3879 if (Val < NumElems) {
3880 Locs[i] = std::make_pair(0, NumLo);
3881 Mask1[NumLo] = Elt;
3882 NumLo++;
3883 } else {
3884 Locs[i] = std::make_pair(1, NumHi);
3885 if (2+NumHi < NumElems)
3886 Mask1[2+NumHi] = Elt;
3887 NumHi++;
3888 }
3889 }
3890 }
3891 if (NumLo <= 2 && NumHi <= 2) {
3892 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3893 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3894 &Mask1[0], Mask1.size()));
3895 for (unsigned i = 0; i != NumElems; ++i) {
3896 if (Locs[i].first == -1)
3897 continue;
3898 else {
3899 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3900 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3901 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3902 }
3903 }
3904
3905 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3906 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3907 &Mask2[0], Mask2.size()));
3908 }
3909
3910 // Break it into (shuffle shuffle_hi, shuffle_lo).
3911 Locs.clear();
3912 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3913 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3914 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3915 unsigned MaskIdx = 0;
3916 unsigned LoIdx = 0;
3917 unsigned HiIdx = NumElems/2;
3918 for (unsigned i = 0; i != NumElems; ++i) {
3919 if (i == NumElems/2) {
3920 MaskPtr = &HiMask;
3921 MaskIdx = 1;
3922 LoIdx = 0;
3923 HiIdx = NumElems/2;
3924 }
3925 SDOperand Elt = PermMask.getOperand(i);
3926 if (Elt.getOpcode() == ISD::UNDEF) {
3927 Locs[i] = std::make_pair(-1, -1);
3928 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3929 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3930 (*MaskPtr)[LoIdx] = Elt;
3931 LoIdx++;
3932 } else {
3933 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3934 (*MaskPtr)[HiIdx] = Elt;
3935 HiIdx++;
3936 }
3937 }
3938
3939 SDOperand LoShuffle =
3940 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3941 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3942 &LoMask[0], LoMask.size()));
3943 SDOperand HiShuffle =
3944 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3945 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3946 &HiMask[0], HiMask.size()));
3947 SmallVector<SDOperand, 8> MaskOps;
3948 for (unsigned i = 0; i != NumElems; ++i) {
3949 if (Locs[i].first == -1) {
3950 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3951 } else {
3952 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3953 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3954 }
3955 }
3956 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3957 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3958 &MaskOps[0], MaskOps.size()));
3959 }
3960
3961 return SDOperand();
3962}
3963
3964SDOperand
3965X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3966 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3967 return SDOperand();
3968
3969 MVT::ValueType VT = Op.getValueType();
3970 // TODO: handle v16i8.
3971 if (MVT::getSizeInBits(VT) == 16) {
Evan Cheng75184a92007-12-11 01:46:18 +00003972 SDOperand Vec = Op.getOperand(0);
3973 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3974 if (Idx == 0)
3975 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3976 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3977 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3978 Op.getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003979 // Transform it so it match pextrw which produces a 32-bit result.
3980 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3981 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3982 Op.getOperand(0), Op.getOperand(1));
3983 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3984 DAG.getValueType(VT));
3985 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3986 } else if (MVT::getSizeInBits(VT) == 32) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003987 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3988 if (Idx == 0)
3989 return Op;
3990 // SHUFPS the element to the lowest double word, then movss.
3991 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3992 SmallVector<SDOperand, 8> IdxVec;
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00003993 IdxVec.
3994 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3995 IdxVec.
3996 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3997 IdxVec.
3998 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3999 IdxVec.
4000 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004001 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4002 &IdxVec[0], IdxVec.size());
Evan Cheng75184a92007-12-11 01:46:18 +00004003 SDOperand Vec = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004004 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4005 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4006 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4007 DAG.getConstant(0, getPointerTy()));
4008 } else if (MVT::getSizeInBits(VT) == 64) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004009 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4010 if (Idx == 0)
4011 return Op;
4012
4013 // UNPCKHPD the element to the lowest double word, then movsd.
4014 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4015 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4016 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
4017 SmallVector<SDOperand, 8> IdxVec;
4018 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004019 IdxVec.
4020 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004021 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4022 &IdxVec[0], IdxVec.size());
Evan Cheng75184a92007-12-11 01:46:18 +00004023 SDOperand Vec = Op.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004024 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4025 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4026 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4027 DAG.getConstant(0, getPointerTy()));
4028 }
4029
4030 return SDOperand();
4031}
4032
4033SDOperand
4034X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004035 MVT::ValueType VT = Op.getValueType();
Evan Chenge12a7eb2007-12-12 07:55:34 +00004036 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4037 if (EVT == MVT::i8)
4038 return SDOperand();
4039
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004040 SDOperand N0 = Op.getOperand(0);
4041 SDOperand N1 = Op.getOperand(1);
4042 SDOperand N2 = Op.getOperand(2);
Evan Chenge12a7eb2007-12-12 07:55:34 +00004043
4044 if (MVT::getSizeInBits(EVT) == 16) {
4045 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4046 // as its second argument.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004047 if (N1.getValueType() != MVT::i32)
4048 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4049 if (N2.getValueType() != MVT::i32)
4050 N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
4051 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004052 }
4053
Evan Chenge12a7eb2007-12-12 07:55:34 +00004054 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
4055 unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
4056 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
4057 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
4058 SmallVector<SDOperand, 4> MaskVec;
4059 for (unsigned i = 0; i < 4; ++i)
4060 MaskVec.push_back(DAG.getConstant((i == Idx) ? i+4 : i, MaskEVT));
4061 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
4062 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4063 &MaskVec[0], MaskVec.size()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004064}
4065
4066SDOperand
4067X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
4068 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4069 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
4070}
4071
4072// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4073// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4074// one of the above mentioned nodes. It has to be wrapped because otherwise
4075// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4076// be used to form addressing mode. These wrapped nodes will be selected
4077// into MOV32ri.
4078SDOperand
4079X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4080 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4081 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4082 getPointerTy(),
4083 CP->getAlignment());
4084 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4085 // With PIC, the address is actually $g + Offset.
4086 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4087 !Subtarget->isPICStyleRIPRel()) {
4088 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4089 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4090 Result);
4091 }
4092
4093 return Result;
4094}
4095
4096SDOperand
4097X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4098 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4099 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4100 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4101 // With PIC, the address is actually $g + Offset.
4102 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4103 !Subtarget->isPICStyleRIPRel()) {
4104 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4105 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4106 Result);
4107 }
4108
4109 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4110 // load the value at address GV, not the value of GV itself. This means that
4111 // the GlobalAddress must be in the base or index register of the address, not
4112 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4113 // The same applies for external symbols during PIC codegen
4114 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4115 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
4116
4117 return Result;
4118}
4119
4120// Lower ISD::GlobalTLSAddress using the "general dynamic" model
4121static SDOperand
4122LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4123 const MVT::ValueType PtrVT) {
4124 SDOperand InFlag;
4125 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4126 DAG.getNode(X86ISD::GlobalBaseReg,
4127 PtrVT), InFlag);
4128 InFlag = Chain.getValue(1);
4129
4130 // emit leal symbol@TLSGD(,%ebx,1), %eax
4131 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4132 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4133 GA->getValueType(0),
4134 GA->getOffset());
4135 SDOperand Ops[] = { Chain, TGA, InFlag };
4136 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4137 InFlag = Result.getValue(2);
4138 Chain = Result.getValue(1);
4139
4140 // call ___tls_get_addr. This function receives its argument in
4141 // the register EAX.
4142 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4143 InFlag = Chain.getValue(1);
4144
4145 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4146 SDOperand Ops1[] = { Chain,
4147 DAG.getTargetExternalSymbol("___tls_get_addr",
4148 PtrVT),
4149 DAG.getRegister(X86::EAX, PtrVT),
4150 DAG.getRegister(X86::EBX, PtrVT),
4151 InFlag };
4152 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4153 InFlag = Chain.getValue(1);
4154
4155 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4156}
4157
4158// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4159// "local exec" model.
4160static SDOperand
4161LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4162 const MVT::ValueType PtrVT) {
4163 // Get the Thread Pointer
4164 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4165 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4166 // exec)
4167 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4168 GA->getValueType(0),
4169 GA->getOffset());
4170 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4171
4172 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4173 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
4174
4175 // The address of the thread local variable is the add of the thread
4176 // pointer with the offset of the variable.
4177 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4178}
4179
4180SDOperand
4181X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4182 // TODO: implement the "local dynamic" model
4183 // TODO: implement the "initial exec"model for pic executables
4184 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4185 "TLS not implemented for non-ELF and 64-bit targets");
4186 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4187 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4188 // otherwise use the "Local Exec"TLS Model
4189 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4190 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4191 else
4192 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4193}
4194
4195SDOperand
4196X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4197 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4198 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4199 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4200 // With PIC, the address is actually $g + Offset.
4201 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4202 !Subtarget->isPICStyleRIPRel()) {
4203 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4204 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4205 Result);
4206 }
4207
4208 return Result;
4209}
4210
4211SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4212 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4213 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4214 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4215 // With PIC, the address is actually $g + Offset.
4216 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4217 !Subtarget->isPICStyleRIPRel()) {
4218 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4219 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4220 Result);
4221 }
4222
4223 return Result;
4224}
4225
Chris Lattner62814a32007-10-17 06:02:13 +00004226/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4227/// take a 2 x i32 value to shift plus a shift amount.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004228SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner62814a32007-10-17 06:02:13 +00004229 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4230 "Not an i64 shift!");
4231 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4232 SDOperand ShOpLo = Op.getOperand(0);
4233 SDOperand ShOpHi = Op.getOperand(1);
4234 SDOperand ShAmt = Op.getOperand(2);
4235 SDOperand Tmp1 = isSRA ?
4236 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4237 DAG.getConstant(0, MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004238
Chris Lattner62814a32007-10-17 06:02:13 +00004239 SDOperand Tmp2, Tmp3;
4240 if (Op.getOpcode() == ISD::SHL_PARTS) {
4241 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4242 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4243 } else {
4244 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4245 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4246 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004247
Chris Lattner62814a32007-10-17 06:02:13 +00004248 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4249 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4250 DAG.getConstant(32, MVT::i8));
4251 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4252 AndNode, DAG.getConstant(0, MVT::i8));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004253
Chris Lattner62814a32007-10-17 06:02:13 +00004254 SDOperand Hi, Lo;
4255 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4256 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4257 SmallVector<SDOperand, 4> Ops;
4258 if (Op.getOpcode() == ISD::SHL_PARTS) {
4259 Ops.push_back(Tmp2);
4260 Ops.push_back(Tmp3);
4261 Ops.push_back(CC);
4262 Ops.push_back(Cond);
4263 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004264
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004265 Ops.clear();
Chris Lattner62814a32007-10-17 06:02:13 +00004266 Ops.push_back(Tmp3);
4267 Ops.push_back(Tmp1);
4268 Ops.push_back(CC);
4269 Ops.push_back(Cond);
4270 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4271 } else {
4272 Ops.push_back(Tmp2);
4273 Ops.push_back(Tmp3);
4274 Ops.push_back(CC);
4275 Ops.push_back(Cond);
4276 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4277
4278 Ops.clear();
4279 Ops.push_back(Tmp3);
4280 Ops.push_back(Tmp1);
4281 Ops.push_back(CC);
4282 Ops.push_back(Cond);
4283 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4284 }
4285
4286 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4287 Ops.clear();
4288 Ops.push_back(Lo);
4289 Ops.push_back(Hi);
4290 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004291}
4292
4293SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4294 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4295 Op.getOperand(0).getValueType() >= MVT::i16 &&
4296 "Unknown SINT_TO_FP to lower!");
4297
4298 SDOperand Result;
4299 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4300 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4301 MachineFunction &MF = DAG.getMachineFunction();
4302 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4303 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4304 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4305 StackSlot, NULL, 0);
4306
Dale Johannesen2fc20782007-09-14 22:26:36 +00004307 // These are really Legal; caller falls through into that case.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004308 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
4309 return Result;
4310 if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
Dale Johannesen2fc20782007-09-14 22:26:36 +00004311 return Result;
Dale Johannesen958b08b2007-09-19 23:55:34 +00004312 if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 &&
4313 Subtarget->is64Bit())
4314 return Result;
Dale Johannesen2fc20782007-09-14 22:26:36 +00004315
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004316 // Build the FILD
4317 SDVTList Tys;
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004318 bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
4319 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
Dale Johannesen2fc20782007-09-14 22:26:36 +00004320 if (useSSE)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004321 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4322 else
4323 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4324 SmallVector<SDOperand, 8> Ops;
4325 Ops.push_back(Chain);
4326 Ops.push_back(StackSlot);
4327 Ops.push_back(DAG.getValueType(SrcVT));
Dale Johannesen2fc20782007-09-14 22:26:36 +00004328 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004329 Tys, &Ops[0], Ops.size());
4330
Dale Johannesen2fc20782007-09-14 22:26:36 +00004331 if (useSSE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004332 Chain = Result.getValue(1);
4333 SDOperand InFlag = Result.getValue(2);
4334
4335 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4336 // shouldn't be necessary except that RFP cannot be live across
4337 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4338 MachineFunction &MF = DAG.getMachineFunction();
4339 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4340 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4341 Tys = DAG.getVTList(MVT::Other);
4342 SmallVector<SDOperand, 8> Ops;
4343 Ops.push_back(Chain);
4344 Ops.push_back(Result);
4345 Ops.push_back(StackSlot);
4346 Ops.push_back(DAG.getValueType(Op.getValueType()));
4347 Ops.push_back(InFlag);
4348 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4349 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
4350 }
4351
4352 return Result;
4353}
4354
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004355std::pair<SDOperand,SDOperand> X86TargetLowering::
4356FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004357 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4358 "Unknown FP_TO_SINT to lower!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004359
Dale Johannesen2fc20782007-09-14 22:26:36 +00004360 // These are really Legal.
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004361 if (Op.getValueType() == MVT::i32 &&
4362 X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004363 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004364 if (Op.getValueType() == MVT::i32 &&
4365 X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004366 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesen958b08b2007-09-19 23:55:34 +00004367 if (Subtarget->is64Bit() &&
4368 Op.getValueType() == MVT::i64 &&
4369 Op.getOperand(0).getValueType() != MVT::f80)
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004370 return std::make_pair(SDOperand(), SDOperand());
Dale Johannesen2fc20782007-09-14 22:26:36 +00004371
Evan Cheng05441e62007-10-15 20:11:21 +00004372 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4373 // stack slot.
4374 MachineFunction &MF = DAG.getMachineFunction();
4375 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4376 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4377 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004378 unsigned Opc;
4379 switch (Op.getValueType()) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004380 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4381 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4382 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4383 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004384 }
4385
4386 SDOperand Chain = DAG.getEntryNode();
4387 SDOperand Value = Op.getOperand(0);
Dale Johannesene0e0fd02007-09-23 14:52:20 +00004388 if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
4389 (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004390 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4391 Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
4392 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4393 SDOperand Ops[] = {
4394 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4395 };
4396 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4397 Chain = Value.getValue(1);
4398 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4399 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4400 }
4401
4402 // Build the FP_TO_INT*_IN_MEM
4403 SDOperand Ops[] = { Chain, Value, StackSlot };
4404 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4405
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004406 return std::make_pair(FIST, StackSlot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004407}
4408
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004409SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00004410 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4411 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4412 if (FIST.Val == 0) return SDOperand();
4413
4414 // Load the result.
4415 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4416}
4417
4418SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4419 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4420 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4421 if (FIST.Val == 0) return 0;
4422
4423 // Return an i64 load from the stack slot.
4424 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4425
4426 // Use a MERGE_VALUES node to drop the chain result value.
4427 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4428}
4429
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004430SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4431 MVT::ValueType VT = Op.getValueType();
4432 MVT::ValueType EltVT = VT;
4433 if (MVT::isVector(VT))
4434 EltVT = MVT::getVectorElementType(VT);
4435 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4436 std::vector<Constant*> CV;
4437 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004438 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004439 CV.push_back(C);
4440 CV.push_back(C);
4441 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004442 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004443 CV.push_back(C);
4444 CV.push_back(C);
4445 CV.push_back(C);
4446 CV.push_back(C);
4447 }
Dan Gohman11821702007-07-27 17:16:43 +00004448 Constant *C = ConstantVector::get(CV);
4449 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4450 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4451 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004452 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4453}
4454
4455SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4456 MVT::ValueType VT = Op.getValueType();
4457 MVT::ValueType EltVT = VT;
Evan Cheng92b8f782007-07-19 23:36:01 +00004458 unsigned EltNum = 1;
4459 if (MVT::isVector(VT)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004460 EltVT = MVT::getVectorElementType(VT);
Evan Cheng92b8f782007-07-19 23:36:01 +00004461 EltNum = MVT::getVectorNumElements(VT);
4462 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004463 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4464 std::vector<Constant*> CV;
4465 if (EltVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004466 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004467 CV.push_back(C);
4468 CV.push_back(C);
4469 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004470 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004471 CV.push_back(C);
4472 CV.push_back(C);
4473 CV.push_back(C);
4474 CV.push_back(C);
4475 }
Dan Gohman11821702007-07-27 17:16:43 +00004476 Constant *C = ConstantVector::get(CV);
4477 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4478 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4479 false, 16);
Evan Cheng92b8f782007-07-19 23:36:01 +00004480 if (MVT::isVector(VT)) {
Evan Cheng92b8f782007-07-19 23:36:01 +00004481 return DAG.getNode(ISD::BIT_CONVERT, VT,
4482 DAG.getNode(ISD::XOR, MVT::v2i64,
4483 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4484 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4485 } else {
Evan Cheng92b8f782007-07-19 23:36:01 +00004486 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4487 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004488}
4489
4490SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4491 SDOperand Op0 = Op.getOperand(0);
4492 SDOperand Op1 = Op.getOperand(1);
4493 MVT::ValueType VT = Op.getValueType();
4494 MVT::ValueType SrcVT = Op1.getValueType();
4495 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4496
4497 // If second operand is smaller, extend it first.
4498 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4499 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4500 SrcVT = VT;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00004501 SrcTy = MVT::getTypeForValueType(SrcVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004502 }
Dale Johannesenfb0fa912007-10-21 01:07:44 +00004503 // And if it is bigger, shrink it first.
4504 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4505 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4506 SrcVT = VT;
4507 SrcTy = MVT::getTypeForValueType(SrcVT);
4508 }
4509
4510 // At this point the operands and the result should have the same
4511 // type, and that won't be f80 since that is not custom lowered.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004512
4513 // First get the sign bit of second operand.
4514 std::vector<Constant*> CV;
4515 if (SrcVT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004516 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4517 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004518 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004519 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4520 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4521 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4522 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004523 }
Dan Gohman11821702007-07-27 17:16:43 +00004524 Constant *C = ConstantVector::get(CV);
4525 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4526 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4527 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004528 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4529
4530 // Shift sign bit right or left if the two operands have different types.
4531 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4532 // Op0 is MVT::f32, Op1 is MVT::f64.
4533 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4534 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4535 DAG.getConstant(32, MVT::i32));
4536 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4537 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4538 DAG.getConstant(0, getPointerTy()));
4539 }
4540
4541 // Clear first operand sign bit.
4542 CV.clear();
4543 if (VT == MVT::f64) {
Dale Johannesen1616e902007-09-11 18:32:33 +00004544 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4545 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004546 } else {
Dale Johannesen1616e902007-09-11 18:32:33 +00004547 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4548 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4549 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4550 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004551 }
Dan Gohman11821702007-07-27 17:16:43 +00004552 C = ConstantVector::get(CV);
4553 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4554 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4555 false, 16);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004556 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4557
4558 // Or the value with the sign bit.
4559 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4560}
4561
Evan Cheng621216e2007-09-29 00:00:36 +00004562SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
Evan Cheng950aac02007-09-25 01:57:46 +00004563 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
Evan Cheng6afec3d2007-09-26 00:45:55 +00004564 SDOperand Cond;
Evan Cheng950aac02007-09-25 01:57:46 +00004565 SDOperand Op0 = Op.getOperand(0);
4566 SDOperand Op1 = Op.getOperand(1);
4567 SDOperand CC = Op.getOperand(2);
4568 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4569 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4570 unsigned X86CC;
4571
Evan Cheng950aac02007-09-25 01:57:46 +00004572 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
Evan Cheng6afec3d2007-09-26 00:45:55 +00004573 Op0, Op1, DAG)) {
Evan Cheng621216e2007-09-29 00:00:36 +00004574 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4575 return DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004576 DAG.getConstant(X86CC, MVT::i8), Cond);
Evan Cheng6afec3d2007-09-26 00:45:55 +00004577 }
Evan Cheng950aac02007-09-25 01:57:46 +00004578
4579 assert(isFP && "Illegal integer SetCC!");
4580
Evan Cheng621216e2007-09-29 00:00:36 +00004581 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
Evan Cheng950aac02007-09-25 01:57:46 +00004582 switch (SetCCOpcode) {
4583 default: assert(false && "Illegal floating point SetCC!");
4584 case ISD::SETOEQ: { // !PF & ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004585 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004586 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004587 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004588 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4589 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4590 }
4591 case ISD::SETUNE: { // PF | !ZF
Evan Cheng621216e2007-09-29 00:00:36 +00004592 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004593 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004594 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
Evan Cheng950aac02007-09-25 01:57:46 +00004595 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4596 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4597 }
4598 }
4599}
4600
4601
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004602SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4603 bool addTest = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004604 SDOperand Cond = Op.getOperand(0);
4605 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004606
4607 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004608 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004609
Evan Cheng50d37ab2007-10-08 22:16:29 +00004610 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4611 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004612 if (Cond.getOpcode() == X86ISD::SETCC) {
4613 CC = Cond.getOperand(0);
4614
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004615 SDOperand Cmp = Cond.getOperand(1);
4616 unsigned Opc = Cmp.getOpcode();
Evan Cheng50d37ab2007-10-08 22:16:29 +00004617 MVT::ValueType VT = Op.getValueType();
4618 bool IllegalFPCMov = false;
4619 if (VT == MVT::f32 && !X86ScalarSSEf32)
4620 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4621 else if (VT == MVT::f64 && !X86ScalarSSEf64)
4622 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Dale Johannesen3b955db2007-10-16 18:09:08 +00004623 else if (VT == MVT::f80)
4624 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
Evan Cheng621216e2007-09-29 00:00:36 +00004625 if ((Opc == X86ISD::CMP ||
4626 Opc == X86ISD::COMI ||
4627 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004628 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004629 addTest = false;
4630 }
4631 }
4632
4633 if (addTest) {
4634 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng50d37ab2007-10-08 22:16:29 +00004635 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004636 }
4637
4638 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4639 MVT::Flag);
4640 SmallVector<SDOperand, 4> Ops;
4641 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4642 // condition is true.
4643 Ops.push_back(Op.getOperand(2));
4644 Ops.push_back(Op.getOperand(1));
4645 Ops.push_back(CC);
4646 Ops.push_back(Cond);
Evan Cheng621216e2007-09-29 00:00:36 +00004647 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
Evan Cheng950aac02007-09-25 01:57:46 +00004648}
4649
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004650SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4651 bool addTest = true;
4652 SDOperand Chain = Op.getOperand(0);
4653 SDOperand Cond = Op.getOperand(1);
4654 SDOperand Dest = Op.getOperand(2);
4655 SDOperand CC;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004656
4657 if (Cond.getOpcode() == ISD::SETCC)
Evan Cheng621216e2007-09-29 00:00:36 +00004658 Cond = LowerSETCC(Cond, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004659
Evan Cheng50d37ab2007-10-08 22:16:29 +00004660 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4661 // setting operand in place of the X86ISD::SETCC.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004662 if (Cond.getOpcode() == X86ISD::SETCC) {
4663 CC = Cond.getOperand(0);
4664
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004665 SDOperand Cmp = Cond.getOperand(1);
4666 unsigned Opc = Cmp.getOpcode();
Evan Cheng621216e2007-09-29 00:00:36 +00004667 if (Opc == X86ISD::CMP ||
4668 Opc == X86ISD::COMI ||
4669 Opc == X86ISD::UCOMI) {
Evan Cheng50d37ab2007-10-08 22:16:29 +00004670 Cond = Cmp;
Evan Cheng950aac02007-09-25 01:57:46 +00004671 addTest = false;
4672 }
4673 }
4674
4675 if (addTest) {
4676 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
Evan Cheng621216e2007-09-29 00:00:36 +00004677 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
Evan Cheng950aac02007-09-25 01:57:46 +00004678 }
Evan Cheng621216e2007-09-29 00:00:36 +00004679 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
Evan Cheng950aac02007-09-25 01:57:46 +00004680 Chain, Op.getOperand(2), CC, Cond);
4681}
4682
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004683SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004684 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4685 bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004686
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004687 if (Subtarget->is64Bit())
4688 if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4689 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4690 else
4691 return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004692 else
4693 switch (CallingConv) {
4694 default:
4695 assert(0 && "Unsupported calling convention");
4696 case CallingConv::Fast:
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00004697 if (isTailCall && PerformTailCallOpt)
4698 return LowerX86_TailCallTo(Op, DAG, CallingConv);
4699 else
4700 return LowerCCCCallTo(Op,DAG, CallingConv);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004701 case CallingConv::C:
4702 case CallingConv::X86_StdCall:
4703 return LowerCCCCallTo(Op, DAG, CallingConv);
4704 case CallingConv::X86_FastCall:
4705 return LowerFastCCCallTo(Op, DAG, CallingConv);
4706 }
4707}
4708
4709
4710// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4711// Calls to _alloca is needed to probe the stack when allocating more than 4k
4712// bytes in one go. Touching the stack at 4K increments is necessary to ensure
4713// that the guard pages used by the OS virtual memory manager are allocated in
4714// correct sequence.
4715SDOperand
4716X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4717 SelectionDAG &DAG) {
4718 assert(Subtarget->isTargetCygMing() &&
4719 "This should be used only on Cygwin/Mingw targets");
4720
4721 // Get the inputs.
4722 SDOperand Chain = Op.getOperand(0);
4723 SDOperand Size = Op.getOperand(1);
4724 // FIXME: Ensure alignment here
4725
4726 SDOperand Flag;
4727
4728 MVT::ValueType IntPtr = getPointerTy();
4729 MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4730
4731 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4732 Flag = Chain.getValue(1);
4733
4734 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4735 SDOperand Ops[] = { Chain,
4736 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4737 DAG.getRegister(X86::EAX, IntPtr),
4738 Flag };
4739 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4740 Flag = Chain.getValue(1);
4741
4742 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4743
4744 std::vector<MVT::ValueType> Tys;
4745 Tys.push_back(SPTy);
4746 Tys.push_back(MVT::Other);
4747 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4748 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4749}
4750
4751SDOperand
4752X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4753 MachineFunction &MF = DAG.getMachineFunction();
4754 const Function* Fn = MF.getFunction();
4755 if (Fn->hasExternalLinkage() &&
4756 Subtarget->isTargetCygMing() &&
4757 Fn->getName() == "main")
4758 MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4759
4760 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4761 if (Subtarget->is64Bit())
4762 return LowerX86_64CCCArguments(Op, DAG);
4763 else
4764 switch(CC) {
4765 default:
4766 assert(0 && "Unsupported calling convention");
4767 case CallingConv::Fast:
Gordon Henriksen6bbcc672008-01-03 16:47:34 +00004768 return LowerCCCArguments(Op, DAG, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004769 case CallingConv::C:
4770 return LowerCCCArguments(Op, DAG);
4771 case CallingConv::X86_StdCall:
4772 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4773 return LowerCCCArguments(Op, DAG, true);
4774 case CallingConv::X86_FastCall:
4775 MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4776 return LowerFastCCArguments(Op, DAG);
4777 }
4778}
4779
4780SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4781 SDOperand InFlag(0, 0);
4782 SDOperand Chain = Op.getOperand(0);
4783 unsigned Align =
4784 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4785 if (Align == 0) Align = 1;
4786
4787 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
Rafael Espindola5d3e7622007-08-27 10:18:20 +00004788 // If not DWORD aligned or size is more than the threshold, call memset.
Rafael Espindolab2e7a6b2007-08-27 17:48:26 +00004789 // The libc version is likely to be faster for these cases. It can use the
4790 // address value and run time information about the CPU.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004791 if ((Align & 3) != 0 ||
Rafael Espindola7afa9b12007-10-31 11:52:06 +00004792 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004793 MVT::ValueType IntPtr = getPointerTy();
4794 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4795 TargetLowering::ArgListTy Args;
4796 TargetLowering::ArgListEntry Entry;
4797 Entry.Node = Op.getOperand(1);
4798 Entry.Ty = IntPtrTy;
4799 Args.push_back(Entry);
4800 // Extend the unsigned i8 argument to be an int value for the call.
4801 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4802 Entry.Ty = IntPtrTy;
4803 Args.push_back(Entry);
4804 Entry.Node = Op.getOperand(3);
4805 Args.push_back(Entry);
4806 std::pair<SDOperand,SDOperand> CallResult =
4807 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4808 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4809 return CallResult.second;
4810 }
4811
4812 MVT::ValueType AVT;
4813 SDOperand Count;
4814 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4815 unsigned BytesLeft = 0;
4816 bool TwoRepStos = false;
4817 if (ValC) {
4818 unsigned ValReg;
4819 uint64_t Val = ValC->getValue() & 255;
4820
4821 // If the value is a constant, then we can potentially use larger sets.
4822 switch (Align & 3) {
4823 case 2: // WORD aligned
4824 AVT = MVT::i16;
4825 ValReg = X86::AX;
4826 Val = (Val << 8) | Val;
4827 break;
4828 case 0: // DWORD aligned
4829 AVT = MVT::i32;
4830 ValReg = X86::EAX;
4831 Val = (Val << 8) | Val;
4832 Val = (Val << 16) | Val;
4833 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4834 AVT = MVT::i64;
4835 ValReg = X86::RAX;
4836 Val = (Val << 32) | Val;
4837 }
4838 break;
4839 default: // Byte aligned
4840 AVT = MVT::i8;
4841 ValReg = X86::AL;
4842 Count = Op.getOperand(3);
4843 break;
4844 }
4845
4846 if (AVT > MVT::i8) {
4847 if (I) {
4848 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4849 Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4850 BytesLeft = I->getValue() % UBytes;
4851 } else {
4852 assert(AVT >= MVT::i32 &&
4853 "Do not use rep;stos if not at least DWORD aligned");
4854 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4855 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4856 TwoRepStos = true;
4857 }
4858 }
4859
4860 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4861 InFlag);
4862 InFlag = Chain.getValue(1);
4863 } else {
4864 AVT = MVT::i8;
4865 Count = Op.getOperand(3);
4866 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4867 InFlag = Chain.getValue(1);
4868 }
4869
4870 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4871 Count, InFlag);
4872 InFlag = Chain.getValue(1);
4873 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4874 Op.getOperand(1), InFlag);
4875 InFlag = Chain.getValue(1);
4876
4877 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4878 SmallVector<SDOperand, 8> Ops;
4879 Ops.push_back(Chain);
4880 Ops.push_back(DAG.getValueType(AVT));
4881 Ops.push_back(InFlag);
4882 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4883
4884 if (TwoRepStos) {
4885 InFlag = Chain.getValue(1);
4886 Count = Op.getOperand(3);
4887 MVT::ValueType CVT = Count.getValueType();
4888 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4889 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4890 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4891 Left, InFlag);
4892 InFlag = Chain.getValue(1);
4893 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4894 Ops.clear();
4895 Ops.push_back(Chain);
4896 Ops.push_back(DAG.getValueType(MVT::i8));
4897 Ops.push_back(InFlag);
4898 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4899 } else if (BytesLeft) {
4900 // Issue stores for the last 1 - 7 bytes.
4901 SDOperand Value;
4902 unsigned Val = ValC->getValue() & 255;
4903 unsigned Offset = I->getValue() - BytesLeft;
4904 SDOperand DstAddr = Op.getOperand(1);
4905 MVT::ValueType AddrVT = DstAddr.getValueType();
4906 if (BytesLeft >= 4) {
4907 Val = (Val << 8) | Val;
4908 Val = (Val << 16) | Val;
4909 Value = DAG.getConstant(Val, MVT::i32);
4910 Chain = DAG.getStore(Chain, Value,
4911 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4912 DAG.getConstant(Offset, AddrVT)),
4913 NULL, 0);
4914 BytesLeft -= 4;
4915 Offset += 4;
4916 }
4917 if (BytesLeft >= 2) {
4918 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4919 Chain = DAG.getStore(Chain, Value,
4920 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4921 DAG.getConstant(Offset, AddrVT)),
4922 NULL, 0);
4923 BytesLeft -= 2;
4924 Offset += 2;
4925 }
4926 if (BytesLeft == 1) {
4927 Value = DAG.getConstant(Val, MVT::i8);
4928 Chain = DAG.getStore(Chain, Value,
4929 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4930 DAG.getConstant(Offset, AddrVT)),
4931 NULL, 0);
4932 }
4933 }
4934
4935 return Chain;
4936}
4937
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004938SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4939 SDOperand Dest,
4940 SDOperand Source,
4941 unsigned Size,
4942 unsigned Align,
4943 SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004944 MVT::ValueType AVT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004945 unsigned BytesLeft = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004946 switch (Align & 3) {
4947 case 2: // WORD aligned
4948 AVT = MVT::i16;
4949 break;
4950 case 0: // DWORD aligned
4951 AVT = MVT::i32;
4952 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4953 AVT = MVT::i64;
4954 break;
4955 default: // Byte aligned
4956 AVT = MVT::i8;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004957 break;
4958 }
4959
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004960 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4961 SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4962 BytesLeft = Size % UBytes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004963
4964 SDOperand InFlag(0, 0);
4965 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4966 Count, InFlag);
4967 InFlag = Chain.getValue(1);
4968 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004969 Dest, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004970 InFlag = Chain.getValue(1);
4971 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004972 Source, InFlag);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004973 InFlag = Chain.getValue(1);
4974
4975 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4976 SmallVector<SDOperand, 8> Ops;
4977 Ops.push_back(Chain);
4978 Ops.push_back(DAG.getValueType(AVT));
4979 Ops.push_back(InFlag);
4980 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4981
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004982 if (BytesLeft) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004983 // Issue loads and stores for the last 1 - 7 bytes.
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004984 unsigned Offset = Size - BytesLeft;
4985 SDOperand DstAddr = Dest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004986 MVT::ValueType DstVT = DstAddr.getValueType();
Rafael Espindolaf12f3a92007-09-28 12:53:01 +00004987 SDOperand SrcAddr = Source;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004988 MVT::ValueType SrcVT = SrcAddr.getValueType();
4989 SDOperand Value;
4990 if (BytesLeft >= 4) {
4991 Value = DAG.getLoad(MVT::i32, Chain,
4992 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4993 DAG.getConstant(Offset, SrcVT)),
4994 NULL, 0);
4995 Chain = Value.getValue(1);
4996 Chain = DAG.getStore(Chain, Value,
4997 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4998 DAG.getConstant(Offset, DstVT)),
4999 NULL, 0);
5000 BytesLeft -= 4;
5001 Offset += 4;
5002 }
5003 if (BytesLeft >= 2) {
5004 Value = DAG.getLoad(MVT::i16, Chain,
5005 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
5006 DAG.getConstant(Offset, SrcVT)),
5007 NULL, 0);
5008 Chain = Value.getValue(1);
5009 Chain = DAG.getStore(Chain, Value,
5010 DAG.getNode(ISD::ADD, DstVT, DstAddr,
5011 DAG.getConstant(Offset, DstVT)),
5012 NULL, 0);
5013 BytesLeft -= 2;
5014 Offset += 2;
5015 }
5016
5017 if (BytesLeft == 1) {
5018 Value = DAG.getLoad(MVT::i8, Chain,
5019 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
5020 DAG.getConstant(Offset, SrcVT)),
5021 NULL, 0);
5022 Chain = Value.getValue(1);
5023 Chain = DAG.getStore(Chain, Value,
5024 DAG.getNode(ISD::ADD, DstVT, DstAddr,
5025 DAG.getConstant(Offset, DstVT)),
5026 NULL, 0);
5027 }
5028 }
5029
5030 return Chain;
5031}
5032
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005033/// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5034SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005036 SDOperand TheChain = N->getOperand(0);
5037 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005038 if (Subtarget->is64Bit()) {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005039 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5040 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5041 MVT::i64, rax.getValue(2));
5042 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005043 DAG.getConstant(32, MVT::i8));
5044 SDOperand Ops[] = {
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005045 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005046 };
5047
5048 Tys = DAG.getVTList(MVT::i64, MVT::Other);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005049 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005050 }
5051
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005052 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5053 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5054 MVT::i32, eax.getValue(2));
5055 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
5056 SDOperand Ops[] = { eax, edx };
5057 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5058
5059 // Use a MERGE_VALUES to return the value and chain.
5060 Ops[1] = edx.getValue(1);
5061 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5062 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005063}
5064
5065SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
5066 SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
5067
5068 if (!Subtarget->is64Bit()) {
5069 // vastart just stores the address of the VarArgsFrameIndex slot into the
5070 // memory location argument.
5071 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5072 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
5073 SV->getOffset());
5074 }
5075
5076 // __va_list_tag:
5077 // gp_offset (0 - 6 * 8)
5078 // fp_offset (48 - 48 + 8 * 16)
5079 // overflow_arg_area (point to parameters coming in memory).
5080 // reg_save_area
5081 SmallVector<SDOperand, 8> MemOps;
5082 SDOperand FIN = Op.getOperand(1);
5083 // Store gp_offset
5084 SDOperand Store = DAG.getStore(Op.getOperand(0),
5085 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5086 FIN, SV->getValue(), SV->getOffset());
5087 MemOps.push_back(Store);
5088
5089 // Store fp_offset
5090 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5091 DAG.getConstant(4, getPointerTy()));
5092 Store = DAG.getStore(Op.getOperand(0),
5093 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5094 FIN, SV->getValue(), SV->getOffset());
5095 MemOps.push_back(Store);
5096
5097 // Store ptr to overflow_arg_area
5098 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5099 DAG.getConstant(4, getPointerTy()));
5100 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5101 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
5102 SV->getOffset());
5103 MemOps.push_back(Store);
5104
5105 // Store ptr to reg_save_area.
5106 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
5107 DAG.getConstant(8, getPointerTy()));
5108 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5109 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
5110 SV->getOffset());
5111 MemOps.push_back(Store);
5112 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5113}
5114
5115SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
5116 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5117 SDOperand Chain = Op.getOperand(0);
5118 SDOperand DstPtr = Op.getOperand(1);
5119 SDOperand SrcPtr = Op.getOperand(2);
5120 SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
5121 SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
5122
5123 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
5124 SrcSV->getValue(), SrcSV->getOffset());
5125 Chain = SrcPtr.getValue(1);
5126 for (unsigned i = 0; i < 3; ++i) {
5127 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
5128 SrcSV->getValue(), SrcSV->getOffset());
5129 Chain = Val.getValue(1);
5130 Chain = DAG.getStore(Chain, Val, DstPtr,
5131 DstSV->getValue(), DstSV->getOffset());
5132 if (i == 2)
5133 break;
5134 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
5135 DAG.getConstant(8, getPointerTy()));
5136 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
5137 DAG.getConstant(8, getPointerTy()));
5138 }
5139 return Chain;
5140}
5141
5142SDOperand
5143X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5144 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5145 switch (IntNo) {
5146 default: return SDOperand(); // Don't custom lower most intrinsics.
5147 // Comparison intrinsics.
5148 case Intrinsic::x86_sse_comieq_ss:
5149 case Intrinsic::x86_sse_comilt_ss:
5150 case Intrinsic::x86_sse_comile_ss:
5151 case Intrinsic::x86_sse_comigt_ss:
5152 case Intrinsic::x86_sse_comige_ss:
5153 case Intrinsic::x86_sse_comineq_ss:
5154 case Intrinsic::x86_sse_ucomieq_ss:
5155 case Intrinsic::x86_sse_ucomilt_ss:
5156 case Intrinsic::x86_sse_ucomile_ss:
5157 case Intrinsic::x86_sse_ucomigt_ss:
5158 case Intrinsic::x86_sse_ucomige_ss:
5159 case Intrinsic::x86_sse_ucomineq_ss:
5160 case Intrinsic::x86_sse2_comieq_sd:
5161 case Intrinsic::x86_sse2_comilt_sd:
5162 case Intrinsic::x86_sse2_comile_sd:
5163 case Intrinsic::x86_sse2_comigt_sd:
5164 case Intrinsic::x86_sse2_comige_sd:
5165 case Intrinsic::x86_sse2_comineq_sd:
5166 case Intrinsic::x86_sse2_ucomieq_sd:
5167 case Intrinsic::x86_sse2_ucomilt_sd:
5168 case Intrinsic::x86_sse2_ucomile_sd:
5169 case Intrinsic::x86_sse2_ucomigt_sd:
5170 case Intrinsic::x86_sse2_ucomige_sd:
5171 case Intrinsic::x86_sse2_ucomineq_sd: {
5172 unsigned Opc = 0;
5173 ISD::CondCode CC = ISD::SETCC_INVALID;
5174 switch (IntNo) {
5175 default: break;
5176 case Intrinsic::x86_sse_comieq_ss:
5177 case Intrinsic::x86_sse2_comieq_sd:
5178 Opc = X86ISD::COMI;
5179 CC = ISD::SETEQ;
5180 break;
5181 case Intrinsic::x86_sse_comilt_ss:
5182 case Intrinsic::x86_sse2_comilt_sd:
5183 Opc = X86ISD::COMI;
5184 CC = ISD::SETLT;
5185 break;
5186 case Intrinsic::x86_sse_comile_ss:
5187 case Intrinsic::x86_sse2_comile_sd:
5188 Opc = X86ISD::COMI;
5189 CC = ISD::SETLE;
5190 break;
5191 case Intrinsic::x86_sse_comigt_ss:
5192 case Intrinsic::x86_sse2_comigt_sd:
5193 Opc = X86ISD::COMI;
5194 CC = ISD::SETGT;
5195 break;
5196 case Intrinsic::x86_sse_comige_ss:
5197 case Intrinsic::x86_sse2_comige_sd:
5198 Opc = X86ISD::COMI;
5199 CC = ISD::SETGE;
5200 break;
5201 case Intrinsic::x86_sse_comineq_ss:
5202 case Intrinsic::x86_sse2_comineq_sd:
5203 Opc = X86ISD::COMI;
5204 CC = ISD::SETNE;
5205 break;
5206 case Intrinsic::x86_sse_ucomieq_ss:
5207 case Intrinsic::x86_sse2_ucomieq_sd:
5208 Opc = X86ISD::UCOMI;
5209 CC = ISD::SETEQ;
5210 break;
5211 case Intrinsic::x86_sse_ucomilt_ss:
5212 case Intrinsic::x86_sse2_ucomilt_sd:
5213 Opc = X86ISD::UCOMI;
5214 CC = ISD::SETLT;
5215 break;
5216 case Intrinsic::x86_sse_ucomile_ss:
5217 case Intrinsic::x86_sse2_ucomile_sd:
5218 Opc = X86ISD::UCOMI;
5219 CC = ISD::SETLE;
5220 break;
5221 case Intrinsic::x86_sse_ucomigt_ss:
5222 case Intrinsic::x86_sse2_ucomigt_sd:
5223 Opc = X86ISD::UCOMI;
5224 CC = ISD::SETGT;
5225 break;
5226 case Intrinsic::x86_sse_ucomige_ss:
5227 case Intrinsic::x86_sse2_ucomige_sd:
5228 Opc = X86ISD::UCOMI;
5229 CC = ISD::SETGE;
5230 break;
5231 case Intrinsic::x86_sse_ucomineq_ss:
5232 case Intrinsic::x86_sse2_ucomineq_sd:
5233 Opc = X86ISD::UCOMI;
5234 CC = ISD::SETNE;
5235 break;
5236 }
5237
5238 unsigned X86CC;
5239 SDOperand LHS = Op.getOperand(1);
5240 SDOperand RHS = Op.getOperand(2);
5241 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5242
Evan Cheng621216e2007-09-29 00:00:36 +00005243 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5244 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5245 DAG.getConstant(X86CC, MVT::i8), Cond);
5246 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005247 }
5248 }
5249}
5250
5251SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5252 // Depths > 0 not supported yet!
5253 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5254 return SDOperand();
5255
5256 // Just load the return address
5257 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5258 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5259}
5260
5261SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5262 // Depths > 0 not supported yet!
5263 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5264 return SDOperand();
5265
5266 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5267 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5268 DAG.getConstant(4, getPointerTy()));
5269}
5270
5271SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5272 SelectionDAG &DAG) {
5273 // Is not yet supported on x86-64
5274 if (Subtarget->is64Bit())
5275 return SDOperand();
5276
5277 return DAG.getConstant(8, getPointerTy());
5278}
5279
5280SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5281{
5282 assert(!Subtarget->is64Bit() &&
5283 "Lowering of eh_return builtin is not supported yet on x86-64");
5284
5285 MachineFunction &MF = DAG.getMachineFunction();
5286 SDOperand Chain = Op.getOperand(0);
5287 SDOperand Offset = Op.getOperand(1);
5288 SDOperand Handler = Op.getOperand(2);
5289
5290 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5291 getPointerTy());
5292
5293 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5294 DAG.getConstant(-4UL, getPointerTy()));
5295 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5296 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5297 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
Chris Lattner1b989192007-12-31 04:13:23 +00005298 MF.getRegInfo().addLiveOut(X86::ECX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005299
5300 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5301 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5302}
5303
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005304SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5305 SelectionDAG &DAG) {
5306 SDOperand Root = Op.getOperand(0);
5307 SDOperand Trmp = Op.getOperand(1); // trampoline
5308 SDOperand FPtr = Op.getOperand(2); // nested function
5309 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5310
5311 SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
5312
5313 if (Subtarget->is64Bit()) {
5314 return SDOperand(); // not yet supported
5315 } else {
5316 Function *Func = (Function *)
5317 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5318 unsigned CC = Func->getCallingConv();
Duncan Sands466eadd2007-08-29 19:01:20 +00005319 unsigned NestReg;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005320
5321 switch (CC) {
5322 default:
5323 assert(0 && "Unsupported calling convention");
5324 case CallingConv::C:
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005325 case CallingConv::X86_StdCall: {
5326 // Pass 'nest' parameter in ECX.
5327 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00005328 NestReg = X86::ECX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005329
5330 // Check that ECX wasn't needed by an 'inreg' parameter.
5331 const FunctionType *FTy = Func->getFunctionType();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00005332 const ParamAttrsList *Attrs = Func->getParamAttrs();
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005333
5334 if (Attrs && !Func->isVarArg()) {
5335 unsigned InRegCount = 0;
5336 unsigned Idx = 1;
5337
5338 for (FunctionType::param_iterator I = FTy->param_begin(),
5339 E = FTy->param_end(); I != E; ++I, ++Idx)
5340 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5341 // FIXME: should only count parameters that are lowered to integers.
5342 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5343
5344 if (InRegCount > 2) {
5345 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5346 abort();
5347 }
5348 }
5349 break;
5350 }
5351 case CallingConv::X86_FastCall:
5352 // Pass 'nest' parameter in EAX.
5353 // Must be kept in sync with X86CallingConv.td
Duncan Sands466eadd2007-08-29 19:01:20 +00005354 NestReg = X86::EAX;
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005355 break;
5356 }
5357
Duncan Sands466eadd2007-08-29 19:01:20 +00005358 const X86InstrInfo *TII =
5359 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5360
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005361 SDOperand OutChains[4];
5362 SDOperand Addr, Disp;
5363
5364 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5365 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5366
Duncan Sands466eadd2007-08-29 19:01:20 +00005367 unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
Chris Lattnerd8559ce2007-12-16 20:26:54 +00005368 unsigned char N86Reg = ((X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
Duncan Sands466eadd2007-08-29 19:01:20 +00005369 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005370 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
5371
5372 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5373 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
5374 TrmpSV->getOffset() + 1, false, 1);
5375
Duncan Sands466eadd2007-08-29 19:01:20 +00005376 unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005377 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5378 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5379 TrmpSV->getValue() + 5, TrmpSV->getOffset());
5380
5381 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5382 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
5383 TrmpSV->getOffset() + 6, false, 1);
5384
Duncan Sands7407a9f2007-09-11 14:10:23 +00005385 SDOperand Ops[] =
5386 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5387 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005388 }
5389}
5390
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005391SDOperand X86TargetLowering::LowerFLT_ROUNDS(SDOperand Op, SelectionDAG &DAG) {
5392 /*
5393 The rounding mode is in bits 11:10 of FPSR, and has the following
5394 settings:
5395 00 Round to nearest
5396 01 Round to -inf
5397 10 Round to +inf
5398 11 Round to 0
5399
5400 FLT_ROUNDS, on the other hand, expects the following:
5401 -1 Undefined
5402 0 Round to 0
5403 1 Round to nearest
5404 2 Round to +inf
5405 3 Round to -inf
5406
5407 To perform the conversion, we do:
5408 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5409 */
5410
5411 MachineFunction &MF = DAG.getMachineFunction();
5412 const TargetMachine &TM = MF.getTarget();
5413 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5414 unsigned StackAlignment = TFI.getStackAlignment();
5415 MVT::ValueType VT = Op.getValueType();
5416
5417 // Save FP Control Word to stack slot
5418 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5419 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5420
5421 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5422 DAG.getEntryNode(), StackSlot);
5423
5424 // Load FP Control Word from stack slot
5425 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5426
5427 // Transform as necessary
5428 SDOperand CWD1 =
5429 DAG.getNode(ISD::SRL, MVT::i16,
5430 DAG.getNode(ISD::AND, MVT::i16,
5431 CWD, DAG.getConstant(0x800, MVT::i16)),
5432 DAG.getConstant(11, MVT::i8));
5433 SDOperand CWD2 =
5434 DAG.getNode(ISD::SRL, MVT::i16,
5435 DAG.getNode(ISD::AND, MVT::i16,
5436 CWD, DAG.getConstant(0x400, MVT::i16)),
5437 DAG.getConstant(9, MVT::i8));
5438
5439 SDOperand RetVal =
5440 DAG.getNode(ISD::AND, MVT::i16,
5441 DAG.getNode(ISD::ADD, MVT::i16,
5442 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5443 DAG.getConstant(1, MVT::i16)),
5444 DAG.getConstant(3, MVT::i16));
5445
5446
5447 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5448 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5449}
5450
Evan Cheng48679f42007-12-14 02:13:44 +00005451SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5452 MVT::ValueType VT = Op.getValueType();
5453 MVT::ValueType OpVT = VT;
5454 unsigned NumBits = MVT::getSizeInBits(VT);
5455
5456 Op = Op.getOperand(0);
5457 if (VT == MVT::i8) {
Evan Cheng7cfbfe32007-12-14 08:30:15 +00005458 // Zero extend to i32 since there is not an i8 bsr.
Evan Cheng48679f42007-12-14 02:13:44 +00005459 OpVT = MVT::i32;
5460 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5461 }
Evan Cheng48679f42007-12-14 02:13:44 +00005462
Evan Cheng7cfbfe32007-12-14 08:30:15 +00005463 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5464 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5465 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5466
5467 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5468 SmallVector<SDOperand, 4> Ops;
5469 Ops.push_back(Op);
5470 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5471 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5472 Ops.push_back(Op.getValue(1));
5473 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5474
5475 // Finally xor with NumBits-1.
5476 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5477
Evan Cheng48679f42007-12-14 02:13:44 +00005478 if (VT == MVT::i8)
5479 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5480 return Op;
5481}
5482
5483SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5484 MVT::ValueType VT = Op.getValueType();
5485 MVT::ValueType OpVT = VT;
Evan Cheng7cfbfe32007-12-14 08:30:15 +00005486 unsigned NumBits = MVT::getSizeInBits(VT);
Evan Cheng48679f42007-12-14 02:13:44 +00005487
5488 Op = Op.getOperand(0);
5489 if (VT == MVT::i8) {
5490 OpVT = MVT::i32;
5491 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5492 }
Evan Cheng7cfbfe32007-12-14 08:30:15 +00005493
5494 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5495 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5496 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5497
5498 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5499 SmallVector<SDOperand, 4> Ops;
5500 Ops.push_back(Op);
5501 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5502 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5503 Ops.push_back(Op.getValue(1));
5504 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5505
Evan Cheng48679f42007-12-14 02:13:44 +00005506 if (VT == MVT::i8)
5507 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5508 return Op;
5509}
5510
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005511/// LowerOperation - Provide custom lowering hooks for some operations.
5512///
5513SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5514 switch (Op.getOpcode()) {
5515 default: assert(0 && "Should not custom lower this!");
5516 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5517 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5518 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5519 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5520 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5521 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5522 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5523 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5524 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5525 case ISD::SHL_PARTS:
5526 case ISD::SRA_PARTS:
5527 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5528 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5529 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5530 case ISD::FABS: return LowerFABS(Op, DAG);
5531 case ISD::FNEG: return LowerFNEG(Op, DAG);
5532 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
Evan Cheng621216e2007-09-29 00:00:36 +00005533 case ISD::SETCC: return LowerSETCC(Op, DAG);
5534 case ISD::SELECT: return LowerSELECT(Op, DAG);
5535 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005536 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5537 case ISD::CALL: return LowerCALL(Op, DAG);
5538 case ISD::RET: return LowerRET(Op, DAG);
5539 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5540 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5541 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005542 case ISD::VASTART: return LowerVASTART(Op, DAG);
5543 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5544 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5545 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5546 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5547 case ISD::FRAME_TO_ARGS_OFFSET:
5548 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5549 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5550 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
Duncan Sandsd8455ca2007-07-27 20:02:49 +00005551 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005552 case ISD::FLT_ROUNDS: return LowerFLT_ROUNDS(Op, DAG);
Evan Cheng48679f42007-12-14 02:13:44 +00005553 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5554 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005555
5556 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5557 case ISD::READCYCLECOUNTER:
5558 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005559 }
Chris Lattnerdfb947d2007-11-24 07:07:01 +00005560}
5561
5562/// ExpandOperation - Provide custom lowering hooks for expanding operations.
5563SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5564 switch (N->getOpcode()) {
5565 default: assert(0 && "Should not custom lower this!");
5566 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5567 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5568 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005569}
5570
5571const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5572 switch (Opcode) {
5573 default: return NULL;
Evan Cheng48679f42007-12-14 02:13:44 +00005574 case X86ISD::BSF: return "X86ISD::BSF";
5575 case X86ISD::BSR: return "X86ISD::BSR";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005576 case X86ISD::SHLD: return "X86ISD::SHLD";
5577 case X86ISD::SHRD: return "X86ISD::SHRD";
5578 case X86ISD::FAND: return "X86ISD::FAND";
5579 case X86ISD::FOR: return "X86ISD::FOR";
5580 case X86ISD::FXOR: return "X86ISD::FXOR";
5581 case X86ISD::FSRL: return "X86ISD::FSRL";
5582 case X86ISD::FILD: return "X86ISD::FILD";
5583 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5584 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5585 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5586 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5587 case X86ISD::FLD: return "X86ISD::FLD";
5588 case X86ISD::FST: return "X86ISD::FST";
5589 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5590 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5591 case X86ISD::CALL: return "X86ISD::CALL";
5592 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5593 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5594 case X86ISD::CMP: return "X86ISD::CMP";
5595 case X86ISD::COMI: return "X86ISD::COMI";
5596 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5597 case X86ISD::SETCC: return "X86ISD::SETCC";
5598 case X86ISD::CMOV: return "X86ISD::CMOV";
5599 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5600 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5601 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5602 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005603 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5604 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5605 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5606 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5607 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5608 case X86ISD::FMAX: return "X86ISD::FMAX";
5609 case X86ISD::FMIN: return "X86ISD::FMIN";
5610 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5611 case X86ISD::FRCP: return "X86ISD::FRCP";
5612 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5613 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5614 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005615 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
Anton Korobeynikovfbe230e2007-11-16 01:31:51 +00005616 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005617 }
5618}
5619
5620// isLegalAddressingMode - Return true if the addressing mode represented
5621// by AM is legal for this target, for a load/store of the specified type.
5622bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5623 const Type *Ty) const {
5624 // X86 supports extremely general addressing modes.
5625
5626 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5627 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5628 return false;
5629
5630 if (AM.BaseGV) {
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005631 // We can only fold this if we don't need an extra load.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005632 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5633 return false;
Evan Cheng6a1f3f12007-08-01 23:46:47 +00005634
5635 // X86-64 only supports addr of globals in small code model.
5636 if (Subtarget->is64Bit()) {
5637 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5638 return false;
5639 // If lower 4G is not available, then we must use rip-relative addressing.
5640 if (AM.BaseOffs || AM.Scale > 1)
5641 return false;
5642 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005643 }
5644
5645 switch (AM.Scale) {
5646 case 0:
5647 case 1:
5648 case 2:
5649 case 4:
5650 case 8:
5651 // These scales always work.
5652 break;
5653 case 3:
5654 case 5:
5655 case 9:
5656 // These scales are formed with basereg+scalereg. Only accept if there is
5657 // no basereg yet.
5658 if (AM.HasBaseReg)
5659 return false;
5660 break;
5661 default: // Other stuff never works.
5662 return false;
5663 }
5664
5665 return true;
5666}
5667
5668
Evan Cheng27a820a2007-10-26 01:56:11 +00005669bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5670 if (!Ty1->isInteger() || !Ty2->isInteger())
5671 return false;
Evan Cheng7f152602007-10-29 07:57:50 +00005672 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5673 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5674 if (NumBits1 <= NumBits2)
5675 return false;
5676 return Subtarget->is64Bit() || NumBits1 < 64;
Evan Cheng27a820a2007-10-26 01:56:11 +00005677}
5678
Evan Cheng9decb332007-10-29 19:58:20 +00005679bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5680 MVT::ValueType VT2) const {
5681 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5682 return false;
5683 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5684 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5685 if (NumBits1 <= NumBits2)
5686 return false;
5687 return Subtarget->is64Bit() || NumBits1 < 64;
5688}
Evan Cheng27a820a2007-10-26 01:56:11 +00005689
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005690/// isShuffleMaskLegal - Targets can use this to indicate that they only
5691/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5692/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5693/// are assumed to be legal.
5694bool
5695X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5696 // Only do shuffles on 128-bit vector types for now.
5697 if (MVT::getSizeInBits(VT) == 64) return false;
5698 return (Mask.Val->getNumOperands() <= 4 ||
5699 isIdentityMask(Mask.Val) ||
5700 isIdentityMask(Mask.Val, true) ||
5701 isSplatMask(Mask.Val) ||
5702 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5703 X86::isUNPCKLMask(Mask.Val) ||
5704 X86::isUNPCKHMask(Mask.Val) ||
5705 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5706 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5707}
5708
5709bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5710 MVT::ValueType EVT,
5711 SelectionDAG &DAG) const {
5712 unsigned NumElts = BVOps.size();
5713 // Only do shuffles on 128-bit vector types for now.
5714 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5715 if (NumElts == 2) return true;
5716 if (NumElts == 4) {
5717 return (isMOVLMask(&BVOps[0], 4) ||
5718 isCommutedMOVL(&BVOps[0], 4, true) ||
5719 isSHUFPMask(&BVOps[0], 4) ||
5720 isCommutedSHUFP(&BVOps[0], 4));
5721 }
5722 return false;
5723}
5724
5725//===----------------------------------------------------------------------===//
5726// X86 Scheduler Hooks
5727//===----------------------------------------------------------------------===//
5728
5729MachineBasicBlock *
5730X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5731 MachineBasicBlock *BB) {
5732 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5733 switch (MI->getOpcode()) {
5734 default: assert(false && "Unexpected instr type to insert");
5735 case X86::CMOV_FR32:
5736 case X86::CMOV_FR64:
5737 case X86::CMOV_V4F32:
5738 case X86::CMOV_V2F64:
Evan Cheng621216e2007-09-29 00:00:36 +00005739 case X86::CMOV_V2I64: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005740 // To "insert" a SELECT_CC instruction, we actually have to insert the
5741 // diamond control-flow pattern. The incoming instruction knows the
5742 // destination vreg to set, the condition code register to branch on, the
5743 // true/false values to select between, and a branch opcode to use.
5744 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5745 ilist<MachineBasicBlock>::iterator It = BB;
5746 ++It;
5747
5748 // thisMBB:
5749 // ...
5750 // TrueVal = ...
5751 // cmpTY ccX, r1, r2
5752 // bCC copy1MBB
5753 // fallthrough --> copy0MBB
5754 MachineBasicBlock *thisMBB = BB;
5755 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5756 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5757 unsigned Opc =
5758 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5759 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5760 MachineFunction *F = BB->getParent();
5761 F->getBasicBlockList().insert(It, copy0MBB);
5762 F->getBasicBlockList().insert(It, sinkMBB);
5763 // Update machine-CFG edges by first adding all successors of the current
5764 // block to the new block which will contain the Phi node for the select.
5765 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5766 e = BB->succ_end(); i != e; ++i)
5767 sinkMBB->addSuccessor(*i);
5768 // Next, remove all successors of the current block, and add the true
5769 // and fallthrough blocks as its successors.
5770 while(!BB->succ_empty())
5771 BB->removeSuccessor(BB->succ_begin());
5772 BB->addSuccessor(copy0MBB);
5773 BB->addSuccessor(sinkMBB);
5774
5775 // copy0MBB:
5776 // %FalseValue = ...
5777 // # fallthrough to sinkMBB
5778 BB = copy0MBB;
5779
5780 // Update machine-CFG edges
5781 BB->addSuccessor(sinkMBB);
5782
5783 // sinkMBB:
5784 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5785 // ...
5786 BB = sinkMBB;
5787 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5788 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5789 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5790
5791 delete MI; // The pseudo instruction is gone now.
5792 return BB;
5793 }
5794
5795 case X86::FP32_TO_INT16_IN_MEM:
5796 case X86::FP32_TO_INT32_IN_MEM:
5797 case X86::FP32_TO_INT64_IN_MEM:
5798 case X86::FP64_TO_INT16_IN_MEM:
5799 case X86::FP64_TO_INT32_IN_MEM:
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005800 case X86::FP64_TO_INT64_IN_MEM:
5801 case X86::FP80_TO_INT16_IN_MEM:
5802 case X86::FP80_TO_INT32_IN_MEM:
5803 case X86::FP80_TO_INT64_IN_MEM: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005804 // Change the floating point control register to use "round towards zero"
5805 // mode when truncating to an integer value.
5806 MachineFunction *F = BB->getParent();
5807 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5808 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5809
5810 // Load the old value of the high byte of the control word...
5811 unsigned OldCW =
Chris Lattner1b989192007-12-31 04:13:23 +00005812 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005813 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5814
5815 // Set the high part to be round to zero...
5816 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5817 .addImm(0xC7F);
5818
5819 // Reload the modified control word now...
5820 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5821
5822 // Restore the memory image of control word to original value
5823 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5824 .addReg(OldCW);
5825
5826 // Get the X86 opcode to use.
5827 unsigned Opc;
5828 switch (MI->getOpcode()) {
5829 default: assert(0 && "illegal opcode!");
5830 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5831 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5832 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5833 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5834 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5835 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
Dale Johannesen6d0e36a2007-08-07 01:17:37 +00005836 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5837 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5838 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005839 }
5840
5841 X86AddressMode AM;
5842 MachineOperand &Op = MI->getOperand(0);
5843 if (Op.isRegister()) {
5844 AM.BaseType = X86AddressMode::RegBase;
5845 AM.Base.Reg = Op.getReg();
5846 } else {
5847 AM.BaseType = X86AddressMode::FrameIndexBase;
Chris Lattner6017d482007-12-30 23:10:15 +00005848 AM.Base.FrameIndex = Op.getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005849 }
5850 Op = MI->getOperand(1);
5851 if (Op.isImmediate())
5852 AM.Scale = Op.getImm();
5853 Op = MI->getOperand(2);
5854 if (Op.isImmediate())
5855 AM.IndexReg = Op.getImm();
5856 Op = MI->getOperand(3);
5857 if (Op.isGlobalAddress()) {
5858 AM.GV = Op.getGlobal();
5859 } else {
5860 AM.Disp = Op.getImm();
5861 }
5862 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5863 .addReg(MI->getOperand(4).getReg());
5864
5865 // Reload the original control word now.
5866 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5867
5868 delete MI; // The pseudo instruction is gone now.
5869 return BB;
5870 }
5871 }
5872}
5873
5874//===----------------------------------------------------------------------===//
5875// X86 Optimization Hooks
5876//===----------------------------------------------------------------------===//
5877
5878void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5879 uint64_t Mask,
5880 uint64_t &KnownZero,
5881 uint64_t &KnownOne,
5882 const SelectionDAG &DAG,
5883 unsigned Depth) const {
5884 unsigned Opc = Op.getOpcode();
5885 assert((Opc >= ISD::BUILTIN_OP_END ||
5886 Opc == ISD::INTRINSIC_WO_CHAIN ||
5887 Opc == ISD::INTRINSIC_W_CHAIN ||
5888 Opc == ISD::INTRINSIC_VOID) &&
5889 "Should use MaskedValueIsZero if you don't know whether Op"
5890 " is a target node!");
5891
5892 KnownZero = KnownOne = 0; // Don't know anything.
5893 switch (Opc) {
5894 default: break;
5895 case X86ISD::SETCC:
5896 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5897 break;
5898 }
5899}
5900
5901/// getShuffleScalarElt - Returns the scalar element that will make up the ith
5902/// element of the result of the vector shuffle.
5903static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5904 MVT::ValueType VT = N->getValueType(0);
5905 SDOperand PermMask = N->getOperand(2);
5906 unsigned NumElems = PermMask.getNumOperands();
5907 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5908 i %= NumElems;
5909 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5910 return (i == 0)
Arnold Schwaighofere2d6bbb2007-10-11 19:40:01 +00005911 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005912 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5913 SDOperand Idx = PermMask.getOperand(i);
5914 if (Idx.getOpcode() == ISD::UNDEF)
5915 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5916 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5917 }
5918 return SDOperand();
5919}
5920
5921/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5922/// node is a GlobalAddress + an offset.
5923static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5924 unsigned Opc = N->getOpcode();
5925 if (Opc == X86ISD::Wrapper) {
5926 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5927 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5928 return true;
5929 }
5930 } else if (Opc == ISD::ADD) {
5931 SDOperand N1 = N->getOperand(0);
5932 SDOperand N2 = N->getOperand(1);
5933 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5934 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5935 if (V) {
5936 Offset += V->getSignExtended();
5937 return true;
5938 }
5939 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5940 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5941 if (V) {
5942 Offset += V->getSignExtended();
5943 return true;
5944 }
5945 }
5946 }
5947 return false;
5948}
5949
5950/// isConsecutiveLoad - Returns true if N is loading from an address of Base
5951/// + Dist * Size.
5952static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5953 MachineFrameInfo *MFI) {
5954 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5955 return false;
5956
5957 SDOperand Loc = N->getOperand(1);
5958 SDOperand BaseLoc = Base->getOperand(1);
5959 if (Loc.getOpcode() == ISD::FrameIndex) {
5960 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5961 return false;
Dan Gohman53491e92007-07-23 20:24:29 +00005962 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5963 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005964 int FS = MFI->getObjectSize(FI);
5965 int BFS = MFI->getObjectSize(BFI);
5966 if (FS != BFS || FS != Size) return false;
5967 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5968 } else {
5969 GlobalValue *GV1 = NULL;
5970 GlobalValue *GV2 = NULL;
5971 int64_t Offset1 = 0;
5972 int64_t Offset2 = 0;
5973 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5974 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5975 if (isGA1 && isGA2 && GV1 == GV2)
5976 return Offset1 == (Offset2 + Dist*Size);
5977 }
5978
5979 return false;
5980}
5981
5982static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5983 const X86Subtarget *Subtarget) {
5984 GlobalValue *GV;
5985 int64_t Offset;
5986 if (isGAPlusOffset(Base, GV, Offset))
5987 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5988 else {
5989 assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
Dan Gohman53491e92007-07-23 20:24:29 +00005990 int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005991 if (BFI < 0)
5992 // Fixed objects do not specify alignment, however the offsets are known.
5993 return ((Subtarget->getStackAlignment() % 16) == 0 &&
5994 (MFI->getObjectOffset(BFI) % 16) == 0);
5995 else
5996 return MFI->getObjectAlignment(BFI) >= 16;
5997 }
5998 return false;
5999}
6000
6001
6002/// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6003/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6004/// if the load addresses are consecutive, non-overlapping, and in the right
6005/// order.
6006static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6007 const X86Subtarget *Subtarget) {
6008 MachineFunction &MF = DAG.getMachineFunction();
6009 MachineFrameInfo *MFI = MF.getFrameInfo();
6010 MVT::ValueType VT = N->getValueType(0);
6011 MVT::ValueType EVT = MVT::getVectorElementType(VT);
6012 SDOperand PermMask = N->getOperand(2);
6013 int NumElems = (int)PermMask.getNumOperands();
6014 SDNode *Base = NULL;
6015 for (int i = 0; i < NumElems; ++i) {
6016 SDOperand Idx = PermMask.getOperand(i);
6017 if (Idx.getOpcode() == ISD::UNDEF) {
6018 if (!Base) return SDOperand();
6019 } else {
6020 SDOperand Arg =
6021 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
6022 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
6023 return SDOperand();
6024 if (!Base)
6025 Base = Arg.Val;
6026 else if (!isConsecutiveLoad(Arg.Val, Base,
6027 i, MVT::getSizeInBits(EVT)/8,MFI))
6028 return SDOperand();
6029 }
6030 }
6031
6032 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
Dan Gohman11821702007-07-27 17:16:43 +00006033 LoadSDNode *LD = cast<LoadSDNode>(Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006034 if (isAlign16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006035 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
Dan Gohman11821702007-07-27 17:16:43 +00006036 LD->getSrcValueOffset(), LD->isVolatile());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006037 } else {
Dan Gohman11821702007-07-27 17:16:43 +00006038 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6039 LD->getSrcValueOffset(), LD->isVolatile(),
6040 LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006041 }
6042}
6043
6044/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6045static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6046 const X86Subtarget *Subtarget) {
6047 SDOperand Cond = N->getOperand(0);
6048
6049 // If we have SSE[12] support, try to form min/max nodes.
6050 if (Subtarget->hasSSE2() &&
6051 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6052 if (Cond.getOpcode() == ISD::SETCC) {
6053 // Get the LHS/RHS of the select.
6054 SDOperand LHS = N->getOperand(1);
6055 SDOperand RHS = N->getOperand(2);
6056 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6057
6058 unsigned Opcode = 0;
6059 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6060 switch (CC) {
6061 default: break;
6062 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6063 case ISD::SETULE:
6064 case ISD::SETLE:
6065 if (!UnsafeFPMath) break;
6066 // FALL THROUGH.
6067 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6068 case ISD::SETLT:
6069 Opcode = X86ISD::FMIN;
6070 break;
6071
6072 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6073 case ISD::SETUGT:
6074 case ISD::SETGT:
6075 if (!UnsafeFPMath) break;
6076 // FALL THROUGH.
6077 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6078 case ISD::SETGE:
6079 Opcode = X86ISD::FMAX;
6080 break;
6081 }
6082 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6083 switch (CC) {
6084 default: break;
6085 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6086 case ISD::SETUGT:
6087 case ISD::SETGT:
6088 if (!UnsafeFPMath) break;
6089 // FALL THROUGH.
6090 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6091 case ISD::SETGE:
6092 Opcode = X86ISD::FMIN;
6093 break;
6094
6095 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6096 case ISD::SETULE:
6097 case ISD::SETLE:
6098 if (!UnsafeFPMath) break;
6099 // FALL THROUGH.
6100 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6101 case ISD::SETLT:
6102 Opcode = X86ISD::FMAX;
6103 break;
6104 }
6105 }
6106
6107 if (Opcode)
6108 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6109 }
6110
6111 }
6112
6113 return SDOperand();
6114}
6115
6116
6117SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6118 DAGCombinerInfo &DCI) const {
6119 SelectionDAG &DAG = DCI.DAG;
6120 switch (N->getOpcode()) {
6121 default: break;
6122 case ISD::VECTOR_SHUFFLE:
6123 return PerformShuffleCombine(N, DAG, Subtarget);
6124 case ISD::SELECT:
6125 return PerformSELECTCombine(N, DAG, Subtarget);
6126 }
6127
6128 return SDOperand();
6129}
6130
6131//===----------------------------------------------------------------------===//
6132// X86 Inline Assembly Support
6133//===----------------------------------------------------------------------===//
6134
6135/// getConstraintType - Given a constraint letter, return the type of
6136/// constraint it is for this target.
6137X86TargetLowering::ConstraintType
6138X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6139 if (Constraint.size() == 1) {
6140 switch (Constraint[0]) {
6141 case 'A':
6142 case 'r':
6143 case 'R':
6144 case 'l':
6145 case 'q':
6146 case 'Q':
6147 case 'x':
6148 case 'Y':
6149 return C_RegisterClass;
6150 default:
6151 break;
6152 }
6153 }
6154 return TargetLowering::getConstraintType(Constraint);
6155}
6156
Chris Lattnera531abc2007-08-25 00:47:38 +00006157/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6158/// vector. If it is invalid, don't add anything to Ops.
6159void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6160 char Constraint,
6161 std::vector<SDOperand>&Ops,
6162 SelectionDAG &DAG) {
6163 SDOperand Result(0, 0);
6164
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006165 switch (Constraint) {
6166 default: break;
6167 case 'I':
6168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00006169 if (C->getValue() <= 31) {
6170 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6171 break;
6172 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006173 }
Chris Lattnera531abc2007-08-25 00:47:38 +00006174 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006175 case 'N':
6176 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
Chris Lattnera531abc2007-08-25 00:47:38 +00006177 if (C->getValue() <= 255) {
6178 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6179 break;
6180 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006181 }
Chris Lattnera531abc2007-08-25 00:47:38 +00006182 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006183 case 'i': {
6184 // Literal immediates are always ok.
Chris Lattnera531abc2007-08-25 00:47:38 +00006185 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6186 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6187 break;
6188 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006189
6190 // If we are in non-pic codegen mode, we allow the address of a global (with
6191 // an optional displacement) to be used with 'i'.
6192 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6193 int64_t Offset = 0;
6194
6195 // Match either (GA) or (GA+C)
6196 if (GA) {
6197 Offset = GA->getOffset();
6198 } else if (Op.getOpcode() == ISD::ADD) {
6199 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6200 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6201 if (C && GA) {
6202 Offset = GA->getOffset()+C->getValue();
6203 } else {
6204 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6205 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6206 if (C && GA)
6207 Offset = GA->getOffset()+C->getValue();
6208 else
6209 C = 0, GA = 0;
6210 }
6211 }
6212
6213 if (GA) {
6214 // If addressing this global requires a load (e.g. in PIC mode), we can't
6215 // match.
6216 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6217 false))
Chris Lattnera531abc2007-08-25 00:47:38 +00006218 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006219
6220 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6221 Offset);
Chris Lattnera531abc2007-08-25 00:47:38 +00006222 Result = Op;
6223 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006224 }
6225
6226 // Otherwise, not valid for this mode.
Chris Lattnera531abc2007-08-25 00:47:38 +00006227 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006228 }
6229 }
Chris Lattnera531abc2007-08-25 00:47:38 +00006230
6231 if (Result.Val) {
6232 Ops.push_back(Result);
6233 return;
6234 }
6235 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006236}
6237
6238std::vector<unsigned> X86TargetLowering::
6239getRegClassForInlineAsmConstraint(const std::string &Constraint,
6240 MVT::ValueType VT) const {
6241 if (Constraint.size() == 1) {
6242 // FIXME: not handling fp-stack yet!
6243 switch (Constraint[0]) { // GCC X86 Constraint Letters
6244 default: break; // Unknown constraint letter
6245 case 'A': // EAX/EDX
6246 if (VT == MVT::i32 || VT == MVT::i64)
6247 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6248 break;
6249 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6250 case 'Q': // Q_REGS
6251 if (VT == MVT::i32)
6252 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6253 else if (VT == MVT::i16)
6254 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6255 else if (VT == MVT::i8)
Evan Chengf85c10f2007-08-13 23:27:11 +00006256 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
Chris Lattner35032592007-11-04 06:51:12 +00006257 else if (VT == MVT::i64)
6258 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6259 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006260 }
6261 }
6262
6263 return std::vector<unsigned>();
6264}
6265
6266std::pair<unsigned, const TargetRegisterClass*>
6267X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6268 MVT::ValueType VT) const {
6269 // First, see if this is a constraint that directly corresponds to an LLVM
6270 // register class.
6271 if (Constraint.size() == 1) {
6272 // GCC Constraint Letters
6273 switch (Constraint[0]) {
6274 default: break;
6275 case 'r': // GENERAL_REGS
6276 case 'R': // LEGACY_REGS
6277 case 'l': // INDEX_REGS
6278 if (VT == MVT::i64 && Subtarget->is64Bit())
6279 return std::make_pair(0U, X86::GR64RegisterClass);
6280 if (VT == MVT::i32)
6281 return std::make_pair(0U, X86::GR32RegisterClass);
6282 else if (VT == MVT::i16)
6283 return std::make_pair(0U, X86::GR16RegisterClass);
6284 else if (VT == MVT::i8)
6285 return std::make_pair(0U, X86::GR8RegisterClass);
6286 break;
6287 case 'y': // MMX_REGS if MMX allowed.
6288 if (!Subtarget->hasMMX()) break;
6289 return std::make_pair(0U, X86::VR64RegisterClass);
6290 break;
6291 case 'Y': // SSE_REGS if SSE2 allowed
6292 if (!Subtarget->hasSSE2()) break;
6293 // FALL THROUGH.
6294 case 'x': // SSE_REGS if SSE1 allowed
6295 if (!Subtarget->hasSSE1()) break;
6296
6297 switch (VT) {
6298 default: break;
6299 // Scalar SSE types.
6300 case MVT::f32:
6301 case MVT::i32:
6302 return std::make_pair(0U, X86::FR32RegisterClass);
6303 case MVT::f64:
6304 case MVT::i64:
6305 return std::make_pair(0U, X86::FR64RegisterClass);
6306 // Vector types.
6307 case MVT::v16i8:
6308 case MVT::v8i16:
6309 case MVT::v4i32:
6310 case MVT::v2i64:
6311 case MVT::v4f32:
6312 case MVT::v2f64:
6313 return std::make_pair(0U, X86::VR128RegisterClass);
6314 }
6315 break;
6316 }
6317 }
6318
6319 // Use the default implementation in TargetLowering to convert the register
6320 // constraint into a member of a register class.
6321 std::pair<unsigned, const TargetRegisterClass*> Res;
6322 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6323
6324 // Not found as a standard register?
6325 if (Res.second == 0) {
6326 // GCC calls "st(0)" just plain "st".
6327 if (StringsEqualNoCase("{st}", Constraint)) {
6328 Res.first = X86::ST0;
Chris Lattner3cfe51b2007-09-24 05:27:37 +00006329 Res.second = X86::RFP80RegisterClass;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006330 }
6331
6332 return Res;
6333 }
6334
6335 // Otherwise, check to see if this is a register class of the wrong value
6336 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6337 // turn into {ax},{dx}.
6338 if (Res.second->hasType(VT))
6339 return Res; // Correct type already, nothing to do.
6340
6341 // All of the single-register GCC register classes map their values onto
6342 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6343 // really want an 8-bit or 32-bit register, map to the appropriate register
6344 // class and return the appropriate register.
6345 if (Res.second != X86::GR16RegisterClass)
6346 return Res;
6347
6348 if (VT == MVT::i8) {
6349 unsigned DestReg = 0;
6350 switch (Res.first) {
6351 default: break;
6352 case X86::AX: DestReg = X86::AL; break;
6353 case X86::DX: DestReg = X86::DL; break;
6354 case X86::CX: DestReg = X86::CL; break;
6355 case X86::BX: DestReg = X86::BL; break;
6356 }
6357 if (DestReg) {
6358 Res.first = DestReg;
6359 Res.second = Res.second = X86::GR8RegisterClass;
6360 }
6361 } else if (VT == MVT::i32) {
6362 unsigned DestReg = 0;
6363 switch (Res.first) {
6364 default: break;
6365 case X86::AX: DestReg = X86::EAX; break;
6366 case X86::DX: DestReg = X86::EDX; break;
6367 case X86::CX: DestReg = X86::ECX; break;
6368 case X86::BX: DestReg = X86::EBX; break;
6369 case X86::SI: DestReg = X86::ESI; break;
6370 case X86::DI: DestReg = X86::EDI; break;
6371 case X86::BP: DestReg = X86::EBP; break;
6372 case X86::SP: DestReg = X86::ESP; break;
6373 }
6374 if (DestReg) {
6375 Res.first = DestReg;
6376 Res.second = Res.second = X86::GR32RegisterClass;
6377 }
6378 } else if (VT == MVT::i64) {
6379 unsigned DestReg = 0;
6380 switch (Res.first) {
6381 default: break;
6382 case X86::AX: DestReg = X86::RAX; break;
6383 case X86::DX: DestReg = X86::RDX; break;
6384 case X86::CX: DestReg = X86::RCX; break;
6385 case X86::BX: DestReg = X86::RBX; break;
6386 case X86::SI: DestReg = X86::RSI; break;
6387 case X86::DI: DestReg = X86::RDI; break;
6388 case X86::BP: DestReg = X86::RBP; break;
6389 case X86::SP: DestReg = X86::RSP; break;
6390 }
6391 if (DestReg) {
6392 Res.first = DestReg;
6393 Res.second = Res.second = X86::GR64RegisterClass;
6394 }
6395 }
6396
6397 return Res;
6398}