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