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