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