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