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