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