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