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