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