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