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