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