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