x86 doesn't actually want to custom lower v3i32
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
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"
26 #include "llvm/ADT/VectorExtras.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/SSARegMap.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ParameterAttributes.h"
40 using namespace llvm;
41
42 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
43   : TargetLowering(TM) {
44   Subtarget = &TM.getSubtarget<X86Subtarget>();
45   X86ScalarSSEf64 = Subtarget->hasSSE2();
46   X86ScalarSSEf32 = Subtarget->hasSSE1();
47   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
48   
49
50   RegInfo = TM.getRegisterInfo();
51
52   // Set up the TargetLowering object.
53
54   // X86 is weird, it always uses i8 for shift amounts and setcc results.
55   setShiftAmountType(MVT::i8);
56   setSetCCResultType(MVT::i8);
57   setSetCCResultContents(ZeroOrOneSetCCResult);
58   setSchedulingPreference(SchedulingForRegPressure);
59   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
60   setStackPointerRegisterToSaveRestore(X86StackPtr);
61
62   if (Subtarget->isTargetDarwin()) {
63     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
64     setUseUnderscoreSetJmp(false);
65     setUseUnderscoreLongJmp(false);
66   } else if (Subtarget->isTargetMingw()) {
67     // MS runtime is weird: it exports _setjmp, but longjmp!
68     setUseUnderscoreSetJmp(true);
69     setUseUnderscoreLongJmp(false);
70   } else {
71     setUseUnderscoreSetJmp(true);
72     setUseUnderscoreLongJmp(true);
73   }
74   
75   // Set up the register classes.
76   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
77   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
78   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
79   if (Subtarget->is64Bit())
80     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
81
82   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Expand);
83
84   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
85   // operation.
86   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
87   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
88   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
89
90   if (Subtarget->is64Bit()) {
91     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
92     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
93   } else {
94     if (X86ScalarSSEf64)
95       // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
96       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Expand);
97     else
98       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
99   }
100
101   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
102   // this operation.
103   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
104   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
105   // SSE has no i16 to fp conversion, only i32
106   if (X86ScalarSSEf32) {
107     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
108     // f32 and f64 cases are Legal, f80 case is not
109     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
110   } else {
111     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
112     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
113   }
114
115   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
116   // are Legal, f80 is custom lowered.
117   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
118   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
119
120   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
121   // this operation.
122   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
123   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
124
125   if (X86ScalarSSEf32) {
126     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
127     // f32 and f64 cases are Legal, f80 case is not
128     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
129   } else {
130     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
131     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
132   }
133
134   // Handle FP_TO_UINT by promoting the destination to a larger signed
135   // conversion.
136   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
137   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
138   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
139
140   if (Subtarget->is64Bit()) {
141     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
142     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
143   } else {
144     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
145       // Expand FP_TO_UINT into a select.
146       // FIXME: We would like to use a Custom expander here eventually to do
147       // the optimal thing for SSE vs. the default expansion in the legalizer.
148       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
149     else
150       // With SSE3 we can use fisttpll to convert to a signed i64.
151       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
152   }
153
154   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
155   if (!X86ScalarSSEf64) {
156     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
157     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
158   }
159
160   // Scalar integer multiply, multiply-high, divide, and remainder are
161   // lowered to use operations that produce two results, to match the
162   // available instructions. This exposes the two-result form to trivial
163   // CSE, which is able to combine x/y and x%y into a single instruction,
164   // for example. The single-result multiply instructions are introduced
165   // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
166   // is not needed.
167   setOperationAction(ISD::MUL             , MVT::i8    , Expand);
168   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
169   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
170   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
171   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
172   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
173   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
174   setOperationAction(ISD::MUL             , MVT::i16   , Expand);
175   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
176   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
177   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
178   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
179   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
180   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
181   setOperationAction(ISD::MUL             , MVT::i32   , Expand);
182   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
183   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
184   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
185   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
186   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
187   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
188   setOperationAction(ISD::MUL             , MVT::i64   , Expand);
189   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
190   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
191   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
192   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
193   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
194   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
195
196   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
197   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
198   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
199   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
200   setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
201   if (Subtarget->is64Bit())
202     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
203   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
204   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
205   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
206   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
207   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
208   setOperationAction(ISD::FLT_ROUNDS       , MVT::i32  , Custom);
209   
210   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
211   setOperationAction(ISD::CTTZ             , MVT::i8   , Expand);
212   setOperationAction(ISD::CTLZ             , MVT::i8   , Expand);
213   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
214   setOperationAction(ISD::CTTZ             , MVT::i16  , Expand);
215   setOperationAction(ISD::CTLZ             , MVT::i16  , Expand);
216   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
217   setOperationAction(ISD::CTTZ             , MVT::i32  , Expand);
218   setOperationAction(ISD::CTLZ             , MVT::i32  , Expand);
219   if (Subtarget->is64Bit()) {
220     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
221     setOperationAction(ISD::CTTZ           , MVT::i64  , Expand);
222     setOperationAction(ISD::CTLZ           , MVT::i64  , Expand);
223   }
224
225   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
226   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
227
228   // These should be promoted to a larger select which is supported.
229   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
230   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
231   // X86 wants to expand cmov itself.
232   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
233   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
234   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
235   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
236   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
237   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
238   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
239   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
240   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
241   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
242   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
243   if (Subtarget->is64Bit()) {
244     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
245     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
246   }
247   // X86 ret instruction may pop stack.
248   setOperationAction(ISD::RET             , MVT::Other, Custom);
249   if (!Subtarget->is64Bit())
250     setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
251
252   // Darwin ABI issue.
253   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
254   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
255   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
256   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
257   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
258   if (Subtarget->is64Bit()) {
259     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
260     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
261     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
262     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
263   }
264   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
265   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
266   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
267   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
268   // X86 wants to expand memset / memcpy itself.
269   setOperationAction(ISD::MEMSET          , MVT::Other, Custom);
270   setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
271
272   // Use the default ISD::LOCATION expansion.
273   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
274   // FIXME - use subtarget debug flags
275   if (!Subtarget->isTargetDarwin() &&
276       !Subtarget->isTargetELF() &&
277       !Subtarget->isTargetCygMing())
278     setOperationAction(ISD::LABEL, MVT::Other, Expand);
279
280   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
281   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
282   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
283   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
284   if (Subtarget->is64Bit()) {
285     // FIXME: Verify
286     setExceptionPointerRegister(X86::RAX);
287     setExceptionSelectorRegister(X86::RDX);
288   } else {
289     setExceptionPointerRegister(X86::EAX);
290     setExceptionSelectorRegister(X86::EDX);
291   }
292   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
293   
294   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
295
296   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
298   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
299   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
300   if (Subtarget->is64Bit())
301     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
302   else
303     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
304
305   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
306   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
307   if (Subtarget->is64Bit())
308     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
309   if (Subtarget->isTargetCygMing())
310     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
311   else
312     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
313
314   if (X86ScalarSSEf64) {
315     // f32 and f64 use SSE.
316     // Set up the FP register classes.
317     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
318     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
319
320     // Use ANDPD to simulate FABS.
321     setOperationAction(ISD::FABS , MVT::f64, Custom);
322     setOperationAction(ISD::FABS , MVT::f32, Custom);
323
324     // Use XORP to simulate FNEG.
325     setOperationAction(ISD::FNEG , MVT::f64, Custom);
326     setOperationAction(ISD::FNEG , MVT::f32, Custom);
327
328     // Use ANDPD and ORPD to simulate FCOPYSIGN.
329     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
330     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
331
332     // We don't support sin/cos/fmod
333     setOperationAction(ISD::FSIN , MVT::f64, Expand);
334     setOperationAction(ISD::FCOS , MVT::f64, Expand);
335     setOperationAction(ISD::FREM , MVT::f64, Expand);
336     setOperationAction(ISD::FSIN , MVT::f32, Expand);
337     setOperationAction(ISD::FCOS , MVT::f32, Expand);
338     setOperationAction(ISD::FREM , MVT::f32, Expand);
339
340     // Expand FP immediates into loads from the stack, except for the special
341     // cases we handle.
342     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
343     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
344     addLegalFPImmediate(APFloat(+0.0)); // xorpd
345     addLegalFPImmediate(APFloat(+0.0f)); // xorps
346
347     // Conversions to long double (in X87) go through memory.
348     setConvertAction(MVT::f32, MVT::f80, Expand);
349     setConvertAction(MVT::f64, MVT::f80, Expand);
350
351     // Conversions from long double (in X87) go through memory.
352     setConvertAction(MVT::f80, MVT::f32, Expand);
353     setConvertAction(MVT::f80, MVT::f64, Expand);
354   } else if (X86ScalarSSEf32) {
355     // Use SSE for f32, x87 for f64.
356     // Set up the FP register classes.
357     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
358     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
359
360     // Use ANDPS to simulate FABS.
361     setOperationAction(ISD::FABS , MVT::f32, Custom);
362
363     // Use XORP to simulate FNEG.
364     setOperationAction(ISD::FNEG , MVT::f32, Custom);
365
366     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
367
368     // Use ANDPS and ORPS to simulate FCOPYSIGN.
369     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
370     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
371
372     // We don't support sin/cos/fmod
373     setOperationAction(ISD::FSIN , MVT::f32, Expand);
374     setOperationAction(ISD::FCOS , MVT::f32, Expand);
375     setOperationAction(ISD::FREM , MVT::f32, Expand);
376
377     // Expand FP immediates into loads from the stack, except for the special
378     // cases we handle.
379     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
380     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
381     addLegalFPImmediate(APFloat(+0.0f)); // xorps
382     addLegalFPImmediate(APFloat(+0.0)); // FLD0
383     addLegalFPImmediate(APFloat(+1.0)); // FLD1
384     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
385     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
386
387     // SSE->x87 conversions go through memory.
388     setConvertAction(MVT::f32, MVT::f64, Expand);
389     setConvertAction(MVT::f32, MVT::f80, Expand);
390
391     // x87->SSE truncations need to go through memory.
392     setConvertAction(MVT::f80, MVT::f32, Expand);    
393     setConvertAction(MVT::f64, MVT::f32, Expand);
394     // And x87->x87 truncations also.
395     setConvertAction(MVT::f80, MVT::f64, Expand);
396
397     if (!UnsafeFPMath) {
398       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
399       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
400     }
401   } else {
402     // f32 and f64 in x87.
403     // Set up the FP register classes.
404     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
405     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
406
407     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
408     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
409     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
410     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
411
412     // Floating truncations need to go through memory.
413     setConvertAction(MVT::f80, MVT::f32, Expand);    
414     setConvertAction(MVT::f64, MVT::f32, Expand);
415     setConvertAction(MVT::f80, MVT::f64, Expand);
416
417     if (!UnsafeFPMath) {
418       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
419       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
420     }
421
422     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
423     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
424     addLegalFPImmediate(APFloat(+0.0)); // FLD0
425     addLegalFPImmediate(APFloat(+1.0)); // FLD1
426     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
427     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
428     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
429     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
430     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
431     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
432   }
433
434   // Long double always uses X87.
435   addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
436   setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
437   setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
438   setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
439   if (!UnsafeFPMath) {
440     setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
441     setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
442   }
443
444   // Always use a library call for pow.
445   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
446   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
447   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
448
449   // First set operation action for all vector types to expand. Then we
450   // will selectively turn on ones that can be effectively codegen'd.
451   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
452        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
453     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
454     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
455     setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
456     setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
457     setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
458     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
459     setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
460     setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
461     setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
462     setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
463     setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
464     setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
465     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
466     setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::ValueType)VT, Expand);
467     setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
468     setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::ValueType)VT, Expand);
469     setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
470     setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
471     setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
472     setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
473     setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
474     setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
475     setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
476     setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
477     setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
478     setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
479     setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
480     setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
481     setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
482     setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
483     setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
484   }
485
486   if (Subtarget->hasMMX()) {
487     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
488     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
489     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
490     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
491
492     // FIXME: add MMX packed arithmetics
493
494     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
495     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
496     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
497     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
498
499     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
500     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
501     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
502     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
503
504     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
505     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
506
507     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
508     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
509     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
510     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
511     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
512     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
513     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
514
515     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
516     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
517     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
518     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
519     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
520     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
521     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
522
523     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
524     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
525     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
526     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
527     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
528     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
529     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
530
531     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
532     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
533     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
534     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
535     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
536     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
537     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
538
539     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
540     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
541     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
542     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
543
544     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
545     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
546     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
547     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
548
549     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
550     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
551     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Custom);
552     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
553   }
554
555   if (Subtarget->hasSSE1()) {
556     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
557
558     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
559     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
560     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
561     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
562     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
563     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
564     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
565     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
566     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
567     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
568     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
569   }
570
571   if (Subtarget->hasSSE2()) {
572     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
573     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
574     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
575     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
576     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
577
578     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
579     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
580     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
581     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
582     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
583     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
584     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
585     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
586     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
587     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
588     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
589     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
590     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
591     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
592     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
593
594     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
595     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
596     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
597     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
598     // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
599     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
600
601     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
602     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
603       // Do not attempt to custom lower non-power-of-2 vectors
604       if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
605         continue;
606       setOperationAction(ISD::BUILD_VECTOR,        (MVT::ValueType)VT, Custom);
607       setOperationAction(ISD::VECTOR_SHUFFLE,      (MVT::ValueType)VT, Custom);
608       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  (MVT::ValueType)VT, Custom);
609     }
610     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
611     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
612     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
613     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
614     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
615     if (Subtarget->is64Bit())
616       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
617
618     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
619     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
620       setOperationAction(ISD::AND,    (MVT::ValueType)VT, Promote);
621       AddPromotedToType (ISD::AND,    (MVT::ValueType)VT, MVT::v2i64);
622       setOperationAction(ISD::OR,     (MVT::ValueType)VT, Promote);
623       AddPromotedToType (ISD::OR,     (MVT::ValueType)VT, MVT::v2i64);
624       setOperationAction(ISD::XOR,    (MVT::ValueType)VT, Promote);
625       AddPromotedToType (ISD::XOR,    (MVT::ValueType)VT, MVT::v2i64);
626       setOperationAction(ISD::LOAD,   (MVT::ValueType)VT, Promote);
627       AddPromotedToType (ISD::LOAD,   (MVT::ValueType)VT, MVT::v2i64);
628       setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
629       AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
630     }
631
632     // Custom lower v2i64 and v2f64 selects.
633     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
634     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
635     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
636     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
637   }
638
639   // We want to custom lower some of our intrinsics.
640   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
641
642   // We have target-specific dag combine patterns for the following nodes:
643   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
644   setTargetDAGCombine(ISD::SELECT);
645
646   computeRegisterProperties();
647
648   // FIXME: These should be based on subtarget info. Plus, the values should
649   // be smaller when we are in optimizing for size mode.
650   maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
651   maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
652   maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
653   allowUnalignedMemoryAccesses = true; // x86 supports it!
654 }
655
656
657 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
658 /// jumptable.
659 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
660                                                       SelectionDAG &DAG) const {
661   if (usesGlobalOffsetTable())
662     return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
663   if (!Subtarget->isPICStyleRIPRel())
664     return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
665   return Table;
666 }
667
668 //===----------------------------------------------------------------------===//
669 //               Return Value Calling Convention Implementation
670 //===----------------------------------------------------------------------===//
671
672 #include "X86GenCallingConv.inc"
673
674 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
675 /// exists skip possible ISD:TokenFactor.
676 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
677   if (Chain.getOpcode()==X86ISD::TAILCALL) {
678     return Chain;
679   } else if (Chain.getOpcode()==ISD::TokenFactor) {
680     if (Chain.getNumOperands() &&
681         Chain.getOperand(0).getOpcode()==X86ISD::TAILCALL)
682       return Chain.getOperand(0);
683   }
684   return Chain;
685 }
686     
687 /// LowerRET - Lower an ISD::RET node.
688 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
689   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
690   
691   SmallVector<CCValAssign, 16> RVLocs;
692   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
693   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
694   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
695   CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
696     
697   // If this is the first return lowered for this function, add the regs to the
698   // liveout set for the function.
699   if (DAG.getMachineFunction().liveout_empty()) {
700     for (unsigned i = 0; i != RVLocs.size(); ++i)
701       if (RVLocs[i].isRegLoc())
702         DAG.getMachineFunction().addLiveOut(RVLocs[i].getLocReg());
703   }
704   SDOperand Chain = Op.getOperand(0);
705   
706   // Handle tail call return.
707   Chain = GetPossiblePreceedingTailCall(Chain);
708   if (Chain.getOpcode() == X86ISD::TAILCALL) {
709     SDOperand TailCall = Chain;
710     SDOperand TargetAddress = TailCall.getOperand(1);
711     SDOperand StackAdjustment = TailCall.getOperand(2);
712     assert ( ((TargetAddress.getOpcode() == ISD::Register &&
713                (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
714                 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
715               TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
716               TargetAddress.getOpcode() == ISD::TargetGlobalAddress) && 
717              "Expecting an global address, external symbol, or register");
718     assert( StackAdjustment.getOpcode() == ISD::Constant &&
719             "Expecting a const value");
720
721     SmallVector<SDOperand,8> Operands;
722     Operands.push_back(Chain.getOperand(0));
723     Operands.push_back(TargetAddress);
724     Operands.push_back(StackAdjustment);
725     // Copy registers used by the call. Last operand is a flag so it is not
726     // copied.
727     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
728       Operands.push_back(Chain.getOperand(i));
729     }
730     return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0], 
731                        Operands.size());
732   }
733   
734   // Regular return.
735   SDOperand Flag;
736
737   // Copy the result values into the output registers.
738   if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
739       RVLocs[0].getLocReg() != X86::ST0) {
740     for (unsigned i = 0; i != RVLocs.size(); ++i) {
741       CCValAssign &VA = RVLocs[i];
742       assert(VA.isRegLoc() && "Can only return in registers!");
743       Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
744                                Flag);
745       Flag = Chain.getValue(1);
746     }
747   } else {
748     // We need to handle a destination of ST0 specially, because it isn't really
749     // a register.
750     SDOperand Value = Op.getOperand(1);
751     
752     // If this is an FP return with ScalarSSE, we need to move the value from
753     // an XMM register onto the fp-stack.
754     if ((X86ScalarSSEf32 && RVLocs[0].getValVT()==MVT::f32) ||
755         (X86ScalarSSEf64 && RVLocs[0].getValVT()==MVT::f64)) {
756       SDOperand MemLoc;
757         
758       // If this is a load into a scalarsse value, don't store the loaded value
759       // back to the stack, only to reload it: just replace the scalar-sse load.
760       if (ISD::isNON_EXTLoad(Value.Val) &&
761           (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
762         Chain  = Value.getOperand(0);
763         MemLoc = Value.getOperand(1);
764       } else {
765         // Spill the value to memory and reload it into top of stack.
766         unsigned Size = MVT::getSizeInBits(RVLocs[0].getValVT())/8;
767         MachineFunction &MF = DAG.getMachineFunction();
768         int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
769         MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
770         Chain = DAG.getStore(Op.getOperand(0), Value, MemLoc, NULL, 0);
771       }
772       SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other);
773       SDOperand Ops[] = {Chain, MemLoc, DAG.getValueType(RVLocs[0].getValVT())};
774       Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
775       Chain = Value.getValue(1);
776     }
777     
778     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
779     SDOperand Ops[] = { Chain, Value };
780     Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
781     Flag = Chain.getValue(1);
782   }
783   
784   SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
785   if (Flag.Val)
786     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
787   else
788     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
789 }
790
791
792 /// LowerCallResult - Lower the result values of an ISD::CALL into the
793 /// appropriate copies out of appropriate physical registers.  This assumes that
794 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
795 /// being lowered.  The returns a SDNode with the same number of values as the
796 /// ISD::CALL.
797 SDNode *X86TargetLowering::
798 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
799                 unsigned CallingConv, SelectionDAG &DAG) {
800   
801   // Assign locations to each value returned by this call.
802   SmallVector<CCValAssign, 16> RVLocs;
803   bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
804   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
805   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
806
807   
808   SmallVector<SDOperand, 8> ResultVals;
809   
810   // Copy all of the result registers out of their specified physreg.
811   if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
812     for (unsigned i = 0; i != RVLocs.size(); ++i) {
813       Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
814                                  RVLocs[i].getValVT(), InFlag).getValue(1);
815       InFlag = Chain.getValue(2);
816       ResultVals.push_back(Chain.getValue(0));
817     }
818   } else {
819     // Copies from the FP stack are special, as ST0 isn't a valid register
820     // before the fp stackifier runs.
821     
822     // Copy ST0 into an RFP register with FP_GET_RESULT.
823     SDVTList Tys = DAG.getVTList(RVLocs[0].getValVT(), MVT::Other, MVT::Flag);
824     SDOperand GROps[] = { Chain, InFlag };
825     SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
826     Chain  = RetVal.getValue(1);
827     InFlag = RetVal.getValue(2);
828     
829     // If we are using ScalarSSE, store ST(0) to the stack and reload it into
830     // an XMM register.
831     if ((X86ScalarSSEf32 && RVLocs[0].getValVT() == MVT::f32) ||
832         (X86ScalarSSEf64 && RVLocs[0].getValVT() == MVT::f64)) {
833       // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
834       // shouldn't be necessary except that RFP cannot be live across
835       // multiple blocks. When stackifier is fixed, they can be uncoupled.
836       MachineFunction &MF = DAG.getMachineFunction();
837       int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
838       SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
839       SDOperand Ops[] = {
840         Chain, RetVal, StackSlot, DAG.getValueType(RVLocs[0].getValVT()), InFlag
841       };
842       Chain = DAG.getNode(X86ISD::FST, MVT::Other, Ops, 5);
843       RetVal = DAG.getLoad(RVLocs[0].getValVT(), Chain, StackSlot, NULL, 0);
844       Chain = RetVal.getValue(1);
845     }
846     ResultVals.push_back(RetVal);
847   }
848   
849   // Merge everything together with a MERGE_VALUES node.
850   ResultVals.push_back(Chain);
851   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
852                      &ResultVals[0], ResultVals.size()).Val;
853 }
854
855
856 //===----------------------------------------------------------------------===//
857 //                C & StdCall & Fast Calling Convention implementation
858 //===----------------------------------------------------------------------===//
859 //  StdCall calling convention seems to be standard for many Windows' API
860 //  routines and around. It differs from C calling convention just a little:
861 //  callee should clean up the stack, not caller. Symbols should be also
862 //  decorated in some fancy way :) It doesn't support any vector arguments.
863 //  For info on fast calling convention see Fast Calling Convention (tail call)
864 //  implementation LowerX86_32FastCCCallTo.
865
866 /// AddLiveIn - This helper function adds the specified physical register to the
867 /// MachineFunction as a live in value.  It also creates a corresponding virtual
868 /// register for it.
869 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
870                           const TargetRegisterClass *RC) {
871   assert(RC->contains(PReg) && "Not the correct regclass!");
872   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
873   MF.addLiveIn(PReg, VReg);
874   return VReg;
875 }
876
877 // align stack arguments according to platform alignment needed for tail calls
878 unsigned GetAlignedArgumentStackSize(unsigned StackSize, SelectionDAG& DAG);
879
880 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
881                                               const CCValAssign &VA,
882                                               MachineFrameInfo *MFI,
883                                               SDOperand Root, unsigned i) {
884   // Create the nodes corresponding to a load from this parameter slot.
885   int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
886                                   VA.getLocMemOffset());
887   SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
888
889   unsigned Flags =  cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
890
891   if (Flags & ISD::ParamFlags::ByVal)
892     return FIN;
893   else
894     return DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0);
895 }
896
897 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG,
898                                                bool isStdCall) {
899   unsigned NumArgs = Op.Val->getNumValues() - 1;
900   MachineFunction &MF = DAG.getMachineFunction();
901   MachineFrameInfo *MFI = MF.getFrameInfo();
902   SDOperand Root = Op.getOperand(0);
903   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
904   unsigned CC = MF.getFunction()->getCallingConv();
905   // Assign locations to all of the incoming arguments.
906   SmallVector<CCValAssign, 16> ArgLocs;
907   CCState CCInfo(CC, isVarArg,
908                  getTargetMachine(), ArgLocs);
909   // Check for possible tail call calling convention.
910   if (CC == CallingConv::Fast && PerformTailCallOpt) 
911     CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_TailCall);
912   else
913     CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_C);
914   
915   SmallVector<SDOperand, 8> ArgValues;
916   unsigned LastVal = ~0U;
917   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
918     CCValAssign &VA = ArgLocs[i];
919     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
920     // places.
921     assert(VA.getValNo() != LastVal &&
922            "Don't support value assigned to multiple locs yet");
923     LastVal = VA.getValNo();
924     
925     if (VA.isRegLoc()) {
926       MVT::ValueType RegVT = VA.getLocVT();
927       TargetRegisterClass *RC;
928       if (RegVT == MVT::i32)
929         RC = X86::GR32RegisterClass;
930       else {
931         assert(MVT::isVector(RegVT));
932         RC = X86::VR128RegisterClass;
933       }
934       
935       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
936       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
937       
938       // If this is an 8 or 16-bit value, it is really passed promoted to 32
939       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
940       // right size.
941       if (VA.getLocInfo() == CCValAssign::SExt)
942         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
943                                DAG.getValueType(VA.getValVT()));
944       else if (VA.getLocInfo() == CCValAssign::ZExt)
945         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
946                                DAG.getValueType(VA.getValVT()));
947       
948       if (VA.getLocInfo() != CCValAssign::Full)
949         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
950       
951       ArgValues.push_back(ArgValue);
952     } else {
953       assert(VA.isMemLoc());
954       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
955     }
956   }
957   
958   unsigned StackSize = CCInfo.getNextStackOffset();
959   // align stack specially for tail calls
960   if (CC==CallingConv::Fast)
961     StackSize = GetAlignedArgumentStackSize(StackSize,DAG);
962
963   ArgValues.push_back(Root);
964
965   // If the function takes variable number of arguments, make a frame index for
966   // the start of the first vararg value... for expansion of llvm.va_start.
967   if (isVarArg)
968     VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
969
970   // Tail call calling convention (CallingConv::Fast) does not support varargs.
971   assert( !(isVarArg && CC == CallingConv::Fast) && 
972          "CallingConv::Fast does not support varargs.");
973
974   if (isStdCall && !isVarArg && 
975       (CC==CallingConv::Fast && PerformTailCallOpt || CC!=CallingConv::Fast)) {
976     BytesToPopOnReturn  = StackSize;    // Callee pops everything..
977     BytesCallerReserves = 0;
978   } else {
979     BytesToPopOnReturn  = 0; // Callee pops nothing.
980     
981     // If this is an sret function, the return should pop the hidden pointer.
982     if (NumArgs &&
983         (cast<ConstantSDNode>(Op.getOperand(3))->getValue() &
984          ISD::ParamFlags::StructReturn))
985       BytesToPopOnReturn = 4;  
986     
987     BytesCallerReserves = StackSize;
988   }
989     
990   RegSaveFrameIndex = 0xAAAAAAA;  // X86-64 only.
991
992   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
993   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
994
995   // Return the new list of results.
996   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
997                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
998 }
999
1000 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG,
1001                                             unsigned CC) {
1002   SDOperand Chain     = Op.getOperand(0);
1003   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1004   SDOperand Callee    = Op.getOperand(4);
1005   unsigned NumOps     = (Op.getNumOperands() - 5) / 2;
1006  
1007   // Analyze operands of the call, assigning locations to each operand.
1008   SmallVector<CCValAssign, 16> ArgLocs;
1009   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1010   if(CC==CallingConv::Fast && PerformTailCallOpt)
1011     CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1012   else
1013     CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_C);
1014   
1015   // Get a count of how many bytes are to be pushed on the stack.
1016   unsigned NumBytes = CCInfo.getNextStackOffset();
1017   if (CC==CallingConv::Fast)
1018     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1019
1020   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1021
1022   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1023   SmallVector<SDOperand, 8> MemOpChains;
1024
1025   SDOperand StackPtr;
1026
1027   // Walk the register/memloc assignments, inserting copies/loads.
1028   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1029     CCValAssign &VA = ArgLocs[i];
1030     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1031     
1032     // Promote the value if needed.
1033     switch (VA.getLocInfo()) {
1034     default: assert(0 && "Unknown loc info!");
1035     case CCValAssign::Full: break;
1036     case CCValAssign::SExt:
1037       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1038       break;
1039     case CCValAssign::ZExt:
1040       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1041       break;
1042     case CCValAssign::AExt:
1043       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1044       break;
1045     }
1046     
1047     if (VA.isRegLoc()) {
1048       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1049     } else {
1050       assert(VA.isMemLoc());
1051       if (StackPtr.Val == 0)
1052         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1053
1054       MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1055                                              Arg));
1056     }
1057   }
1058
1059   // If the first argument is an sret pointer, remember it.
1060   bool isSRet = NumOps &&
1061     (cast<ConstantSDNode>(Op.getOperand(6))->getValue() &
1062      ISD::ParamFlags::StructReturn);
1063   
1064   if (!MemOpChains.empty())
1065     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1066                         &MemOpChains[0], MemOpChains.size());
1067
1068   // Build a sequence of copy-to-reg nodes chained together with token chain
1069   // and flag operands which copy the outgoing args into registers.
1070   SDOperand InFlag;
1071   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1072     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1073                              InFlag);
1074     InFlag = Chain.getValue(1);
1075   }
1076
1077   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1078   // GOT pointer.
1079   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1080       Subtarget->isPICStyleGOT()) {
1081     Chain = DAG.getCopyToReg(Chain, X86::EBX,
1082                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1083                              InFlag);
1084     InFlag = Chain.getValue(1);
1085   }
1086   
1087   // If the callee is a GlobalAddress node (quite common, every direct call is)
1088   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1089   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1090     // We should use extra load for direct calls to dllimported functions in
1091     // non-JIT mode.
1092     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1093                                         getTargetMachine(), true))
1094       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1095   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1096     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1097
1098   // Returns a chain & a flag for retval copy to use.
1099   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1100   SmallVector<SDOperand, 8> Ops;
1101   Ops.push_back(Chain);
1102   Ops.push_back(Callee);
1103
1104   // Add argument registers to the end of the list so that they are known live
1105   // into the call.
1106   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1107     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1108                                   RegsToPass[i].second.getValueType()));
1109
1110   // Add an implicit use GOT pointer in EBX.
1111   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1112       Subtarget->isPICStyleGOT())
1113     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1114   
1115   if (InFlag.Val)
1116     Ops.push_back(InFlag);
1117  
1118   Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1119   InFlag = Chain.getValue(1);
1120
1121   // Create the CALLSEQ_END node.
1122   unsigned NumBytesForCalleeToPush = 0;
1123
1124   if (CC == CallingConv::X86_StdCall || 
1125       (CC == CallingConv::Fast && PerformTailCallOpt)) {
1126     if (isVarArg)
1127       NumBytesForCalleeToPush = isSRet ? 4 : 0;
1128     else
1129       NumBytesForCalleeToPush = NumBytes;
1130     assert(!(isVarArg && CC==CallingConv::Fast) &&
1131             "CallingConv::Fast does not support varargs.");
1132   } else {
1133     // If this is is a call to a struct-return function, the callee
1134     // pops the hidden struct pointer, so we have to push it back.
1135     // This is common for Darwin/X86, Linux & Mingw32 targets.
1136     NumBytesForCalleeToPush = isSRet ? 4 : 0;
1137   }
1138
1139   Chain = DAG.getCALLSEQ_END(Chain,
1140                              DAG.getConstant(NumBytes, getPointerTy()),
1141                              DAG.getConstant(NumBytesForCalleeToPush,
1142                                              getPointerTy()),
1143                              InFlag);
1144   InFlag = Chain.getValue(1);
1145
1146   // Handle result values, copying them out of physregs into vregs that we
1147   // return.
1148   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1149 }
1150
1151
1152 //===----------------------------------------------------------------------===//
1153 //                   FastCall Calling Convention implementation
1154 //===----------------------------------------------------------------------===//
1155 //
1156 // The X86 'fastcall' calling convention passes up to two integer arguments in
1157 // registers (an appropriate portion of ECX/EDX), passes arguments in C order,
1158 // and requires that the callee pop its arguments off the stack (allowing proper
1159 // tail calls), and has the same return value conventions as C calling convs.
1160 //
1161 // This calling convention always arranges for the callee pop value to be 8n+4
1162 // bytes, which is needed for tail recursion elimination and stack alignment
1163 // reasons.
1164 SDOperand
1165 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
1166   MachineFunction &MF = DAG.getMachineFunction();
1167   MachineFrameInfo *MFI = MF.getFrameInfo();
1168   SDOperand Root = Op.getOperand(0);
1169   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1170
1171   // Assign locations to all of the incoming arguments.
1172   SmallVector<CCValAssign, 16> ArgLocs;
1173   CCState CCInfo(MF.getFunction()->getCallingConv(), isVarArg,
1174                  getTargetMachine(), ArgLocs);
1175   CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_32_FastCall);
1176   
1177   SmallVector<SDOperand, 8> ArgValues;
1178   unsigned LastVal = ~0U;
1179   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1180     CCValAssign &VA = ArgLocs[i];
1181     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1182     // places.
1183     assert(VA.getValNo() != LastVal &&
1184            "Don't support value assigned to multiple locs yet");
1185     LastVal = VA.getValNo();
1186     
1187     if (VA.isRegLoc()) {
1188       MVT::ValueType RegVT = VA.getLocVT();
1189       TargetRegisterClass *RC;
1190       if (RegVT == MVT::i32)
1191         RC = X86::GR32RegisterClass;
1192       else {
1193         assert(MVT::isVector(RegVT));
1194         RC = X86::VR128RegisterClass;
1195       }
1196       
1197       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1198       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1199       
1200       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1201       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1202       // right size.
1203       if (VA.getLocInfo() == CCValAssign::SExt)
1204         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1205                                DAG.getValueType(VA.getValVT()));
1206       else if (VA.getLocInfo() == CCValAssign::ZExt)
1207         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1208                                DAG.getValueType(VA.getValVT()));
1209       
1210       if (VA.getLocInfo() != CCValAssign::Full)
1211         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1212       
1213       ArgValues.push_back(ArgValue);
1214     } else {
1215       assert(VA.isMemLoc());
1216       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1217     }
1218   }
1219   
1220   ArgValues.push_back(Root);
1221
1222   unsigned StackSize = CCInfo.getNextStackOffset();
1223
1224   if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1225     // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1226     // arguments and the arguments after the retaddr has been pushed are
1227     // aligned.
1228     if ((StackSize & 7) == 0)
1229       StackSize += 4;
1230   }
1231
1232   VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1233   RegSaveFrameIndex = 0xAAAAAAA;   // X86-64 only.
1234   BytesToPopOnReturn = StackSize;  // Callee pops all stack arguments.
1235   BytesCallerReserves = 0;
1236
1237   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1238   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1239
1240   // Return the new list of results.
1241   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1242                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1243 }
1244
1245 SDOperand
1246 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1247                                     const SDOperand &StackPtr,
1248                                     const CCValAssign &VA,
1249                                     SDOperand Chain,
1250                                     SDOperand Arg) {
1251   SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1252   PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1253   SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1254   unsigned Flags    = cast<ConstantSDNode>(FlagsOp)->getValue();
1255   if (Flags & ISD::ParamFlags::ByVal) {
1256     unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1257                            ISD::ParamFlags::ByValAlignOffs);
1258
1259     unsigned  Size = (Flags & ISD::ParamFlags::ByValSize) >>
1260         ISD::ParamFlags::ByValSizeOffs;
1261
1262     SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1263     SDOperand  SizeNode = DAG.getConstant(Size, MVT::i32);
1264     SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1265
1266     return DAG.getMemcpy(Chain, PtrOff, Arg, SizeNode, AlignNode,
1267                          AlwaysInline);
1268   } else {
1269     return DAG.getStore(Chain, Arg, PtrOff, NULL, 0);
1270   }
1271 }
1272
1273 SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG,
1274                                                unsigned CC) {
1275   SDOperand Chain     = Op.getOperand(0);
1276   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1277   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1278   SDOperand Callee    = Op.getOperand(4);
1279
1280   // Analyze operands of the call, assigning locations to each operand.
1281   SmallVector<CCValAssign, 16> ArgLocs;
1282   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1283   CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_FastCall);
1284   
1285   // Get a count of how many bytes are to be pushed on the stack.
1286   unsigned NumBytes = CCInfo.getNextStackOffset();
1287
1288   if (!Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows()) {
1289     // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1290     // arguments and the arguments after the retaddr has been pushed are
1291     // aligned.
1292     if ((NumBytes & 7) == 0)
1293       NumBytes += 4;
1294   }
1295
1296   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1297   
1298   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1299   SmallVector<SDOperand, 8> MemOpChains;
1300   
1301   SDOperand StackPtr;
1302   
1303   // Walk the register/memloc assignments, inserting copies/loads.
1304   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1305     CCValAssign &VA = ArgLocs[i];
1306     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1307     
1308     // Promote the value if needed.
1309     switch (VA.getLocInfo()) {
1310       default: assert(0 && "Unknown loc info!");
1311       case CCValAssign::Full: break;
1312       case CCValAssign::SExt:
1313         Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1314         break;
1315       case CCValAssign::ZExt:
1316         Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1317         break;
1318       case CCValAssign::AExt:
1319         Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1320         break;
1321     }
1322     
1323     if (VA.isRegLoc()) {
1324       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1325     } else {
1326       assert(VA.isMemLoc());
1327       if (StackPtr.Val == 0)
1328         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1329
1330       MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1331                                              Arg));
1332     }
1333   }
1334
1335   if (!MemOpChains.empty())
1336     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1337                         &MemOpChains[0], MemOpChains.size());
1338
1339   // Build a sequence of copy-to-reg nodes chained together with token chain
1340   // and flag operands which copy the outgoing args into registers.
1341   SDOperand InFlag;
1342   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1343     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1344                              InFlag);
1345     InFlag = Chain.getValue(1);
1346   }
1347
1348   // If the callee is a GlobalAddress node (quite common, every direct call is)
1349   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1350   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1351     // We should use extra load for direct calls to dllimported functions in
1352     // non-JIT mode.
1353     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1354                                         getTargetMachine(), true))
1355       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1356   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1357     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1358
1359   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1360   // GOT pointer.
1361   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1362       Subtarget->isPICStyleGOT()) {
1363     Chain = DAG.getCopyToReg(Chain, X86::EBX,
1364                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1365                              InFlag);
1366     InFlag = Chain.getValue(1);
1367   }
1368
1369   // Returns a chain & a flag for retval copy to use.
1370   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1371   SmallVector<SDOperand, 8> Ops;
1372   Ops.push_back(Chain);
1373   Ops.push_back(Callee);
1374
1375   // Add argument registers to the end of the list so that they are known live
1376   // into the call.
1377   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1378     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1379                                   RegsToPass[i].second.getValueType()));
1380
1381   // Add an implicit use GOT pointer in EBX.
1382   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1383       Subtarget->isPICStyleGOT())
1384     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1385
1386   if (InFlag.Val)
1387     Ops.push_back(InFlag);
1388
1389   assert(isTailCall==false && "no tail call here");
1390   Chain = DAG.getNode(X86ISD::CALL,
1391                       NodeTys, &Ops[0], Ops.size());
1392   InFlag = Chain.getValue(1);
1393
1394   // Returns a flag for retval copy to use.
1395   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1396   Ops.clear();
1397   Ops.push_back(Chain);
1398   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1399   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1400   Ops.push_back(InFlag);
1401   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1402   InFlag = Chain.getValue(1);
1403
1404   // Handle result values, copying them out of physregs into vregs that we
1405   // return.
1406   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1407 }
1408
1409 //===----------------------------------------------------------------------===//
1410 //                Fast Calling Convention (tail call) implementation
1411 //===----------------------------------------------------------------------===//
1412
1413 //  Like std call, callee cleans arguments, convention except that ECX is
1414 //  reserved for storing the tail called function address. Only 2 registers are
1415 //  free for argument passing (inreg). Tail call optimization is performed
1416 //  provided:
1417 //                * tailcallopt is enabled
1418 //                * caller/callee are fastcc
1419 //                * elf/pic is disabled OR
1420 //                * elf/pic enabled + callee is in module + callee has
1421 //                  visibility protected or hidden
1422 //  To keep the stack aligned according to platform abi the function
1423 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
1424 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1425 //  If a tail called function callee has more arguments than the caller the
1426 //  caller needs to make sure that there is room to move the RETADDR to. This is
1427 //  achieved by reserving an area the size of the argument delta right after the
1428 //  original REtADDR, but before the saved framepointer or the spilled registers
1429 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1430 //  stack layout:
1431 //    arg1
1432 //    arg2
1433 //    RETADDR
1434 //    [ new RETADDR 
1435 //      move area ]
1436 //    (possible EBP)
1437 //    ESI
1438 //    EDI
1439 //    local1 ..
1440
1441 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1442 /// for a 16 byte align requirement.
1443 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 
1444                                                         SelectionDAG& DAG) {
1445   if (PerformTailCallOpt) {
1446     MachineFunction &MF = DAG.getMachineFunction();
1447     const TargetMachine &TM = MF.getTarget();
1448     const TargetFrameInfo &TFI = *TM.getFrameInfo();
1449     unsigned StackAlignment = TFI.getStackAlignment();
1450     uint64_t AlignMask = StackAlignment - 1; 
1451     int64_t Offset = StackSize;
1452     unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1453     if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1454       // Number smaller than 12 so just add the difference.
1455       Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1456     } else {
1457       // Mask out lower bits, add stackalignment once plus the 12 bytes.
1458       Offset = ((~AlignMask) & Offset) + StackAlignment + 
1459         (StackAlignment-SlotSize);
1460     }
1461     StackSize = Offset;
1462   }
1463   return StackSize;
1464 }
1465
1466 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1467 /// following the call is a return. A function is eligible if caller/callee
1468 /// calling conventions match, currently only fastcc supports tail calls, and
1469 /// the function CALL is immediatly followed by a RET.
1470 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1471                                                       SDOperand Ret,
1472                                                       SelectionDAG& DAG) const {
1473   if (!PerformTailCallOpt)
1474     return false;
1475
1476   // Check whether CALL node immediatly preceeds the RET node and whether the
1477   // return uses the result of the node or is a void return.
1478   unsigned NumOps = Ret.getNumOperands();
1479   if ((NumOps == 1 && 
1480        (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1481         Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1482       (NumOps > 1 &&
1483        Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1484        Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1485     MachineFunction &MF = DAG.getMachineFunction();
1486     unsigned CallerCC = MF.getFunction()->getCallingConv();
1487     unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1488     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1489       SDOperand Callee = Call.getOperand(4);
1490       // On elf/pic %ebx needs to be livein.
1491       if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1492           !Subtarget->isPICStyleGOT())
1493         return true;
1494
1495       // Can only do local tail calls with PIC.
1496       GlobalValue * GV = 0;
1497       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1498       if(G != 0 &&
1499          (GV = G->getGlobal()) &&
1500          (GV->hasHiddenVisibility() || GV->hasProtectedVisibility()))
1501         return true;
1502     }
1503   }
1504
1505   return false;
1506 }
1507
1508 SDOperand X86TargetLowering::LowerX86_TailCallTo(SDOperand Op, 
1509                                                      SelectionDAG &DAG,
1510                                                      unsigned CC) {
1511   SDOperand Chain     = Op.getOperand(0);
1512   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1513   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
1514   SDOperand Callee    = Op.getOperand(4);
1515   bool is64Bit        = Subtarget->is64Bit();
1516
1517   assert(isTailCall && PerformTailCallOpt && "Should only emit tail calls.");
1518
1519   // Analyze operands of the call, assigning locations to each operand.
1520   SmallVector<CCValAssign, 16> ArgLocs;
1521   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1522   if (is64Bit)
1523     CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1524   else
1525     CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_32_TailCall);
1526   
1527   
1528   // Lower arguments at fp - stackoffset + fpdiff.
1529   MachineFunction &MF = DAG.getMachineFunction();
1530
1531   unsigned NumBytesToBePushed = 
1532     GetAlignedArgumentStackSize(CCInfo.getNextStackOffset(), DAG);
1533     
1534   unsigned NumBytesCallerPushed = 
1535     MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1536   int FPDiff = NumBytesCallerPushed - NumBytesToBePushed;
1537
1538   // Set the delta of movement of the returnaddr stackslot.
1539   // But only set if delta is greater than previous delta.
1540   if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1541     MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1542
1543   Chain = DAG.
1544    getCALLSEQ_START(Chain, DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1545
1546   // Adjust the Return address stack slot.
1547   SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
1548   if (FPDiff) {
1549     MVT::ValueType VT = is64Bit ? MVT::i64 : MVT::i32;
1550     RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1551     // Load the "old" Return address.
1552     RetAddrFrIdx = 
1553       DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1554     // Calculate the new stack slot for the return address.
1555     int SlotSize = is64Bit ? 8 : 4;
1556     int NewReturnAddrFI = 
1557       MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1558     NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1559     Chain = SDOperand(RetAddrFrIdx.Val, 1);
1560   }
1561
1562   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1563   SmallVector<SDOperand, 8> MemOpChains;
1564   SmallVector<SDOperand, 8> MemOpChains2;
1565   SDOperand FramePtr, StackPtr;
1566   SDOperand PtrOff;
1567   SDOperand FIN;
1568   int FI = 0;
1569
1570   // Walk the register/memloc assignments, inserting copies/loads.  Lower
1571   // arguments first to the stack slot where they would normally - in case of a
1572   // normal function call - be.
1573   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1574     CCValAssign &VA = ArgLocs[i];
1575     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1576     
1577     // Promote the value if needed.
1578     switch (VA.getLocInfo()) {
1579     default: assert(0 && "Unknown loc info!");
1580     case CCValAssign::Full: break;
1581     case CCValAssign::SExt:
1582       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1583       break;
1584     case CCValAssign::ZExt:
1585       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1586       break;
1587     case CCValAssign::AExt:
1588       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1589       break;
1590     }
1591     
1592     if (VA.isRegLoc()) {
1593       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1594     } else {
1595       assert(VA.isMemLoc());
1596       if (StackPtr.Val == 0)
1597         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1598
1599       MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1600                                              Arg));
1601     }
1602   }
1603
1604   if (!MemOpChains.empty())
1605     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1606                         &MemOpChains[0], MemOpChains.size());
1607
1608   // Build a sequence of copy-to-reg nodes chained together with token chain
1609   // and flag operands which copy the outgoing args into registers.
1610   SDOperand InFlag;
1611   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1612     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1613                              InFlag);
1614     InFlag = Chain.getValue(1);
1615   }
1616   InFlag = SDOperand();
1617
1618   // Copy from stack slots to stack slot of a tail called function. This needs
1619   // to be done because if we would lower the arguments directly to their real
1620   // stack slot we might end up overwriting each other.
1621   // TODO: To make this more efficient (sometimes saving a store/load) we could
1622   // analyse the arguments and emit this store/load/store sequence only for
1623   // arguments which would be overwritten otherwise.
1624   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1625     CCValAssign &VA = ArgLocs[i];
1626     if (!VA.isRegLoc()) {
1627       SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1628       unsigned Flags    = cast<ConstantSDNode>(FlagsOp)->getValue();
1629       
1630       // Get source stack slot. 
1631       SDOperand PtrOff = DAG.getConstant(VA.getLocMemOffset(), getPointerTy());
1632       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1633       // Create frame index.
1634       int32_t Offset = VA.getLocMemOffset()+FPDiff;
1635       uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1636       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1637       FIN = DAG.getFrameIndex(FI, MVT::i32);
1638       if (Flags & ISD::ParamFlags::ByVal) {
1639         // Copy relative to framepointer.
1640         unsigned Align = 1 << ((Flags & ISD::ParamFlags::ByValAlign) >>
1641                                ISD::ParamFlags::ByValAlignOffs);
1642
1643         unsigned  Size = (Flags & ISD::ParamFlags::ByValSize) >>
1644           ISD::ParamFlags::ByValSizeOffs;
1645  
1646         SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1647         SDOperand  SizeNode = DAG.getConstant(Size, MVT::i32);
1648         SDOperand AlwaysInline = DAG.getConstant(1, MVT::i1);
1649
1650         MemOpChains2.push_back(DAG.getMemcpy(Chain, FIN, PtrOff, SizeNode, 
1651                                              AlignNode,AlwaysInline));
1652       } else {
1653         SDOperand LoadedArg = DAG.getLoad(VA.getValVT(), Chain, PtrOff, NULL,0);
1654         // Store relative to framepointer.
1655         MemOpChains2.push_back(DAG.getStore(Chain, LoadedArg, FIN, NULL, 0));
1656       }
1657     }
1658   }
1659
1660   if (!MemOpChains2.empty())
1661     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1662                         &MemOpChains2[0], MemOpChains.size());
1663
1664   // Store the return address to the appropriate stack slot.
1665   if (FPDiff)
1666     Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1667
1668   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1669   // GOT pointer.
1670   // Does not work with tail call since ebx is not restored correctly by
1671   // tailcaller. TODO: at least for x86 - verify for x86-64
1672
1673   // If the callee is a GlobalAddress node (quite common, every direct call is)
1674   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1675   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1676     // We should use extra load for direct calls to dllimported functions in
1677     // non-JIT mode.
1678     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1679                                         getTargetMachine(), true))
1680       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1681   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1682     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1683   else {
1684     assert(Callee.getOpcode() == ISD::LOAD && 
1685            "Function destination must be loaded into virtual register");
1686     unsigned Opc = is64Bit ? X86::R9 : X86::ECX;
1687
1688     Chain = DAG.getCopyToReg(Chain, 
1689                              DAG.getRegister(Opc, getPointerTy()) , 
1690                              Callee,InFlag);
1691     Callee = DAG.getRegister(Opc, getPointerTy());
1692     // Add register as live out.
1693     DAG.getMachineFunction().addLiveOut(Opc);
1694   }
1695    
1696   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1697   SmallVector<SDOperand, 8> Ops;
1698
1699   Ops.push_back(Chain);
1700   Ops.push_back(DAG.getConstant(NumBytesToBePushed, getPointerTy()));
1701   Ops.push_back(DAG.getConstant(0, getPointerTy()));
1702   if (InFlag.Val)
1703     Ops.push_back(InFlag);
1704   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1705   InFlag = Chain.getValue(1);
1706
1707   // Returns a chain & a flag for retval copy to use.
1708   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1709   Ops.clear();
1710   Ops.push_back(Chain);
1711   Ops.push_back(Callee);
1712   Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1713   // Add argument registers to the end of the list so that they are known live
1714   // into the call.
1715   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1716     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1717                                   RegsToPass[i].second.getValueType()));
1718   if (InFlag.Val)
1719     Ops.push_back(InFlag);
1720   assert(InFlag.Val && 
1721          "Flag must be set. Depend on flag being set in LowerRET");
1722   Chain = DAG.getNode(X86ISD::TAILCALL,
1723                       Op.Val->getVTList(), &Ops[0], Ops.size());
1724     
1725   return SDOperand(Chain.Val, Op.ResNo);
1726 }
1727
1728 //===----------------------------------------------------------------------===//
1729 //                 X86-64 C Calling Convention implementation
1730 //===----------------------------------------------------------------------===//
1731
1732 SDOperand
1733 X86TargetLowering::LowerX86_64CCCArguments(SDOperand Op, SelectionDAG &DAG) {
1734   MachineFunction &MF = DAG.getMachineFunction();
1735   MachineFrameInfo *MFI = MF.getFrameInfo();
1736   SDOperand Root = Op.getOperand(0);
1737   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1738   unsigned CC= MF.getFunction()->getCallingConv();
1739
1740   static const unsigned GPR64ArgRegs[] = {
1741     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8,  X86::R9
1742   };
1743   static const unsigned XMMArgRegs[] = {
1744     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1745     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1746   };
1747
1748   
1749   // Assign locations to all of the incoming arguments.
1750   SmallVector<CCValAssign, 16> ArgLocs;
1751   CCState CCInfo(CC, isVarArg,
1752                  getTargetMachine(), ArgLocs);
1753   if (CC == CallingConv::Fast && PerformTailCallOpt)
1754     CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_TailCall);
1755   else
1756     CCInfo.AnalyzeFormalArguments(Op.Val, CC_X86_64_C);
1757   
1758   SmallVector<SDOperand, 8> ArgValues;
1759   unsigned LastVal = ~0U;
1760   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1761     CCValAssign &VA = ArgLocs[i];
1762     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1763     // places.
1764     assert(VA.getValNo() != LastVal &&
1765            "Don't support value assigned to multiple locs yet");
1766     LastVal = VA.getValNo();
1767     
1768     if (VA.isRegLoc()) {
1769       MVT::ValueType RegVT = VA.getLocVT();
1770       TargetRegisterClass *RC;
1771       if (RegVT == MVT::i32)
1772         RC = X86::GR32RegisterClass;
1773       else if (RegVT == MVT::i64)
1774         RC = X86::GR64RegisterClass;
1775       else if (RegVT == MVT::f32)
1776         RC = X86::FR32RegisterClass;
1777       else if (RegVT == MVT::f64)
1778         RC = X86::FR64RegisterClass;
1779       else {
1780         assert(MVT::isVector(RegVT));
1781         if (MVT::getSizeInBits(RegVT) == 64) {
1782           RC = X86::GR64RegisterClass;       // MMX values are passed in GPRs.
1783           RegVT = MVT::i64;
1784         } else
1785           RC = X86::VR128RegisterClass;
1786       }
1787
1788       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1789       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1790       
1791       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1792       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1793       // right size.
1794       if (VA.getLocInfo() == CCValAssign::SExt)
1795         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1796                                DAG.getValueType(VA.getValVT()));
1797       else if (VA.getLocInfo() == CCValAssign::ZExt)
1798         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1799                                DAG.getValueType(VA.getValVT()));
1800       
1801       if (VA.getLocInfo() != CCValAssign::Full)
1802         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1803       
1804       // Handle MMX values passed in GPRs.
1805       if (RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1806           MVT::getSizeInBits(RegVT) == 64)
1807         ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1808       
1809       ArgValues.push_back(ArgValue);
1810     } else {
1811       assert(VA.isMemLoc());
1812       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1813     }
1814   }
1815   
1816   unsigned StackSize = CCInfo.getNextStackOffset();
1817   if (CC==CallingConv::Fast)
1818     StackSize =GetAlignedArgumentStackSize(StackSize, DAG);
1819   
1820   // If the function takes variable number of arguments, make a frame index for
1821   // the start of the first vararg value... for expansion of llvm.va_start.
1822   if (isVarArg) {
1823     assert(CC!=CallingConv::Fast 
1824            && "Var arg not supported with calling convention fastcc");
1825     unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1826     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1827     
1828     // For X86-64, if there are vararg parameters that are passed via
1829     // registers, then we must store them to their spots on the stack so they
1830     // may be loaded by deferencing the result of va_next.
1831     VarArgsGPOffset = NumIntRegs * 8;
1832     VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1833     VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1834     RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1835
1836     // Store the integer parameter registers.
1837     SmallVector<SDOperand, 8> MemOps;
1838     SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1839     SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1840                               DAG.getConstant(VarArgsGPOffset, getPointerTy()));
1841     for (; NumIntRegs != 6; ++NumIntRegs) {
1842       unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1843                                 X86::GR64RegisterClass);
1844       SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1845       SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1846       MemOps.push_back(Store);
1847       FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1848                         DAG.getConstant(8, getPointerTy()));
1849     }
1850
1851     // Now store the XMM (fp + vector) parameter registers.
1852     FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1853                       DAG.getConstant(VarArgsFPOffset, getPointerTy()));
1854     for (; NumXMMRegs != 8; ++NumXMMRegs) {
1855       unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1856                                 X86::VR128RegisterClass);
1857       SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1858       SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1859       MemOps.push_back(Store);
1860       FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1861                         DAG.getConstant(16, getPointerTy()));
1862     }
1863     if (!MemOps.empty())
1864         Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1865                            &MemOps[0], MemOps.size());
1866   }
1867
1868   ArgValues.push_back(Root);
1869   // Tail call convention (fastcc) needs callee pop.
1870   if (CC == CallingConv::Fast && PerformTailCallOpt) {
1871     BytesToPopOnReturn = StackSize;  // Callee pops everything.
1872     BytesCallerReserves = 0;
1873   } else {
1874     BytesToPopOnReturn = 0;  // Callee pops nothing.
1875     BytesCallerReserves = StackSize;
1876   }
1877   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1878   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1879
1880   // Return the new list of results.
1881   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1882                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1883 }
1884
1885 SDOperand
1886 X86TargetLowering::LowerX86_64CCCCallTo(SDOperand Op, SelectionDAG &DAG,
1887                                         unsigned CC) {
1888   SDOperand Chain     = Op.getOperand(0);
1889   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1890   SDOperand Callee    = Op.getOperand(4);
1891   
1892   // Analyze operands of the call, assigning locations to each operand.
1893   SmallVector<CCValAssign, 16> ArgLocs;
1894   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1895   if (CC==CallingConv::Fast && PerformTailCallOpt)
1896     CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_TailCall);
1897   else
1898     CCInfo.AnalyzeCallOperands(Op.Val, CC_X86_64_C);
1899     
1900   // Get a count of how many bytes are to be pushed on the stack.
1901   unsigned NumBytes = CCInfo.getNextStackOffset();
1902   if (CC == CallingConv::Fast)
1903     NumBytes = GetAlignedArgumentStackSize(NumBytes,DAG);
1904
1905   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1906
1907   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1908   SmallVector<SDOperand, 8> MemOpChains;
1909
1910   SDOperand StackPtr;
1911   
1912   // Walk the register/memloc assignments, inserting copies/loads.
1913   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1914     CCValAssign &VA = ArgLocs[i];
1915     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1916     
1917     // Promote the value if needed.
1918     switch (VA.getLocInfo()) {
1919     default: assert(0 && "Unknown loc info!");
1920     case CCValAssign::Full: break;
1921     case CCValAssign::SExt:
1922       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1923       break;
1924     case CCValAssign::ZExt:
1925       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1926       break;
1927     case CCValAssign::AExt:
1928       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1929       break;
1930     }
1931     
1932     if (VA.isRegLoc()) {
1933       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1934     } else {
1935       assert(VA.isMemLoc());
1936       if (StackPtr.Val == 0)
1937         StackPtr = DAG.getRegister(getStackPtrReg(), getPointerTy());
1938
1939       MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1940                                              Arg));
1941     }
1942   }
1943   
1944   if (!MemOpChains.empty())
1945     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1946                         &MemOpChains[0], MemOpChains.size());
1947
1948   // Build a sequence of copy-to-reg nodes chained together with token chain
1949   // and flag operands which copy the outgoing args into registers.
1950   SDOperand InFlag;
1951   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1952     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1953                              InFlag);
1954     InFlag = Chain.getValue(1);
1955   }
1956
1957   if (isVarArg) {
1958     assert ( CallingConv::Fast != CC &&
1959              "Var args not supported with calling convention fastcc");
1960
1961     // From AMD64 ABI document:
1962     // For calls that may call functions that use varargs or stdargs
1963     // (prototype-less calls or calls to functions containing ellipsis (...) in
1964     // the declaration) %al is used as hidden argument to specify the number
1965     // of SSE registers used. The contents of %al do not need to match exactly
1966     // the number of registers, but must be an ubound on the number of SSE
1967     // registers used and is in the range 0 - 8 inclusive.
1968     
1969     // Count the number of XMM registers allocated.
1970     static const unsigned XMMArgRegs[] = {
1971       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1972       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1973     };
1974     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1975     
1976     Chain = DAG.getCopyToReg(Chain, X86::AL,
1977                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1978     InFlag = Chain.getValue(1);
1979   }
1980
1981   // If the callee is a GlobalAddress node (quite common, every direct call is)
1982   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1983   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1984     // We should use extra load for direct calls to dllimported functions in
1985     // non-JIT mode.
1986     if (getTargetMachine().getCodeModel() != CodeModel::Large
1987         && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1988                                            getTargetMachine(), true))
1989       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1990   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1991     if (getTargetMachine().getCodeModel() != CodeModel::Large)
1992       Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1993
1994   // Returns a chain & a flag for retval copy to use.
1995   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1996   SmallVector<SDOperand, 8> Ops;
1997   Ops.push_back(Chain);
1998   Ops.push_back(Callee);
1999
2000   // Add argument registers to the end of the list so that they are known live
2001   // into the call.
2002   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2003     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2004                                   RegsToPass[i].second.getValueType()));
2005
2006   if (InFlag.Val)
2007     Ops.push_back(InFlag);
2008
2009   Chain = DAG.getNode(X86ISD::CALL,
2010                       NodeTys, &Ops[0], Ops.size());
2011   InFlag = Chain.getValue(1);
2012   int NumBytesForCalleeToPush = 0;
2013    if (CC==CallingConv::Fast && PerformTailCallOpt) {
2014     NumBytesForCalleeToPush = NumBytes;  // Callee pops everything
2015   } else {
2016     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2017   }
2018   // Returns a flag for retval copy to use.
2019   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2020   Ops.clear();
2021   Ops.push_back(Chain);
2022   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
2023   Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
2024   Ops.push_back(InFlag);
2025   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
2026   InFlag = Chain.getValue(1);
2027   
2028   // Handle result values, copying them out of physregs into vregs that we
2029   // return.
2030   return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
2031 }
2032
2033
2034 //===----------------------------------------------------------------------===//
2035 //                           Other Lowering Hooks
2036 //===----------------------------------------------------------------------===//
2037
2038
2039 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2040   MachineFunction &MF = DAG.getMachineFunction();
2041   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2042   int ReturnAddrIndex = FuncInfo->getRAIndex();
2043
2044   if (ReturnAddrIndex == 0) {
2045     // Set up a frame object for the return address.
2046     if (Subtarget->is64Bit())
2047       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
2048     else
2049       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
2050
2051     FuncInfo->setRAIndex(ReturnAddrIndex);
2052   }
2053
2054   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2055 }
2056
2057
2058
2059 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
2060 /// specific condition code. It returns a false if it cannot do a direct
2061 /// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
2062 /// needed.
2063 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2064                            unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
2065                            SelectionDAG &DAG) {
2066   X86CC = X86::COND_INVALID;
2067   if (!isFP) {
2068     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2069       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2070         // X > -1   -> X == 0, jump !sign.
2071         RHS = DAG.getConstant(0, RHS.getValueType());
2072         X86CC = X86::COND_NS;
2073         return true;
2074       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2075         // X < 0   -> X == 0, jump on sign.
2076         X86CC = X86::COND_S;
2077         return true;
2078       } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
2079         // X < 1   -> X <= 0
2080         RHS = DAG.getConstant(0, RHS.getValueType());
2081         X86CC = X86::COND_LE;
2082         return true;
2083       }
2084     }
2085
2086     switch (SetCCOpcode) {
2087     default: break;
2088     case ISD::SETEQ:  X86CC = X86::COND_E;  break;
2089     case ISD::SETGT:  X86CC = X86::COND_G;  break;
2090     case ISD::SETGE:  X86CC = X86::COND_GE; break;
2091     case ISD::SETLT:  X86CC = X86::COND_L;  break;
2092     case ISD::SETLE:  X86CC = X86::COND_LE; break;
2093     case ISD::SETNE:  X86CC = X86::COND_NE; break;
2094     case ISD::SETULT: X86CC = X86::COND_B;  break;
2095     case ISD::SETUGT: X86CC = X86::COND_A;  break;
2096     case ISD::SETULE: X86CC = X86::COND_BE; break;
2097     case ISD::SETUGE: X86CC = X86::COND_AE; break;
2098     }
2099   } else {
2100     // On a floating point condition, the flags are set as follows:
2101     // ZF  PF  CF   op
2102     //  0 | 0 | 0 | X > Y
2103     //  0 | 0 | 1 | X < Y
2104     //  1 | 0 | 0 | X == Y
2105     //  1 | 1 | 1 | unordered
2106     bool Flip = false;
2107     switch (SetCCOpcode) {
2108     default: break;
2109     case ISD::SETUEQ:
2110     case ISD::SETEQ: X86CC = X86::COND_E;  break;
2111     case ISD::SETOLT: Flip = true; // Fallthrough
2112     case ISD::SETOGT:
2113     case ISD::SETGT: X86CC = X86::COND_A;  break;
2114     case ISD::SETOLE: Flip = true; // Fallthrough
2115     case ISD::SETOGE:
2116     case ISD::SETGE: X86CC = X86::COND_AE; break;
2117     case ISD::SETUGT: Flip = true; // Fallthrough
2118     case ISD::SETULT:
2119     case ISD::SETLT: X86CC = X86::COND_B;  break;
2120     case ISD::SETUGE: Flip = true; // Fallthrough
2121     case ISD::SETULE:
2122     case ISD::SETLE: X86CC = X86::COND_BE; break;
2123     case ISD::SETONE:
2124     case ISD::SETNE: X86CC = X86::COND_NE; break;
2125     case ISD::SETUO: X86CC = X86::COND_P;  break;
2126     case ISD::SETO:  X86CC = X86::COND_NP; break;
2127     }
2128     if (Flip)
2129       std::swap(LHS, RHS);
2130   }
2131
2132   return X86CC != X86::COND_INVALID;
2133 }
2134
2135 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2136 /// code. Current x86 isa includes the following FP cmov instructions:
2137 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2138 static bool hasFPCMov(unsigned X86CC) {
2139   switch (X86CC) {
2140   default:
2141     return false;
2142   case X86::COND_B:
2143   case X86::COND_BE:
2144   case X86::COND_E:
2145   case X86::COND_P:
2146   case X86::COND_A:
2147   case X86::COND_AE:
2148   case X86::COND_NE:
2149   case X86::COND_NP:
2150     return true;
2151   }
2152 }
2153
2154 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
2155 /// true if Op is undef or if its value falls within the specified range (L, H].
2156 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2157   if (Op.getOpcode() == ISD::UNDEF)
2158     return true;
2159
2160   unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2161   return (Val >= Low && Val < Hi);
2162 }
2163
2164 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
2165 /// true if Op is undef or if its value equal to the specified value.
2166 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2167   if (Op.getOpcode() == ISD::UNDEF)
2168     return true;
2169   return cast<ConstantSDNode>(Op)->getValue() == Val;
2170 }
2171
2172 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2173 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2174 bool X86::isPSHUFDMask(SDNode *N) {
2175   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2176
2177   if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2178     return false;
2179
2180   // Check if the value doesn't reference the second vector.
2181   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2182     SDOperand Arg = N->getOperand(i);
2183     if (Arg.getOpcode() == ISD::UNDEF) continue;
2184     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2185     if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2186       return false;
2187   }
2188
2189   return true;
2190 }
2191
2192 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2193 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2194 bool X86::isPSHUFHWMask(SDNode *N) {
2195   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2196
2197   if (N->getNumOperands() != 8)
2198     return false;
2199
2200   // Lower quadword copied in order.
2201   for (unsigned i = 0; i != 4; ++i) {
2202     SDOperand Arg = N->getOperand(i);
2203     if (Arg.getOpcode() == ISD::UNDEF) continue;
2204     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2205     if (cast<ConstantSDNode>(Arg)->getValue() != i)
2206       return false;
2207   }
2208
2209   // Upper quadword shuffled.
2210   for (unsigned i = 4; i != 8; ++i) {
2211     SDOperand Arg = N->getOperand(i);
2212     if (Arg.getOpcode() == ISD::UNDEF) continue;
2213     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2214     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2215     if (Val < 4 || Val > 7)
2216       return false;
2217   }
2218
2219   return true;
2220 }
2221
2222 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2223 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2224 bool X86::isPSHUFLWMask(SDNode *N) {
2225   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2226
2227   if (N->getNumOperands() != 8)
2228     return false;
2229
2230   // Upper quadword copied in order.
2231   for (unsigned i = 4; i != 8; ++i)
2232     if (!isUndefOrEqual(N->getOperand(i), i))
2233       return false;
2234
2235   // Lower quadword shuffled.
2236   for (unsigned i = 0; i != 4; ++i)
2237     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2238       return false;
2239
2240   return true;
2241 }
2242
2243 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2244 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2245 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2246   if (NumElems != 2 && NumElems != 4) return false;
2247
2248   unsigned Half = NumElems / 2;
2249   for (unsigned i = 0; i < Half; ++i)
2250     if (!isUndefOrInRange(Elems[i], 0, NumElems))
2251       return false;
2252   for (unsigned i = Half; i < NumElems; ++i)
2253     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2254       return false;
2255
2256   return true;
2257 }
2258
2259 bool X86::isSHUFPMask(SDNode *N) {
2260   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2261   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2262 }
2263
2264 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2265 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2266 /// half elements to come from vector 1 (which would equal the dest.) and
2267 /// the upper half to come from vector 2.
2268 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2269   if (NumOps != 2 && NumOps != 4) return false;
2270
2271   unsigned Half = NumOps / 2;
2272   for (unsigned i = 0; i < Half; ++i)
2273     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2274       return false;
2275   for (unsigned i = Half; i < NumOps; ++i)
2276     if (!isUndefOrInRange(Ops[i], 0, NumOps))
2277       return false;
2278   return true;
2279 }
2280
2281 static bool isCommutedSHUFP(SDNode *N) {
2282   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2283   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2284 }
2285
2286 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2287 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2288 bool X86::isMOVHLPSMask(SDNode *N) {
2289   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2290
2291   if (N->getNumOperands() != 4)
2292     return false;
2293
2294   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2295   return isUndefOrEqual(N->getOperand(0), 6) &&
2296          isUndefOrEqual(N->getOperand(1), 7) &&
2297          isUndefOrEqual(N->getOperand(2), 2) &&
2298          isUndefOrEqual(N->getOperand(3), 3);
2299 }
2300
2301 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2302 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2303 /// <2, 3, 2, 3>
2304 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2305   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2306
2307   if (N->getNumOperands() != 4)
2308     return false;
2309
2310   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2311   return isUndefOrEqual(N->getOperand(0), 2) &&
2312          isUndefOrEqual(N->getOperand(1), 3) &&
2313          isUndefOrEqual(N->getOperand(2), 2) &&
2314          isUndefOrEqual(N->getOperand(3), 3);
2315 }
2316
2317 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2318 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2319 bool X86::isMOVLPMask(SDNode *N) {
2320   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2321
2322   unsigned NumElems = N->getNumOperands();
2323   if (NumElems != 2 && NumElems != 4)
2324     return false;
2325
2326   for (unsigned i = 0; i < NumElems/2; ++i)
2327     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2328       return false;
2329
2330   for (unsigned i = NumElems/2; i < NumElems; ++i)
2331     if (!isUndefOrEqual(N->getOperand(i), i))
2332       return false;
2333
2334   return true;
2335 }
2336
2337 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2338 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2339 /// and MOVLHPS.
2340 bool X86::isMOVHPMask(SDNode *N) {
2341   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2342
2343   unsigned NumElems = N->getNumOperands();
2344   if (NumElems != 2 && NumElems != 4)
2345     return false;
2346
2347   for (unsigned i = 0; i < NumElems/2; ++i)
2348     if (!isUndefOrEqual(N->getOperand(i), i))
2349       return false;
2350
2351   for (unsigned i = 0; i < NumElems/2; ++i) {
2352     SDOperand Arg = N->getOperand(i + NumElems/2);
2353     if (!isUndefOrEqual(Arg, i + NumElems))
2354       return false;
2355   }
2356
2357   return true;
2358 }
2359
2360 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2361 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2362 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2363                          bool V2IsSplat = false) {
2364   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2365     return false;
2366
2367   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2368     SDOperand BitI  = Elts[i];
2369     SDOperand BitI1 = Elts[i+1];
2370     if (!isUndefOrEqual(BitI, j))
2371       return false;
2372     if (V2IsSplat) {
2373       if (isUndefOrEqual(BitI1, NumElts))
2374         return false;
2375     } else {
2376       if (!isUndefOrEqual(BitI1, j + NumElts))
2377         return false;
2378     }
2379   }
2380
2381   return true;
2382 }
2383
2384 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2385   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2386   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2387 }
2388
2389 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2390 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2391 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2392                          bool V2IsSplat = false) {
2393   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2394     return false;
2395
2396   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2397     SDOperand BitI  = Elts[i];
2398     SDOperand BitI1 = Elts[i+1];
2399     if (!isUndefOrEqual(BitI, j + NumElts/2))
2400       return false;
2401     if (V2IsSplat) {
2402       if (isUndefOrEqual(BitI1, NumElts))
2403         return false;
2404     } else {
2405       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2406         return false;
2407     }
2408   }
2409
2410   return true;
2411 }
2412
2413 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2414   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2415   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2416 }
2417
2418 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2419 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2420 /// <0, 0, 1, 1>
2421 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2422   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2423
2424   unsigned NumElems = N->getNumOperands();
2425   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2426     return false;
2427
2428   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2429     SDOperand BitI  = N->getOperand(i);
2430     SDOperand BitI1 = N->getOperand(i+1);
2431
2432     if (!isUndefOrEqual(BitI, j))
2433       return false;
2434     if (!isUndefOrEqual(BitI1, j))
2435       return false;
2436   }
2437
2438   return true;
2439 }
2440
2441 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2442 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2443 /// <2, 2, 3, 3>
2444 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2445   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2446
2447   unsigned NumElems = N->getNumOperands();
2448   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2449     return false;
2450
2451   for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2452     SDOperand BitI  = N->getOperand(i);
2453     SDOperand BitI1 = N->getOperand(i + 1);
2454
2455     if (!isUndefOrEqual(BitI, j))
2456       return false;
2457     if (!isUndefOrEqual(BitI1, j))
2458       return false;
2459   }
2460
2461   return true;
2462 }
2463
2464 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2465 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2466 /// MOVSD, and MOVD, i.e. setting the lowest element.
2467 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2468   if (NumElts != 2 && NumElts != 4)
2469     return false;
2470
2471   if (!isUndefOrEqual(Elts[0], NumElts))
2472     return false;
2473
2474   for (unsigned i = 1; i < NumElts; ++i) {
2475     if (!isUndefOrEqual(Elts[i], i))
2476       return false;
2477   }
2478
2479   return true;
2480 }
2481
2482 bool X86::isMOVLMask(SDNode *N) {
2483   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2484   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2485 }
2486
2487 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2488 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2489 /// element of vector 2 and the other elements to come from vector 1 in order.
2490 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2491                            bool V2IsSplat = false,
2492                            bool V2IsUndef = false) {
2493   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2494     return false;
2495
2496   if (!isUndefOrEqual(Ops[0], 0))
2497     return false;
2498
2499   for (unsigned i = 1; i < NumOps; ++i) {
2500     SDOperand Arg = Ops[i];
2501     if (!(isUndefOrEqual(Arg, i+NumOps) ||
2502           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2503           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2504       return false;
2505   }
2506
2507   return true;
2508 }
2509
2510 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2511                            bool V2IsUndef = false) {
2512   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2513   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2514                         V2IsSplat, V2IsUndef);
2515 }
2516
2517 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2518 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2519 bool X86::isMOVSHDUPMask(SDNode *N) {
2520   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2521
2522   if (N->getNumOperands() != 4)
2523     return false;
2524
2525   // Expect 1, 1, 3, 3
2526   for (unsigned i = 0; i < 2; ++i) {
2527     SDOperand Arg = N->getOperand(i);
2528     if (Arg.getOpcode() == ISD::UNDEF) continue;
2529     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2530     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2531     if (Val != 1) return false;
2532   }
2533
2534   bool HasHi = false;
2535   for (unsigned i = 2; i < 4; ++i) {
2536     SDOperand Arg = N->getOperand(i);
2537     if (Arg.getOpcode() == ISD::UNDEF) continue;
2538     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2539     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2540     if (Val != 3) return false;
2541     HasHi = true;
2542   }
2543
2544   // Don't use movshdup if it can be done with a shufps.
2545   return HasHi;
2546 }
2547
2548 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2549 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2550 bool X86::isMOVSLDUPMask(SDNode *N) {
2551   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2552
2553   if (N->getNumOperands() != 4)
2554     return false;
2555
2556   // Expect 0, 0, 2, 2
2557   for (unsigned i = 0; i < 2; ++i) {
2558     SDOperand Arg = N->getOperand(i);
2559     if (Arg.getOpcode() == ISD::UNDEF) continue;
2560     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2561     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2562     if (Val != 0) return false;
2563   }
2564
2565   bool HasHi = false;
2566   for (unsigned i = 2; i < 4; ++i) {
2567     SDOperand Arg = N->getOperand(i);
2568     if (Arg.getOpcode() == ISD::UNDEF) continue;
2569     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2570     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2571     if (Val != 2) return false;
2572     HasHi = true;
2573   }
2574
2575   // Don't use movshdup if it can be done with a shufps.
2576   return HasHi;
2577 }
2578
2579 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2580 /// specifies a identity operation on the LHS or RHS.
2581 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2582   unsigned NumElems = N->getNumOperands();
2583   for (unsigned i = 0; i < NumElems; ++i)
2584     if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2585       return false;
2586   return true;
2587 }
2588
2589 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2590 /// a splat of a single element.
2591 static bool isSplatMask(SDNode *N) {
2592   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2593
2594   // This is a splat operation if each element of the permute is the same, and
2595   // if the value doesn't reference the second vector.
2596   unsigned NumElems = N->getNumOperands();
2597   SDOperand ElementBase;
2598   unsigned i = 0;
2599   for (; i != NumElems; ++i) {
2600     SDOperand Elt = N->getOperand(i);
2601     if (isa<ConstantSDNode>(Elt)) {
2602       ElementBase = Elt;
2603       break;
2604     }
2605   }
2606
2607   if (!ElementBase.Val)
2608     return false;
2609
2610   for (; i != NumElems; ++i) {
2611     SDOperand Arg = N->getOperand(i);
2612     if (Arg.getOpcode() == ISD::UNDEF) continue;
2613     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2614     if (Arg != ElementBase) return false;
2615   }
2616
2617   // Make sure it is a splat of the first vector operand.
2618   return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2619 }
2620
2621 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2622 /// a splat of a single element and it's a 2 or 4 element mask.
2623 bool X86::isSplatMask(SDNode *N) {
2624   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2625
2626   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2627   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2628     return false;
2629   return ::isSplatMask(N);
2630 }
2631
2632 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2633 /// specifies a splat of zero element.
2634 bool X86::isSplatLoMask(SDNode *N) {
2635   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2636
2637   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2638     if (!isUndefOrEqual(N->getOperand(i), 0))
2639       return false;
2640   return true;
2641 }
2642
2643 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2644 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2645 /// instructions.
2646 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2647   unsigned NumOperands = N->getNumOperands();
2648   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2649   unsigned Mask = 0;
2650   for (unsigned i = 0; i < NumOperands; ++i) {
2651     unsigned Val = 0;
2652     SDOperand Arg = N->getOperand(NumOperands-i-1);
2653     if (Arg.getOpcode() != ISD::UNDEF)
2654       Val = cast<ConstantSDNode>(Arg)->getValue();
2655     if (Val >= NumOperands) Val -= NumOperands;
2656     Mask |= Val;
2657     if (i != NumOperands - 1)
2658       Mask <<= Shift;
2659   }
2660
2661   return Mask;
2662 }
2663
2664 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2665 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2666 /// instructions.
2667 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2668   unsigned Mask = 0;
2669   // 8 nodes, but we only care about the last 4.
2670   for (unsigned i = 7; i >= 4; --i) {
2671     unsigned Val = 0;
2672     SDOperand Arg = N->getOperand(i);
2673     if (Arg.getOpcode() != ISD::UNDEF)
2674       Val = cast<ConstantSDNode>(Arg)->getValue();
2675     Mask |= (Val - 4);
2676     if (i != 4)
2677       Mask <<= 2;
2678   }
2679
2680   return Mask;
2681 }
2682
2683 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2684 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2685 /// instructions.
2686 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2687   unsigned Mask = 0;
2688   // 8 nodes, but we only care about the first 4.
2689   for (int i = 3; i >= 0; --i) {
2690     unsigned Val = 0;
2691     SDOperand Arg = N->getOperand(i);
2692     if (Arg.getOpcode() != ISD::UNDEF)
2693       Val = cast<ConstantSDNode>(Arg)->getValue();
2694     Mask |= Val;
2695     if (i != 0)
2696       Mask <<= 2;
2697   }
2698
2699   return Mask;
2700 }
2701
2702 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2703 /// specifies a 8 element shuffle that can be broken into a pair of
2704 /// PSHUFHW and PSHUFLW.
2705 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2706   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2707
2708   if (N->getNumOperands() != 8)
2709     return false;
2710
2711   // Lower quadword shuffled.
2712   for (unsigned i = 0; i != 4; ++i) {
2713     SDOperand Arg = N->getOperand(i);
2714     if (Arg.getOpcode() == ISD::UNDEF) continue;
2715     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2716     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2717     if (Val > 4)
2718       return false;
2719   }
2720
2721   // Upper quadword shuffled.
2722   for (unsigned i = 4; i != 8; ++i) {
2723     SDOperand Arg = N->getOperand(i);
2724     if (Arg.getOpcode() == ISD::UNDEF) continue;
2725     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2726     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2727     if (Val < 4 || Val > 7)
2728       return false;
2729   }
2730
2731   return true;
2732 }
2733
2734 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2735 /// values in ther permute mask.
2736 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2737                                       SDOperand &V2, SDOperand &Mask,
2738                                       SelectionDAG &DAG) {
2739   MVT::ValueType VT = Op.getValueType();
2740   MVT::ValueType MaskVT = Mask.getValueType();
2741   MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2742   unsigned NumElems = Mask.getNumOperands();
2743   SmallVector<SDOperand, 8> MaskVec;
2744
2745   for (unsigned i = 0; i != NumElems; ++i) {
2746     SDOperand Arg = Mask.getOperand(i);
2747     if (Arg.getOpcode() == ISD::UNDEF) {
2748       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2749       continue;
2750     }
2751     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2752     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2753     if (Val < NumElems)
2754       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2755     else
2756       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2757   }
2758
2759   std::swap(V1, V2);
2760   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2761   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2762 }
2763
2764 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2765 /// the two vector operands have swapped position.
2766 static
2767 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2768   MVT::ValueType MaskVT = Mask.getValueType();
2769   MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2770   unsigned NumElems = Mask.getNumOperands();
2771   SmallVector<SDOperand, 8> MaskVec;
2772   for (unsigned i = 0; i != NumElems; ++i) {
2773     SDOperand Arg = Mask.getOperand(i);
2774     if (Arg.getOpcode() == ISD::UNDEF) {
2775       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2776       continue;
2777     }
2778     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2779     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2780     if (Val < NumElems)
2781       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2782     else
2783       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2784   }
2785   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2786 }
2787
2788
2789 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2790 /// match movhlps. The lower half elements should come from upper half of
2791 /// V1 (and in order), and the upper half elements should come from the upper
2792 /// half of V2 (and in order).
2793 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2794   unsigned NumElems = Mask->getNumOperands();
2795   if (NumElems != 4)
2796     return false;
2797   for (unsigned i = 0, e = 2; i != e; ++i)
2798     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2799       return false;
2800   for (unsigned i = 2; i != 4; ++i)
2801     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2802       return false;
2803   return true;
2804 }
2805
2806 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2807 /// is promoted to a vector.
2808 static inline bool isScalarLoadToVector(SDNode *N) {
2809   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2810     N = N->getOperand(0).Val;
2811     return ISD::isNON_EXTLoad(N);
2812   }
2813   return false;
2814 }
2815
2816 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2817 /// match movlp{s|d}. The lower half elements should come from lower half of
2818 /// V1 (and in order), and the upper half elements should come from the upper
2819 /// half of V2 (and in order). And since V1 will become the source of the
2820 /// MOVLP, it must be either a vector load or a scalar load to vector.
2821 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2822   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2823     return false;
2824   // Is V2 is a vector load, don't do this transformation. We will try to use
2825   // load folding shufps op.
2826   if (ISD::isNON_EXTLoad(V2))
2827     return false;
2828
2829   unsigned NumElems = Mask->getNumOperands();
2830   if (NumElems != 2 && NumElems != 4)
2831     return false;
2832   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2833     if (!isUndefOrEqual(Mask->getOperand(i), i))
2834       return false;
2835   for (unsigned i = NumElems/2; i != NumElems; ++i)
2836     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2837       return false;
2838   return true;
2839 }
2840
2841 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2842 /// all the same.
2843 static bool isSplatVector(SDNode *N) {
2844   if (N->getOpcode() != ISD::BUILD_VECTOR)
2845     return false;
2846
2847   SDOperand SplatValue = N->getOperand(0);
2848   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2849     if (N->getOperand(i) != SplatValue)
2850       return false;
2851   return true;
2852 }
2853
2854 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2855 /// to an undef.
2856 static bool isUndefShuffle(SDNode *N) {
2857   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2858     return false;
2859
2860   SDOperand V1 = N->getOperand(0);
2861   SDOperand V2 = N->getOperand(1);
2862   SDOperand Mask = N->getOperand(2);
2863   unsigned NumElems = Mask.getNumOperands();
2864   for (unsigned i = 0; i != NumElems; ++i) {
2865     SDOperand Arg = Mask.getOperand(i);
2866     if (Arg.getOpcode() != ISD::UNDEF) {
2867       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2868       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2869         return false;
2870       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2871         return false;
2872     }
2873   }
2874   return true;
2875 }
2876
2877 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2878 /// constant +0.0.
2879 static inline bool isZeroNode(SDOperand Elt) {
2880   return ((isa<ConstantSDNode>(Elt) &&
2881            cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2882           (isa<ConstantFPSDNode>(Elt) &&
2883            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2884 }
2885
2886 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2887 /// to an zero vector.
2888 static bool isZeroShuffle(SDNode *N) {
2889   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2890     return false;
2891
2892   SDOperand V1 = N->getOperand(0);
2893   SDOperand V2 = N->getOperand(1);
2894   SDOperand Mask = N->getOperand(2);
2895   unsigned NumElems = Mask.getNumOperands();
2896   for (unsigned i = 0; i != NumElems; ++i) {
2897     SDOperand Arg = Mask.getOperand(i);
2898     if (Arg.getOpcode() == ISD::UNDEF)
2899       continue;
2900     
2901     unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2902     if (Idx < NumElems) {
2903       unsigned Opc = V1.Val->getOpcode();
2904       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2905         continue;
2906       if (Opc != ISD::BUILD_VECTOR ||
2907           !isZeroNode(V1.Val->getOperand(Idx)))
2908         return false;
2909     } else if (Idx >= NumElems) {
2910       unsigned Opc = V2.Val->getOpcode();
2911       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2912         continue;
2913       if (Opc != ISD::BUILD_VECTOR ||
2914           !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2915         return false;
2916     }
2917   }
2918   return true;
2919 }
2920
2921 /// getZeroVector - Returns a vector of specified type with all zero elements.
2922 ///
2923 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2924   assert(MVT::isVector(VT) && "Expected a vector type");
2925   
2926   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2927   // type.  This ensures they get CSE'd.
2928   SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2929   SDOperand Vec;
2930   if (MVT::getSizeInBits(VT) == 64)  // MMX
2931     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2932   else                                              // SSE
2933     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2934   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2935 }
2936
2937 /// getOnesVector - Returns a vector of specified type with all bits set.
2938 ///
2939 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2940   assert(MVT::isVector(VT) && "Expected a vector type");
2941   
2942   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2943   // type.  This ensures they get CSE'd.
2944   SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2945   SDOperand Vec;
2946   if (MVT::getSizeInBits(VT) == 64)  // MMX
2947     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2948   else                                              // SSE
2949     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2950   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2951 }
2952
2953
2954 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2955 /// that point to V2 points to its first element.
2956 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2957   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2958
2959   bool Changed = false;
2960   SmallVector<SDOperand, 8> MaskVec;
2961   unsigned NumElems = Mask.getNumOperands();
2962   for (unsigned i = 0; i != NumElems; ++i) {
2963     SDOperand Arg = Mask.getOperand(i);
2964     if (Arg.getOpcode() != ISD::UNDEF) {
2965       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2966       if (Val > NumElems) {
2967         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2968         Changed = true;
2969       }
2970     }
2971     MaskVec.push_back(Arg);
2972   }
2973
2974   if (Changed)
2975     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2976                        &MaskVec[0], MaskVec.size());
2977   return Mask;
2978 }
2979
2980 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2981 /// operation of specified width.
2982 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2983   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2984   MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2985
2986   SmallVector<SDOperand, 8> MaskVec;
2987   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2988   for (unsigned i = 1; i != NumElems; ++i)
2989     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2990   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2991 }
2992
2993 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2994 /// of specified width.
2995 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2996   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2997   MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2998   SmallVector<SDOperand, 8> MaskVec;
2999   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3000     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
3001     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3002   }
3003   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3004 }
3005
3006 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3007 /// of specified width.
3008 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
3009   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3010   MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3011   unsigned Half = NumElems/2;
3012   SmallVector<SDOperand, 8> MaskVec;
3013   for (unsigned i = 0; i != Half; ++i) {
3014     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
3015     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3016   }
3017   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
3018 }
3019
3020 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
3021 ///
3022 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
3023   SDOperand V1 = Op.getOperand(0);
3024   SDOperand Mask = Op.getOperand(2);
3025   MVT::ValueType VT = Op.getValueType();
3026   unsigned NumElems = Mask.getNumOperands();
3027   Mask = getUnpacklMask(NumElems, DAG);
3028   while (NumElems != 4) {
3029     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
3030     NumElems >>= 1;
3031   }
3032   V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
3033
3034   Mask = getZeroVector(MVT::v4i32, DAG);
3035   SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
3036                                   DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
3037   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3038 }
3039
3040 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3041 /// vector of zero or undef vector.  This produces a shuffle where the low
3042 /// element of V2 is swizzled into the zero/undef vector, landing at element
3043 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3044 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
3045                                              unsigned NumElems, unsigned Idx,
3046                                              bool isZero, SelectionDAG &DAG) {
3047   SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
3048   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3049   MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3050   SmallVector<SDOperand, 16> MaskVec;
3051   for (unsigned i = 0; i != NumElems; ++i)
3052     if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
3053       MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3054     else
3055       MaskVec.push_back(DAG.getConstant(i, EVT));
3056   SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3057                                &MaskVec[0], MaskVec.size());
3058   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3059 }
3060
3061 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3062 ///
3063 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
3064                                        unsigned NumNonZero, unsigned NumZero,
3065                                        SelectionDAG &DAG, TargetLowering &TLI) {
3066   if (NumNonZero > 8)
3067     return SDOperand();
3068
3069   SDOperand V(0, 0);
3070   bool First = true;
3071   for (unsigned i = 0; i < 16; ++i) {
3072     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3073     if (ThisIsNonZero && First) {
3074       if (NumZero)
3075         V = getZeroVector(MVT::v8i16, DAG);
3076       else
3077         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3078       First = false;
3079     }
3080
3081     if ((i & 1) != 0) {
3082       SDOperand ThisElt(0, 0), LastElt(0, 0);
3083       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3084       if (LastIsNonZero) {
3085         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3086       }
3087       if (ThisIsNonZero) {
3088         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3089         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3090                               ThisElt, DAG.getConstant(8, MVT::i8));
3091         if (LastIsNonZero)
3092           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3093       } else
3094         ThisElt = LastElt;
3095
3096       if (ThisElt.Val)
3097         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3098                         DAG.getConstant(i/2, TLI.getPointerTy()));
3099     }
3100   }
3101
3102   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3103 }
3104
3105 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3106 ///
3107 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3108                                        unsigned NumNonZero, unsigned NumZero,
3109                                        SelectionDAG &DAG, TargetLowering &TLI) {
3110   if (NumNonZero > 4)
3111     return SDOperand();
3112
3113   SDOperand V(0, 0);
3114   bool First = true;
3115   for (unsigned i = 0; i < 8; ++i) {
3116     bool isNonZero = (NonZeros & (1 << i)) != 0;
3117     if (isNonZero) {
3118       if (First) {
3119         if (NumZero)
3120           V = getZeroVector(MVT::v8i16, DAG);
3121         else
3122           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3123         First = false;
3124       }
3125       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3126                       DAG.getConstant(i, TLI.getPointerTy()));
3127     }
3128   }
3129
3130   return V;
3131 }
3132
3133 SDOperand
3134 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3135   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3136   if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3137     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3138     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3139     // eliminated on x86-32 hosts.
3140     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3141       return Op;
3142
3143     if (ISD::isBuildVectorAllOnes(Op.Val))
3144       return getOnesVector(Op.getValueType(), DAG);
3145     return getZeroVector(Op.getValueType(), DAG);
3146   }
3147
3148   MVT::ValueType VT = Op.getValueType();
3149   MVT::ValueType EVT = MVT::getVectorElementType(VT);
3150   unsigned EVTBits = MVT::getSizeInBits(EVT);
3151
3152   unsigned NumElems = Op.getNumOperands();
3153   unsigned NumZero  = 0;
3154   unsigned NumNonZero = 0;
3155   unsigned NonZeros = 0;
3156   unsigned NumNonZeroImms = 0;
3157   std::set<SDOperand> Values;
3158   for (unsigned i = 0; i < NumElems; ++i) {
3159     SDOperand Elt = Op.getOperand(i);
3160     if (Elt.getOpcode() != ISD::UNDEF) {
3161       Values.insert(Elt);
3162       if (isZeroNode(Elt))
3163         NumZero++;
3164       else {
3165         NonZeros |= (1 << i);
3166         NumNonZero++;
3167         if (Elt.getOpcode() == ISD::Constant ||
3168             Elt.getOpcode() == ISD::ConstantFP)
3169           NumNonZeroImms++;
3170       }
3171     }
3172   }
3173
3174   if (NumNonZero == 0) {
3175     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3176     return DAG.getNode(ISD::UNDEF, VT);
3177   }
3178
3179   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3180   if (Values.size() == 1)
3181     return SDOperand();
3182
3183   // Special case for single non-zero element.
3184   if (NumNonZero == 1) {
3185     unsigned Idx = CountTrailingZeros_32(NonZeros);
3186     SDOperand Item = Op.getOperand(Idx);
3187     Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3188     if (Idx == 0)
3189       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3190       return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3191                                          NumZero > 0, DAG);
3192
3193     if (EVTBits == 32) {
3194       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3195       Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3196                                          DAG);
3197       MVT::ValueType MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
3198       MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3199       SmallVector<SDOperand, 8> MaskVec;
3200       for (unsigned i = 0; i < NumElems; i++)
3201         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3202       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3203                                    &MaskVec[0], MaskVec.size());
3204       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3205                          DAG.getNode(ISD::UNDEF, VT), Mask);
3206     }
3207   }
3208
3209   // A vector full of immediates; various special cases are already
3210   // handled, so this is best done with a single constant-pool load.
3211   if (NumNonZero == NumNonZeroImms)
3212     return SDOperand();
3213
3214   // Let legalizer expand 2-wide build_vectors.
3215   if (EVTBits == 64)
3216     return SDOperand();
3217
3218   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3219   if (EVTBits == 8 && NumElems == 16) {
3220     SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3221                                         *this);
3222     if (V.Val) return V;
3223   }
3224
3225   if (EVTBits == 16 && NumElems == 8) {
3226     SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3227                                         *this);
3228     if (V.Val) return V;
3229   }
3230
3231   // If element VT is == 32 bits, turn it into a number of shuffles.
3232   SmallVector<SDOperand, 8> V;
3233   V.resize(NumElems);
3234   if (NumElems == 4 && NumZero > 0) {
3235     for (unsigned i = 0; i < 4; ++i) {
3236       bool isZero = !(NonZeros & (1 << i));
3237       if (isZero)
3238         V[i] = getZeroVector(VT, DAG);
3239       else
3240         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3241     }
3242
3243     for (unsigned i = 0; i < 2; ++i) {
3244       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3245         default: break;
3246         case 0:
3247           V[i] = V[i*2];  // Must be a zero vector.
3248           break;
3249         case 1:
3250           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3251                              getMOVLMask(NumElems, DAG));
3252           break;
3253         case 2:
3254           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3255                              getMOVLMask(NumElems, DAG));
3256           break;
3257         case 3:
3258           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3259                              getUnpacklMask(NumElems, DAG));
3260           break;
3261       }
3262     }
3263
3264     // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3265     // clears the upper bits.
3266     // FIXME: we can do the same for v4f32 case when we know both parts of
3267     // the lower half come from scalar_to_vector (loadf32). We should do
3268     // that in post legalizer dag combiner with target specific hooks.
3269     if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3270       return V[0];
3271     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3272     MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3273     SmallVector<SDOperand, 8> MaskVec;
3274     bool Reverse = (NonZeros & 0x3) == 2;
3275     for (unsigned i = 0; i < 2; ++i)
3276       if (Reverse)
3277         MaskVec.push_back(DAG.getConstant(1-i, EVT));
3278       else
3279         MaskVec.push_back(DAG.getConstant(i, EVT));
3280     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3281     for (unsigned i = 0; i < 2; ++i)
3282       if (Reverse)
3283         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3284       else
3285         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3286     SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3287                                      &MaskVec[0], MaskVec.size());
3288     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3289   }
3290
3291   if (Values.size() > 2) {
3292     // Expand into a number of unpckl*.
3293     // e.g. for v4f32
3294     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3295     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3296     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3297     SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3298     for (unsigned i = 0; i < NumElems; ++i)
3299       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3300     NumElems >>= 1;
3301     while (NumElems != 0) {
3302       for (unsigned i = 0; i < NumElems; ++i)
3303         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3304                            UnpckMask);
3305       NumElems >>= 1;
3306     }
3307     return V[0];
3308   }
3309
3310   return SDOperand();
3311 }
3312
3313 static
3314 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3315                                    SDOperand PermMask, SelectionDAG &DAG,
3316                                    TargetLowering &TLI) {
3317   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3318   MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3319   if (isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
3320     // Handle v8i16 shuffle high / low shuffle node pair.
3321     SmallVector<SDOperand, 8> MaskVec;
3322     for (unsigned i = 0; i != 4; ++i)
3323       MaskVec.push_back(PermMask.getOperand(i));
3324     for (unsigned i = 4; i != 8; ++i)
3325       MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3326     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3327     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V2, Mask);
3328     MaskVec.clear();
3329     for (unsigned i = 0; i != 4; ++i)
3330       MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3331     for (unsigned i = 4; i != 8; ++i)
3332       MaskVec.push_back(PermMask.getOperand(i));
3333     Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3334     return DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V2, Mask);
3335   }
3336
3337   // Lower than into extracts and inserts but try to do as few as possible.
3338   // First, let's find out how many elements are already in the right order.
3339   unsigned V1InOrder = 0;
3340   unsigned V1FromV1 = 0;
3341   unsigned V2InOrder = 0;
3342   unsigned V2FromV2 = 0;
3343   SmallVector<unsigned, 8> V1Elts;
3344   SmallVector<unsigned, 8> V2Elts;
3345   for (unsigned i = 0; i < 8; ++i) {
3346     SDOperand Elt = PermMask.getOperand(i);
3347     if (Elt.getOpcode() == ISD::UNDEF) {
3348       V1Elts.push_back(i);
3349       V2Elts.push_back(i);
3350       ++V1InOrder;
3351       ++V2InOrder;
3352     } else {
3353       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3354       if (EltIdx == i) {
3355         V1Elts.push_back(i);
3356         V2Elts.push_back(i+8);
3357         ++V1InOrder;
3358       } else if (EltIdx == i+8) {
3359         V1Elts.push_back(i+8);
3360         V2Elts.push_back(i);
3361         ++V2InOrder;
3362       } else {
3363         V1Elts.push_back(EltIdx);
3364         V2Elts.push_back(EltIdx);
3365         if (EltIdx < 8)
3366           ++V1FromV1;
3367         else
3368           ++V2FromV2;
3369       }
3370     }
3371   }
3372
3373   if (V2InOrder > V1InOrder) {
3374     PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3375     std::swap(V1, V2);
3376     std::swap(V1Elts, V2Elts);
3377     std::swap(V1FromV1, V2FromV2);
3378   }
3379
3380   MVT::ValueType PtrVT = TLI.getPointerTy();
3381   if (V1FromV1) {
3382     // If there are elements that are from V1 but out of place,
3383     // then first sort them in place
3384     SmallVector<SDOperand, 8> MaskVec;
3385     for (unsigned i = 0; i < 8; ++i) {
3386       unsigned EltIdx = V1Elts[i];
3387       if (EltIdx >= 8)
3388         MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3389       else
3390         MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3391     }
3392     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3393     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3394   }
3395
3396   // Now let's insert elements from the other vector.
3397   for (unsigned i = 0; i < 8; ++i) {
3398     unsigned EltIdx = V1Elts[i];
3399     if (EltIdx < 8)
3400       continue;
3401     SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3402                                   DAG.getConstant(EltIdx - 8, PtrVT));
3403     V1 = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V1, ExtOp,
3404                      DAG.getConstant(i, PtrVT));
3405   }
3406   return V1;
3407 }
3408
3409 SDOperand
3410 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3411   SDOperand V1 = Op.getOperand(0);
3412   SDOperand V2 = Op.getOperand(1);
3413   SDOperand PermMask = Op.getOperand(2);
3414   MVT::ValueType VT = Op.getValueType();
3415   unsigned NumElems = PermMask.getNumOperands();
3416   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3417   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3418   bool V1IsSplat = false;
3419   bool V2IsSplat = false;
3420
3421   if (isUndefShuffle(Op.Val))
3422     return DAG.getNode(ISD::UNDEF, VT);
3423
3424   if (isZeroShuffle(Op.Val))
3425     return getZeroVector(VT, DAG);
3426
3427   if (isIdentityMask(PermMask.Val))
3428     return V1;
3429   else if (isIdentityMask(PermMask.Val, true))
3430     return V2;
3431
3432   if (isSplatMask(PermMask.Val)) {
3433     if (NumElems <= 4) return Op;
3434     // Promote it to a v4i32 splat.
3435     return PromoteSplat(Op, DAG);
3436   }
3437
3438   if (X86::isMOVLMask(PermMask.Val))
3439     return (V1IsUndef) ? V2 : Op;
3440
3441   if (X86::isMOVSHDUPMask(PermMask.Val) ||
3442       X86::isMOVSLDUPMask(PermMask.Val) ||
3443       X86::isMOVHLPSMask(PermMask.Val) ||
3444       X86::isMOVHPMask(PermMask.Val) ||
3445       X86::isMOVLPMask(PermMask.Val))
3446     return Op;
3447
3448   if (ShouldXformToMOVHLPS(PermMask.Val) ||
3449       ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3450     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3451
3452   bool Commuted = false;
3453   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3454   // 1,1,1,1 -> v8i16 though.
3455   V1IsSplat = isSplatVector(V1.Val);
3456   V2IsSplat = isSplatVector(V2.Val);
3457   
3458   // Canonicalize the splat or undef, if present, to be on the RHS.
3459   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3460     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3461     std::swap(V1IsSplat, V2IsSplat);
3462     std::swap(V1IsUndef, V2IsUndef);
3463     Commuted = true;
3464   }
3465
3466   if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3467     if (V2IsUndef) return V1;
3468     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3469     if (V2IsSplat) {
3470       // V2 is a splat, so the mask may be malformed. That is, it may point
3471       // to any V2 element. The instruction selectior won't like this. Get
3472       // a corrected mask and commute to form a proper MOVS{S|D}.
3473       SDOperand NewMask = getMOVLMask(NumElems, DAG);
3474       if (NewMask.Val != PermMask.Val)
3475         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3476     }
3477     return Op;
3478   }
3479
3480   if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3481       X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3482       X86::isUNPCKLMask(PermMask.Val) ||
3483       X86::isUNPCKHMask(PermMask.Val))
3484     return Op;
3485
3486   if (V2IsSplat) {
3487     // Normalize mask so all entries that point to V2 points to its first
3488     // element then try to match unpck{h|l} again. If match, return a
3489     // new vector_shuffle with the corrected mask.
3490     SDOperand NewMask = NormalizeMask(PermMask, DAG);
3491     if (NewMask.Val != PermMask.Val) {
3492       if (X86::isUNPCKLMask(PermMask.Val, true)) {
3493         SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3494         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3495       } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3496         SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3497         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3498       }
3499     }
3500   }
3501
3502   // Normalize the node to match x86 shuffle ops if needed
3503   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3504       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3505
3506   if (Commuted) {
3507     // Commute is back and try unpck* again.
3508     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3509     if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3510         X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3511         X86::isUNPCKLMask(PermMask.Val) ||
3512         X86::isUNPCKHMask(PermMask.Val))
3513       return Op;
3514   }
3515
3516   // If VT is integer, try PSHUF* first, then SHUFP*.
3517   if (MVT::isInteger(VT)) {
3518     // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3519     // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3520     if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3521          X86::isPSHUFDMask(PermMask.Val)) ||
3522         X86::isPSHUFHWMask(PermMask.Val) ||
3523         X86::isPSHUFLWMask(PermMask.Val)) {
3524       if (V2.getOpcode() != ISD::UNDEF)
3525         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3526                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3527       return Op;
3528     }
3529
3530     if (X86::isSHUFPMask(PermMask.Val) &&
3531         MVT::getSizeInBits(VT) != 64)    // Don't do this for MMX.
3532       return Op;
3533   } else {
3534     // Floating point cases in the other order.
3535     if (X86::isSHUFPMask(PermMask.Val))
3536       return Op;
3537     if (X86::isPSHUFDMask(PermMask.Val) ||
3538         X86::isPSHUFHWMask(PermMask.Val) ||
3539         X86::isPSHUFLWMask(PermMask.Val)) {
3540       if (V2.getOpcode() != ISD::UNDEF)
3541         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3542                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3543       return Op;
3544     }
3545   }
3546
3547   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3548   if (VT == MVT::v8i16)
3549     return LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3550
3551   if (NumElems == 4 &&  MVT::getSizeInBits(VT) != 64) {
3552     // Don't do this for MMX.
3553     MVT::ValueType MaskVT = PermMask.getValueType();
3554     MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3555     SmallVector<std::pair<int, int>, 8> Locs;
3556     Locs.reserve(NumElems);
3557     SmallVector<SDOperand, 8> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3558     SmallVector<SDOperand, 8> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3559     unsigned NumHi = 0;
3560     unsigned NumLo = 0;
3561     // If no more than two elements come from either vector. This can be
3562     // implemented with two shuffles. First shuffle gather the elements.
3563     // The second shuffle, which takes the first shuffle as both of its
3564     // vector operands, put the elements into the right order.
3565     for (unsigned i = 0; i != NumElems; ++i) {
3566       SDOperand Elt = PermMask.getOperand(i);
3567       if (Elt.getOpcode() == ISD::UNDEF) {
3568         Locs[i] = std::make_pair(-1, -1);
3569       } else {
3570         unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3571         if (Val < NumElems) {
3572           Locs[i] = std::make_pair(0, NumLo);
3573           Mask1[NumLo] = Elt;
3574           NumLo++;
3575         } else {
3576           Locs[i] = std::make_pair(1, NumHi);
3577           if (2+NumHi < NumElems)
3578             Mask1[2+NumHi] = Elt;
3579           NumHi++;
3580         }
3581       }
3582     }
3583     if (NumLo <= 2 && NumHi <= 2) {
3584       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3585                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3586                                    &Mask1[0], Mask1.size()));
3587       for (unsigned i = 0; i != NumElems; ++i) {
3588         if (Locs[i].first == -1)
3589           continue;
3590         else {
3591           unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3592           Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3593           Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3594         }
3595       }
3596
3597       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3598                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3599                                      &Mask2[0], Mask2.size()));
3600     }
3601
3602     // Break it into (shuffle shuffle_hi, shuffle_lo).
3603     Locs.clear();
3604     SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3605     SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3606     SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3607     unsigned MaskIdx = 0;
3608     unsigned LoIdx = 0;
3609     unsigned HiIdx = NumElems/2;
3610     for (unsigned i = 0; i != NumElems; ++i) {
3611       if (i == NumElems/2) {
3612         MaskPtr = &HiMask;
3613         MaskIdx = 1;
3614         LoIdx = 0;
3615         HiIdx = NumElems/2;
3616       }
3617       SDOperand Elt = PermMask.getOperand(i);
3618       if (Elt.getOpcode() == ISD::UNDEF) {
3619         Locs[i] = std::make_pair(-1, -1);
3620       } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3621         Locs[i] = std::make_pair(MaskIdx, LoIdx);
3622         (*MaskPtr)[LoIdx] = Elt;
3623         LoIdx++;
3624       } else {
3625         Locs[i] = std::make_pair(MaskIdx, HiIdx);
3626         (*MaskPtr)[HiIdx] = Elt;
3627         HiIdx++;
3628       }
3629     }
3630
3631     SDOperand LoShuffle =
3632       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3633                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3634                               &LoMask[0], LoMask.size()));
3635     SDOperand HiShuffle =
3636       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3637                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3638                               &HiMask[0], HiMask.size()));
3639     SmallVector<SDOperand, 8> MaskOps;
3640     for (unsigned i = 0; i != NumElems; ++i) {
3641       if (Locs[i].first == -1) {
3642         MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3643       } else {
3644         unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3645         MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3646       }
3647     }
3648     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3649                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3650                                    &MaskOps[0], MaskOps.size()));
3651   }
3652
3653   return SDOperand();
3654 }
3655
3656 SDOperand
3657 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3658   if (!isa<ConstantSDNode>(Op.getOperand(1)))
3659     return SDOperand();
3660
3661   MVT::ValueType VT = Op.getValueType();
3662   // TODO: handle v16i8.
3663   if (MVT::getSizeInBits(VT) == 16) {
3664     // Transform it so it match pextrw which produces a 32-bit result.
3665     MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3666     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3667                                     Op.getOperand(0), Op.getOperand(1));
3668     SDOperand Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
3669                                     DAG.getValueType(VT));
3670     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3671   } else if (MVT::getSizeInBits(VT) == 32) {
3672     SDOperand Vec = Op.getOperand(0);
3673     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3674     if (Idx == 0)
3675       return Op;
3676     // SHUFPS the element to the lowest double word, then movss.
3677     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3678     SmallVector<SDOperand, 8> IdxVec;
3679     IdxVec.
3680       push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3681     IdxVec.
3682       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3683     IdxVec.
3684       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3685     IdxVec.
3686       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3687     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3688                                  &IdxVec[0], IdxVec.size());
3689     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3690                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3691     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3692                        DAG.getConstant(0, getPointerTy()));
3693   } else if (MVT::getSizeInBits(VT) == 64) {
3694     SDOperand Vec = Op.getOperand(0);
3695     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3696     if (Idx == 0)
3697       return Op;
3698
3699     // UNPCKHPD the element to the lowest double word, then movsd.
3700     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3701     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3702     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3703     SmallVector<SDOperand, 8> IdxVec;
3704     IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3705     IdxVec.
3706       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3707     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3708                                  &IdxVec[0], IdxVec.size());
3709     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3710                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3711     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3712                        DAG.getConstant(0, getPointerTy()));
3713   }
3714
3715   return SDOperand();
3716 }
3717
3718 SDOperand
3719 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3720   // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3721   // as its second argument.
3722   MVT::ValueType VT = Op.getValueType();
3723   MVT::ValueType BaseVT = MVT::getVectorElementType(VT);
3724   SDOperand N0 = Op.getOperand(0);
3725   SDOperand N1 = Op.getOperand(1);
3726   SDOperand N2 = Op.getOperand(2);
3727   if (MVT::getSizeInBits(BaseVT) == 16) {
3728     if (N1.getValueType() != MVT::i32)
3729       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3730     if (N2.getValueType() != MVT::i32)
3731       N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(),getPointerTy());
3732     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3733   } else if (MVT::getSizeInBits(BaseVT) == 32) {
3734     unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
3735     if (Idx == 0) {
3736       // Use a movss.
3737       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
3738       MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3739       MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
3740       SmallVector<SDOperand, 8> MaskVec;
3741       MaskVec.push_back(DAG.getConstant(4, BaseVT));
3742       for (unsigned i = 1; i <= 3; ++i)
3743         MaskVec.push_back(DAG.getConstant(i, BaseVT));
3744       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
3745                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3746                                      &MaskVec[0], MaskVec.size()));
3747     } else {
3748       // Use two pinsrw instructions to insert a 32 bit value.
3749       Idx <<= 1;
3750       if (MVT::isFloatingPoint(N1.getValueType())) {
3751         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
3752         N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
3753         N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
3754                          DAG.getConstant(0, getPointerTy()));
3755       }
3756       N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
3757       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3758                        DAG.getConstant(Idx, getPointerTy()));
3759       N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
3760       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
3761                        DAG.getConstant(Idx+1, getPointerTy()));
3762       return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3763     }
3764   }
3765
3766   return SDOperand();
3767 }
3768
3769 SDOperand
3770 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3771   SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3772   return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3773 }
3774
3775 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3776 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3777 // one of the above mentioned nodes. It has to be wrapped because otherwise
3778 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3779 // be used to form addressing mode. These wrapped nodes will be selected
3780 // into MOV32ri.
3781 SDOperand
3782 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3783   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3784   SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3785                                                getPointerTy(),
3786                                                CP->getAlignment());
3787   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3788   // With PIC, the address is actually $g + Offset.
3789   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3790       !Subtarget->isPICStyleRIPRel()) {
3791     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3792                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3793                          Result);
3794   }
3795
3796   return Result;
3797 }
3798
3799 SDOperand
3800 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3801   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3802   SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3803   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3804   // With PIC, the address is actually $g + Offset.
3805   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3806       !Subtarget->isPICStyleRIPRel()) {
3807     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3808                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3809                          Result);
3810   }
3811   
3812   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3813   // load the value at address GV, not the value of GV itself. This means that
3814   // the GlobalAddress must be in the base or index register of the address, not
3815   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3816   // The same applies for external symbols during PIC codegen
3817   if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3818     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result, NULL, 0);
3819
3820   return Result;
3821 }
3822
3823 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3824 static SDOperand
3825 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3826                               const MVT::ValueType PtrVT) {
3827   SDOperand InFlag;
3828   SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3829                                      DAG.getNode(X86ISD::GlobalBaseReg,
3830                                                  PtrVT), InFlag);
3831   InFlag = Chain.getValue(1);
3832
3833   // emit leal symbol@TLSGD(,%ebx,1), %eax
3834   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3835   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3836                                              GA->getValueType(0),
3837                                              GA->getOffset());
3838   SDOperand Ops[] = { Chain,  TGA, InFlag };
3839   SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3840   InFlag = Result.getValue(2);
3841   Chain = Result.getValue(1);
3842
3843   // call ___tls_get_addr. This function receives its argument in
3844   // the register EAX.
3845   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3846   InFlag = Chain.getValue(1);
3847
3848   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3849   SDOperand Ops1[] = { Chain,
3850                       DAG.getTargetExternalSymbol("___tls_get_addr",
3851                                                   PtrVT),
3852                       DAG.getRegister(X86::EAX, PtrVT),
3853                       DAG.getRegister(X86::EBX, PtrVT),
3854                       InFlag };
3855   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3856   InFlag = Chain.getValue(1);
3857
3858   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3859 }
3860
3861 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3862 // "local exec" model.
3863 static SDOperand
3864 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3865                          const MVT::ValueType PtrVT) {
3866   // Get the Thread Pointer
3867   SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3868   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3869   // exec)
3870   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3871                                              GA->getValueType(0),
3872                                              GA->getOffset());
3873   SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3874
3875   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3876     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset, NULL, 0);
3877
3878   // The address of the thread local variable is the add of the thread
3879   // pointer with the offset of the variable.
3880   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3881 }
3882
3883 SDOperand
3884 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3885   // TODO: implement the "local dynamic" model
3886   // TODO: implement the "initial exec"model for pic executables
3887   assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3888          "TLS not implemented for non-ELF and 64-bit targets");
3889   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3890   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3891   // otherwise use the "Local Exec"TLS Model
3892   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3893     return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3894   else
3895     return LowerToTLSExecModel(GA, DAG, getPointerTy());
3896 }
3897
3898 SDOperand
3899 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3900   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3901   SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3902   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3903   // With PIC, the address is actually $g + Offset.
3904   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3905       !Subtarget->isPICStyleRIPRel()) {
3906     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3907                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3908                          Result);
3909   }
3910
3911   return Result;
3912 }
3913
3914 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3915   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3916   SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3917   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3918   // With PIC, the address is actually $g + Offset.
3919   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3920       !Subtarget->isPICStyleRIPRel()) {
3921     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3922                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3923                          Result);
3924   }
3925
3926   return Result;
3927 }
3928
3929 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
3930 /// take a 2 x i32 value to shift plus a shift amount. 
3931 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
3932   assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
3933          "Not an i64 shift!");
3934   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
3935   SDOperand ShOpLo = Op.getOperand(0);
3936   SDOperand ShOpHi = Op.getOperand(1);
3937   SDOperand ShAmt  = Op.getOperand(2);
3938   SDOperand Tmp1 = isSRA ?
3939     DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
3940     DAG.getConstant(0, MVT::i32);
3941
3942   SDOperand Tmp2, Tmp3;
3943   if (Op.getOpcode() == ISD::SHL_PARTS) {
3944     Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
3945     Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
3946   } else {
3947     Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
3948     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
3949   }
3950
3951   const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
3952   SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
3953                                   DAG.getConstant(32, MVT::i8));
3954   SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
3955                                AndNode, DAG.getConstant(0, MVT::i8));
3956
3957   SDOperand Hi, Lo;
3958   SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
3959   VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
3960   SmallVector<SDOperand, 4> Ops;
3961   if (Op.getOpcode() == ISD::SHL_PARTS) {
3962     Ops.push_back(Tmp2);
3963     Ops.push_back(Tmp3);
3964     Ops.push_back(CC);
3965     Ops.push_back(Cond);
3966     Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3967
3968     Ops.clear();
3969     Ops.push_back(Tmp3);
3970     Ops.push_back(Tmp1);
3971     Ops.push_back(CC);
3972     Ops.push_back(Cond);
3973     Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3974   } else {
3975     Ops.push_back(Tmp2);
3976     Ops.push_back(Tmp3);
3977     Ops.push_back(CC);
3978     Ops.push_back(Cond);
3979     Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3980
3981     Ops.clear();
3982     Ops.push_back(Tmp3);
3983     Ops.push_back(Tmp1);
3984     Ops.push_back(CC);
3985     Ops.push_back(Cond);
3986     Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
3987   }
3988
3989   VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
3990   Ops.clear();
3991   Ops.push_back(Lo);
3992   Ops.push_back(Hi);
3993   return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
3994 }
3995
3996 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
3997   assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
3998          Op.getOperand(0).getValueType() >= MVT::i16 &&
3999          "Unknown SINT_TO_FP to lower!");
4000
4001   SDOperand Result;
4002   MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4003   unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4004   MachineFunction &MF = DAG.getMachineFunction();
4005   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4006   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4007   SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4008                                  StackSlot, NULL, 0);
4009
4010   // These are really Legal; caller falls through into that case.
4011   if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f32 && X86ScalarSSEf32)
4012     return Result;
4013   if (SrcVT==MVT::i32 && Op.getValueType() == MVT::f64 && X86ScalarSSEf64)
4014     return Result;
4015   if (SrcVT==MVT::i64 && Op.getValueType() != MVT::f80 && 
4016       Subtarget->is64Bit())
4017     return Result;
4018
4019   // Build the FILD
4020   SDVTList Tys;
4021   bool useSSE = (X86ScalarSSEf32 && Op.getValueType() == MVT::f32) ||
4022                 (X86ScalarSSEf64 && Op.getValueType() == MVT::f64);
4023   if (useSSE)
4024     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4025   else
4026     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4027   SmallVector<SDOperand, 8> Ops;
4028   Ops.push_back(Chain);
4029   Ops.push_back(StackSlot);
4030   Ops.push_back(DAG.getValueType(SrcVT));
4031   Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4032                        Tys, &Ops[0], Ops.size());
4033
4034   if (useSSE) {
4035     Chain = Result.getValue(1);
4036     SDOperand InFlag = Result.getValue(2);
4037
4038     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4039     // shouldn't be necessary except that RFP cannot be live across
4040     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4041     MachineFunction &MF = DAG.getMachineFunction();
4042     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4043     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4044     Tys = DAG.getVTList(MVT::Other);
4045     SmallVector<SDOperand, 8> Ops;
4046     Ops.push_back(Chain);
4047     Ops.push_back(Result);
4048     Ops.push_back(StackSlot);
4049     Ops.push_back(DAG.getValueType(Op.getValueType()));
4050     Ops.push_back(InFlag);
4051     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4052     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot, NULL, 0);
4053   }
4054
4055   return Result;
4056 }
4057
4058 std::pair<SDOperand,SDOperand> X86TargetLowering::
4059 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4060   assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4061          "Unknown FP_TO_SINT to lower!");
4062
4063   // These are really Legal.
4064   if (Op.getValueType() == MVT::i32 && 
4065       X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32)
4066     return std::make_pair(SDOperand(), SDOperand());
4067   if (Op.getValueType() == MVT::i32 && 
4068       X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)
4069     return std::make_pair(SDOperand(), SDOperand());
4070   if (Subtarget->is64Bit() &&
4071       Op.getValueType() == MVT::i64 &&
4072       Op.getOperand(0).getValueType() != MVT::f80)
4073     return std::make_pair(SDOperand(), SDOperand());
4074
4075   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4076   // stack slot.
4077   MachineFunction &MF = DAG.getMachineFunction();
4078   unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4079   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4080   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4081   unsigned Opc;
4082   switch (Op.getValueType()) {
4083   default: assert(0 && "Invalid FP_TO_SINT to lower!");
4084   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4085   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4086   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4087   }
4088
4089   SDOperand Chain = DAG.getEntryNode();
4090   SDOperand Value = Op.getOperand(0);
4091   if ((X86ScalarSSEf32 && Op.getOperand(0).getValueType() == MVT::f32) ||
4092       (X86ScalarSSEf64 && Op.getOperand(0).getValueType() == MVT::f64)) {
4093     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4094     Chain = DAG.getStore(Chain, Value, StackSlot, NULL, 0);
4095     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4096     SDOperand Ops[] = {
4097       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4098     };
4099     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4100     Chain = Value.getValue(1);
4101     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4102     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4103   }
4104
4105   // Build the FP_TO_INT*_IN_MEM
4106   SDOperand Ops[] = { Chain, Value, StackSlot };
4107   SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4108
4109   return std::make_pair(FIST, StackSlot);
4110 }
4111
4112 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4113   std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4114   SDOperand FIST = Vals.first, StackSlot = Vals.second;
4115   if (FIST.Val == 0) return SDOperand();
4116   
4117   // Load the result.
4118   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4119 }
4120
4121 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4122   std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4123   SDOperand FIST = Vals.first, StackSlot = Vals.second;
4124   if (FIST.Val == 0) return 0;
4125   
4126   // Return an i64 load from the stack slot.
4127   SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4128
4129   // Use a MERGE_VALUES node to drop the chain result value.
4130   return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4131 }  
4132
4133 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4134   MVT::ValueType VT = Op.getValueType();
4135   MVT::ValueType EltVT = VT;
4136   if (MVT::isVector(VT))
4137     EltVT = MVT::getVectorElementType(VT);
4138   const Type *OpNTy =  MVT::getTypeForValueType(EltVT);
4139   std::vector<Constant*> CV;
4140   if (EltVT == MVT::f64) {
4141     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4142     CV.push_back(C);
4143     CV.push_back(C);
4144   } else {
4145     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4146     CV.push_back(C);
4147     CV.push_back(C);
4148     CV.push_back(C);
4149     CV.push_back(C);
4150   }
4151   Constant *C = ConstantVector::get(CV);
4152   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4153   SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4154                                false, 16);
4155   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4156 }
4157
4158 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4159   MVT::ValueType VT = Op.getValueType();
4160   MVT::ValueType EltVT = VT;
4161   unsigned EltNum = 1;
4162   if (MVT::isVector(VT)) {
4163     EltVT = MVT::getVectorElementType(VT);
4164     EltNum = MVT::getVectorNumElements(VT);
4165   }
4166   const Type *OpNTy =  MVT::getTypeForValueType(EltVT);
4167   std::vector<Constant*> CV;
4168   if (EltVT == MVT::f64) {
4169     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4170     CV.push_back(C);
4171     CV.push_back(C);
4172   } else {
4173     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4174     CV.push_back(C);
4175     CV.push_back(C);
4176     CV.push_back(C);
4177     CV.push_back(C);
4178   }
4179   Constant *C = ConstantVector::get(CV);
4180   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4181   SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4182                                false, 16);
4183   if (MVT::isVector(VT)) {
4184     return DAG.getNode(ISD::BIT_CONVERT, VT,
4185                        DAG.getNode(ISD::XOR, MVT::v2i64,
4186                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4187                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4188   } else {
4189     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4190   }
4191 }
4192
4193 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4194   SDOperand Op0 = Op.getOperand(0);
4195   SDOperand Op1 = Op.getOperand(1);
4196   MVT::ValueType VT = Op.getValueType();
4197   MVT::ValueType SrcVT = Op1.getValueType();
4198   const Type *SrcTy =  MVT::getTypeForValueType(SrcVT);
4199
4200   // If second operand is smaller, extend it first.
4201   if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4202     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4203     SrcVT = VT;
4204     SrcTy = MVT::getTypeForValueType(SrcVT);
4205   }
4206   // And if it is bigger, shrink it first.
4207   if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4208     Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1);
4209     SrcVT = VT;
4210     SrcTy = MVT::getTypeForValueType(SrcVT);
4211   }
4212
4213   // At this point the operands and the result should have the same
4214   // type, and that won't be f80 since that is not custom lowered.
4215
4216   // First get the sign bit of second operand.
4217   std::vector<Constant*> CV;
4218   if (SrcVT == MVT::f64) {
4219     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4220     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4221   } else {
4222     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4223     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4224     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4225     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4226   }
4227   Constant *C = ConstantVector::get(CV);
4228   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4229   SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx, NULL, 0,
4230                                 false, 16);
4231   SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4232
4233   // Shift sign bit right or left if the two operands have different types.
4234   if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4235     // Op0 is MVT::f32, Op1 is MVT::f64.
4236     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4237     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4238                           DAG.getConstant(32, MVT::i32));
4239     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4240     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4241                           DAG.getConstant(0, getPointerTy()));
4242   }
4243
4244   // Clear first operand sign bit.
4245   CV.clear();
4246   if (VT == MVT::f64) {
4247     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4248     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4249   } else {
4250     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4251     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4252     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4253     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4254   }
4255   C = ConstantVector::get(CV);
4256   CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4257   SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0,
4258                                 false, 16);
4259   SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4260
4261   // Or the value with the sign bit.
4262   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4263 }
4264
4265 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4266   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4267   SDOperand Cond;
4268   SDOperand Op0 = Op.getOperand(0);
4269   SDOperand Op1 = Op.getOperand(1);
4270   SDOperand CC = Op.getOperand(2);
4271   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4272   bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4273   unsigned X86CC;
4274
4275   if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4276                      Op0, Op1, DAG)) {
4277     Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4278     return DAG.getNode(X86ISD::SETCC, MVT::i8,
4279                        DAG.getConstant(X86CC, MVT::i8), Cond);
4280   }
4281
4282   assert(isFP && "Illegal integer SetCC!");
4283
4284   Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4285   switch (SetCCOpcode) {
4286   default: assert(false && "Illegal floating point SetCC!");
4287   case ISD::SETOEQ: {  // !PF & ZF
4288     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4289                                  DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4290     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4291                                  DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4292     return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4293   }
4294   case ISD::SETUNE: {  // PF | !ZF
4295     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4296                                  DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4297     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4298                                  DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4299     return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4300   }
4301   }
4302 }
4303
4304
4305 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4306   bool addTest = true;
4307   SDOperand Cond  = Op.getOperand(0);
4308   SDOperand CC;
4309
4310   if (Cond.getOpcode() == ISD::SETCC)
4311     Cond = LowerSETCC(Cond, DAG);
4312
4313   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4314   // setting operand in place of the X86ISD::SETCC.
4315   if (Cond.getOpcode() == X86ISD::SETCC) {
4316     CC = Cond.getOperand(0);
4317
4318     SDOperand Cmp = Cond.getOperand(1);
4319     unsigned Opc = Cmp.getOpcode();
4320     MVT::ValueType VT = Op.getValueType();
4321     bool IllegalFPCMov = false;
4322     if (VT == MVT::f32 && !X86ScalarSSEf32)
4323       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4324     else if (VT == MVT::f64 && !X86ScalarSSEf64)
4325       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4326     else if (VT == MVT::f80)
4327       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4328     if ((Opc == X86ISD::CMP ||
4329          Opc == X86ISD::COMI ||
4330          Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4331       Cond = Cmp;
4332       addTest = false;
4333     }
4334   }
4335
4336   if (addTest) {
4337     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4338     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4339   }
4340
4341   const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4342                                                     MVT::Flag);
4343   SmallVector<SDOperand, 4> Ops;
4344   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4345   // condition is true.
4346   Ops.push_back(Op.getOperand(2));
4347   Ops.push_back(Op.getOperand(1));
4348   Ops.push_back(CC);
4349   Ops.push_back(Cond);
4350   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4351 }
4352
4353 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4354   bool addTest = true;
4355   SDOperand Chain = Op.getOperand(0);
4356   SDOperand Cond  = Op.getOperand(1);
4357   SDOperand Dest  = Op.getOperand(2);
4358   SDOperand CC;
4359
4360   if (Cond.getOpcode() == ISD::SETCC)
4361     Cond = LowerSETCC(Cond, DAG);
4362
4363   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4364   // setting operand in place of the X86ISD::SETCC.
4365   if (Cond.getOpcode() == X86ISD::SETCC) {
4366     CC = Cond.getOperand(0);
4367
4368     SDOperand Cmp = Cond.getOperand(1);
4369     unsigned Opc = Cmp.getOpcode();
4370     if (Opc == X86ISD::CMP ||
4371         Opc == X86ISD::COMI ||
4372         Opc == X86ISD::UCOMI) {
4373       Cond = Cmp;
4374       addTest = false;
4375     }
4376   }
4377
4378   if (addTest) {
4379     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4380     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4381   }
4382   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4383                      Chain, Op.getOperand(2), CC, Cond);
4384 }
4385
4386 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
4387   unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4388   bool isTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
4389
4390    if (Subtarget->is64Bit())
4391      if(CallingConv==CallingConv::Fast && isTailCall && PerformTailCallOpt)
4392        return LowerX86_TailCallTo(Op, DAG, CallingConv);
4393      else
4394        return LowerX86_64CCCCallTo(Op, DAG, CallingConv);
4395   else
4396     switch (CallingConv) {
4397     default:
4398       assert(0 && "Unsupported calling convention");
4399     case CallingConv::Fast:
4400       if (isTailCall && PerformTailCallOpt)
4401         return LowerX86_TailCallTo(Op, DAG, CallingConv);
4402       else
4403         return LowerCCCCallTo(Op,DAG, CallingConv);
4404     case CallingConv::C:
4405     case CallingConv::X86_StdCall:
4406       return LowerCCCCallTo(Op, DAG, CallingConv);
4407     case CallingConv::X86_FastCall:
4408       return LowerFastCCCallTo(Op, DAG, CallingConv);
4409     }
4410 }
4411
4412
4413 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4414 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4415 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4416 // that the guard pages used by the OS virtual memory manager are allocated in
4417 // correct sequence.
4418 SDOperand
4419 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4420                                            SelectionDAG &DAG) {
4421   assert(Subtarget->isTargetCygMing() &&
4422          "This should be used only on Cygwin/Mingw targets");
4423   
4424   // Get the inputs.
4425   SDOperand Chain = Op.getOperand(0);
4426   SDOperand Size  = Op.getOperand(1);
4427   // FIXME: Ensure alignment here
4428
4429   SDOperand Flag;
4430   
4431   MVT::ValueType IntPtr = getPointerTy();
4432   MVT::ValueType SPTy = (Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
4433
4434   Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4435   Flag = Chain.getValue(1);
4436
4437   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4438   SDOperand Ops[] = { Chain,
4439                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
4440                       DAG.getRegister(X86::EAX, IntPtr),
4441                       Flag };
4442   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4443   Flag = Chain.getValue(1);
4444
4445   Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4446   
4447   std::vector<MVT::ValueType> Tys;
4448   Tys.push_back(SPTy);
4449   Tys.push_back(MVT::Other);
4450   SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4451   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4452 }
4453
4454 SDOperand
4455 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
4456   MachineFunction &MF = DAG.getMachineFunction();
4457   const Function* Fn = MF.getFunction();
4458   if (Fn->hasExternalLinkage() &&
4459       Subtarget->isTargetCygMing() &&
4460       Fn->getName() == "main")
4461     MF.getInfo<X86MachineFunctionInfo>()->setForceFramePointer(true);
4462
4463   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
4464   if (Subtarget->is64Bit())
4465     return LowerX86_64CCCArguments(Op, DAG);
4466   else
4467     switch(CC) {
4468     default:
4469       assert(0 && "Unsupported calling convention");
4470     case CallingConv::Fast:
4471       return LowerCCCArguments(Op,DAG, true);
4472       // Falls through
4473     case CallingConv::C:
4474       return LowerCCCArguments(Op, DAG);
4475     case CallingConv::X86_StdCall:
4476       MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(StdCall);
4477       return LowerCCCArguments(Op, DAG, true);
4478     case CallingConv::X86_FastCall:
4479       MF.getInfo<X86MachineFunctionInfo>()->setDecorationStyle(FastCall);
4480       return LowerFastCCArguments(Op, DAG);
4481     }
4482 }
4483
4484 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4485   SDOperand InFlag(0, 0);
4486   SDOperand Chain = Op.getOperand(0);
4487   unsigned Align =
4488     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4489   if (Align == 0) Align = 1;
4490
4491   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4492   // If not DWORD aligned or size is more than the threshold, call memset.
4493   // The libc version is likely to be faster for these cases. It can use the
4494   // address value and run time information about the CPU.
4495   if ((Align & 3) != 0 ||
4496       (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4497     MVT::ValueType IntPtr = getPointerTy();
4498     const Type *IntPtrTy = getTargetData()->getIntPtrType();
4499     TargetLowering::ArgListTy Args; 
4500     TargetLowering::ArgListEntry Entry;
4501     Entry.Node = Op.getOperand(1);
4502     Entry.Ty = IntPtrTy;
4503     Args.push_back(Entry);
4504     // Extend the unsigned i8 argument to be an int value for the call.
4505     Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4506     Entry.Ty = IntPtrTy;
4507     Args.push_back(Entry);
4508     Entry.Node = Op.getOperand(3);
4509     Args.push_back(Entry);
4510     std::pair<SDOperand,SDOperand> CallResult =
4511       LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4512                   DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4513     return CallResult.second;
4514   }
4515
4516   MVT::ValueType AVT;
4517   SDOperand Count;
4518   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4519   unsigned BytesLeft = 0;
4520   bool TwoRepStos = false;
4521   if (ValC) {
4522     unsigned ValReg;
4523     uint64_t Val = ValC->getValue() & 255;
4524
4525     // If the value is a constant, then we can potentially use larger sets.
4526     switch (Align & 3) {
4527       case 2:   // WORD aligned
4528         AVT = MVT::i16;
4529         ValReg = X86::AX;
4530         Val = (Val << 8) | Val;
4531         break;
4532       case 0:  // DWORD aligned
4533         AVT = MVT::i32;
4534         ValReg = X86::EAX;
4535         Val = (Val << 8)  | Val;
4536         Val = (Val << 16) | Val;
4537         if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) {  // QWORD aligned
4538           AVT = MVT::i64;
4539           ValReg = X86::RAX;
4540           Val = (Val << 32) | Val;
4541         }
4542         break;
4543       default:  // Byte aligned
4544         AVT = MVT::i8;
4545         ValReg = X86::AL;
4546         Count = Op.getOperand(3);
4547         break;
4548     }
4549
4550     if (AVT > MVT::i8) {
4551       if (I) {
4552         unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4553         Count = DAG.getConstant(I->getValue() / UBytes, getPointerTy());
4554         BytesLeft = I->getValue() % UBytes;
4555       } else {
4556         assert(AVT >= MVT::i32 &&
4557                "Do not use rep;stos if not at least DWORD aligned");
4558         Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4559                             Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4560         TwoRepStos = true;
4561       }
4562     }
4563
4564     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4565                               InFlag);
4566     InFlag = Chain.getValue(1);
4567   } else {
4568     AVT = MVT::i8;
4569     Count  = Op.getOperand(3);
4570     Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4571     InFlag = Chain.getValue(1);
4572   }
4573
4574   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4575                             Count, InFlag);
4576   InFlag = Chain.getValue(1);
4577   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4578                             Op.getOperand(1), InFlag);
4579   InFlag = Chain.getValue(1);
4580
4581   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4582   SmallVector<SDOperand, 8> Ops;
4583   Ops.push_back(Chain);
4584   Ops.push_back(DAG.getValueType(AVT));
4585   Ops.push_back(InFlag);
4586   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4587
4588   if (TwoRepStos) {
4589     InFlag = Chain.getValue(1);
4590     Count = Op.getOperand(3);
4591     MVT::ValueType CVT = Count.getValueType();
4592     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4593                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4594     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4595                               Left, InFlag);
4596     InFlag = Chain.getValue(1);
4597     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4598     Ops.clear();
4599     Ops.push_back(Chain);
4600     Ops.push_back(DAG.getValueType(MVT::i8));
4601     Ops.push_back(InFlag);
4602     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4603   } else if (BytesLeft) {
4604     // Issue stores for the last 1 - 7 bytes.
4605     SDOperand Value;
4606     unsigned Val = ValC->getValue() & 255;
4607     unsigned Offset = I->getValue() - BytesLeft;
4608     SDOperand DstAddr = Op.getOperand(1);
4609     MVT::ValueType AddrVT = DstAddr.getValueType();
4610     if (BytesLeft >= 4) {
4611       Val = (Val << 8)  | Val;
4612       Val = (Val << 16) | Val;
4613       Value = DAG.getConstant(Val, MVT::i32);
4614       Chain = DAG.getStore(Chain, Value,
4615                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4616                                        DAG.getConstant(Offset, AddrVT)),
4617                            NULL, 0);
4618       BytesLeft -= 4;
4619       Offset += 4;
4620     }
4621     if (BytesLeft >= 2) {
4622       Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4623       Chain = DAG.getStore(Chain, Value,
4624                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4625                                        DAG.getConstant(Offset, AddrVT)),
4626                            NULL, 0);
4627       BytesLeft -= 2;
4628       Offset += 2;
4629     }
4630     if (BytesLeft == 1) {
4631       Value = DAG.getConstant(Val, MVT::i8);
4632       Chain = DAG.getStore(Chain, Value,
4633                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4634                                        DAG.getConstant(Offset, AddrVT)),
4635                            NULL, 0);
4636     }
4637   }
4638
4639   return Chain;
4640 }
4641
4642 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4643                                                SDOperand Dest,
4644                                                SDOperand Source,
4645                                                unsigned Size,
4646                                                unsigned Align,
4647                                                SelectionDAG &DAG) {
4648   MVT::ValueType AVT;
4649   unsigned BytesLeft = 0;
4650   switch (Align & 3) {
4651     case 2:   // WORD aligned
4652       AVT = MVT::i16;
4653       break;
4654     case 0:  // DWORD aligned
4655       AVT = MVT::i32;
4656       if (Subtarget->is64Bit() && ((Align & 0xF) == 0))  // QWORD aligned
4657         AVT = MVT::i64;
4658       break;
4659     default:  // Byte aligned
4660       AVT = MVT::i8;
4661       break;
4662   }
4663
4664   unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4665   SDOperand Count = DAG.getConstant(Size / UBytes, getPointerTy());
4666   BytesLeft = Size % UBytes;
4667
4668   SDOperand InFlag(0, 0);
4669   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4670                             Count, InFlag);
4671   InFlag = Chain.getValue(1);
4672   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4673                             Dest, InFlag);
4674   InFlag = Chain.getValue(1);
4675   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4676                             Source, InFlag);
4677   InFlag = Chain.getValue(1);
4678
4679   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4680   SmallVector<SDOperand, 8> Ops;
4681   Ops.push_back(Chain);
4682   Ops.push_back(DAG.getValueType(AVT));
4683   Ops.push_back(InFlag);
4684   Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4685
4686   if (BytesLeft) {
4687     // Issue loads and stores for the last 1 - 7 bytes.
4688     unsigned Offset = Size - BytesLeft;
4689     SDOperand DstAddr = Dest;
4690     MVT::ValueType DstVT = DstAddr.getValueType();
4691     SDOperand SrcAddr = Source;
4692     MVT::ValueType SrcVT = SrcAddr.getValueType();
4693     SDOperand Value;
4694     if (BytesLeft >= 4) {
4695       Value = DAG.getLoad(MVT::i32, Chain,
4696                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4697                                       DAG.getConstant(Offset, SrcVT)),
4698                           NULL, 0);
4699       Chain = Value.getValue(1);
4700       Chain = DAG.getStore(Chain, Value,
4701                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
4702                                        DAG.getConstant(Offset, DstVT)),
4703                            NULL, 0);
4704       BytesLeft -= 4;
4705       Offset += 4;
4706     }
4707     if (BytesLeft >= 2) {
4708       Value = DAG.getLoad(MVT::i16, Chain,
4709                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4710                                       DAG.getConstant(Offset, SrcVT)),
4711                           NULL, 0);
4712       Chain = Value.getValue(1);
4713       Chain = DAG.getStore(Chain, Value,
4714                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
4715                                        DAG.getConstant(Offset, DstVT)),
4716                            NULL, 0);
4717       BytesLeft -= 2;
4718       Offset += 2;
4719     }
4720
4721     if (BytesLeft == 1) {
4722       Value = DAG.getLoad(MVT::i8, Chain,
4723                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4724                                       DAG.getConstant(Offset, SrcVT)),
4725                           NULL, 0);
4726       Chain = Value.getValue(1);
4727       Chain = DAG.getStore(Chain, Value,
4728                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
4729                                        DAG.getConstant(Offset, DstVT)),
4730                            NULL, 0);
4731     }
4732   }
4733
4734   return Chain;
4735 }
4736
4737 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4738 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4739   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4740   SDOperand TheChain = N->getOperand(0);
4741   SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4742   if (Subtarget->is64Bit()) {
4743     SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4744     SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4745                                        MVT::i64, rax.getValue(2));
4746     SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4747                                 DAG.getConstant(32, MVT::i8));
4748     SDOperand Ops[] = {
4749       DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4750     };
4751     
4752     Tys = DAG.getVTList(MVT::i64, MVT::Other);
4753     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4754   }
4755   
4756   SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4757   SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4758                                        MVT::i32, eax.getValue(2));
4759   // Use a buildpair to merge the two 32-bit values into a 64-bit one. 
4760   SDOperand Ops[] = { eax, edx };
4761   Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4762
4763   // Use a MERGE_VALUES to return the value and chain.
4764   Ops[1] = edx.getValue(1);
4765   Tys = DAG.getVTList(MVT::i64, MVT::Other);
4766   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4767 }
4768
4769 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4770   SrcValueSDNode *SV = cast<SrcValueSDNode>(Op.getOperand(2));
4771
4772   if (!Subtarget->is64Bit()) {
4773     // vastart just stores the address of the VarArgsFrameIndex slot into the
4774     // memory location argument.
4775     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4776     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV->getValue(),
4777                         SV->getOffset());
4778   }
4779
4780   // __va_list_tag:
4781   //   gp_offset         (0 - 6 * 8)
4782   //   fp_offset         (48 - 48 + 8 * 16)
4783   //   overflow_arg_area (point to parameters coming in memory).
4784   //   reg_save_area
4785   SmallVector<SDOperand, 8> MemOps;
4786   SDOperand FIN = Op.getOperand(1);
4787   // Store gp_offset
4788   SDOperand Store = DAG.getStore(Op.getOperand(0),
4789                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
4790                                  FIN, SV->getValue(), SV->getOffset());
4791   MemOps.push_back(Store);
4792
4793   // Store fp_offset
4794   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4795                     DAG.getConstant(4, getPointerTy()));
4796   Store = DAG.getStore(Op.getOperand(0),
4797                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
4798                        FIN, SV->getValue(), SV->getOffset());
4799   MemOps.push_back(Store);
4800
4801   // Store ptr to overflow_arg_area
4802   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4803                     DAG.getConstant(4, getPointerTy()));
4804   SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4805   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV->getValue(),
4806                        SV->getOffset());
4807   MemOps.push_back(Store);
4808
4809   // Store ptr to reg_save_area.
4810   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
4811                     DAG.getConstant(8, getPointerTy()));
4812   SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4813   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV->getValue(),
4814                        SV->getOffset());
4815   MemOps.push_back(Store);
4816   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4817 }
4818
4819 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4820   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4821   SDOperand Chain = Op.getOperand(0);
4822   SDOperand DstPtr = Op.getOperand(1);
4823   SDOperand SrcPtr = Op.getOperand(2);
4824   SrcValueSDNode *DstSV = cast<SrcValueSDNode>(Op.getOperand(3));
4825   SrcValueSDNode *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4));
4826
4827   SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr,
4828                        SrcSV->getValue(), SrcSV->getOffset());
4829   Chain = SrcPtr.getValue(1);
4830   for (unsigned i = 0; i < 3; ++i) {
4831     SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr,
4832                                 SrcSV->getValue(), SrcSV->getOffset());
4833     Chain = Val.getValue(1);
4834     Chain = DAG.getStore(Chain, Val, DstPtr,
4835                          DstSV->getValue(), DstSV->getOffset());
4836     if (i == 2)
4837       break;
4838     SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr, 
4839                          DAG.getConstant(8, getPointerTy()));
4840     DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr, 
4841                          DAG.getConstant(8, getPointerTy()));
4842   }
4843   return Chain;
4844 }
4845
4846 SDOperand
4847 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4848   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4849   switch (IntNo) {
4850   default: return SDOperand();    // Don't custom lower most intrinsics.
4851     // Comparison intrinsics.
4852   case Intrinsic::x86_sse_comieq_ss:
4853   case Intrinsic::x86_sse_comilt_ss:
4854   case Intrinsic::x86_sse_comile_ss:
4855   case Intrinsic::x86_sse_comigt_ss:
4856   case Intrinsic::x86_sse_comige_ss:
4857   case Intrinsic::x86_sse_comineq_ss:
4858   case Intrinsic::x86_sse_ucomieq_ss:
4859   case Intrinsic::x86_sse_ucomilt_ss:
4860   case Intrinsic::x86_sse_ucomile_ss:
4861   case Intrinsic::x86_sse_ucomigt_ss:
4862   case Intrinsic::x86_sse_ucomige_ss:
4863   case Intrinsic::x86_sse_ucomineq_ss:
4864   case Intrinsic::x86_sse2_comieq_sd:
4865   case Intrinsic::x86_sse2_comilt_sd:
4866   case Intrinsic::x86_sse2_comile_sd:
4867   case Intrinsic::x86_sse2_comigt_sd:
4868   case Intrinsic::x86_sse2_comige_sd:
4869   case Intrinsic::x86_sse2_comineq_sd:
4870   case Intrinsic::x86_sse2_ucomieq_sd:
4871   case Intrinsic::x86_sse2_ucomilt_sd:
4872   case Intrinsic::x86_sse2_ucomile_sd:
4873   case Intrinsic::x86_sse2_ucomigt_sd:
4874   case Intrinsic::x86_sse2_ucomige_sd:
4875   case Intrinsic::x86_sse2_ucomineq_sd: {
4876     unsigned Opc = 0;
4877     ISD::CondCode CC = ISD::SETCC_INVALID;
4878     switch (IntNo) {
4879     default: break;
4880     case Intrinsic::x86_sse_comieq_ss:
4881     case Intrinsic::x86_sse2_comieq_sd:
4882       Opc = X86ISD::COMI;
4883       CC = ISD::SETEQ;
4884       break;
4885     case Intrinsic::x86_sse_comilt_ss:
4886     case Intrinsic::x86_sse2_comilt_sd:
4887       Opc = X86ISD::COMI;
4888       CC = ISD::SETLT;
4889       break;
4890     case Intrinsic::x86_sse_comile_ss:
4891     case Intrinsic::x86_sse2_comile_sd:
4892       Opc = X86ISD::COMI;
4893       CC = ISD::SETLE;
4894       break;
4895     case Intrinsic::x86_sse_comigt_ss:
4896     case Intrinsic::x86_sse2_comigt_sd:
4897       Opc = X86ISD::COMI;
4898       CC = ISD::SETGT;
4899       break;
4900     case Intrinsic::x86_sse_comige_ss:
4901     case Intrinsic::x86_sse2_comige_sd:
4902       Opc = X86ISD::COMI;
4903       CC = ISD::SETGE;
4904       break;
4905     case Intrinsic::x86_sse_comineq_ss:
4906     case Intrinsic::x86_sse2_comineq_sd:
4907       Opc = X86ISD::COMI;
4908       CC = ISD::SETNE;
4909       break;
4910     case Intrinsic::x86_sse_ucomieq_ss:
4911     case Intrinsic::x86_sse2_ucomieq_sd:
4912       Opc = X86ISD::UCOMI;
4913       CC = ISD::SETEQ;
4914       break;
4915     case Intrinsic::x86_sse_ucomilt_ss:
4916     case Intrinsic::x86_sse2_ucomilt_sd:
4917       Opc = X86ISD::UCOMI;
4918       CC = ISD::SETLT;
4919       break;
4920     case Intrinsic::x86_sse_ucomile_ss:
4921     case Intrinsic::x86_sse2_ucomile_sd:
4922       Opc = X86ISD::UCOMI;
4923       CC = ISD::SETLE;
4924       break;
4925     case Intrinsic::x86_sse_ucomigt_ss:
4926     case Intrinsic::x86_sse2_ucomigt_sd:
4927       Opc = X86ISD::UCOMI;
4928       CC = ISD::SETGT;
4929       break;
4930     case Intrinsic::x86_sse_ucomige_ss:
4931     case Intrinsic::x86_sse2_ucomige_sd:
4932       Opc = X86ISD::UCOMI;
4933       CC = ISD::SETGE;
4934       break;
4935     case Intrinsic::x86_sse_ucomineq_ss:
4936     case Intrinsic::x86_sse2_ucomineq_sd:
4937       Opc = X86ISD::UCOMI;
4938       CC = ISD::SETNE;
4939       break;
4940     }
4941
4942     unsigned X86CC;
4943     SDOperand LHS = Op.getOperand(1);
4944     SDOperand RHS = Op.getOperand(2);
4945     translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4946
4947     SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4948     SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4949                                   DAG.getConstant(X86CC, MVT::i8), Cond);
4950     return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4951   }
4952   }
4953 }
4954
4955 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4956   // Depths > 0 not supported yet!
4957   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4958     return SDOperand();
4959   
4960   // Just load the return address
4961   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4962   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4963 }
4964
4965 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4966   // Depths > 0 not supported yet!
4967   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4968     return SDOperand();
4969     
4970   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4971   return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI, 
4972                      DAG.getConstant(4, getPointerTy()));
4973 }
4974
4975 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4976                                                        SelectionDAG &DAG) {
4977   // Is not yet supported on x86-64
4978   if (Subtarget->is64Bit())
4979     return SDOperand();
4980   
4981   return DAG.getConstant(8, getPointerTy());
4982 }
4983
4984 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4985 {
4986   assert(!Subtarget->is64Bit() &&
4987          "Lowering of eh_return builtin is not supported yet on x86-64");
4988     
4989   MachineFunction &MF = DAG.getMachineFunction();
4990   SDOperand Chain     = Op.getOperand(0);
4991   SDOperand Offset    = Op.getOperand(1);
4992   SDOperand Handler   = Op.getOperand(2);
4993
4994   SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
4995                                     getPointerTy());
4996
4997   SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
4998                                     DAG.getConstant(-4UL, getPointerTy()));
4999   StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5000   Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5001   Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5002   MF.addLiveOut(X86::ECX);
5003
5004   return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5005                      Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5006 }
5007
5008 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5009                                              SelectionDAG &DAG) {
5010   SDOperand Root = Op.getOperand(0);
5011   SDOperand Trmp = Op.getOperand(1); // trampoline
5012   SDOperand FPtr = Op.getOperand(2); // nested function
5013   SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5014
5015   SrcValueSDNode *TrmpSV = cast<SrcValueSDNode>(Op.getOperand(4));
5016
5017   if (Subtarget->is64Bit()) {
5018     return SDOperand(); // not yet supported
5019   } else {
5020     Function *Func = (Function *)
5021       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5022     unsigned CC = Func->getCallingConv();
5023     unsigned NestReg;
5024
5025     switch (CC) {
5026     default:
5027       assert(0 && "Unsupported calling convention");
5028     case CallingConv::C:
5029     case CallingConv::X86_StdCall: {
5030       // Pass 'nest' parameter in ECX.
5031       // Must be kept in sync with X86CallingConv.td
5032       NestReg = X86::ECX;
5033
5034       // Check that ECX wasn't needed by an 'inreg' parameter.
5035       const FunctionType *FTy = Func->getFunctionType();
5036       const ParamAttrsList *Attrs = Func->getParamAttrs();
5037
5038       if (Attrs && !Func->isVarArg()) {
5039         unsigned InRegCount = 0;
5040         unsigned Idx = 1;
5041
5042         for (FunctionType::param_iterator I = FTy->param_begin(),
5043              E = FTy->param_end(); I != E; ++I, ++Idx)
5044           if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5045             // FIXME: should only count parameters that are lowered to integers.
5046             InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5047
5048         if (InRegCount > 2) {
5049           cerr << "Nest register in use - reduce number of inreg parameters!\n";
5050           abort();
5051         }
5052       }
5053       break;
5054     }
5055     case CallingConv::X86_FastCall:
5056       // Pass 'nest' parameter in EAX.
5057       // Must be kept in sync with X86CallingConv.td
5058       NestReg = X86::EAX;
5059       break;
5060     }
5061
5062     const X86InstrInfo *TII =
5063       ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5064
5065     SDOperand OutChains[4];
5066     SDOperand Addr, Disp;
5067
5068     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5069     Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5070
5071     unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5072     unsigned char N86Reg  = ((X86RegisterInfo&)RegInfo).getX86RegNum(NestReg);
5073     OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5074                                 Trmp, TrmpSV->getValue(), TrmpSV->getOffset());
5075
5076     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5077     OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpSV->getValue(),
5078                                 TrmpSV->getOffset() + 1, false, 1);
5079
5080     unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5081     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5082     OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5083                                 TrmpSV->getValue() + 5, TrmpSV->getOffset());
5084
5085     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5086     OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpSV->getValue(),
5087                                 TrmpSV->getOffset() + 6, false, 1);
5088
5089     SDOperand Ops[] =
5090       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5091     return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5092   }
5093 }
5094
5095 SDOperand X86TargetLowering::LowerFLT_ROUNDS(SDOperand Op, SelectionDAG &DAG) {
5096   /*
5097    The rounding mode is in bits 11:10 of FPSR, and has the following
5098    settings:
5099      00 Round to nearest
5100      01 Round to -inf
5101      10 Round to +inf
5102      11 Round to 0
5103
5104   FLT_ROUNDS, on the other hand, expects the following:
5105     -1 Undefined
5106      0 Round to 0
5107      1 Round to nearest
5108      2 Round to +inf
5109      3 Round to -inf
5110
5111   To perform the conversion, we do:
5112     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5113   */
5114
5115   MachineFunction &MF = DAG.getMachineFunction();
5116   const TargetMachine &TM = MF.getTarget();
5117   const TargetFrameInfo &TFI = *TM.getFrameInfo();
5118   unsigned StackAlignment = TFI.getStackAlignment();
5119   MVT::ValueType VT = Op.getValueType();
5120
5121   // Save FP Control Word to stack slot
5122   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5123   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5124
5125   SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5126                                 DAG.getEntryNode(), StackSlot);
5127
5128   // Load FP Control Word from stack slot
5129   SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5130
5131   // Transform as necessary
5132   SDOperand CWD1 =
5133     DAG.getNode(ISD::SRL, MVT::i16,
5134                 DAG.getNode(ISD::AND, MVT::i16,
5135                             CWD, DAG.getConstant(0x800, MVT::i16)),
5136                 DAG.getConstant(11, MVT::i8));
5137   SDOperand CWD2 =
5138     DAG.getNode(ISD::SRL, MVT::i16,
5139                 DAG.getNode(ISD::AND, MVT::i16,
5140                             CWD, DAG.getConstant(0x400, MVT::i16)),
5141                 DAG.getConstant(9, MVT::i8));
5142
5143   SDOperand RetVal =
5144     DAG.getNode(ISD::AND, MVT::i16,
5145                 DAG.getNode(ISD::ADD, MVT::i16,
5146                             DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5147                             DAG.getConstant(1, MVT::i16)),
5148                 DAG.getConstant(3, MVT::i16));
5149
5150
5151   return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5152                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5153 }
5154
5155 /// LowerOperation - Provide custom lowering hooks for some operations.
5156 ///
5157 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5158   switch (Op.getOpcode()) {
5159   default: assert(0 && "Should not custom lower this!");
5160   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5161   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5162   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5163   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
5164   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5165   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5166   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5167   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5168   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
5169   case ISD::SHL_PARTS:
5170   case ISD::SRA_PARTS:
5171   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
5172   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5173   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
5174   case ISD::FABS:               return LowerFABS(Op, DAG);
5175   case ISD::FNEG:               return LowerFNEG(Op, DAG);
5176   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
5177   case ISD::SETCC:              return LowerSETCC(Op, DAG);
5178   case ISD::SELECT:             return LowerSELECT(Op, DAG);
5179   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
5180   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5181   case ISD::CALL:               return LowerCALL(Op, DAG);
5182   case ISD::RET:                return LowerRET(Op, DAG);
5183   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
5184   case ISD::MEMSET:             return LowerMEMSET(Op, DAG);
5185   case ISD::MEMCPY:             return LowerMEMCPY(Op, DAG);
5186   case ISD::VASTART:            return LowerVASTART(Op, DAG);
5187   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
5188   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5189   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
5190   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
5191   case ISD::FRAME_TO_ARGS_OFFSET:
5192                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5193   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5194   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
5195   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
5196   case ISD::FLT_ROUNDS:         return LowerFLT_ROUNDS(Op, DAG);
5197       
5198       
5199   // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5200   case ISD::READCYCLECOUNTER:
5201     return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5202   }
5203 }
5204
5205 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5206 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5207   switch (N->getOpcode()) {
5208   default: assert(0 && "Should not custom lower this!");
5209   case ISD::FP_TO_SINT:         return ExpandFP_TO_SINT(N, DAG);
5210   case ISD::READCYCLECOUNTER:   return ExpandREADCYCLECOUNTER(N, DAG);
5211   }
5212 }
5213
5214 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5215   switch (Opcode) {
5216   default: return NULL;
5217   case X86ISD::SHLD:               return "X86ISD::SHLD";
5218   case X86ISD::SHRD:               return "X86ISD::SHRD";
5219   case X86ISD::FAND:               return "X86ISD::FAND";
5220   case X86ISD::FOR:                return "X86ISD::FOR";
5221   case X86ISD::FXOR:               return "X86ISD::FXOR";
5222   case X86ISD::FSRL:               return "X86ISD::FSRL";
5223   case X86ISD::FILD:               return "X86ISD::FILD";
5224   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
5225   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5226   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5227   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5228   case X86ISD::FLD:                return "X86ISD::FLD";
5229   case X86ISD::FST:                return "X86ISD::FST";
5230   case X86ISD::FP_GET_RESULT:      return "X86ISD::FP_GET_RESULT";
5231   case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
5232   case X86ISD::CALL:               return "X86ISD::CALL";
5233   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
5234   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
5235   case X86ISD::CMP:                return "X86ISD::CMP";
5236   case X86ISD::COMI:               return "X86ISD::COMI";
5237   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
5238   case X86ISD::SETCC:              return "X86ISD::SETCC";
5239   case X86ISD::CMOV:               return "X86ISD::CMOV";
5240   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
5241   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
5242   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
5243   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
5244   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
5245   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
5246   case X86ISD::S2VEC:              return "X86ISD::S2VEC";
5247   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
5248   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
5249   case X86ISD::FMAX:               return "X86ISD::FMAX";
5250   case X86ISD::FMIN:               return "X86ISD::FMIN";
5251   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
5252   case X86ISD::FRCP:               return "X86ISD::FRCP";
5253   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
5254   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
5255   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
5256   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
5257   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
5258   }
5259 }
5260
5261 // isLegalAddressingMode - Return true if the addressing mode represented
5262 // by AM is legal for this target, for a load/store of the specified type.
5263 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
5264                                               const Type *Ty) const {
5265   // X86 supports extremely general addressing modes.
5266   
5267   // X86 allows a sign-extended 32-bit immediate field as a displacement.
5268   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5269     return false;
5270   
5271   if (AM.BaseGV) {
5272     // We can only fold this if we don't need an extra load.
5273     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5274       return false;
5275
5276     // X86-64 only supports addr of globals in small code model.
5277     if (Subtarget->is64Bit()) {
5278       if (getTargetMachine().getCodeModel() != CodeModel::Small)
5279         return false;
5280       // If lower 4G is not available, then we must use rip-relative addressing.
5281       if (AM.BaseOffs || AM.Scale > 1)
5282         return false;
5283     }
5284   }
5285   
5286   switch (AM.Scale) {
5287   case 0:
5288   case 1:
5289   case 2:
5290   case 4:
5291   case 8:
5292     // These scales always work.
5293     break;
5294   case 3:
5295   case 5:
5296   case 9:
5297     // These scales are formed with basereg+scalereg.  Only accept if there is
5298     // no basereg yet.
5299     if (AM.HasBaseReg)
5300       return false;
5301     break;
5302   default:  // Other stuff never works.
5303     return false;
5304   }
5305   
5306   return true;
5307 }
5308
5309
5310 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5311   if (!Ty1->isInteger() || !Ty2->isInteger())
5312     return false;
5313   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5314   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5315   if (NumBits1 <= NumBits2)
5316     return false;
5317   return Subtarget->is64Bit() || NumBits1 < 64;
5318 }
5319
5320 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5321                                        MVT::ValueType VT2) const {
5322   if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5323     return false;
5324   unsigned NumBits1 = MVT::getSizeInBits(VT1);
5325   unsigned NumBits2 = MVT::getSizeInBits(VT2);
5326   if (NumBits1 <= NumBits2)
5327     return false;
5328   return Subtarget->is64Bit() || NumBits1 < 64;
5329 }
5330
5331 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5332 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5333 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5334 /// are assumed to be legal.
5335 bool
5336 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5337   // Only do shuffles on 128-bit vector types for now.
5338   if (MVT::getSizeInBits(VT) == 64) return false;
5339   return (Mask.Val->getNumOperands() <= 4 ||
5340           isIdentityMask(Mask.Val) ||
5341           isIdentityMask(Mask.Val, true) ||
5342           isSplatMask(Mask.Val)  ||
5343           isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5344           X86::isUNPCKLMask(Mask.Val) ||
5345           X86::isUNPCKHMask(Mask.Val) ||
5346           X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5347           X86::isUNPCKH_v_undef_Mask(Mask.Val));
5348 }
5349
5350 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5351                                                MVT::ValueType EVT,
5352                                                SelectionDAG &DAG) const {
5353   unsigned NumElts = BVOps.size();
5354   // Only do shuffles on 128-bit vector types for now.
5355   if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5356   if (NumElts == 2) return true;
5357   if (NumElts == 4) {
5358     return (isMOVLMask(&BVOps[0], 4)  ||
5359             isCommutedMOVL(&BVOps[0], 4, true) ||
5360             isSHUFPMask(&BVOps[0], 4) || 
5361             isCommutedSHUFP(&BVOps[0], 4));
5362   }
5363   return false;
5364 }
5365
5366 //===----------------------------------------------------------------------===//
5367 //                           X86 Scheduler Hooks
5368 //===----------------------------------------------------------------------===//
5369
5370 MachineBasicBlock *
5371 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
5372                                            MachineBasicBlock *BB) {
5373   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5374   switch (MI->getOpcode()) {
5375   default: assert(false && "Unexpected instr type to insert");
5376   case X86::CMOV_FR32:
5377   case X86::CMOV_FR64:
5378   case X86::CMOV_V4F32:
5379   case X86::CMOV_V2F64:
5380   case X86::CMOV_V2I64: {
5381     // To "insert" a SELECT_CC instruction, we actually have to insert the
5382     // diamond control-flow pattern.  The incoming instruction knows the
5383     // destination vreg to set, the condition code register to branch on, the
5384     // true/false values to select between, and a branch opcode to use.
5385     const BasicBlock *LLVM_BB = BB->getBasicBlock();
5386     ilist<MachineBasicBlock>::iterator It = BB;
5387     ++It;
5388
5389     //  thisMBB:
5390     //  ...
5391     //   TrueVal = ...
5392     //   cmpTY ccX, r1, r2
5393     //   bCC copy1MBB
5394     //   fallthrough --> copy0MBB
5395     MachineBasicBlock *thisMBB = BB;
5396     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5397     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5398     unsigned Opc =
5399       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5400     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5401     MachineFunction *F = BB->getParent();
5402     F->getBasicBlockList().insert(It, copy0MBB);
5403     F->getBasicBlockList().insert(It, sinkMBB);
5404     // Update machine-CFG edges by first adding all successors of the current
5405     // block to the new block which will contain the Phi node for the select.
5406     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5407         e = BB->succ_end(); i != e; ++i)
5408       sinkMBB->addSuccessor(*i);
5409     // Next, remove all successors of the current block, and add the true
5410     // and fallthrough blocks as its successors.
5411     while(!BB->succ_empty())
5412       BB->removeSuccessor(BB->succ_begin());
5413     BB->addSuccessor(copy0MBB);
5414     BB->addSuccessor(sinkMBB);
5415
5416     //  copy0MBB:
5417     //   %FalseValue = ...
5418     //   # fallthrough to sinkMBB
5419     BB = copy0MBB;
5420
5421     // Update machine-CFG edges
5422     BB->addSuccessor(sinkMBB);
5423
5424     //  sinkMBB:
5425     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5426     //  ...
5427     BB = sinkMBB;
5428     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5429       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5430       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5431
5432     delete MI;   // The pseudo instruction is gone now.
5433     return BB;
5434   }
5435
5436   case X86::FP32_TO_INT16_IN_MEM:
5437   case X86::FP32_TO_INT32_IN_MEM:
5438   case X86::FP32_TO_INT64_IN_MEM:
5439   case X86::FP64_TO_INT16_IN_MEM:
5440   case X86::FP64_TO_INT32_IN_MEM:
5441   case X86::FP64_TO_INT64_IN_MEM:
5442   case X86::FP80_TO_INT16_IN_MEM:
5443   case X86::FP80_TO_INT32_IN_MEM:
5444   case X86::FP80_TO_INT64_IN_MEM: {
5445     // Change the floating point control register to use "round towards zero"
5446     // mode when truncating to an integer value.
5447     MachineFunction *F = BB->getParent();
5448     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5449     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5450
5451     // Load the old value of the high byte of the control word...
5452     unsigned OldCW =
5453       F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
5454     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5455
5456     // Set the high part to be round to zero...
5457     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5458       .addImm(0xC7F);
5459
5460     // Reload the modified control word now...
5461     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5462
5463     // Restore the memory image of control word to original value
5464     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5465       .addReg(OldCW);
5466
5467     // Get the X86 opcode to use.
5468     unsigned Opc;
5469     switch (MI->getOpcode()) {
5470     default: assert(0 && "illegal opcode!");
5471     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5472     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5473     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5474     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5475     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5476     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5477     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5478     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5479     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5480     }
5481
5482     X86AddressMode AM;
5483     MachineOperand &Op = MI->getOperand(0);
5484     if (Op.isRegister()) {
5485       AM.BaseType = X86AddressMode::RegBase;
5486       AM.Base.Reg = Op.getReg();
5487     } else {
5488       AM.BaseType = X86AddressMode::FrameIndexBase;
5489       AM.Base.FrameIndex = Op.getFrameIndex();
5490     }
5491     Op = MI->getOperand(1);
5492     if (Op.isImmediate())
5493       AM.Scale = Op.getImm();
5494     Op = MI->getOperand(2);
5495     if (Op.isImmediate())
5496       AM.IndexReg = Op.getImm();
5497     Op = MI->getOperand(3);
5498     if (Op.isGlobalAddress()) {
5499       AM.GV = Op.getGlobal();
5500     } else {
5501       AM.Disp = Op.getImm();
5502     }
5503     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5504                       .addReg(MI->getOperand(4).getReg());
5505
5506     // Reload the original control word now.
5507     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5508
5509     delete MI;   // The pseudo instruction is gone now.
5510     return BB;
5511   }
5512   }
5513 }
5514
5515 //===----------------------------------------------------------------------===//
5516 //                           X86 Optimization Hooks
5517 //===----------------------------------------------------------------------===//
5518
5519 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5520                                                        uint64_t Mask,
5521                                                        uint64_t &KnownZero,
5522                                                        uint64_t &KnownOne,
5523                                                        const SelectionDAG &DAG,
5524                                                        unsigned Depth) const {
5525   unsigned Opc = Op.getOpcode();
5526   assert((Opc >= ISD::BUILTIN_OP_END ||
5527           Opc == ISD::INTRINSIC_WO_CHAIN ||
5528           Opc == ISD::INTRINSIC_W_CHAIN ||
5529           Opc == ISD::INTRINSIC_VOID) &&
5530          "Should use MaskedValueIsZero if you don't know whether Op"
5531          " is a target node!");
5532
5533   KnownZero = KnownOne = 0;   // Don't know anything.
5534   switch (Opc) {
5535   default: break;
5536   case X86ISD::SETCC:
5537     KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5538     break;
5539   }
5540 }
5541
5542 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5543 /// element of the result of the vector shuffle.
5544 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5545   MVT::ValueType VT = N->getValueType(0);
5546   SDOperand PermMask = N->getOperand(2);
5547   unsigned NumElems = PermMask.getNumOperands();
5548   SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5549   i %= NumElems;
5550   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5551     return (i == 0)
5552      ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5553   } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5554     SDOperand Idx = PermMask.getOperand(i);
5555     if (Idx.getOpcode() == ISD::UNDEF)
5556       return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5557     return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5558   }
5559   return SDOperand();
5560 }
5561
5562 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5563 /// node is a GlobalAddress + an offset.
5564 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5565   unsigned Opc = N->getOpcode();
5566   if (Opc == X86ISD::Wrapper) {
5567     if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5568       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5569       return true;
5570     }
5571   } else if (Opc == ISD::ADD) {
5572     SDOperand N1 = N->getOperand(0);
5573     SDOperand N2 = N->getOperand(1);
5574     if (isGAPlusOffset(N1.Val, GA, Offset)) {
5575       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5576       if (V) {
5577         Offset += V->getSignExtended();
5578         return true;
5579       }
5580     } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5581       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5582       if (V) {
5583         Offset += V->getSignExtended();
5584         return true;
5585       }
5586     }
5587   }
5588   return false;
5589 }
5590
5591 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5592 /// + Dist * Size.
5593 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5594                               MachineFrameInfo *MFI) {
5595   if (N->getOperand(0).Val != Base->getOperand(0).Val)
5596     return false;
5597
5598   SDOperand Loc = N->getOperand(1);
5599   SDOperand BaseLoc = Base->getOperand(1);
5600   if (Loc.getOpcode() == ISD::FrameIndex) {
5601     if (BaseLoc.getOpcode() != ISD::FrameIndex)
5602       return false;
5603     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
5604     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5605     int FS  = MFI->getObjectSize(FI);
5606     int BFS = MFI->getObjectSize(BFI);
5607     if (FS != BFS || FS != Size) return false;
5608     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5609   } else {
5610     GlobalValue *GV1 = NULL;
5611     GlobalValue *GV2 = NULL;
5612     int64_t Offset1 = 0;
5613     int64_t Offset2 = 0;
5614     bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5615     bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5616     if (isGA1 && isGA2 && GV1 == GV2)
5617       return Offset1 == (Offset2 + Dist*Size);
5618   }
5619
5620   return false;
5621 }
5622
5623 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5624                               const X86Subtarget *Subtarget) {
5625   GlobalValue *GV;
5626   int64_t Offset;
5627   if (isGAPlusOffset(Base, GV, Offset))
5628     return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5629   else {
5630     assert(Base->getOpcode() == ISD::FrameIndex && "Unexpected base node!");
5631     int BFI = cast<FrameIndexSDNode>(Base)->getIndex();
5632     if (BFI < 0)
5633       // Fixed objects do not specify alignment, however the offsets are known.
5634       return ((Subtarget->getStackAlignment() % 16) == 0 &&
5635               (MFI->getObjectOffset(BFI) % 16) == 0);
5636     else
5637       return MFI->getObjectAlignment(BFI) >= 16;
5638   }
5639   return false;
5640 }
5641
5642
5643 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5644 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5645 /// if the load addresses are consecutive, non-overlapping, and in the right
5646 /// order.
5647 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5648                                        const X86Subtarget *Subtarget) {
5649   MachineFunction &MF = DAG.getMachineFunction();
5650   MachineFrameInfo *MFI = MF.getFrameInfo();
5651   MVT::ValueType VT = N->getValueType(0);
5652   MVT::ValueType EVT = MVT::getVectorElementType(VT);
5653   SDOperand PermMask = N->getOperand(2);
5654   int NumElems = (int)PermMask.getNumOperands();
5655   SDNode *Base = NULL;
5656   for (int i = 0; i < NumElems; ++i) {
5657     SDOperand Idx = PermMask.getOperand(i);
5658     if (Idx.getOpcode() == ISD::UNDEF) {
5659       if (!Base) return SDOperand();
5660     } else {
5661       SDOperand Arg =
5662         getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5663       if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5664         return SDOperand();
5665       if (!Base)
5666         Base = Arg.Val;
5667       else if (!isConsecutiveLoad(Arg.Val, Base,
5668                                   i, MVT::getSizeInBits(EVT)/8,MFI))
5669         return SDOperand();
5670     }
5671   }
5672
5673   bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5674   LoadSDNode *LD = cast<LoadSDNode>(Base);
5675   if (isAlign16) {
5676     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5677                        LD->getSrcValueOffset(), LD->isVolatile());
5678   } else {
5679     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5680                        LD->getSrcValueOffset(), LD->isVolatile(),
5681                        LD->getAlignment());
5682   }
5683 }
5684
5685 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5686 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5687                                       const X86Subtarget *Subtarget) {
5688   SDOperand Cond = N->getOperand(0);
5689
5690   // If we have SSE[12] support, try to form min/max nodes.
5691   if (Subtarget->hasSSE2() &&
5692       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5693     if (Cond.getOpcode() == ISD::SETCC) {
5694       // Get the LHS/RHS of the select.
5695       SDOperand LHS = N->getOperand(1);
5696       SDOperand RHS = N->getOperand(2);
5697       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5698
5699       unsigned Opcode = 0;
5700       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5701         switch (CC) {
5702         default: break;
5703         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5704         case ISD::SETULE:
5705         case ISD::SETLE:
5706           if (!UnsafeFPMath) break;
5707           // FALL THROUGH.
5708         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
5709         case ISD::SETLT:
5710           Opcode = X86ISD::FMIN;
5711           break;
5712
5713         case ISD::SETOGT: // (X > Y) ? X : Y -> max
5714         case ISD::SETUGT:
5715         case ISD::SETGT:
5716           if (!UnsafeFPMath) break;
5717           // FALL THROUGH.
5718         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
5719         case ISD::SETGE:
5720           Opcode = X86ISD::FMAX;
5721           break;
5722         }
5723       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5724         switch (CC) {
5725         default: break;
5726         case ISD::SETOGT: // (X > Y) ? Y : X -> min
5727         case ISD::SETUGT:
5728         case ISD::SETGT:
5729           if (!UnsafeFPMath) break;
5730           // FALL THROUGH.
5731         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
5732         case ISD::SETGE:
5733           Opcode = X86ISD::FMIN;
5734           break;
5735
5736         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
5737         case ISD::SETULE:
5738         case ISD::SETLE:
5739           if (!UnsafeFPMath) break;
5740           // FALL THROUGH.
5741         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
5742         case ISD::SETLT:
5743           Opcode = X86ISD::FMAX;
5744           break;
5745         }
5746       }
5747
5748       if (Opcode)
5749         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5750     }
5751
5752   }
5753
5754   return SDOperand();
5755 }
5756
5757
5758 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5759                                                DAGCombinerInfo &DCI) const {
5760   SelectionDAG &DAG = DCI.DAG;
5761   switch (N->getOpcode()) {
5762   default: break;
5763   case ISD::VECTOR_SHUFFLE:
5764     return PerformShuffleCombine(N, DAG, Subtarget);
5765   case ISD::SELECT:
5766     return PerformSELECTCombine(N, DAG, Subtarget);
5767   }
5768
5769   return SDOperand();
5770 }
5771
5772 //===----------------------------------------------------------------------===//
5773 //                           X86 Inline Assembly Support
5774 //===----------------------------------------------------------------------===//
5775
5776 /// getConstraintType - Given a constraint letter, return the type of
5777 /// constraint it is for this target.
5778 X86TargetLowering::ConstraintType
5779 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5780   if (Constraint.size() == 1) {
5781     switch (Constraint[0]) {
5782     case 'A':
5783     case 'r':
5784     case 'R':
5785     case 'l':
5786     case 'q':
5787     case 'Q':
5788     case 'x':
5789     case 'Y':
5790       return C_RegisterClass;
5791     default:
5792       break;
5793     }
5794   }
5795   return TargetLowering::getConstraintType(Constraint);
5796 }
5797
5798 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5799 /// vector.  If it is invalid, don't add anything to Ops.
5800 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5801                                                      char Constraint,
5802                                                      std::vector<SDOperand>&Ops,
5803                                                      SelectionDAG &DAG) {
5804   SDOperand Result(0, 0);
5805   
5806   switch (Constraint) {
5807   default: break;
5808   case 'I':
5809     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5810       if (C->getValue() <= 31) {
5811         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5812         break;
5813       }
5814     }
5815     return;
5816   case 'N':
5817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5818       if (C->getValue() <= 255) {
5819         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5820         break;
5821       }
5822     }
5823     return;
5824   case 'i': {
5825     // Literal immediates are always ok.
5826     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5827       Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5828       break;
5829     }
5830
5831     // If we are in non-pic codegen mode, we allow the address of a global (with
5832     // an optional displacement) to be used with 'i'.
5833     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5834     int64_t Offset = 0;
5835     
5836     // Match either (GA) or (GA+C)
5837     if (GA) {
5838       Offset = GA->getOffset();
5839     } else if (Op.getOpcode() == ISD::ADD) {
5840       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5841       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5842       if (C && GA) {
5843         Offset = GA->getOffset()+C->getValue();
5844       } else {
5845         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5846         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5847         if (C && GA)
5848           Offset = GA->getOffset()+C->getValue();
5849         else
5850           C = 0, GA = 0;
5851       }
5852     }
5853     
5854     if (GA) {
5855       // If addressing this global requires a load (e.g. in PIC mode), we can't
5856       // match.
5857       if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
5858                                          false))
5859         return;
5860
5861       Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5862                                       Offset);
5863       Result = Op;
5864       break;
5865     }
5866
5867     // Otherwise, not valid for this mode.
5868     return;
5869   }
5870   }
5871   
5872   if (Result.Val) {
5873     Ops.push_back(Result);
5874     return;
5875   }
5876   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5877 }
5878
5879 std::vector<unsigned> X86TargetLowering::
5880 getRegClassForInlineAsmConstraint(const std::string &Constraint,
5881                                   MVT::ValueType VT) const {
5882   if (Constraint.size() == 1) {
5883     // FIXME: not handling fp-stack yet!
5884     switch (Constraint[0]) {      // GCC X86 Constraint Letters
5885     default: break;  // Unknown constraint letter
5886     case 'A':   // EAX/EDX
5887       if (VT == MVT::i32 || VT == MVT::i64)
5888         return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
5889       break;
5890     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
5891     case 'Q':   // Q_REGS
5892       if (VT == MVT::i32)
5893         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
5894       else if (VT == MVT::i16)
5895         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
5896       else if (VT == MVT::i8)
5897         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
5898       else if (VT == MVT::i64)
5899         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
5900       break;
5901     }
5902   }
5903
5904   return std::vector<unsigned>();
5905 }
5906
5907 std::pair<unsigned, const TargetRegisterClass*>
5908 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5909                                                 MVT::ValueType VT) const {
5910   // First, see if this is a constraint that directly corresponds to an LLVM
5911   // register class.
5912   if (Constraint.size() == 1) {
5913     // GCC Constraint Letters
5914     switch (Constraint[0]) {
5915     default: break;
5916     case 'r':   // GENERAL_REGS
5917     case 'R':   // LEGACY_REGS
5918     case 'l':   // INDEX_REGS
5919       if (VT == MVT::i64 && Subtarget->is64Bit())
5920         return std::make_pair(0U, X86::GR64RegisterClass);
5921       if (VT == MVT::i32)
5922         return std::make_pair(0U, X86::GR32RegisterClass);
5923       else if (VT == MVT::i16)
5924         return std::make_pair(0U, X86::GR16RegisterClass);
5925       else if (VT == MVT::i8)
5926         return std::make_pair(0U, X86::GR8RegisterClass);
5927       break;
5928     case 'y':   // MMX_REGS if MMX allowed.
5929       if (!Subtarget->hasMMX()) break;
5930       return std::make_pair(0U, X86::VR64RegisterClass);
5931       break;
5932     case 'Y':   // SSE_REGS if SSE2 allowed
5933       if (!Subtarget->hasSSE2()) break;
5934       // FALL THROUGH.
5935     case 'x':   // SSE_REGS if SSE1 allowed
5936       if (!Subtarget->hasSSE1()) break;
5937       
5938       switch (VT) {
5939       default: break;
5940       // Scalar SSE types.
5941       case MVT::f32:
5942       case MVT::i32:
5943         return std::make_pair(0U, X86::FR32RegisterClass);
5944       case MVT::f64:
5945       case MVT::i64:
5946         return std::make_pair(0U, X86::FR64RegisterClass);
5947       // Vector types.
5948       case MVT::v16i8:
5949       case MVT::v8i16:
5950       case MVT::v4i32:
5951       case MVT::v2i64:
5952       case MVT::v4f32:
5953       case MVT::v2f64:
5954         return std::make_pair(0U, X86::VR128RegisterClass);
5955       }
5956       break;
5957     }
5958   }
5959   
5960   // Use the default implementation in TargetLowering to convert the register
5961   // constraint into a member of a register class.
5962   std::pair<unsigned, const TargetRegisterClass*> Res;
5963   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5964
5965   // Not found as a standard register?
5966   if (Res.second == 0) {
5967     // GCC calls "st(0)" just plain "st".
5968     if (StringsEqualNoCase("{st}", Constraint)) {
5969       Res.first = X86::ST0;
5970       Res.second = X86::RFP80RegisterClass;
5971     }
5972
5973     return Res;
5974   }
5975
5976   // Otherwise, check to see if this is a register class of the wrong value
5977   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
5978   // turn into {ax},{dx}.
5979   if (Res.second->hasType(VT))
5980     return Res;   // Correct type already, nothing to do.
5981
5982   // All of the single-register GCC register classes map their values onto
5983   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
5984   // really want an 8-bit or 32-bit register, map to the appropriate register
5985   // class and return the appropriate register.
5986   if (Res.second != X86::GR16RegisterClass)
5987     return Res;
5988
5989   if (VT == MVT::i8) {
5990     unsigned DestReg = 0;
5991     switch (Res.first) {
5992     default: break;
5993     case X86::AX: DestReg = X86::AL; break;
5994     case X86::DX: DestReg = X86::DL; break;
5995     case X86::CX: DestReg = X86::CL; break;
5996     case X86::BX: DestReg = X86::BL; break;
5997     }
5998     if (DestReg) {
5999       Res.first = DestReg;
6000       Res.second = Res.second = X86::GR8RegisterClass;
6001     }
6002   } else if (VT == MVT::i32) {
6003     unsigned DestReg = 0;
6004     switch (Res.first) {
6005     default: break;
6006     case X86::AX: DestReg = X86::EAX; break;
6007     case X86::DX: DestReg = X86::EDX; break;
6008     case X86::CX: DestReg = X86::ECX; break;
6009     case X86::BX: DestReg = X86::EBX; break;
6010     case X86::SI: DestReg = X86::ESI; break;
6011     case X86::DI: DestReg = X86::EDI; break;
6012     case X86::BP: DestReg = X86::EBP; break;
6013     case X86::SP: DestReg = X86::ESP; break;
6014     }
6015     if (DestReg) {
6016       Res.first = DestReg;
6017       Res.second = Res.second = X86::GR32RegisterClass;
6018     }
6019   } else if (VT == MVT::i64) {
6020     unsigned DestReg = 0;
6021     switch (Res.first) {
6022     default: break;
6023     case X86::AX: DestReg = X86::RAX; break;
6024     case X86::DX: DestReg = X86::RDX; break;
6025     case X86::CX: DestReg = X86::RCX; break;
6026     case X86::BX: DestReg = X86::RBX; break;
6027     case X86::SI: DestReg = X86::RSI; break;
6028     case X86::DI: DestReg = X86::RDI; break;
6029     case X86::BP: DestReg = X86::RBP; break;
6030     case X86::SP: DestReg = X86::RSP; break;
6031     }
6032     if (DestReg) {
6033       Res.first = DestReg;
6034       Res.second = Res.second = X86::GR64RegisterClass;
6035     }
6036   }
6037
6038   return Res;
6039 }