Only using x86-64 rip relative addressing in non-staic mode?
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/SmallSet.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/ParameterAttributes.h"
43 using namespace llvm;
44
45 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
46   : TargetLowering(TM) {
47   Subtarget = &TM.getSubtarget<X86Subtarget>();
48   X86ScalarSSEf64 = Subtarget->hasSSE2();
49   X86ScalarSSEf32 = Subtarget->hasSSE1();
50   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
51   
52   bool Fast = false;
53
54   RegInfo = TM.getRegisterInfo();
55
56   // Set up the TargetLowering object.
57
58   // X86 is weird, it always uses i8 for shift amounts and setcc results.
59   setShiftAmountType(MVT::i8);
60   setSetCCResultType(MVT::i8);
61   setSetCCResultContents(ZeroOrOneSetCCResult);
62   setSchedulingPreference(SchedulingForRegPressure);
63   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
64   setStackPointerRegisterToSaveRestore(X86StackPtr);
65
66   if (Subtarget->isTargetDarwin()) {
67     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
68     setUseUnderscoreSetJmp(false);
69     setUseUnderscoreLongJmp(false);
70   } else if (Subtarget->isTargetMingw()) {
71     // MS runtime is weird: it exports _setjmp, but longjmp!
72     setUseUnderscoreSetJmp(true);
73     setUseUnderscoreLongJmp(false);
74   } else {
75     setUseUnderscoreSetJmp(true);
76     setUseUnderscoreLongJmp(true);
77   }
78   
79   // Set up the register classes.
80   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
81   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
82   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
83   if (Subtarget->is64Bit())
84     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
85
86   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
87
88   // We don't accept any truncstore of integer registers.  
89   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
90   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
91   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
92   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
93   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
94   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
95
96   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
97   // operation.
98   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
99   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
100   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
101
102   if (Subtarget->is64Bit()) {
103     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
104     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
105   } else {
106     if (X86ScalarSSEf64)
107       // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
108       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Expand);
109     else
110       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
111   }
112
113   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
114   // this operation.
115   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
116   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
117   // SSE has no i16 to fp conversion, only i32
118   if (X86ScalarSSEf32) {
119     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
120     // f32 and f64 cases are Legal, f80 case is not
121     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
122   } else {
123     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
124     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
125   }
126
127   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
128   // are Legal, f80 is custom lowered.
129   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
130   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
131
132   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
133   // this operation.
134   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
135   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
136
137   if (X86ScalarSSEf32) {
138     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
139     // f32 and f64 cases are Legal, f80 case is not
140     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
141   } else {
142     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
143     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
144   }
145
146   // Handle FP_TO_UINT by promoting the destination to a larger signed
147   // conversion.
148   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
149   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
150   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
151
152   if (Subtarget->is64Bit()) {
153     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
154     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
155   } else {
156     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
157       // Expand FP_TO_UINT into a select.
158       // FIXME: We would like to use a Custom expander here eventually to do
159       // the optimal thing for SSE vs. the default expansion in the legalizer.
160       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
161     else
162       // With SSE3 we can use fisttpll to convert to a signed i64.
163       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
164   }
165
166   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
167   if (!X86ScalarSSEf64) {
168     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
169     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
170   }
171
172   // Scalar integer multiply, multiply-high, divide, and remainder are
173   // lowered to use operations that produce two results, to match the
174   // available instructions. This exposes the two-result form to trivial
175   // CSE, which is able to combine x/y and x%y into a single instruction,
176   // for example. The single-result multiply instructions are introduced
177   // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
178   // is not needed.
179   setOperationAction(ISD::MUL             , MVT::i8    , Expand);
180   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
181   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
182   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
183   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
184   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
185   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
186   setOperationAction(ISD::MUL             , MVT::i16   , Expand);
187   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
188   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
189   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
190   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
191   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
192   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
193   setOperationAction(ISD::MUL             , MVT::i32   , Expand);
194   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
195   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
196   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
197   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
198   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
199   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
200   setOperationAction(ISD::MUL             , MVT::i64   , Expand);
201   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
202   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
203   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
204   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
205   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
206   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
207
208   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
209   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
210   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
211   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
212   setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
213   if (Subtarget->is64Bit())
214     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
218   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
219   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
220   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
221   
222   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
223   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
224   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
225   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
226   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
227   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
228   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
229   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
230   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
231   if (Subtarget->is64Bit()) {
232     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
233     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
234     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
235   }
236
237   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
238   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
239
240   // These should be promoted to a larger select which is supported.
241   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
242   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
243   // X86 wants to expand cmov itself.
244   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
245   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
246   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
247   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
248   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
249   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
250   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
251   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
252   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
253   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
254   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
255   if (Subtarget->is64Bit()) {
256     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
257     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
258   }
259   // X86 ret instruction may pop stack.
260   setOperationAction(ISD::RET             , MVT::Other, Custom);
261   if (!Subtarget->is64Bit())
262     setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
263
264   // Darwin ABI issue.
265   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
266   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
267   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
268   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
269   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
270   if (Subtarget->is64Bit()) {
271     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
272     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
273     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
274     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
275   }
276   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
277   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
278   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
279   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
280   // X86 wants to expand memset / memcpy itself.
281   setOperationAction(ISD::MEMSET          , MVT::Other, Custom);
282   setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
283
284   // Use the default ISD::LOCATION, ISD::DECLARE expansion.
285   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
286   // FIXME - use subtarget debug flags
287   if (!Subtarget->isTargetDarwin() &&
288       !Subtarget->isTargetELF() &&
289       !Subtarget->isTargetCygMing())
290     setOperationAction(ISD::LABEL, MVT::Other, Expand);
291
292   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
293   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
294   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
295   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
296   if (Subtarget->is64Bit()) {
297     // FIXME: Verify
298     setExceptionPointerRegister(X86::RAX);
299     setExceptionSelectorRegister(X86::RDX);
300   } else {
301     setExceptionPointerRegister(X86::EAX);
302     setExceptionSelectorRegister(X86::EDX);
303   }
304   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
305   
306   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
307
308   setOperationAction(ISD::TRAP, MVT::Other, Legal);
309
310   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
311   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
312   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
313   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
314   if (Subtarget->is64Bit())
315     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
316   else
317     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
318
319   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
320   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
321   if (Subtarget->is64Bit())
322     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
323   if (Subtarget->isTargetCygMing())
324     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
325   else
326     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
327
328   if (X86ScalarSSEf64) {
329     // f32 and f64 use SSE.
330     // Set up the FP register classes.
331     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
332     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
333
334     // Use ANDPD to simulate FABS.
335     setOperationAction(ISD::FABS , MVT::f64, Custom);
336     setOperationAction(ISD::FABS , MVT::f32, Custom);
337
338     // Use XORP to simulate FNEG.
339     setOperationAction(ISD::FNEG , MVT::f64, Custom);
340     setOperationAction(ISD::FNEG , MVT::f32, Custom);
341
342     // Use ANDPD and ORPD to simulate FCOPYSIGN.
343     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
344     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
345
346     // We don't support sin/cos/fmod
347     setOperationAction(ISD::FSIN , MVT::f64, Expand);
348     setOperationAction(ISD::FCOS , MVT::f64, Expand);
349     setOperationAction(ISD::FREM , MVT::f64, Expand);
350     setOperationAction(ISD::FSIN , MVT::f32, Expand);
351     setOperationAction(ISD::FCOS , MVT::f32, Expand);
352     setOperationAction(ISD::FREM , MVT::f32, Expand);
353
354     // Expand FP immediates into loads from the stack, except for the special
355     // cases we handle.
356     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
357     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
358     addLegalFPImmediate(APFloat(+0.0)); // xorpd
359     addLegalFPImmediate(APFloat(+0.0f)); // xorps
360
361     // Floating truncations from f80 and extensions to f80 go through memory.
362     // If optimizing, we lie about this though and handle it in
363     // InstructionSelectPreprocess so that dagcombine2 can hack on these.
364     if (Fast) {
365       setConvertAction(MVT::f32, MVT::f80, Expand);
366       setConvertAction(MVT::f64, MVT::f80, Expand);
367       setConvertAction(MVT::f80, MVT::f32, Expand);
368       setConvertAction(MVT::f80, MVT::f64, Expand);
369     }
370   } else if (X86ScalarSSEf32) {
371     // Use SSE for f32, x87 for f64.
372     // Set up the FP register classes.
373     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
374     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
375
376     // Use ANDPS to simulate FABS.
377     setOperationAction(ISD::FABS , MVT::f32, Custom);
378
379     // Use XORP to simulate FNEG.
380     setOperationAction(ISD::FNEG , MVT::f32, Custom);
381
382     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
383
384     // Use ANDPS and ORPS to simulate FCOPYSIGN.
385     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
386     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
387
388     // We don't support sin/cos/fmod
389     setOperationAction(ISD::FSIN , MVT::f32, Expand);
390     setOperationAction(ISD::FCOS , MVT::f32, Expand);
391     setOperationAction(ISD::FREM , MVT::f32, Expand);
392
393     // Expand FP immediates into loads from the stack, except for the special
394     // cases we handle.
395     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
396     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
397     addLegalFPImmediate(APFloat(+0.0f)); // xorps
398     addLegalFPImmediate(APFloat(+0.0)); // FLD0
399     addLegalFPImmediate(APFloat(+1.0)); // FLD1
400     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
401     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
402
403     // SSE <-> X87 conversions go through memory.  If optimizing, we lie about
404     // this though and handle it in InstructionSelectPreprocess so that
405     // dagcombine2 can hack on these.
406     if (Fast) {
407       setConvertAction(MVT::f32, MVT::f64, Expand);
408       setConvertAction(MVT::f32, MVT::f80, Expand);
409       setConvertAction(MVT::f80, MVT::f32, Expand);    
410       setConvertAction(MVT::f64, MVT::f32, Expand);
411       // And x87->x87 truncations also.
412       setConvertAction(MVT::f80, MVT::f64, Expand);
413     }
414
415     if (!UnsafeFPMath) {
416       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
417       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
418     }
419   } else {
420     // f32 and f64 in x87.
421     // Set up the FP register classes.
422     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
423     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
424
425     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
426     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
427     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
428     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
429
430     // Floating truncations go through memory.  If optimizing, we lie about
431     // this though and handle it in InstructionSelectPreprocess so that
432     // dagcombine2 can hack on these.
433     if (Fast) {
434       setConvertAction(MVT::f80, MVT::f32, Expand);    
435       setConvertAction(MVT::f64, MVT::f32, Expand);
436       setConvertAction(MVT::f80, MVT::f64, Expand);
437     }
438
439     if (!UnsafeFPMath) {
440       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
441       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
442     }
443
444     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
445     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
446     addLegalFPImmediate(APFloat(+0.0)); // FLD0
447     addLegalFPImmediate(APFloat(+1.0)); // FLD1
448     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
449     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
450     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
451     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
452     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
453     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
454   }
455
456   // Long double always uses X87.
457   addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
458   setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
459   setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
460   {
461     setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
462     APFloat TmpFlt(+0.0);
463     TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
464     addLegalFPImmediate(TmpFlt);  // FLD0
465     TmpFlt.changeSign();
466     addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
467     APFloat TmpFlt2(+1.0);
468     TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
469     addLegalFPImmediate(TmpFlt2);  // FLD1
470     TmpFlt2.changeSign();
471     addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
472   }
473     
474   if (!UnsafeFPMath) {
475     setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
476     setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
477   }
478
479   // Always use a library call for pow.
480   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
481   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
482   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
483
484   // First set operation action for all vector types to expand. Then we
485   // will selectively turn on ones that can be effectively codegen'd.
486   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
487        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
488     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
489     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
490     setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
491     setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
492     setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
493     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
494     setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
495     setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
496     setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
497     setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
498     setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
499     setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
500     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
501     setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::ValueType)VT, Expand);
502     setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
503     setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::ValueType)VT, Expand);
504     setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
505     setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
506     setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
507     setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
508     setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
509     setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
510     setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
511     setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
512     setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
513     setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
514     setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
515     setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
516     setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
517     setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
518     setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
519     setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
520     setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
521     setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
522     setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
523     setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
524     setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
525   }
526
527   if (Subtarget->hasMMX()) {
528     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
529     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
530     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
531     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
532
533     // FIXME: add MMX packed arithmetics
534
535     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
536     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
537     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
538     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
539
540     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
541     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
542     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
543     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
544
545     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
546     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
547
548     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
549     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
550     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
551     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
552     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
553     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
554     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
555
556     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
557     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
558     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
559     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
560     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
561     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
562     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
563
564     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
565     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
566     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
567     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
568     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
569     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
570     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
571
572     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
573     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
574     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
575     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
576     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
577     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
578     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
579
580     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
581     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
582     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
583     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
584
585     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
586     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
587     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
588     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
589
590     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
591     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
592     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Custom);
593     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
594   }
595
596   if (Subtarget->hasSSE1()) {
597     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
598
599     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
600     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
601     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
602     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
603     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
604     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
605     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
606     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
607     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
608     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
609     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
610   }
611
612   if (Subtarget->hasSSE2()) {
613     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
614     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
615     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
616     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
617     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
618
619     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
620     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
621     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
622     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
623     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
624     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
625     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
626     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
627     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
628     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
629     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
630     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
631     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
632     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
633     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
634
635     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
636     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
637     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
638     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
639     // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
640     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
641
642     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
643     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
644       // Do not attempt to custom lower non-power-of-2 vectors
645       if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
646         continue;
647       setOperationAction(ISD::BUILD_VECTOR,        (MVT::ValueType)VT, Custom);
648       setOperationAction(ISD::VECTOR_SHUFFLE,      (MVT::ValueType)VT, Custom);
649       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  (MVT::ValueType)VT, Custom);
650     }
651     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
652     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
653     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
654     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
655     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
656     if (Subtarget->is64Bit())
657       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
658
659     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
660     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
661       setOperationAction(ISD::AND,    (MVT::ValueType)VT, Promote);
662       AddPromotedToType (ISD::AND,    (MVT::ValueType)VT, MVT::v2i64);
663       setOperationAction(ISD::OR,     (MVT::ValueType)VT, Promote);
664       AddPromotedToType (ISD::OR,     (MVT::ValueType)VT, MVT::v2i64);
665       setOperationAction(ISD::XOR,    (MVT::ValueType)VT, Promote);
666       AddPromotedToType (ISD::XOR,    (MVT::ValueType)VT, MVT::v2i64);
667       setOperationAction(ISD::LOAD,   (MVT::ValueType)VT, Promote);
668       AddPromotedToType (ISD::LOAD,   (MVT::ValueType)VT, MVT::v2i64);
669       setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
670       AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
671     }
672
673     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
674
675     // Custom lower v2i64 and v2f64 selects.
676     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
677     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
678     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
679     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
680   }
681   
682   if (Subtarget->hasSSE41()) {
683     // FIXME: Do we need to handle scalar-to-vector here?
684     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
685
686     // i8 and i16 vectors are custom , because the source register and source
687     // source memory operand types are not the same width.  f32 vectors are
688     // custom since the immediate controlling the insert encodes additional
689     // information.
690     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
691     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
692     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Legal);
693     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
694
695     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
696     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
697     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
698     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
699
700     if (Subtarget->is64Bit()) {
701       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
702       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
703
704       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
705       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
706     }
707   }
708
709   // We want to custom lower some of our intrinsics.
710   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
711
712   // We have target-specific dag combine patterns for the following nodes:
713   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
714   setTargetDAGCombine(ISD::SELECT);
715
716   computeRegisterProperties();
717
718   // FIXME: These should be based on subtarget info. Plus, the values should
719   // be smaller when we are in optimizing for size mode.
720   maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
721   maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
722   maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
723   allowUnalignedMemoryAccesses = true; // x86 supports it!
724 }
725
726 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
727 /// the desired ByVal argument alignment.
728 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
729   if (MaxAlign == 16)
730     return;
731   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
732     if (VTy->getBitWidth() == 128)
733       MaxAlign = 16;
734   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
735     unsigned EltAlign = 0;
736     getMaxByValAlign(ATy->getElementType(), EltAlign);
737     if (EltAlign > MaxAlign)
738       MaxAlign = EltAlign;
739   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
740     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
741       unsigned EltAlign = 0;
742       getMaxByValAlign(STy->getElementType(i), EltAlign);
743       if (EltAlign > MaxAlign)
744         MaxAlign = EltAlign;
745       if (MaxAlign == 16)
746         break;
747     }
748   }
749   return;
750 }
751
752 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
753 /// function arguments in the caller parameter area. For X86, aggregates
754 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
755 /// are at 4-byte boundaries.
756 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
757   if (Subtarget->is64Bit())
758     return getTargetData()->getABITypeAlignment(Ty);
759   unsigned Align = 4;
760   if (Subtarget->hasSSE1())
761     getMaxByValAlign(Ty, Align);
762   return Align;
763 }
764
765 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
766 /// jumptable.
767 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
768                                                       SelectionDAG &DAG) const {
769   if (usesGlobalOffsetTable())
770     return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
771   if (!Subtarget->isPICStyleRIPRel())
772     return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
773   return Table;
774 }
775
776 //===----------------------------------------------------------------------===//
777 //               Return Value Calling Convention Implementation
778 //===----------------------------------------------------------------------===//
779
780 #include "X86GenCallingConv.inc"
781
782 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
783 /// exists skip possible ISD:TokenFactor.
784 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
785   if (Chain.getOpcode() == X86ISD::TAILCALL) {
786     return Chain;
787   } else if (Chain.getOpcode() == ISD::TokenFactor) {
788     if (Chain.getNumOperands() &&
789         Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
790       return Chain.getOperand(0);
791   }
792   return Chain;
793 }
794
795 /// LowerRET - Lower an ISD::RET node.
796 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
797   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
798   
799   SmallVector<CCValAssign, 16> RVLocs;
800   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
801   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
802   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
803   CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
804     
805   // If this is the first return lowered for this function, add the regs to the
806   // liveout set for the function.
807   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
808     for (unsigned i = 0; i != RVLocs.size(); ++i)
809       if (RVLocs[i].isRegLoc())
810         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
811   }
812   SDOperand Chain = Op.getOperand(0);
813   
814   // Handle tail call return.
815   Chain = GetPossiblePreceedingTailCall(Chain);
816   if (Chain.getOpcode() == X86ISD::TAILCALL) {
817     SDOperand TailCall = Chain;
818     SDOperand TargetAddress = TailCall.getOperand(1);
819     SDOperand StackAdjustment = TailCall.getOperand(2);
820     assert(((TargetAddress.getOpcode() == ISD::Register &&
821                (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
822                 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
823               TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
824               TargetAddress.getOpcode() == ISD::TargetGlobalAddress) && 
825              "Expecting an global address, external symbol, or register");
826     assert(StackAdjustment.getOpcode() == ISD::Constant &&
827            "Expecting a const value");
828
829     SmallVector<SDOperand,8> Operands;
830     Operands.push_back(Chain.getOperand(0));
831     Operands.push_back(TargetAddress);
832     Operands.push_back(StackAdjustment);
833     // Copy registers used by the call. Last operand is a flag so it is not
834     // copied.
835     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
836       Operands.push_back(Chain.getOperand(i));
837     }
838     return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0], 
839                        Operands.size());
840   }
841   
842   // Regular return.
843   SDOperand Flag;
844
845   // Copy the result values into the output registers.
846   if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
847       RVLocs[0].getLocReg() != X86::ST0) {
848     for (unsigned i = 0; i != RVLocs.size(); ++i) {
849       CCValAssign &VA = RVLocs[i];
850       assert(VA.isRegLoc() && "Can only return in registers!");
851       Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
852                                Flag);
853       Flag = Chain.getValue(1);
854     }
855   } else {
856     // We need to handle a destination of ST0 specially, because it isn't really
857     // a register.
858     SDOperand Value = Op.getOperand(1);
859     
860     // an XMM register onto the fp-stack.  Do this with an FP_EXTEND to f80.
861     // This will get legalized into a load/store if it can't get optimized away.
862     if (isScalarFPTypeInSSEReg(RVLocs[0].getValVT()))
863       Value = DAG.getNode(ISD::FP_EXTEND, MVT::f80, Value);
864     
865     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
866     SDOperand Ops[] = { Chain, Value };
867     Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
868     Flag = Chain.getValue(1);
869   }
870   
871   SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
872   if (Flag.Val)
873     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
874   else
875     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
876 }
877
878
879 /// LowerCallResult - Lower the result values of an ISD::CALL into the
880 /// appropriate copies out of appropriate physical registers.  This assumes that
881 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
882 /// being lowered.  The returns a SDNode with the same number of values as the
883 /// ISD::CALL.
884 SDNode *X86TargetLowering::
885 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall, 
886                 unsigned CallingConv, SelectionDAG &DAG) {
887   
888   // Assign locations to each value returned by this call.
889   SmallVector<CCValAssign, 16> RVLocs;
890   bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
891   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
892   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
893
894   SmallVector<SDOperand, 8> ResultVals;
895   
896   // Copy all of the result registers out of their specified physreg.
897   if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
898     for (unsigned i = 0; i != RVLocs.size(); ++i) {
899       Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
900                                  RVLocs[i].getValVT(), InFlag).getValue(1);
901       InFlag = Chain.getValue(2);
902       ResultVals.push_back(Chain.getValue(0));
903     }
904   } else {
905     // Copies from the FP stack are special, as ST0 isn't a valid register
906     // before the fp stackifier runs.
907     
908     // Copy ST0 into an RFP register with FP_GET_RESULT.  If this will end up
909     // in an SSE register, copy it out as F80 and do a truncate, otherwise use
910     // the specified value type.
911     MVT::ValueType GetResultTy = RVLocs[0].getValVT();
912     if (isScalarFPTypeInSSEReg(GetResultTy))
913       GetResultTy = MVT::f80;
914     SDVTList Tys = DAG.getVTList(GetResultTy, MVT::Other, MVT::Flag);
915     
916     SDOperand GROps[] = { Chain, InFlag };
917     SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
918     Chain  = RetVal.getValue(1);
919     InFlag = RetVal.getValue(2);
920
921     // If we want the result in an SSE register, use an FP_TRUNCATE to get it
922     // there.
923     if (GetResultTy != RVLocs[0].getValVT())
924       RetVal = DAG.getNode(ISD::FP_ROUND, RVLocs[0].getValVT(), RetVal,
925                            // This truncation won't change the value.
926                            DAG.getIntPtrConstant(1));
927     
928     ResultVals.push_back(RetVal);
929   }
930   
931   // Merge everything together with a MERGE_VALUES node.
932   ResultVals.push_back(Chain);
933   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
934                      &ResultVals[0], ResultVals.size()).Val;
935 }
936
937 /// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
938 /// ISD::CALL where the results are known to be in two 64-bit registers,
939 /// e.g. XMM0 and XMM1. This simplify store the two values back to the
940 /// fixed stack slot allocated for StructRet.
941 SDNode *X86TargetLowering::
942 LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
943                               SDNode *TheCall, unsigned Reg1, unsigned Reg2,
944                               MVT::ValueType VT, SelectionDAG &DAG) {
945   SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
946   Chain = RetVal1.getValue(1);
947   InFlag = RetVal1.getValue(2);
948   SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
949   Chain = RetVal2.getValue(1);
950   InFlag = RetVal2.getValue(2);
951   SDOperand FIN = TheCall->getOperand(5);
952   Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
953   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
954   Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
955   return Chain.Val;
956 }
957
958 /// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
959 /// where the results are known to be in ST0 and ST1.
960 SDNode *X86TargetLowering::
961 LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
962                             SDNode *TheCall, SelectionDAG &DAG) {
963   SmallVector<SDOperand, 8> ResultVals;
964   const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
965   SDVTList Tys = DAG.getVTList(VTs, 4);
966   SDOperand Ops[] = { Chain, InFlag };
967   SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT2, Tys, Ops, 2);
968   Chain = RetVal.getValue(2);
969   SDOperand FIN = TheCall->getOperand(5);
970   Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
971   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
972   Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
973   return Chain.Val;
974 }
975
976 //===----------------------------------------------------------------------===//
977 //                C & StdCall & Fast Calling Convention implementation
978 //===----------------------------------------------------------------------===//
979 //  StdCall calling convention seems to be standard for many Windows' API
980 //  routines and around. It differs from C calling convention just a little:
981 //  callee should clean up the stack, not caller. Symbols should be also
982 //  decorated in some fancy way :) It doesn't support any vector arguments.
983 //  For info on fast calling convention see Fast Calling Convention (tail call)
984 //  implementation LowerX86_32FastCCCallTo.
985
986 /// AddLiveIn - This helper function adds the specified physical register to the
987 /// MachineFunction as a live in value.  It also creates a corresponding virtual
988 /// register for it.
989 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
990                           const TargetRegisterClass *RC) {
991   assert(RC->contains(PReg) && "Not the correct regclass!");
992   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
993   MF.getRegInfo().addLiveIn(PReg, VReg);
994   return VReg;
995 }
996
997 // Determines whether a CALL node uses struct return semantics.
998 static bool CallIsStructReturn(SDOperand Op) {
999   unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1000   if (!NumOps)
1001     return false;
1002   
1003   ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
1004   return Flags->getValue() & ISD::ParamFlags::StructReturn;
1005 }
1006
1007 // Determines whether a FORMAL_ARGUMENTS node uses struct return semantics.
1008 static bool ArgsAreStructReturn(SDOperand Op) {
1009   unsigned NumArgs = Op.Val->getNumValues() - 1;
1010   if (!NumArgs)
1011     return false;
1012   
1013   ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
1014   return Flags->getValue() & ISD::ParamFlags::StructReturn;
1015 }
1016
1017 // Determines whether a CALL or FORMAL_ARGUMENTS node requires the callee to pop
1018 // its own arguments. Callee pop is necessary to support tail calls.
1019 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1020   bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1021   if (IsVarArg)
1022     return false;
1023
1024   switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1025   default:
1026     return false;
1027   case CallingConv::X86_StdCall:
1028     return !Subtarget->is64Bit();
1029   case CallingConv::X86_FastCall:
1030     return !Subtarget->is64Bit();
1031   case CallingConv::Fast:
1032     return PerformTailCallOpt;
1033   }
1034 }
1035
1036 // Selects the correct CCAssignFn for a CALL or FORMAL_ARGUMENTS node.
1037 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1038   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1039   
1040   if (Subtarget->is64Bit())
1041     if (CC == CallingConv::Fast && PerformTailCallOpt)
1042       return CC_X86_64_TailCall;
1043     else
1044       return CC_X86_64_C;
1045   
1046   if (CC == CallingConv::X86_FastCall)
1047     return CC_X86_32_FastCall;
1048   else if (CC == CallingConv::Fast && PerformTailCallOpt)
1049     return CC_X86_32_TailCall;
1050   else
1051     return CC_X86_32_C;
1052 }
1053
1054 // Selects the appropriate decoration to apply to a MachineFunction containing a
1055 // given FORMAL_ARGUMENTS node.
1056 NameDecorationStyle
1057 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1058   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1059   if (CC == CallingConv::X86_FastCall)
1060     return FastCall;
1061   else if (CC == CallingConv::X86_StdCall)
1062     return StdCall;
1063   return None;
1064 }
1065
1066
1067 // IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could possibly
1068 // be overwritten when lowering the outgoing arguments in a tail call. Currently
1069 // the implementation of this call is very conservative and assumes all
1070 // arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with virtual
1071 // registers would be overwritten by direct lowering.  
1072 // Possible improvement:
1073 // Check FORMAL_ARGUMENTS corresponding MERGE_VALUES for CopyFromReg nodes
1074 // indicating inreg passed arguments which also need not be lowered to a safe
1075 // stack slot.
1076 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op) {
1077   RegisterSDNode * OpReg = NULL;
1078   if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1079       (Op.getOpcode()== ISD::CopyFromReg &&
1080        (OpReg = cast<RegisterSDNode>(Op.getOperand(1))) &&
1081        OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister))
1082     return true;
1083   return false;
1084 }
1085
1086 // CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1087 // by "Src" to address "Dst" with size and alignment information specified by
1088 // the specific parameter attribute. The copy will be passed as a byval function
1089 // parameter.
1090 static SDOperand 
1091 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1092                           unsigned Flags, SelectionDAG &DAG) {
1093   unsigned Align = 1 <<
1094     ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1095   unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1096     ISD::ParamFlags::ByValSizeOffs;
1097   SDOperand AlignNode    = DAG.getConstant(Align, MVT::i32);
1098   SDOperand SizeNode     = DAG.getConstant(Size, MVT::i32);
1099   SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1100   return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1101 }
1102
1103 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1104                                               const CCValAssign &VA,
1105                                               MachineFrameInfo *MFI,
1106                                               SDOperand Root, unsigned i) {
1107   // Create the nodes corresponding to a load from this parameter slot.
1108   unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1109   bool isByVal = Flags & ISD::ParamFlags::ByVal;
1110
1111   // FIXME: For now, all byval parameter objects are marked mutable. This
1112   // can be changed with more analysis.
1113   int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1114                                   VA.getLocMemOffset(), !isByVal);
1115   SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1116   if (isByVal)
1117     return FIN;
1118   return DAG.getLoad(VA.getValVT(), Root, FIN,
1119                      PseudoSourceValue::getFixedStack(), FI);
1120 }
1121
1122 SDOperand
1123 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1124   MachineFunction &MF = DAG.getMachineFunction();
1125   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1126   
1127   const Function* Fn = MF.getFunction();
1128   if (Fn->hasExternalLinkage() &&
1129       Subtarget->isTargetCygMing() &&
1130       Fn->getName() == "main")
1131     FuncInfo->setForceFramePointer(true);
1132
1133   // Decorate the function name.
1134   FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1135   
1136   MachineFrameInfo *MFI = MF.getFrameInfo();
1137   SDOperand Root = Op.getOperand(0);
1138   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1139   unsigned CC = MF.getFunction()->getCallingConv();
1140   bool Is64Bit = Subtarget->is64Bit();
1141
1142   assert(!(isVarArg && CC == CallingConv::Fast) &&
1143          "Var args not supported with calling convention fastcc");
1144
1145   // Assign locations to all of the incoming arguments.
1146   SmallVector<CCValAssign, 16> ArgLocs;
1147   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1148   CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1149   
1150   SmallVector<SDOperand, 8> ArgValues;
1151   unsigned LastVal = ~0U;
1152   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1153     CCValAssign &VA = ArgLocs[i];
1154     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1155     // places.
1156     assert(VA.getValNo() != LastVal &&
1157            "Don't support value assigned to multiple locs yet");
1158     LastVal = VA.getValNo();
1159     
1160     if (VA.isRegLoc()) {
1161       MVT::ValueType RegVT = VA.getLocVT();
1162       TargetRegisterClass *RC;
1163       if (RegVT == MVT::i32)
1164         RC = X86::GR32RegisterClass;
1165       else if (Is64Bit && RegVT == MVT::i64)
1166         RC = X86::GR64RegisterClass;
1167       else if (RegVT == MVT::f32)
1168         RC = X86::FR32RegisterClass;
1169       else if (RegVT == MVT::f64)
1170         RC = X86::FR64RegisterClass;
1171       else {
1172         assert(MVT::isVector(RegVT));
1173         if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1174           RC = X86::GR64RegisterClass;       // MMX values are passed in GPRs.
1175           RegVT = MVT::i64;
1176         } else
1177           RC = X86::VR128RegisterClass;
1178       }
1179
1180       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1181       SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1182       
1183       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1184       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1185       // right size.
1186       if (VA.getLocInfo() == CCValAssign::SExt)
1187         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1188                                DAG.getValueType(VA.getValVT()));
1189       else if (VA.getLocInfo() == CCValAssign::ZExt)
1190         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1191                                DAG.getValueType(VA.getValVT()));
1192       
1193       if (VA.getLocInfo() != CCValAssign::Full)
1194         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1195       
1196       // Handle MMX values passed in GPRs.
1197       if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1198           MVT::getSizeInBits(RegVT) == 64)
1199         ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1200       
1201       ArgValues.push_back(ArgValue);
1202     } else {
1203       assert(VA.isMemLoc());
1204       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1205     }
1206   }
1207
1208   unsigned StackSize = CCInfo.getNextStackOffset();
1209   // align stack specially for tail calls
1210   if (CC == CallingConv::Fast)
1211     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1212
1213   // If the function takes variable number of arguments, make a frame index for
1214   // the start of the first vararg value... for expansion of llvm.va_start.
1215   if (isVarArg) {
1216     if (Is64Bit || CC != CallingConv::X86_FastCall) {
1217       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1218     }
1219     if (Is64Bit) {
1220       static const unsigned GPR64ArgRegs[] = {
1221         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8,  X86::R9
1222       };
1223       static const unsigned XMMArgRegs[] = {
1224         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1225         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1226       };
1227       
1228       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1229       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1230     
1231       // For X86-64, if there are vararg parameters that are passed via
1232       // registers, then we must store them to their spots on the stack so they
1233       // may be loaded by deferencing the result of va_next.
1234       VarArgsGPOffset = NumIntRegs * 8;
1235       VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1236       RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1237       
1238       // Store the integer parameter registers.
1239       SmallVector<SDOperand, 8> MemOps;
1240       SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1241       SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1242                                   DAG.getIntPtrConstant(VarArgsGPOffset));
1243       for (; NumIntRegs != 6; ++NumIntRegs) {
1244         unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1245                                   X86::GR64RegisterClass);
1246         SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1247         SDOperand Store =
1248           DAG.getStore(Val.getValue(1), Val, FIN,
1249                        PseudoSourceValue::getFixedStack(),
1250                        RegSaveFrameIndex);
1251         MemOps.push_back(Store);
1252         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1253                           DAG.getIntPtrConstant(8));
1254       }
1255       
1256       // Now store the XMM (fp + vector) parameter registers.
1257       FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1258                         DAG.getIntPtrConstant(VarArgsFPOffset));
1259       for (; NumXMMRegs != 8; ++NumXMMRegs) {
1260         unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1261                                   X86::VR128RegisterClass);
1262         SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1263         SDOperand Store =
1264           DAG.getStore(Val.getValue(1), Val, FIN,
1265                        PseudoSourceValue::getFixedStack(),
1266                        RegSaveFrameIndex);
1267         MemOps.push_back(Store);
1268         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1269                           DAG.getIntPtrConstant(16));
1270       }
1271       if (!MemOps.empty())
1272           Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1273                              &MemOps[0], MemOps.size());
1274     }
1275   }
1276   
1277   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1278   // arguments and the arguments after the retaddr has been pushed are
1279   // aligned.
1280   if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1281       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1282       (StackSize & 7) == 0)
1283     StackSize += 4;
1284
1285   ArgValues.push_back(Root);
1286
1287   // Some CCs need callee pop.
1288   if (IsCalleePop(Op)) {
1289     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1290     BytesCallerReserves = 0;
1291   } else {
1292     BytesToPopOnReturn  = 0; // Callee pops nothing.
1293     // If this is an sret function, the return should pop the hidden pointer.
1294     if (!Is64Bit && ArgsAreStructReturn(Op))
1295       BytesToPopOnReturn = 4;  
1296     BytesCallerReserves = StackSize;
1297   }
1298
1299   if (!Is64Bit) {
1300     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1301     if (CC == CallingConv::X86_FastCall)
1302       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1303   }
1304
1305   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1306
1307   // Return the new list of results.
1308   return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1309                      &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1310 }
1311
1312 SDOperand
1313 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1314                                     const SDOperand &StackPtr,
1315                                     const CCValAssign &VA,
1316                                     SDOperand Chain,
1317                                     SDOperand Arg) {
1318   unsigned LocMemOffset = VA.getLocMemOffset();
1319   SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1320   PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1321   SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1322   unsigned Flags    = cast<ConstantSDNode>(FlagsOp)->getValue();
1323   if (Flags & ISD::ParamFlags::ByVal) {
1324     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1325   }
1326   return DAG.getStore(Chain, Arg, PtrOff,
1327                       PseudoSourceValue::getStack(), LocMemOffset);
1328 }
1329
1330 /// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1331 /// struct return call to the specified function. X86-64 ABI specifies
1332 /// some SRet calls are actually returned in registers. Since current
1333 /// LLVM cannot represent multi-value calls, they are represent as 
1334 /// calls where the results are passed in a hidden struct provided by
1335 /// the caller. This function examines the type of the struct to
1336 /// determine the correct way to implement the call.
1337 X86::X86_64SRet
1338 X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1339   // FIXME: Disabled for now.
1340   return X86::InMemory;
1341
1342   const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1343   const Type *RTy = PTy->getElementType();
1344   unsigned Size = getTargetData()->getABITypeSize(RTy);
1345   if (Size != 16 && Size != 32)
1346     return X86::InMemory;
1347
1348   if (Size == 32) {
1349     const StructType *STy = dyn_cast<StructType>(RTy);
1350     if (!STy) return X86::InMemory;
1351     if (STy->getNumElements() == 2 &&
1352         STy->getElementType(0) == Type::X86_FP80Ty &&
1353         STy->getElementType(1) == Type::X86_FP80Ty)
1354       return X86::InX87;
1355   }
1356
1357   bool AllFP = true;
1358   for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1359        I != E; ++I) {
1360     const Type *STy = I->get();
1361     if (!STy->isFPOrFPVector()) {
1362       AllFP = false;
1363       break;
1364     }
1365   }
1366
1367   if (AllFP)
1368     return X86::InSSE;
1369   return X86::InGPR64;
1370 }
1371
1372 void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1373                                                       CCAssignFn *Fn,
1374                                                       CCState &CCInfo) {
1375   unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1376   for (unsigned i = 1; i != NumOps; ++i) {
1377     MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1378     SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1379     unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1380     if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1381       cerr << "Call operand #" << i << " has unhandled type "
1382            << MVT::getValueTypeString(ArgVT) << "\n";
1383       abort();
1384     }
1385   }
1386 }
1387
1388 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1389   MachineFunction &MF = DAG.getMachineFunction();
1390   SDOperand Chain     = Op.getOperand(0);
1391   unsigned CC         = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1392   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1393   bool IsTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1394                         && CC == CallingConv::Fast && PerformTailCallOpt;
1395   SDOperand Callee    = Op.getOperand(4);
1396   bool Is64Bit        = Subtarget->is64Bit();
1397   bool IsStructRet    = CallIsStructReturn(Op);
1398
1399   assert(!(isVarArg && CC == CallingConv::Fast) &&
1400          "Var args not supported with calling convention fastcc");
1401
1402   // Analyze operands of the call, assigning locations to each operand.
1403   SmallVector<CCValAssign, 16> ArgLocs;
1404   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1405   CCAssignFn *CCFn = CCAssignFnForNode(Op);
1406
1407   X86::X86_64SRet SRetMethod = X86::InMemory;
1408   if (Is64Bit && IsStructRet)
1409     // FIXME: We can't figure out type of the sret structure for indirect
1410     // calls. We need to copy more information from CallSite to the ISD::CALL
1411     // node.
1412     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1413       SRetMethod =
1414         ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1415
1416   // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1417   // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1418   // a sret call.
1419   if (SRetMethod != X86::InMemory)
1420     X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1421   else 
1422     CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1423   
1424   // Get a count of how many bytes are to be pushed on the stack.
1425   unsigned NumBytes = CCInfo.getNextStackOffset();
1426   if (CC == CallingConv::Fast)
1427     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1428
1429   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1430   // arguments and the arguments after the retaddr has been pushed are aligned.
1431   if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1432       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1433       (NumBytes & 7) == 0)
1434     NumBytes += 4;
1435
1436   int FPDiff = 0;
1437   if (IsTailCall) {
1438     // Lower arguments at fp - stackoffset + fpdiff.
1439     unsigned NumBytesCallerPushed = 
1440       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1441     FPDiff = NumBytesCallerPushed - NumBytes;
1442
1443     // Set the delta of movement of the returnaddr stackslot.
1444     // But only set if delta is greater than previous delta.
1445     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1446       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1447   }
1448
1449   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1450
1451   SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
1452   if (IsTailCall) {
1453     // Adjust the Return address stack slot.
1454     if (FPDiff) {
1455       MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1456       RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1457       // Load the "old" Return address.
1458       RetAddrFrIdx = 
1459         DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1460       // Calculate the new stack slot for the return address.
1461       int SlotSize = Is64Bit ? 8 : 4;
1462       int NewReturnAddrFI = 
1463         MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1464       NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1465       Chain = SDOperand(RetAddrFrIdx.Val, 1);
1466     }
1467   }
1468
1469   SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1470   SmallVector<SDOperand, 8> MemOpChains;
1471
1472   SDOperand StackPtr;
1473
1474   // Walk the register/memloc assignments, inserting copies/loads.  For tail
1475   // calls, lower arguments which could otherwise be possibly overwritten to the
1476   // stack slot where they would go on normal function calls.
1477   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1478     CCValAssign &VA = ArgLocs[i];
1479     SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1480     
1481     // Promote the value if needed.
1482     switch (VA.getLocInfo()) {
1483     default: assert(0 && "Unknown loc info!");
1484     case CCValAssign::Full: break;
1485     case CCValAssign::SExt:
1486       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1487       break;
1488     case CCValAssign::ZExt:
1489       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1490       break;
1491     case CCValAssign::AExt:
1492       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1493       break;
1494     }
1495     
1496     if (VA.isRegLoc()) {
1497       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1498     } else {
1499       if (!IsTailCall || IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1500         assert(VA.isMemLoc());
1501         if (StackPtr.Val == 0)
1502           StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1503         
1504         MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1505                                                Arg));
1506       }
1507     }
1508   }
1509   
1510   if (!MemOpChains.empty())
1511     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1512                         &MemOpChains[0], MemOpChains.size());
1513
1514   // Build a sequence of copy-to-reg nodes chained together with token chain
1515   // and flag operands which copy the outgoing args into registers.
1516   SDOperand InFlag;
1517   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1518     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1519                              InFlag);
1520     InFlag = Chain.getValue(1);
1521   }
1522
1523   if (IsTailCall)
1524     InFlag = SDOperand(); // ??? Isn't this nuking the preceding loop's output?
1525
1526   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1527   // GOT pointer.
1528   // Does not work with tail call since ebx is not restored correctly by
1529   // tailcaller. TODO: at least for x86 - verify for x86-64
1530   if (!IsTailCall && !Is64Bit &&
1531       getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1532       Subtarget->isPICStyleGOT()) {
1533     Chain = DAG.getCopyToReg(Chain, X86::EBX,
1534                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1535                              InFlag);
1536     InFlag = Chain.getValue(1);
1537   }
1538
1539   if (Is64Bit && isVarArg) {
1540     // From AMD64 ABI document:
1541     // For calls that may call functions that use varargs or stdargs
1542     // (prototype-less calls or calls to functions containing ellipsis (...) in
1543     // the declaration) %al is used as hidden argument to specify the number
1544     // of SSE registers used. The contents of %al do not need to match exactly
1545     // the number of registers, but must be an ubound on the number of SSE
1546     // registers used and is in the range 0 - 8 inclusive.
1547     
1548     // Count the number of XMM registers allocated.
1549     static const unsigned XMMArgRegs[] = {
1550       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1551       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1552     };
1553     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1554     
1555     Chain = DAG.getCopyToReg(Chain, X86::AL,
1556                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1557     InFlag = Chain.getValue(1);
1558   }
1559
1560   // For tail calls lower the arguments to the 'real' stack slot.
1561   if (IsTailCall) {
1562     SmallVector<SDOperand, 8> MemOpChains2;
1563     SDOperand FIN;
1564     int FI = 0;
1565     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1566       CCValAssign &VA = ArgLocs[i];
1567       if (!VA.isRegLoc()) {
1568         assert(VA.isMemLoc());
1569         SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1570         SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1571         unsigned Flags    = cast<ConstantSDNode>(FlagsOp)->getValue();
1572         // Create frame index.
1573         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1574         uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1575         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1576         FIN = DAG.getFrameIndex(FI, MVT::i32);
1577         SDOperand Source = Arg;
1578         if (IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1579           // Copy from stack slots to stack slot of a tail called function. This
1580           // needs to be done because if we would lower the arguments directly
1581           // to their real stack slot we might end up overwriting each other.
1582           // Get source stack slot.
1583           Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1584           if (StackPtr.Val == 0)
1585             StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1586           Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1587           if ((Flags & ISD::ParamFlags::ByVal)==0) 
1588             Source = DAG.getLoad(VA.getValVT(), Chain, Source, NULL, 0);
1589         } 
1590
1591         if (Flags & ISD::ParamFlags::ByVal) {
1592           // Copy relative to framepointer.
1593           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1594                                                            Flags, DAG));
1595         } else {
1596           // Store relative to framepointer.
1597           MemOpChains2.push_back(
1598             DAG.getStore(Chain, Source, FIN,
1599                          PseudoSourceValue::getFixedStack(), FI));
1600         }            
1601       }
1602     }
1603
1604     if (!MemOpChains2.empty())
1605       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1606                           &MemOpChains2[0], MemOpChains2.size());
1607
1608     // Store the return address to the appropriate stack slot.
1609     if (FPDiff)
1610       Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1611   }
1612
1613   // If the callee is a GlobalAddress node (quite common, every direct call is)
1614   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1615   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1616     // We should use extra load for direct calls to dllimported functions in
1617     // non-JIT mode.
1618     if ((IsTailCall || !Is64Bit ||
1619          getTargetMachine().getCodeModel() != CodeModel::Large)
1620         && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1621                                            getTargetMachine(), true))
1622       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1623   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1624     if (IsTailCall || !Is64Bit ||
1625         getTargetMachine().getCodeModel() != CodeModel::Large)
1626       Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1627   } else if (IsTailCall) {
1628     assert(Callee.getOpcode() == ISD::LOAD && 
1629            "Function destination must be loaded into virtual register");
1630     unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1631
1632     Chain = DAG.getCopyToReg(Chain, 
1633                              DAG.getRegister(Opc, getPointerTy()) , 
1634                              Callee,InFlag);
1635     Callee = DAG.getRegister(Opc, getPointerTy());
1636     // Add register as live out.
1637     DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1638   }
1639  
1640   // Returns a chain & a flag for retval copy to use.
1641   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1642   SmallVector<SDOperand, 8> Ops;
1643
1644   if (IsTailCall) {
1645     Ops.push_back(Chain);
1646     Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1647     Ops.push_back(DAG.getIntPtrConstant(0));
1648     if (InFlag.Val)
1649       Ops.push_back(InFlag);
1650     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1651     InFlag = Chain.getValue(1);
1652  
1653     // Returns a chain & a flag for retval copy to use.
1654     NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1655     Ops.clear();
1656   }
1657   
1658   Ops.push_back(Chain);
1659   Ops.push_back(Callee);
1660
1661   if (IsTailCall)
1662     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1663
1664   // Add an implicit use GOT pointer in EBX.
1665   if (!IsTailCall && !Is64Bit &&
1666       getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1667       Subtarget->isPICStyleGOT())
1668     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1669
1670   // Add argument registers to the end of the list so that they are known live
1671   // into the call.
1672   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1673     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1674                                   RegsToPass[i].second.getValueType()));
1675   
1676   if (InFlag.Val)
1677     Ops.push_back(InFlag);
1678
1679   if (IsTailCall) {
1680     assert(InFlag.Val && 
1681            "Flag must be set. Depend on flag being set in LowerRET");
1682     Chain = DAG.getNode(X86ISD::TAILCALL,
1683                         Op.Val->getVTList(), &Ops[0], Ops.size());
1684       
1685     return SDOperand(Chain.Val, Op.ResNo);
1686   }
1687
1688   Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1689   InFlag = Chain.getValue(1);
1690
1691   // Create the CALLSEQ_END node.
1692   unsigned NumBytesForCalleeToPush;
1693   if (IsCalleePop(Op))
1694     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
1695   else if (!Is64Bit && IsStructRet)
1696     // If this is is a call to a struct-return function, the callee
1697     // pops the hidden struct pointer, so we have to push it back.
1698     // This is common for Darwin/X86, Linux & Mingw32 targets.
1699     NumBytesForCalleeToPush = 4;
1700   else
1701     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
1702   
1703   // Returns a flag for retval copy to use.
1704   Chain = DAG.getCALLSEQ_END(Chain,
1705                              DAG.getIntPtrConstant(NumBytes),
1706                              DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1707                              InFlag);
1708   InFlag = Chain.getValue(1);
1709
1710   // Handle result values, copying them out of physregs into vregs that we
1711   // return.
1712   switch (SRetMethod) {
1713   default:
1714     return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1715   case X86::InGPR64:
1716     return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1717                                                    X86::RAX, X86::RDX,
1718                                                    MVT::i64, DAG), Op.ResNo);
1719   case X86::InSSE:
1720     return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1721                                                    X86::XMM0, X86::XMM1,
1722                                                    MVT::f64, DAG), Op.ResNo);
1723   case X86::InX87:
1724     return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1725                      Op.ResNo);
1726   }
1727 }
1728
1729
1730 //===----------------------------------------------------------------------===//
1731 //                Fast Calling Convention (tail call) implementation
1732 //===----------------------------------------------------------------------===//
1733
1734 //  Like std call, callee cleans arguments, convention except that ECX is
1735 //  reserved for storing the tail called function address. Only 2 registers are
1736 //  free for argument passing (inreg). Tail call optimization is performed
1737 //  provided:
1738 //                * tailcallopt is enabled
1739 //                * caller/callee are fastcc
1740 //                * elf/pic is disabled OR
1741 //                * elf/pic enabled + callee is in module + callee has
1742 //                  visibility protected or hidden
1743 //  To keep the stack aligned according to platform abi the function
1744 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
1745 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1746 //  If a tail called function callee has more arguments than the caller the
1747 //  caller needs to make sure that there is room to move the RETADDR to. This is
1748 //  achieved by reserving an area the size of the argument delta right after the
1749 //  original REtADDR, but before the saved framepointer or the spilled registers
1750 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1751 //  stack layout:
1752 //    arg1
1753 //    arg2
1754 //    RETADDR
1755 //    [ new RETADDR 
1756 //      move area ]
1757 //    (possible EBP)
1758 //    ESI
1759 //    EDI
1760 //    local1 ..
1761
1762 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1763 /// for a 16 byte align requirement.
1764 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 
1765                                                         SelectionDAG& DAG) {
1766   if (PerformTailCallOpt) {
1767     MachineFunction &MF = DAG.getMachineFunction();
1768     const TargetMachine &TM = MF.getTarget();
1769     const TargetFrameInfo &TFI = *TM.getFrameInfo();
1770     unsigned StackAlignment = TFI.getStackAlignment();
1771     uint64_t AlignMask = StackAlignment - 1; 
1772     int64_t Offset = StackSize;
1773     unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1774     if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1775       // Number smaller than 12 so just add the difference.
1776       Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1777     } else {
1778       // Mask out lower bits, add stackalignment once plus the 12 bytes.
1779       Offset = ((~AlignMask) & Offset) + StackAlignment + 
1780         (StackAlignment-SlotSize);
1781     }
1782     StackSize = Offset;
1783   }
1784   return StackSize;
1785 }
1786
1787 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1788 /// following the call is a return. A function is eligible if caller/callee
1789 /// calling conventions match, currently only fastcc supports tail calls, and
1790 /// the function CALL is immediatly followed by a RET.
1791 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1792                                                       SDOperand Ret,
1793                                                       SelectionDAG& DAG) const {
1794   if (!PerformTailCallOpt)
1795     return false;
1796
1797   // Check whether CALL node immediatly preceeds the RET node and whether the
1798   // return uses the result of the node or is a void return.
1799   unsigned NumOps = Ret.getNumOperands();
1800   if ((NumOps == 1 && 
1801        (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1802         Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1803       (NumOps > 1 &&
1804        Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1805        Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1806     MachineFunction &MF = DAG.getMachineFunction();
1807     unsigned CallerCC = MF.getFunction()->getCallingConv();
1808     unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1809     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1810       SDOperand Callee = Call.getOperand(4);
1811       // On elf/pic %ebx needs to be livein.
1812       if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1813           !Subtarget->isPICStyleGOT())
1814         return true;
1815
1816       // Can only do local tail calls with PIC.
1817       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1818         return G->getGlobal()->hasHiddenVisibility()
1819             || G->getGlobal()->hasProtectedVisibility();
1820     }
1821   }
1822
1823   return false;
1824 }
1825
1826 //===----------------------------------------------------------------------===//
1827 //                           Other Lowering Hooks
1828 //===----------------------------------------------------------------------===//
1829
1830
1831 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1832   MachineFunction &MF = DAG.getMachineFunction();
1833   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1834   int ReturnAddrIndex = FuncInfo->getRAIndex();
1835
1836   if (ReturnAddrIndex == 0) {
1837     // Set up a frame object for the return address.
1838     if (Subtarget->is64Bit())
1839       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1840     else
1841       ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1842
1843     FuncInfo->setRAIndex(ReturnAddrIndex);
1844   }
1845
1846   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1847 }
1848
1849
1850
1851 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1852 /// specific condition code. It returns a false if it cannot do a direct
1853 /// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
1854 /// needed.
1855 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1856                            unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1857                            SelectionDAG &DAG) {
1858   X86CC = X86::COND_INVALID;
1859   if (!isFP) {
1860     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1861       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1862         // X > -1   -> X == 0, jump !sign.
1863         RHS = DAG.getConstant(0, RHS.getValueType());
1864         X86CC = X86::COND_NS;
1865         return true;
1866       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1867         // X < 0   -> X == 0, jump on sign.
1868         X86CC = X86::COND_S;
1869         return true;
1870       } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1871         // X < 1   -> X <= 0
1872         RHS = DAG.getConstant(0, RHS.getValueType());
1873         X86CC = X86::COND_LE;
1874         return true;
1875       }
1876     }
1877
1878     switch (SetCCOpcode) {
1879     default: break;
1880     case ISD::SETEQ:  X86CC = X86::COND_E;  break;
1881     case ISD::SETGT:  X86CC = X86::COND_G;  break;
1882     case ISD::SETGE:  X86CC = X86::COND_GE; break;
1883     case ISD::SETLT:  X86CC = X86::COND_L;  break;
1884     case ISD::SETLE:  X86CC = X86::COND_LE; break;
1885     case ISD::SETNE:  X86CC = X86::COND_NE; break;
1886     case ISD::SETULT: X86CC = X86::COND_B;  break;
1887     case ISD::SETUGT: X86CC = X86::COND_A;  break;
1888     case ISD::SETULE: X86CC = X86::COND_BE; break;
1889     case ISD::SETUGE: X86CC = X86::COND_AE; break;
1890     }
1891   } else {
1892     // On a floating point condition, the flags are set as follows:
1893     // ZF  PF  CF   op
1894     //  0 | 0 | 0 | X > Y
1895     //  0 | 0 | 1 | X < Y
1896     //  1 | 0 | 0 | X == Y
1897     //  1 | 1 | 1 | unordered
1898     bool Flip = false;
1899     switch (SetCCOpcode) {
1900     default: break;
1901     case ISD::SETUEQ:
1902     case ISD::SETEQ: X86CC = X86::COND_E;  break;
1903     case ISD::SETOLT: Flip = true; // Fallthrough
1904     case ISD::SETOGT:
1905     case ISD::SETGT: X86CC = X86::COND_A;  break;
1906     case ISD::SETOLE: Flip = true; // Fallthrough
1907     case ISD::SETOGE:
1908     case ISD::SETGE: X86CC = X86::COND_AE; break;
1909     case ISD::SETUGT: Flip = true; // Fallthrough
1910     case ISD::SETULT:
1911     case ISD::SETLT: X86CC = X86::COND_B;  break;
1912     case ISD::SETUGE: Flip = true; // Fallthrough
1913     case ISD::SETULE:
1914     case ISD::SETLE: X86CC = X86::COND_BE; break;
1915     case ISD::SETONE:
1916     case ISD::SETNE: X86CC = X86::COND_NE; break;
1917     case ISD::SETUO: X86CC = X86::COND_P;  break;
1918     case ISD::SETO:  X86CC = X86::COND_NP; break;
1919     }
1920     if (Flip)
1921       std::swap(LHS, RHS);
1922   }
1923
1924   return X86CC != X86::COND_INVALID;
1925 }
1926
1927 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1928 /// code. Current x86 isa includes the following FP cmov instructions:
1929 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1930 static bool hasFPCMov(unsigned X86CC) {
1931   switch (X86CC) {
1932   default:
1933     return false;
1934   case X86::COND_B:
1935   case X86::COND_BE:
1936   case X86::COND_E:
1937   case X86::COND_P:
1938   case X86::COND_A:
1939   case X86::COND_AE:
1940   case X86::COND_NE:
1941   case X86::COND_NP:
1942     return true;
1943   }
1944 }
1945
1946 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
1947 /// true if Op is undef or if its value falls within the specified range (L, H].
1948 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1949   if (Op.getOpcode() == ISD::UNDEF)
1950     return true;
1951
1952   unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1953   return (Val >= Low && Val < Hi);
1954 }
1955
1956 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
1957 /// true if Op is undef or if its value equal to the specified value.
1958 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1959   if (Op.getOpcode() == ISD::UNDEF)
1960     return true;
1961   return cast<ConstantSDNode>(Op)->getValue() == Val;
1962 }
1963
1964 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1965 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1966 bool X86::isPSHUFDMask(SDNode *N) {
1967   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1968
1969   if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1970     return false;
1971
1972   // Check if the value doesn't reference the second vector.
1973   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1974     SDOperand Arg = N->getOperand(i);
1975     if (Arg.getOpcode() == ISD::UNDEF) continue;
1976     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1977     if (cast<ConstantSDNode>(Arg)->getValue() >= e)
1978       return false;
1979   }
1980
1981   return true;
1982 }
1983
1984 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1985 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1986 bool X86::isPSHUFHWMask(SDNode *N) {
1987   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1988
1989   if (N->getNumOperands() != 8)
1990     return false;
1991
1992   // Lower quadword copied in order.
1993   for (unsigned i = 0; i != 4; ++i) {
1994     SDOperand Arg = N->getOperand(i);
1995     if (Arg.getOpcode() == ISD::UNDEF) continue;
1996     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1997     if (cast<ConstantSDNode>(Arg)->getValue() != i)
1998       return false;
1999   }
2000
2001   // Upper quadword shuffled.
2002   for (unsigned i = 4; i != 8; ++i) {
2003     SDOperand Arg = N->getOperand(i);
2004     if (Arg.getOpcode() == ISD::UNDEF) continue;
2005     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2006     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2007     if (Val < 4 || Val > 7)
2008       return false;
2009   }
2010
2011   return true;
2012 }
2013
2014 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2015 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2016 bool X86::isPSHUFLWMask(SDNode *N) {
2017   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2018
2019   if (N->getNumOperands() != 8)
2020     return false;
2021
2022   // Upper quadword copied in order.
2023   for (unsigned i = 4; i != 8; ++i)
2024     if (!isUndefOrEqual(N->getOperand(i), i))
2025       return false;
2026
2027   // Lower quadword shuffled.
2028   for (unsigned i = 0; i != 4; ++i)
2029     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2030       return false;
2031
2032   return true;
2033 }
2034
2035 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2036 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2037 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2038   if (NumElems != 2 && NumElems != 4) return false;
2039
2040   unsigned Half = NumElems / 2;
2041   for (unsigned i = 0; i < Half; ++i)
2042     if (!isUndefOrInRange(Elems[i], 0, NumElems))
2043       return false;
2044   for (unsigned i = Half; i < NumElems; ++i)
2045     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2046       return false;
2047
2048   return true;
2049 }
2050
2051 bool X86::isSHUFPMask(SDNode *N) {
2052   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2053   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2054 }
2055
2056 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2057 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2058 /// half elements to come from vector 1 (which would equal the dest.) and
2059 /// the upper half to come from vector 2.
2060 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2061   if (NumOps != 2 && NumOps != 4) return false;
2062
2063   unsigned Half = NumOps / 2;
2064   for (unsigned i = 0; i < Half; ++i)
2065     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2066       return false;
2067   for (unsigned i = Half; i < NumOps; ++i)
2068     if (!isUndefOrInRange(Ops[i], 0, NumOps))
2069       return false;
2070   return true;
2071 }
2072
2073 static bool isCommutedSHUFP(SDNode *N) {
2074   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2075   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2076 }
2077
2078 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2079 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2080 bool X86::isMOVHLPSMask(SDNode *N) {
2081   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2082
2083   if (N->getNumOperands() != 4)
2084     return false;
2085
2086   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2087   return isUndefOrEqual(N->getOperand(0), 6) &&
2088          isUndefOrEqual(N->getOperand(1), 7) &&
2089          isUndefOrEqual(N->getOperand(2), 2) &&
2090          isUndefOrEqual(N->getOperand(3), 3);
2091 }
2092
2093 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2094 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2095 /// <2, 3, 2, 3>
2096 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2097   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2098
2099   if (N->getNumOperands() != 4)
2100     return false;
2101
2102   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2103   return isUndefOrEqual(N->getOperand(0), 2) &&
2104          isUndefOrEqual(N->getOperand(1), 3) &&
2105          isUndefOrEqual(N->getOperand(2), 2) &&
2106          isUndefOrEqual(N->getOperand(3), 3);
2107 }
2108
2109 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2110 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2111 bool X86::isMOVLPMask(SDNode *N) {
2112   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2113
2114   unsigned NumElems = N->getNumOperands();
2115   if (NumElems != 2 && NumElems != 4)
2116     return false;
2117
2118   for (unsigned i = 0; i < NumElems/2; ++i)
2119     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2120       return false;
2121
2122   for (unsigned i = NumElems/2; i < NumElems; ++i)
2123     if (!isUndefOrEqual(N->getOperand(i), i))
2124       return false;
2125
2126   return true;
2127 }
2128
2129 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2130 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2131 /// and MOVLHPS.
2132 bool X86::isMOVHPMask(SDNode *N) {
2133   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2134
2135   unsigned NumElems = N->getNumOperands();
2136   if (NumElems != 2 && NumElems != 4)
2137     return false;
2138
2139   for (unsigned i = 0; i < NumElems/2; ++i)
2140     if (!isUndefOrEqual(N->getOperand(i), i))
2141       return false;
2142
2143   for (unsigned i = 0; i < NumElems/2; ++i) {
2144     SDOperand Arg = N->getOperand(i + NumElems/2);
2145     if (!isUndefOrEqual(Arg, i + NumElems))
2146       return false;
2147   }
2148
2149   return true;
2150 }
2151
2152 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2153 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2154 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2155                          bool V2IsSplat = false) {
2156   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2157     return false;
2158
2159   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2160     SDOperand BitI  = Elts[i];
2161     SDOperand BitI1 = Elts[i+1];
2162     if (!isUndefOrEqual(BitI, j))
2163       return false;
2164     if (V2IsSplat) {
2165       if (isUndefOrEqual(BitI1, NumElts))
2166         return false;
2167     } else {
2168       if (!isUndefOrEqual(BitI1, j + NumElts))
2169         return false;
2170     }
2171   }
2172
2173   return true;
2174 }
2175
2176 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2177   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2178   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2179 }
2180
2181 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2182 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2183 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2184                          bool V2IsSplat = false) {
2185   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2186     return false;
2187
2188   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2189     SDOperand BitI  = Elts[i];
2190     SDOperand BitI1 = Elts[i+1];
2191     if (!isUndefOrEqual(BitI, j + NumElts/2))
2192       return false;
2193     if (V2IsSplat) {
2194       if (isUndefOrEqual(BitI1, NumElts))
2195         return false;
2196     } else {
2197       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2198         return false;
2199     }
2200   }
2201
2202   return true;
2203 }
2204
2205 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2206   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2207   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2208 }
2209
2210 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2211 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2212 /// <0, 0, 1, 1>
2213 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2214   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2215
2216   unsigned NumElems = N->getNumOperands();
2217   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2218     return false;
2219
2220   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2221     SDOperand BitI  = N->getOperand(i);
2222     SDOperand BitI1 = N->getOperand(i+1);
2223
2224     if (!isUndefOrEqual(BitI, j))
2225       return false;
2226     if (!isUndefOrEqual(BitI1, j))
2227       return false;
2228   }
2229
2230   return true;
2231 }
2232
2233 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2234 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2235 /// <2, 2, 3, 3>
2236 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2237   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2238
2239   unsigned NumElems = N->getNumOperands();
2240   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2241     return false;
2242
2243   for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2244     SDOperand BitI  = N->getOperand(i);
2245     SDOperand BitI1 = N->getOperand(i + 1);
2246
2247     if (!isUndefOrEqual(BitI, j))
2248       return false;
2249     if (!isUndefOrEqual(BitI1, j))
2250       return false;
2251   }
2252
2253   return true;
2254 }
2255
2256 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2257 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2258 /// MOVSD, and MOVD, i.e. setting the lowest element.
2259 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2260   if (NumElts != 2 && NumElts != 4)
2261     return false;
2262
2263   if (!isUndefOrEqual(Elts[0], NumElts))
2264     return false;
2265
2266   for (unsigned i = 1; i < NumElts; ++i) {
2267     if (!isUndefOrEqual(Elts[i], i))
2268       return false;
2269   }
2270
2271   return true;
2272 }
2273
2274 bool X86::isMOVLMask(SDNode *N) {
2275   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2276   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2277 }
2278
2279 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2280 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2281 /// element of vector 2 and the other elements to come from vector 1 in order.
2282 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2283                            bool V2IsSplat = false,
2284                            bool V2IsUndef = false) {
2285   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2286     return false;
2287
2288   if (!isUndefOrEqual(Ops[0], 0))
2289     return false;
2290
2291   for (unsigned i = 1; i < NumOps; ++i) {
2292     SDOperand Arg = Ops[i];
2293     if (!(isUndefOrEqual(Arg, i+NumOps) ||
2294           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2295           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2296       return false;
2297   }
2298
2299   return true;
2300 }
2301
2302 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2303                            bool V2IsUndef = false) {
2304   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2305   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2306                         V2IsSplat, V2IsUndef);
2307 }
2308
2309 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2310 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2311 bool X86::isMOVSHDUPMask(SDNode *N) {
2312   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2313
2314   if (N->getNumOperands() != 4)
2315     return false;
2316
2317   // Expect 1, 1, 3, 3
2318   for (unsigned i = 0; i < 2; ++i) {
2319     SDOperand Arg = N->getOperand(i);
2320     if (Arg.getOpcode() == ISD::UNDEF) continue;
2321     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2322     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2323     if (Val != 1) return false;
2324   }
2325
2326   bool HasHi = false;
2327   for (unsigned i = 2; i < 4; ++i) {
2328     SDOperand Arg = N->getOperand(i);
2329     if (Arg.getOpcode() == ISD::UNDEF) continue;
2330     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2331     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2332     if (Val != 3) return false;
2333     HasHi = true;
2334   }
2335
2336   // Don't use movshdup if it can be done with a shufps.
2337   return HasHi;
2338 }
2339
2340 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2341 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2342 bool X86::isMOVSLDUPMask(SDNode *N) {
2343   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2344
2345   if (N->getNumOperands() != 4)
2346     return false;
2347
2348   // Expect 0, 0, 2, 2
2349   for (unsigned i = 0; i < 2; ++i) {
2350     SDOperand Arg = N->getOperand(i);
2351     if (Arg.getOpcode() == ISD::UNDEF) continue;
2352     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2353     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2354     if (Val != 0) return false;
2355   }
2356
2357   bool HasHi = false;
2358   for (unsigned i = 2; i < 4; ++i) {
2359     SDOperand Arg = N->getOperand(i);
2360     if (Arg.getOpcode() == ISD::UNDEF) continue;
2361     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2362     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2363     if (Val != 2) return false;
2364     HasHi = true;
2365   }
2366
2367   // Don't use movshdup if it can be done with a shufps.
2368   return HasHi;
2369 }
2370
2371 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2372 /// specifies a identity operation on the LHS or RHS.
2373 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2374   unsigned NumElems = N->getNumOperands();
2375   for (unsigned i = 0; i < NumElems; ++i)
2376     if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2377       return false;
2378   return true;
2379 }
2380
2381 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2382 /// a splat of a single element.
2383 static bool isSplatMask(SDNode *N) {
2384   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2385
2386   // This is a splat operation if each element of the permute is the same, and
2387   // if the value doesn't reference the second vector.
2388   unsigned NumElems = N->getNumOperands();
2389   SDOperand ElementBase;
2390   unsigned i = 0;
2391   for (; i != NumElems; ++i) {
2392     SDOperand Elt = N->getOperand(i);
2393     if (isa<ConstantSDNode>(Elt)) {
2394       ElementBase = Elt;
2395       break;
2396     }
2397   }
2398
2399   if (!ElementBase.Val)
2400     return false;
2401
2402   for (; i != NumElems; ++i) {
2403     SDOperand Arg = N->getOperand(i);
2404     if (Arg.getOpcode() == ISD::UNDEF) continue;
2405     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2406     if (Arg != ElementBase) return false;
2407   }
2408
2409   // Make sure it is a splat of the first vector operand.
2410   return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2411 }
2412
2413 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2414 /// a splat of a single element and it's a 2 or 4 element mask.
2415 bool X86::isSplatMask(SDNode *N) {
2416   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2417
2418   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2419   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2420     return false;
2421   return ::isSplatMask(N);
2422 }
2423
2424 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2425 /// specifies a splat of zero element.
2426 bool X86::isSplatLoMask(SDNode *N) {
2427   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2428
2429   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2430     if (!isUndefOrEqual(N->getOperand(i), 0))
2431       return false;
2432   return true;
2433 }
2434
2435 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2436 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2437 /// instructions.
2438 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2439   unsigned NumOperands = N->getNumOperands();
2440   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2441   unsigned Mask = 0;
2442   for (unsigned i = 0; i < NumOperands; ++i) {
2443     unsigned Val = 0;
2444     SDOperand Arg = N->getOperand(NumOperands-i-1);
2445     if (Arg.getOpcode() != ISD::UNDEF)
2446       Val = cast<ConstantSDNode>(Arg)->getValue();
2447     if (Val >= NumOperands) Val -= NumOperands;
2448     Mask |= Val;
2449     if (i != NumOperands - 1)
2450       Mask <<= Shift;
2451   }
2452
2453   return Mask;
2454 }
2455
2456 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2457 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2458 /// instructions.
2459 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2460   unsigned Mask = 0;
2461   // 8 nodes, but we only care about the last 4.
2462   for (unsigned i = 7; i >= 4; --i) {
2463     unsigned Val = 0;
2464     SDOperand Arg = N->getOperand(i);
2465     if (Arg.getOpcode() != ISD::UNDEF)
2466       Val = cast<ConstantSDNode>(Arg)->getValue();
2467     Mask |= (Val - 4);
2468     if (i != 4)
2469       Mask <<= 2;
2470   }
2471
2472   return Mask;
2473 }
2474
2475 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2476 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2477 /// instructions.
2478 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2479   unsigned Mask = 0;
2480   // 8 nodes, but we only care about the first 4.
2481   for (int i = 3; i >= 0; --i) {
2482     unsigned Val = 0;
2483     SDOperand Arg = N->getOperand(i);
2484     if (Arg.getOpcode() != ISD::UNDEF)
2485       Val = cast<ConstantSDNode>(Arg)->getValue();
2486     Mask |= Val;
2487     if (i != 0)
2488       Mask <<= 2;
2489   }
2490
2491   return Mask;
2492 }
2493
2494 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2495 /// specifies a 8 element shuffle that can be broken into a pair of
2496 /// PSHUFHW and PSHUFLW.
2497 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2498   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2499
2500   if (N->getNumOperands() != 8)
2501     return false;
2502
2503   // Lower quadword shuffled.
2504   for (unsigned i = 0; i != 4; ++i) {
2505     SDOperand Arg = N->getOperand(i);
2506     if (Arg.getOpcode() == ISD::UNDEF) continue;
2507     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2508     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2509     if (Val >= 4)
2510       return false;
2511   }
2512
2513   // Upper quadword shuffled.
2514   for (unsigned i = 4; i != 8; ++i) {
2515     SDOperand Arg = N->getOperand(i);
2516     if (Arg.getOpcode() == ISD::UNDEF) continue;
2517     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2518     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2519     if (Val < 4 || Val > 7)
2520       return false;
2521   }
2522
2523   return true;
2524 }
2525
2526 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2527 /// values in ther permute mask.
2528 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2529                                       SDOperand &V2, SDOperand &Mask,
2530                                       SelectionDAG &DAG) {
2531   MVT::ValueType VT = Op.getValueType();
2532   MVT::ValueType MaskVT = Mask.getValueType();
2533   MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2534   unsigned NumElems = Mask.getNumOperands();
2535   SmallVector<SDOperand, 8> MaskVec;
2536
2537   for (unsigned i = 0; i != NumElems; ++i) {
2538     SDOperand Arg = Mask.getOperand(i);
2539     if (Arg.getOpcode() == ISD::UNDEF) {
2540       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2541       continue;
2542     }
2543     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2544     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2545     if (Val < NumElems)
2546       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2547     else
2548       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2549   }
2550
2551   std::swap(V1, V2);
2552   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2553   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2554 }
2555
2556 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2557 /// the two vector operands have swapped position.
2558 static
2559 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2560   MVT::ValueType MaskVT = Mask.getValueType();
2561   MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2562   unsigned NumElems = Mask.getNumOperands();
2563   SmallVector<SDOperand, 8> MaskVec;
2564   for (unsigned i = 0; i != NumElems; ++i) {
2565     SDOperand Arg = Mask.getOperand(i);
2566     if (Arg.getOpcode() == ISD::UNDEF) {
2567       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2568       continue;
2569     }
2570     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2571     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2572     if (Val < NumElems)
2573       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2574     else
2575       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2576   }
2577   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2578 }
2579
2580
2581 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2582 /// match movhlps. The lower half elements should come from upper half of
2583 /// V1 (and in order), and the upper half elements should come from the upper
2584 /// half of V2 (and in order).
2585 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2586   unsigned NumElems = Mask->getNumOperands();
2587   if (NumElems != 4)
2588     return false;
2589   for (unsigned i = 0, e = 2; i != e; ++i)
2590     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2591       return false;
2592   for (unsigned i = 2; i != 4; ++i)
2593     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2594       return false;
2595   return true;
2596 }
2597
2598 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2599 /// is promoted to a vector.
2600 static inline bool isScalarLoadToVector(SDNode *N) {
2601   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2602     N = N->getOperand(0).Val;
2603     return ISD::isNON_EXTLoad(N);
2604   }
2605   return false;
2606 }
2607
2608 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2609 /// match movlp{s|d}. The lower half elements should come from lower half of
2610 /// V1 (and in order), and the upper half elements should come from the upper
2611 /// half of V2 (and in order). And since V1 will become the source of the
2612 /// MOVLP, it must be either a vector load or a scalar load to vector.
2613 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2614   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2615     return false;
2616   // Is V2 is a vector load, don't do this transformation. We will try to use
2617   // load folding shufps op.
2618   if (ISD::isNON_EXTLoad(V2))
2619     return false;
2620
2621   unsigned NumElems = Mask->getNumOperands();
2622   if (NumElems != 2 && NumElems != 4)
2623     return false;
2624   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2625     if (!isUndefOrEqual(Mask->getOperand(i), i))
2626       return false;
2627   for (unsigned i = NumElems/2; i != NumElems; ++i)
2628     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2629       return false;
2630   return true;
2631 }
2632
2633 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2634 /// all the same.
2635 static bool isSplatVector(SDNode *N) {
2636   if (N->getOpcode() != ISD::BUILD_VECTOR)
2637     return false;
2638
2639   SDOperand SplatValue = N->getOperand(0);
2640   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2641     if (N->getOperand(i) != SplatValue)
2642       return false;
2643   return true;
2644 }
2645
2646 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2647 /// to an undef.
2648 static bool isUndefShuffle(SDNode *N) {
2649   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2650     return false;
2651
2652   SDOperand V1 = N->getOperand(0);
2653   SDOperand V2 = N->getOperand(1);
2654   SDOperand Mask = N->getOperand(2);
2655   unsigned NumElems = Mask.getNumOperands();
2656   for (unsigned i = 0; i != NumElems; ++i) {
2657     SDOperand Arg = Mask.getOperand(i);
2658     if (Arg.getOpcode() != ISD::UNDEF) {
2659       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2660       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2661         return false;
2662       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2663         return false;
2664     }
2665   }
2666   return true;
2667 }
2668
2669 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2670 /// constant +0.0.
2671 static inline bool isZeroNode(SDOperand Elt) {
2672   return ((isa<ConstantSDNode>(Elt) &&
2673            cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2674           (isa<ConstantFPSDNode>(Elt) &&
2675            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2676 }
2677
2678 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2679 /// to an zero vector.
2680 static bool isZeroShuffle(SDNode *N) {
2681   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2682     return false;
2683
2684   SDOperand V1 = N->getOperand(0);
2685   SDOperand V2 = N->getOperand(1);
2686   SDOperand Mask = N->getOperand(2);
2687   unsigned NumElems = Mask.getNumOperands();
2688   for (unsigned i = 0; i != NumElems; ++i) {
2689     SDOperand Arg = Mask.getOperand(i);
2690     if (Arg.getOpcode() == ISD::UNDEF)
2691       continue;
2692     
2693     unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2694     if (Idx < NumElems) {
2695       unsigned Opc = V1.Val->getOpcode();
2696       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2697         continue;
2698       if (Opc != ISD::BUILD_VECTOR ||
2699           !isZeroNode(V1.Val->getOperand(Idx)))
2700         return false;
2701     } else if (Idx >= NumElems) {
2702       unsigned Opc = V2.Val->getOpcode();
2703       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2704         continue;
2705       if (Opc != ISD::BUILD_VECTOR ||
2706           !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2707         return false;
2708     }
2709   }
2710   return true;
2711 }
2712
2713 /// getZeroVector - Returns a vector of specified type with all zero elements.
2714 ///
2715 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2716   assert(MVT::isVector(VT) && "Expected a vector type");
2717   
2718   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2719   // type.  This ensures they get CSE'd.
2720   SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2721   SDOperand Vec;
2722   if (MVT::getSizeInBits(VT) == 64)  // MMX
2723     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2724   else                                              // SSE
2725     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2726   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2727 }
2728
2729 /// getOnesVector - Returns a vector of specified type with all bits set.
2730 ///
2731 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2732   assert(MVT::isVector(VT) && "Expected a vector type");
2733   
2734   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2735   // type.  This ensures they get CSE'd.
2736   SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2737   SDOperand Vec;
2738   if (MVT::getSizeInBits(VT) == 64)  // MMX
2739     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2740   else                                              // SSE
2741     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2742   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2743 }
2744
2745
2746 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2747 /// that point to V2 points to its first element.
2748 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2749   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2750
2751   bool Changed = false;
2752   SmallVector<SDOperand, 8> MaskVec;
2753   unsigned NumElems = Mask.getNumOperands();
2754   for (unsigned i = 0; i != NumElems; ++i) {
2755     SDOperand Arg = Mask.getOperand(i);
2756     if (Arg.getOpcode() != ISD::UNDEF) {
2757       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2758       if (Val > NumElems) {
2759         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2760         Changed = true;
2761       }
2762     }
2763     MaskVec.push_back(Arg);
2764   }
2765
2766   if (Changed)
2767     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2768                        &MaskVec[0], MaskVec.size());
2769   return Mask;
2770 }
2771
2772 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2773 /// operation of specified width.
2774 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2775   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2776   MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2777
2778   SmallVector<SDOperand, 8> MaskVec;
2779   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2780   for (unsigned i = 1; i != NumElems; ++i)
2781     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2782   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2783 }
2784
2785 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2786 /// of specified width.
2787 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2788   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2789   MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2790   SmallVector<SDOperand, 8> MaskVec;
2791   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2792     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2793     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2794   }
2795   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2796 }
2797
2798 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2799 /// of specified width.
2800 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2801   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2802   MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2803   unsigned Half = NumElems/2;
2804   SmallVector<SDOperand, 8> MaskVec;
2805   for (unsigned i = 0; i != Half; ++i) {
2806     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2807     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2808   }
2809   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2810 }
2811
2812 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2813 ///
2814 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2815   SDOperand V1 = Op.getOperand(0);
2816   SDOperand Mask = Op.getOperand(2);
2817   MVT::ValueType VT = Op.getValueType();
2818   unsigned NumElems = Mask.getNumOperands();
2819   Mask = getUnpacklMask(NumElems, DAG);
2820   while (NumElems != 4) {
2821     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2822     NumElems >>= 1;
2823   }
2824   V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2825
2826   Mask = getZeroVector(MVT::v4i32, DAG);
2827   SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2828                                   DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2829   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2830 }
2831
2832 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2833 /// vector of zero or undef vector.  This produces a shuffle where the low
2834 /// element of V2 is swizzled into the zero/undef vector, landing at element
2835 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2836 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2837                                              unsigned NumElems, unsigned Idx,
2838                                              bool isZero, SelectionDAG &DAG) {
2839   SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2840   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2841   MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2842   SmallVector<SDOperand, 16> MaskVec;
2843   for (unsigned i = 0; i != NumElems; ++i)
2844     if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
2845       MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2846     else
2847       MaskVec.push_back(DAG.getConstant(i, EVT));
2848   SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2849                                &MaskVec[0], MaskVec.size());
2850   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2851 }
2852
2853 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2854 ///
2855 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2856                                        unsigned NumNonZero, unsigned NumZero,
2857                                        SelectionDAG &DAG, TargetLowering &TLI) {
2858   if (NumNonZero > 8)
2859     return SDOperand();
2860
2861   SDOperand V(0, 0);
2862   bool First = true;
2863   for (unsigned i = 0; i < 16; ++i) {
2864     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2865     if (ThisIsNonZero && First) {
2866       if (NumZero)
2867         V = getZeroVector(MVT::v8i16, DAG);
2868       else
2869         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2870       First = false;
2871     }
2872
2873     if ((i & 1) != 0) {
2874       SDOperand ThisElt(0, 0), LastElt(0, 0);
2875       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2876       if (LastIsNonZero) {
2877         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2878       }
2879       if (ThisIsNonZero) {
2880         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2881         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2882                               ThisElt, DAG.getConstant(8, MVT::i8));
2883         if (LastIsNonZero)
2884           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2885       } else
2886         ThisElt = LastElt;
2887
2888       if (ThisElt.Val)
2889         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2890                         DAG.getIntPtrConstant(i/2));
2891     }
2892   }
2893
2894   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2895 }
2896
2897 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2898 ///
2899 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2900                                        unsigned NumNonZero, unsigned NumZero,
2901                                        SelectionDAG &DAG, TargetLowering &TLI) {
2902   if (NumNonZero > 4)
2903     return SDOperand();
2904
2905   SDOperand V(0, 0);
2906   bool First = true;
2907   for (unsigned i = 0; i < 8; ++i) {
2908     bool isNonZero = (NonZeros & (1 << i)) != 0;
2909     if (isNonZero) {
2910       if (First) {
2911         if (NumZero)
2912           V = getZeroVector(MVT::v8i16, DAG);
2913         else
2914           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2915         First = false;
2916       }
2917       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2918                       DAG.getIntPtrConstant(i));
2919     }
2920   }
2921
2922   return V;
2923 }
2924
2925 SDOperand
2926 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2927   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2928   if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2929     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2930     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2931     // eliminated on x86-32 hosts.
2932     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2933       return Op;
2934
2935     if (ISD::isBuildVectorAllOnes(Op.Val))
2936       return getOnesVector(Op.getValueType(), DAG);
2937     return getZeroVector(Op.getValueType(), DAG);
2938   }
2939
2940   MVT::ValueType VT = Op.getValueType();
2941   MVT::ValueType EVT = MVT::getVectorElementType(VT);
2942   unsigned EVTBits = MVT::getSizeInBits(EVT);
2943
2944   unsigned NumElems = Op.getNumOperands();
2945   unsigned NumZero  = 0;
2946   unsigned NumNonZero = 0;
2947   unsigned NonZeros = 0;
2948   bool HasNonImms = false;
2949   SmallSet<SDOperand, 8> Values;
2950   for (unsigned i = 0; i < NumElems; ++i) {
2951     SDOperand Elt = Op.getOperand(i);
2952     if (Elt.getOpcode() == ISD::UNDEF)
2953       continue;
2954     Values.insert(Elt);
2955     if (Elt.getOpcode() != ISD::Constant &&
2956         Elt.getOpcode() != ISD::ConstantFP)
2957       HasNonImms = true;
2958     if (isZeroNode(Elt))
2959       NumZero++;
2960     else {
2961       NonZeros |= (1 << i);
2962       NumNonZero++;
2963     }
2964   }
2965
2966   if (NumNonZero == 0) {
2967     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
2968     return DAG.getNode(ISD::UNDEF, VT);
2969   }
2970
2971   // Splat is obviously ok. Let legalizer expand it to a shuffle.
2972   if (Values.size() == 1)
2973     return SDOperand();
2974
2975   // Special case for single non-zero element.
2976   if (NumNonZero == 1 && NumElems <= 4) {
2977     unsigned Idx = CountTrailingZeros_32(NonZeros);
2978     SDOperand Item = Op.getOperand(Idx);
2979     Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2980     if (Idx == 0)
2981       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2982       return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2983                                          NumZero > 0, DAG);
2984     else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
2985       return SDOperand();
2986
2987     if (EVTBits == 32) {
2988       // Turn it into a shuffle of zero and zero-extended scalar to vector.
2989       Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2990                                          DAG);
2991       MVT::ValueType MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
2992       MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
2993       SmallVector<SDOperand, 8> MaskVec;
2994       for (unsigned i = 0; i < NumElems; i++)
2995         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2996       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2997                                    &MaskVec[0], MaskVec.size());
2998       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2999                          DAG.getNode(ISD::UNDEF, VT), Mask);
3000     }
3001   }
3002
3003   // A vector full of immediates; various special cases are already
3004   // handled, so this is best done with a single constant-pool load.
3005   if (!HasNonImms)
3006     return SDOperand();
3007
3008   // Let legalizer expand 2-wide build_vectors.
3009   if (EVTBits == 64)
3010     return SDOperand();
3011
3012   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3013   if (EVTBits == 8 && NumElems == 16) {
3014     SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3015                                         *this);
3016     if (V.Val) return V;
3017   }
3018
3019   if (EVTBits == 16 && NumElems == 8) {
3020     SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3021                                         *this);
3022     if (V.Val) return V;
3023   }
3024
3025   // If element VT is == 32 bits, turn it into a number of shuffles.
3026   SmallVector<SDOperand, 8> V;
3027   V.resize(NumElems);
3028   if (NumElems == 4 && NumZero > 0) {
3029     for (unsigned i = 0; i < 4; ++i) {
3030       bool isZero = !(NonZeros & (1 << i));
3031       if (isZero)
3032         V[i] = getZeroVector(VT, DAG);
3033       else
3034         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3035     }
3036
3037     for (unsigned i = 0; i < 2; ++i) {
3038       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3039         default: break;
3040         case 0:
3041           V[i] = V[i*2];  // Must be a zero vector.
3042           break;
3043         case 1:
3044           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3045                              getMOVLMask(NumElems, DAG));
3046           break;
3047         case 2:
3048           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3049                              getMOVLMask(NumElems, DAG));
3050           break;
3051         case 3:
3052           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3053                              getUnpacklMask(NumElems, DAG));
3054           break;
3055       }
3056     }
3057
3058     // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3059     // clears the upper bits.
3060     // FIXME: we can do the same for v4f32 case when we know both parts of
3061     // the lower half come from scalar_to_vector (loadf32). We should do
3062     // that in post legalizer dag combiner with target specific hooks.
3063     if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3064       return V[0];
3065     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3066     MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3067     SmallVector<SDOperand, 8> MaskVec;
3068     bool Reverse = (NonZeros & 0x3) == 2;
3069     for (unsigned i = 0; i < 2; ++i)
3070       if (Reverse)
3071         MaskVec.push_back(DAG.getConstant(1-i, EVT));
3072       else
3073         MaskVec.push_back(DAG.getConstant(i, EVT));
3074     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3075     for (unsigned i = 0; i < 2; ++i)
3076       if (Reverse)
3077         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3078       else
3079         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3080     SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3081                                      &MaskVec[0], MaskVec.size());
3082     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3083   }
3084
3085   if (Values.size() > 2) {
3086     // Expand into a number of unpckl*.
3087     // e.g. for v4f32
3088     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3089     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3090     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3091     SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3092     for (unsigned i = 0; i < NumElems; ++i)
3093       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3094     NumElems >>= 1;
3095     while (NumElems != 0) {
3096       for (unsigned i = 0; i < NumElems; ++i)
3097         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3098                            UnpckMask);
3099       NumElems >>= 1;
3100     }
3101     return V[0];
3102   }
3103
3104   return SDOperand();
3105 }
3106
3107 static
3108 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3109                                    SDOperand PermMask, SelectionDAG &DAG,
3110                                    TargetLowering &TLI) {
3111   SDOperand NewV;
3112   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3113   MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3114   MVT::ValueType PtrVT = TLI.getPointerTy();
3115   SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3116                                      PermMask.Val->op_end());
3117
3118   // First record which half of which vector the low elements come from.
3119   SmallVector<unsigned, 4> LowQuad(4);
3120   for (unsigned i = 0; i < 4; ++i) {
3121     SDOperand Elt = MaskElts[i];
3122     if (Elt.getOpcode() == ISD::UNDEF)
3123       continue;
3124     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3125     int QuadIdx = EltIdx / 4;
3126     ++LowQuad[QuadIdx];
3127   }
3128   int BestLowQuad = -1;
3129   unsigned MaxQuad = 1;
3130   for (unsigned i = 0; i < 4; ++i) {
3131     if (LowQuad[i] > MaxQuad) {
3132       BestLowQuad = i;
3133       MaxQuad = LowQuad[i];
3134     }
3135   }
3136
3137   // Record which half of which vector the high elements come from.
3138   SmallVector<unsigned, 4> HighQuad(4);
3139   for (unsigned i = 4; i < 8; ++i) {
3140     SDOperand Elt = MaskElts[i];
3141     if (Elt.getOpcode() == ISD::UNDEF)
3142       continue;
3143     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3144     int QuadIdx = EltIdx / 4;
3145     ++HighQuad[QuadIdx];
3146   }
3147   int BestHighQuad = -1;
3148   MaxQuad = 1;
3149   for (unsigned i = 0; i < 4; ++i) {
3150     if (HighQuad[i] > MaxQuad) {
3151       BestHighQuad = i;
3152       MaxQuad = HighQuad[i];
3153     }
3154   }
3155
3156   // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3157   if (BestLowQuad != -1 || BestHighQuad != -1) {
3158     // First sort the 4 chunks in order using shufpd.
3159     SmallVector<SDOperand, 8> MaskVec;
3160     if (BestLowQuad != -1)
3161       MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3162     else
3163       MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3164     if (BestHighQuad != -1)
3165       MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3166     else
3167       MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3168     SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3169     NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3170                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3171                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3172     NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3173
3174     // Now sort high and low parts separately.
3175     BitVector InOrder(8);
3176     if (BestLowQuad != -1) {
3177       // Sort lower half in order using PSHUFLW.
3178       MaskVec.clear();
3179       bool AnyOutOrder = false;
3180       for (unsigned i = 0; i != 4; ++i) {
3181         SDOperand Elt = MaskElts[i];
3182         if (Elt.getOpcode() == ISD::UNDEF) {
3183           MaskVec.push_back(Elt);
3184           InOrder.set(i);
3185         } else {
3186           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3187           if (EltIdx != i)
3188             AnyOutOrder = true;
3189           MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3190           // If this element is in the right place after this shuffle, then
3191           // remember it.
3192           if ((int)(EltIdx / 4) == BestLowQuad)
3193             InOrder.set(i);
3194         }
3195       }
3196       if (AnyOutOrder) {
3197         for (unsigned i = 4; i != 8; ++i)
3198           MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3199         SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3200         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3201       }
3202     }
3203
3204     if (BestHighQuad != -1) {
3205       // Sort high half in order using PSHUFHW if possible.
3206       MaskVec.clear();
3207       for (unsigned i = 0; i != 4; ++i)
3208         MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3209       bool AnyOutOrder = false;
3210       for (unsigned i = 4; i != 8; ++i) {
3211         SDOperand Elt = MaskElts[i];
3212         if (Elt.getOpcode() == ISD::UNDEF) {
3213           MaskVec.push_back(Elt);
3214           InOrder.set(i);
3215         } else {
3216           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3217           if (EltIdx != i)
3218             AnyOutOrder = true;
3219           MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3220           // If this element is in the right place after this shuffle, then
3221           // remember it.
3222           if ((int)(EltIdx / 4) == BestHighQuad)
3223             InOrder.set(i);
3224         }
3225       }
3226       if (AnyOutOrder) {
3227         SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3228         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3229       }
3230     }
3231
3232     // The other elements are put in the right place using pextrw and pinsrw.
3233     for (unsigned i = 0; i != 8; ++i) {
3234       if (InOrder[i])
3235         continue;
3236       SDOperand Elt = MaskElts[i];
3237       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3238       if (EltIdx == i)
3239         continue;
3240       SDOperand ExtOp = (EltIdx < 8)
3241         ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3242                       DAG.getConstant(EltIdx, PtrVT))
3243         : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3244                       DAG.getConstant(EltIdx - 8, PtrVT));
3245       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3246                          DAG.getConstant(i, PtrVT));
3247     }
3248     return NewV;
3249   }
3250
3251   // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3252   ///as few as possible.
3253   // First, let's find out how many elements are already in the right order.
3254   unsigned V1InOrder = 0;
3255   unsigned V1FromV1 = 0;
3256   unsigned V2InOrder = 0;
3257   unsigned V2FromV2 = 0;
3258   SmallVector<SDOperand, 8> V1Elts;
3259   SmallVector<SDOperand, 8> V2Elts;
3260   for (unsigned i = 0; i < 8; ++i) {
3261     SDOperand Elt = MaskElts[i];
3262     if (Elt.getOpcode() == ISD::UNDEF) {
3263       V1Elts.push_back(Elt);
3264       V2Elts.push_back(Elt);
3265       ++V1InOrder;
3266       ++V2InOrder;
3267       continue;
3268     }
3269     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3270     if (EltIdx == i) {
3271       V1Elts.push_back(Elt);
3272       V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3273       ++V1InOrder;
3274     } else if (EltIdx == i+8) {
3275       V1Elts.push_back(Elt);
3276       V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3277       ++V2InOrder;
3278     } else if (EltIdx < 8) {
3279       V1Elts.push_back(Elt);
3280       ++V1FromV1;
3281     } else {
3282       V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3283       ++V2FromV2;
3284     }
3285   }
3286
3287   if (V2InOrder > V1InOrder) {
3288     PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3289     std::swap(V1, V2);
3290     std::swap(V1Elts, V2Elts);
3291     std::swap(V1FromV1, V2FromV2);
3292   }
3293
3294   if ((V1FromV1 + V1InOrder) != 8) {
3295     // Some elements are from V2.
3296     if (V1FromV1) {
3297       // If there are elements that are from V1 but out of place,
3298       // then first sort them in place
3299       SmallVector<SDOperand, 8> MaskVec;
3300       for (unsigned i = 0; i < 8; ++i) {
3301         SDOperand Elt = V1Elts[i];
3302         if (Elt.getOpcode() == ISD::UNDEF) {
3303           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3304           continue;
3305         }
3306         unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3307         if (EltIdx >= 8)
3308           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3309         else
3310           MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3311       }
3312       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3313       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3314     }
3315
3316     NewV = V1;
3317     for (unsigned i = 0; i < 8; ++i) {
3318       SDOperand Elt = V1Elts[i];
3319       if (Elt.getOpcode() == ISD::UNDEF)
3320         continue;
3321       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3322       if (EltIdx < 8)
3323         continue;
3324       SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3325                                     DAG.getConstant(EltIdx - 8, PtrVT));
3326       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3327                          DAG.getConstant(i, PtrVT));
3328     }
3329     return NewV;
3330   } else {
3331     // All elements are from V1.
3332     NewV = V1;
3333     for (unsigned i = 0; i < 8; ++i) {
3334       SDOperand Elt = V1Elts[i];
3335       if (Elt.getOpcode() == ISD::UNDEF)
3336         continue;
3337       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3338       SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3339                                     DAG.getConstant(EltIdx, PtrVT));
3340       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3341                          DAG.getConstant(i, PtrVT));
3342     }
3343     return NewV;
3344   }
3345 }
3346
3347 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3348 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3349 /// done when every pair / quad of shuffle mask elements point to elements in
3350 /// the right sequence. e.g.
3351 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3352 static
3353 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3354                                 MVT::ValueType VT,
3355                                 SDOperand PermMask, SelectionDAG &DAG,
3356                                 TargetLowering &TLI) {
3357   unsigned NumElems = PermMask.getNumOperands();
3358   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3359   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3360   MVT::ValueType NewVT = MaskVT;
3361   switch (VT) {
3362   case MVT::v4f32: NewVT = MVT::v2f64; break;
3363   case MVT::v4i32: NewVT = MVT::v2i64; break;
3364   case MVT::v8i16: NewVT = MVT::v4i32; break;
3365   case MVT::v16i8: NewVT = MVT::v4i32; break;
3366   default: assert(false && "Unexpected!");
3367   }
3368
3369   if (NewWidth == 2)
3370     if (MVT::isInteger(VT))
3371       NewVT = MVT::v2i64;
3372     else
3373       NewVT = MVT::v2f64;
3374   unsigned Scale = NumElems / NewWidth;
3375   SmallVector<SDOperand, 8> MaskVec;
3376   for (unsigned i = 0; i < NumElems; i += Scale) {
3377     unsigned StartIdx = ~0U;
3378     for (unsigned j = 0; j < Scale; ++j) {
3379       SDOperand Elt = PermMask.getOperand(i+j);
3380       if (Elt.getOpcode() == ISD::UNDEF)
3381         continue;
3382       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3383       if (StartIdx == ~0U)
3384         StartIdx = EltIdx - (EltIdx % Scale);
3385       if (EltIdx != StartIdx + j)
3386         return SDOperand();
3387     }
3388     if (StartIdx == ~0U)
3389       MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3390     else
3391       MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3392   }
3393
3394   V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3395   V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3396   return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3397                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3398                                  &MaskVec[0], MaskVec.size()));
3399 }
3400
3401 SDOperand
3402 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3403   SDOperand V1 = Op.getOperand(0);
3404   SDOperand V2 = Op.getOperand(1);
3405   SDOperand PermMask = Op.getOperand(2);
3406   MVT::ValueType VT = Op.getValueType();
3407   unsigned NumElems = PermMask.getNumOperands();
3408   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3409   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3410   bool V1IsSplat = false;
3411   bool V2IsSplat = false;
3412
3413   if (isUndefShuffle(Op.Val))
3414     return DAG.getNode(ISD::UNDEF, VT);
3415
3416   if (isZeroShuffle(Op.Val))
3417     return getZeroVector(VT, DAG);
3418
3419   if (isIdentityMask(PermMask.Val))
3420     return V1;
3421   else if (isIdentityMask(PermMask.Val, true))
3422     return V2;
3423
3424   if (isSplatMask(PermMask.Val)) {
3425     if (NumElems <= 4) return Op;
3426     // Promote it to a v4i32 splat.
3427     return PromoteSplat(Op, DAG);
3428   }
3429
3430   // If the shuffle can be profitably rewritten as a narrower shuffle, then
3431   // do it!
3432   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3433     SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3434     if (NewOp.Val)
3435       return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3436   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3437     // FIXME: Figure out a cleaner way to do this.
3438     // Try to make use of movq to zero out the top part.
3439     if (ISD::isBuildVectorAllZeros(V2.Val)) {
3440       SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3441       if (NewOp.Val) {
3442         SDOperand NewV1 = NewOp.getOperand(0);
3443         SDOperand NewV2 = NewOp.getOperand(1);
3444         SDOperand NewMask = NewOp.getOperand(2);
3445         if (isCommutedMOVL(NewMask.Val, true, false)) {
3446           NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3447           NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3448                               NewV1, NewV2, getMOVLMask(2, DAG));
3449           return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3450         }
3451       }
3452     } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3453       SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3454       if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3455         return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3456     }
3457   }
3458
3459   if (X86::isMOVLMask(PermMask.Val))
3460     return (V1IsUndef) ? V2 : Op;
3461
3462   if (X86::isMOVSHDUPMask(PermMask.Val) ||
3463       X86::isMOVSLDUPMask(PermMask.Val) ||
3464       X86::isMOVHLPSMask(PermMask.Val) ||
3465       X86::isMOVHPMask(PermMask.Val) ||
3466       X86::isMOVLPMask(PermMask.Val))
3467     return Op;
3468
3469   if (ShouldXformToMOVHLPS(PermMask.Val) ||
3470       ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3471     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3472
3473   bool Commuted = false;
3474   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3475   // 1,1,1,1 -> v8i16 though.
3476   V1IsSplat = isSplatVector(V1.Val);
3477   V2IsSplat = isSplatVector(V2.Val);
3478   
3479   // Canonicalize the splat or undef, if present, to be on the RHS.
3480   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3481     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3482     std::swap(V1IsSplat, V2IsSplat);
3483     std::swap(V1IsUndef, V2IsUndef);
3484     Commuted = true;
3485   }
3486
3487   // FIXME: Figure out a cleaner way to do this.
3488   if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3489     if (V2IsUndef) return V1;
3490     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3491     if (V2IsSplat) {
3492       // V2 is a splat, so the mask may be malformed. That is, it may point
3493       // to any V2 element. The instruction selectior won't like this. Get
3494       // a corrected mask and commute to form a proper MOVS{S|D}.
3495       SDOperand NewMask = getMOVLMask(NumElems, DAG);
3496       if (NewMask.Val != PermMask.Val)
3497         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3498     }
3499     return Op;
3500   }
3501
3502   if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3503       X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3504       X86::isUNPCKLMask(PermMask.Val) ||
3505       X86::isUNPCKHMask(PermMask.Val))
3506     return Op;
3507
3508   if (V2IsSplat) {
3509     // Normalize mask so all entries that point to V2 points to its first
3510     // element then try to match unpck{h|l} again. If match, return a
3511     // new vector_shuffle with the corrected mask.
3512     SDOperand NewMask = NormalizeMask(PermMask, DAG);
3513     if (NewMask.Val != PermMask.Val) {
3514       if (X86::isUNPCKLMask(PermMask.Val, true)) {
3515         SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3516         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3517       } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3518         SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3519         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3520       }
3521     }
3522   }
3523
3524   // Normalize the node to match x86 shuffle ops if needed
3525   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3526       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3527
3528   if (Commuted) {
3529     // Commute is back and try unpck* again.
3530     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3531     if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3532         X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3533         X86::isUNPCKLMask(PermMask.Val) ||
3534         X86::isUNPCKHMask(PermMask.Val))
3535       return Op;
3536   }
3537
3538   // If VT is integer, try PSHUF* first, then SHUFP*.
3539   if (MVT::isInteger(VT)) {
3540     // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3541     // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3542     if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3543          X86::isPSHUFDMask(PermMask.Val)) ||
3544         X86::isPSHUFHWMask(PermMask.Val) ||
3545         X86::isPSHUFLWMask(PermMask.Val)) {
3546       if (V2.getOpcode() != ISD::UNDEF)
3547         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3548                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3549       return Op;
3550     }
3551
3552     if (X86::isSHUFPMask(PermMask.Val) &&
3553         MVT::getSizeInBits(VT) != 64)    // Don't do this for MMX.
3554       return Op;
3555   } else {
3556     // Floating point cases in the other order.
3557     if (X86::isSHUFPMask(PermMask.Val))
3558       return Op;
3559     if (X86::isPSHUFDMask(PermMask.Val) ||
3560         X86::isPSHUFHWMask(PermMask.Val) ||
3561         X86::isPSHUFLWMask(PermMask.Val)) {
3562       if (V2.getOpcode() != ISD::UNDEF)
3563         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3564                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3565       return Op;
3566     }
3567   }
3568
3569   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3570   if (VT == MVT::v8i16) {
3571     SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3572     if (NewOp.Val)
3573       return NewOp;
3574   }
3575
3576   // Handle all 4 wide cases with a number of shuffles.
3577   if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3578     // Don't do this for MMX.
3579     MVT::ValueType MaskVT = PermMask.getValueType();
3580     MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3581     SmallVector<std::pair<int, int>, 8> Locs;
3582     Locs.reserve(NumElems);
3583     SmallVector<SDOperand, 8> Mask1(NumElems,
3584                                     DAG.getNode(ISD::UNDEF, MaskEVT));
3585     SmallVector<SDOperand, 8> Mask2(NumElems,
3586                                     DAG.getNode(ISD::UNDEF, MaskEVT));
3587     unsigned NumHi = 0;
3588     unsigned NumLo = 0;
3589     // If no more than two elements come from either vector. This can be
3590     // implemented with two shuffles. First shuffle gather the elements.
3591     // The second shuffle, which takes the first shuffle as both of its
3592     // vector operands, put the elements into the right order.
3593     for (unsigned i = 0; i != NumElems; ++i) {
3594       SDOperand Elt = PermMask.getOperand(i);
3595       if (Elt.getOpcode() == ISD::UNDEF) {
3596         Locs[i] = std::make_pair(-1, -1);
3597       } else {
3598         unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3599         if (Val < NumElems) {
3600           Locs[i] = std::make_pair(0, NumLo);
3601           Mask1[NumLo] = Elt;
3602           NumLo++;
3603         } else {
3604           Locs[i] = std::make_pair(1, NumHi);
3605           if (2+NumHi < NumElems)
3606             Mask1[2+NumHi] = Elt;
3607           NumHi++;
3608         }
3609       }
3610     }
3611     if (NumLo <= 2 && NumHi <= 2) {
3612       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3613                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3614                                    &Mask1[0], Mask1.size()));
3615       for (unsigned i = 0; i != NumElems; ++i) {
3616         if (Locs[i].first == -1)
3617           continue;
3618         else {
3619           unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3620           Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3621           Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3622         }
3623       }
3624
3625       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3626                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3627                                      &Mask2[0], Mask2.size()));
3628     }
3629
3630     // Break it into (shuffle shuffle_hi, shuffle_lo).
3631     Locs.clear();
3632     SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3633     SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3634     SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3635     unsigned MaskIdx = 0;
3636     unsigned LoIdx = 0;
3637     unsigned HiIdx = NumElems/2;
3638     for (unsigned i = 0; i != NumElems; ++i) {
3639       if (i == NumElems/2) {
3640         MaskPtr = &HiMask;
3641         MaskIdx = 1;
3642         LoIdx = 0;
3643         HiIdx = NumElems/2;
3644       }
3645       SDOperand Elt = PermMask.getOperand(i);
3646       if (Elt.getOpcode() == ISD::UNDEF) {
3647         Locs[i] = std::make_pair(-1, -1);
3648       } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3649         Locs[i] = std::make_pair(MaskIdx, LoIdx);
3650         (*MaskPtr)[LoIdx] = Elt;
3651         LoIdx++;
3652       } else {
3653         Locs[i] = std::make_pair(MaskIdx, HiIdx);
3654         (*MaskPtr)[HiIdx] = Elt;
3655         HiIdx++;
3656       }
3657     }
3658
3659     SDOperand LoShuffle =
3660       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3661                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3662                               &LoMask[0], LoMask.size()));
3663     SDOperand HiShuffle =
3664       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3665                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3666                               &HiMask[0], HiMask.size()));
3667     SmallVector<SDOperand, 8> MaskOps;
3668     for (unsigned i = 0; i != NumElems; ++i) {
3669       if (Locs[i].first == -1) {
3670         MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3671       } else {
3672         unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3673         MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3674       }
3675     }
3676     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3677                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3678                                    &MaskOps[0], MaskOps.size()));
3679   }
3680
3681   return SDOperand();
3682 }
3683
3684 SDOperand
3685 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3686                                                 SelectionDAG &DAG) {
3687   MVT::ValueType VT = Op.getValueType();
3688   if (MVT::getSizeInBits(VT) == 8) {
3689     SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3690                                     Op.getOperand(0), Op.getOperand(1));
3691     SDOperand Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3692                                     DAG.getValueType(VT));
3693     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3694   } else if (MVT::getSizeInBits(VT) == 16) {
3695     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3696                                     Op.getOperand(0), Op.getOperand(1));
3697     SDOperand Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3698                                     DAG.getValueType(VT));
3699     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3700   }
3701   return SDOperand();
3702 }
3703
3704
3705 SDOperand
3706 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3707   if (!isa<ConstantSDNode>(Op.getOperand(1)))
3708     return SDOperand();
3709
3710   if (Subtarget->hasSSE41())
3711     return LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3712
3713   MVT::ValueType VT = Op.getValueType();
3714   // TODO: handle v16i8.
3715   if (MVT::getSizeInBits(VT) == 16) {
3716     SDOperand Vec = Op.getOperand(0);
3717     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3718     if (Idx == 0)
3719       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3720                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3721                                  DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3722                                      Op.getOperand(1)));
3723     // Transform it so it match pextrw which produces a 32-bit result.
3724     MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3725     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3726                                     Op.getOperand(0), Op.getOperand(1));
3727     SDOperand Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
3728                                     DAG.getValueType(VT));
3729     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3730   } else if (MVT::getSizeInBits(VT) == 32) {
3731     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3732     if (Idx == 0)
3733       return Op;
3734     // SHUFPS the element to the lowest double word, then movss.
3735     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3736     SmallVector<SDOperand, 8> IdxVec;
3737     IdxVec.
3738       push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3739     IdxVec.
3740       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3741     IdxVec.
3742       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3743     IdxVec.
3744       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3745     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3746                                  &IdxVec[0], IdxVec.size());
3747     SDOperand Vec = Op.getOperand(0);
3748     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3749                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3750     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3751                        DAG.getIntPtrConstant(0));
3752   } else if (MVT::getSizeInBits(VT) == 64) {
3753     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3754     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3755     //        to match extract_elt for f64.
3756     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3757     if (Idx == 0)
3758       return Op;
3759
3760     // UNPCKHPD the element to the lowest double word, then movsd.
3761     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3762     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3763     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3764     SmallVector<SDOperand, 8> IdxVec;
3765     IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3766     IdxVec.
3767       push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3768     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3769                                  &IdxVec[0], IdxVec.size());
3770     SDOperand Vec = Op.getOperand(0);
3771     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3772                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3773     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3774                        DAG.getIntPtrConstant(0));
3775   }
3776
3777   return SDOperand();
3778 }
3779
3780 SDOperand
3781 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3782   MVT::ValueType VT = Op.getValueType();
3783   MVT::ValueType EVT = MVT::getVectorElementType(VT);
3784
3785   SDOperand N0 = Op.getOperand(0);
3786   SDOperand N1 = Op.getOperand(1);
3787   SDOperand N2 = Op.getOperand(2);
3788
3789   if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3790     unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3791                                                   : X86ISD::PINSRW;
3792     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3793     // argument.
3794     if (N1.getValueType() != MVT::i32)
3795       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3796     if (N2.getValueType() != MVT::i32)
3797       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3798     return DAG.getNode(Opc, VT, N0, N1, N2);
3799   } else if (EVT == MVT::f32) {
3800     // Bits [7:6] of the constant are the source select.  This will always be
3801     //  zero here.  The DAG Combiner may combine an extract_elt index into these
3802     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
3803     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
3804     // Bits [5:4] of the constant are the destination select.  This is the 
3805     //  value of the incoming immediate.
3806     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may 
3807     //   combine either bitwise AND or insert of float 0.0 to set these bits.
3808     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3809     return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3810   }
3811   return SDOperand();
3812 }
3813
3814 SDOperand
3815 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3816   MVT::ValueType VT = Op.getValueType();
3817   MVT::ValueType EVT = MVT::getVectorElementType(VT);
3818
3819   if (Subtarget->hasSSE41())
3820     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3821
3822   if (EVT == MVT::i8)
3823     return SDOperand();
3824
3825   SDOperand N0 = Op.getOperand(0);
3826   SDOperand N1 = Op.getOperand(1);
3827   SDOperand N2 = Op.getOperand(2);
3828
3829   if (MVT::getSizeInBits(EVT) == 16) {
3830     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3831     // as its second argument.
3832     if (N1.getValueType() != MVT::i32)
3833       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3834     if (N2.getValueType() != MVT::i32)
3835       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3836     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3837   }
3838   return SDOperand();
3839 }
3840
3841 SDOperand
3842 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3843   SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3844   return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3845 }
3846
3847 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3848 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3849 // one of the above mentioned nodes. It has to be wrapped because otherwise
3850 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3851 // be used to form addressing mode. These wrapped nodes will be selected
3852 // into MOV32ri.
3853 SDOperand
3854 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3855   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3856   SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3857                                                getPointerTy(),
3858                                                CP->getAlignment());
3859   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3860   // With PIC, the address is actually $g + Offset.
3861   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3862       !Subtarget->isPICStyleRIPRel()) {
3863     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3864                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3865                          Result);
3866   }
3867
3868   return Result;
3869 }
3870
3871 SDOperand
3872 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3873   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3874   SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3875   // If it's a debug information descriptor, don't mess with it.
3876   if (DAG.isVerifiedDebugInfoDesc(Op))
3877     return Result;
3878   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3879   // With PIC, the address is actually $g + Offset.
3880   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3881       !Subtarget->isPICStyleRIPRel()) {
3882     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3883                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3884                          Result);
3885   }
3886   
3887   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3888   // load the value at address GV, not the value of GV itself. This means that
3889   // the GlobalAddress must be in the base or index register of the address, not
3890   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3891   // The same applies for external symbols during PIC codegen
3892   if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3893     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
3894                          PseudoSourceValue::getGOT(), 0);
3895
3896   return Result;
3897 }
3898
3899 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3900 static SDOperand
3901 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3902                               const MVT::ValueType PtrVT) {
3903   SDOperand InFlag;
3904   SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3905                                      DAG.getNode(X86ISD::GlobalBaseReg,
3906                                                  PtrVT), InFlag);
3907   InFlag = Chain.getValue(1);
3908
3909   // emit leal symbol@TLSGD(,%ebx,1), %eax
3910   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3911   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3912                                              GA->getValueType(0),
3913                                              GA->getOffset());
3914   SDOperand Ops[] = { Chain,  TGA, InFlag };
3915   SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3916   InFlag = Result.getValue(2);
3917   Chain = Result.getValue(1);
3918
3919   // call ___tls_get_addr. This function receives its argument in
3920   // the register EAX.
3921   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3922   InFlag = Chain.getValue(1);
3923
3924   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3925   SDOperand Ops1[] = { Chain,
3926                       DAG.getTargetExternalSymbol("___tls_get_addr",
3927                                                   PtrVT),
3928                       DAG.getRegister(X86::EAX, PtrVT),
3929                       DAG.getRegister(X86::EBX, PtrVT),
3930                       InFlag };
3931   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3932   InFlag = Chain.getValue(1);
3933
3934   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3935 }
3936
3937 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3938 // "local exec" model.
3939 static SDOperand
3940 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3941                          const MVT::ValueType PtrVT) {
3942   // Get the Thread Pointer
3943   SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3944   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3945   // exec)
3946   SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3947                                              GA->getValueType(0),
3948                                              GA->getOffset());
3949   SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3950
3951   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3952     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
3953                          PseudoSourceValue::getGOT(), 0);
3954
3955   // The address of the thread local variable is the add of the thread
3956   // pointer with the offset of the variable.
3957   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3958 }
3959
3960 SDOperand
3961 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3962   // TODO: implement the "local dynamic" model
3963   // TODO: implement the "initial exec"model for pic executables
3964   assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3965          "TLS not implemented for non-ELF and 64-bit targets");
3966   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3967   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3968   // otherwise use the "Local Exec"TLS Model
3969   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3970     return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3971   else
3972     return LowerToTLSExecModel(GA, DAG, getPointerTy());
3973 }
3974
3975 SDOperand
3976 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3977   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3978   SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3979   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3980   // With PIC, the address is actually $g + Offset.
3981   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3982       !Subtarget->isPICStyleRIPRel()) {
3983     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3984                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3985                          Result);
3986   }
3987
3988   return Result;
3989 }
3990
3991 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3992   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3993   SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3994   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3995   // With PIC, the address is actually $g + Offset.
3996   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3997       !Subtarget->isPICStyleRIPRel()) {
3998     Result = DAG.getNode(ISD::ADD, getPointerTy(),
3999                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4000                          Result);
4001   }
4002
4003   return Result;
4004 }
4005
4006 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4007 /// take a 2 x i32 value to shift plus a shift amount. 
4008 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4009   assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4010          "Not an i64 shift!");
4011   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4012   SDOperand ShOpLo = Op.getOperand(0);
4013   SDOperand ShOpHi = Op.getOperand(1);
4014   SDOperand ShAmt  = Op.getOperand(2);
4015   SDOperand Tmp1 = isSRA ?
4016     DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4017     DAG.getConstant(0, MVT::i32);
4018
4019   SDOperand Tmp2, Tmp3;
4020   if (Op.getOpcode() == ISD::SHL_PARTS) {
4021     Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4022     Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4023   } else {
4024     Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4025     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4026   }
4027
4028   const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4029   SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4030                                   DAG.getConstant(32, MVT::i8));
4031   SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4032                                AndNode, DAG.getConstant(0, MVT::i8));
4033
4034   SDOperand Hi, Lo;
4035   SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4036   VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4037   SmallVector<SDOperand, 4> Ops;
4038   if (Op.getOpcode() == ISD::SHL_PARTS) {
4039     Ops.push_back(Tmp2);
4040     Ops.push_back(Tmp3);
4041     Ops.push_back(CC);
4042     Ops.push_back(Cond);
4043     Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4044
4045     Ops.clear();
4046     Ops.push_back(Tmp3);
4047     Ops.push_back(Tmp1);
4048     Ops.push_back(CC);
4049     Ops.push_back(Cond);
4050     Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4051   } else {
4052     Ops.push_back(Tmp2);
4053     Ops.push_back(Tmp3);
4054     Ops.push_back(CC);
4055     Ops.push_back(Cond);
4056     Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4057
4058     Ops.clear();
4059     Ops.push_back(Tmp3);
4060     Ops.push_back(Tmp1);
4061     Ops.push_back(CC);
4062     Ops.push_back(Cond);
4063     Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4064   }
4065
4066   VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4067   Ops.clear();
4068   Ops.push_back(Lo);
4069   Ops.push_back(Hi);
4070   return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4071 }
4072
4073 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4074   assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4075          Op.getOperand(0).getValueType() >= MVT::i16 &&
4076          "Unknown SINT_TO_FP to lower!");
4077
4078   SDOperand Result;
4079   MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4080   unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4081   MachineFunction &MF = DAG.getMachineFunction();
4082   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4083   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4084   SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4085                                  StackSlot,
4086                                  PseudoSourceValue::getFixedStack(),
4087                                  SSFI);
4088
4089   // These are really Legal; caller falls through into that case.
4090   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4091     return Result;
4092   if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 && 
4093       Subtarget->is64Bit())
4094     return Result;
4095
4096   // Build the FILD
4097   SDVTList Tys;
4098   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4099   if (useSSE)
4100     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4101   else
4102     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4103   SmallVector<SDOperand, 8> Ops;
4104   Ops.push_back(Chain);
4105   Ops.push_back(StackSlot);
4106   Ops.push_back(DAG.getValueType(SrcVT));
4107   Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4108                        Tys, &Ops[0], Ops.size());
4109
4110   if (useSSE) {
4111     Chain = Result.getValue(1);
4112     SDOperand InFlag = Result.getValue(2);
4113
4114     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4115     // shouldn't be necessary except that RFP cannot be live across
4116     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4117     MachineFunction &MF = DAG.getMachineFunction();
4118     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4119     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4120     Tys = DAG.getVTList(MVT::Other);
4121     SmallVector<SDOperand, 8> Ops;
4122     Ops.push_back(Chain);
4123     Ops.push_back(Result);
4124     Ops.push_back(StackSlot);
4125     Ops.push_back(DAG.getValueType(Op.getValueType()));
4126     Ops.push_back(InFlag);
4127     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4128     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4129                          PseudoSourceValue::getFixedStack(), SSFI);
4130   }
4131
4132   return Result;
4133 }
4134
4135 std::pair<SDOperand,SDOperand> X86TargetLowering::
4136 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4137   assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4138          "Unknown FP_TO_SINT to lower!");
4139
4140   // These are really Legal.
4141   if (Op.getValueType() == MVT::i32 && 
4142       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4143     return std::make_pair(SDOperand(), SDOperand());
4144   if (Subtarget->is64Bit() &&
4145       Op.getValueType() == MVT::i64 &&
4146       Op.getOperand(0).getValueType() != MVT::f80)
4147     return std::make_pair(SDOperand(), SDOperand());
4148
4149   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4150   // stack slot.
4151   MachineFunction &MF = DAG.getMachineFunction();
4152   unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4153   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4154   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4155   unsigned Opc;
4156   switch (Op.getValueType()) {
4157   default: assert(0 && "Invalid FP_TO_SINT to lower!");
4158   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4159   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4160   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4161   }
4162
4163   SDOperand Chain = DAG.getEntryNode();
4164   SDOperand Value = Op.getOperand(0);
4165   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4166     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4167     Chain = DAG.getStore(Chain, Value, StackSlot,
4168                          PseudoSourceValue::getFixedStack(), SSFI);
4169     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4170     SDOperand Ops[] = {
4171       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4172     };
4173     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4174     Chain = Value.getValue(1);
4175     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4176     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4177   }
4178
4179   // Build the FP_TO_INT*_IN_MEM
4180   SDOperand Ops[] = { Chain, Value, StackSlot };
4181   SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4182
4183   return std::make_pair(FIST, StackSlot);
4184 }
4185
4186 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4187   std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4188   SDOperand FIST = Vals.first, StackSlot = Vals.second;
4189   if (FIST.Val == 0) return SDOperand();
4190   
4191   // Load the result.
4192   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4193 }
4194
4195 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4196   std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4197   SDOperand FIST = Vals.first, StackSlot = Vals.second;
4198   if (FIST.Val == 0) return 0;
4199   
4200   // Return an i64 load from the stack slot.
4201   SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4202
4203   // Use a MERGE_VALUES node to drop the chain result value.
4204   return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4205 }  
4206
4207 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4208   MVT::ValueType VT = Op.getValueType();
4209   MVT::ValueType EltVT = VT;
4210   if (MVT::isVector(VT))
4211     EltVT = MVT::getVectorElementType(VT);
4212   const Type *OpNTy =  MVT::getTypeForValueType(EltVT);
4213   std::vector<Constant*> CV;
4214   if (EltVT == MVT::f64) {
4215     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4216     CV.push_back(C);
4217     CV.push_back(C);
4218   } else {
4219     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4220     CV.push_back(C);
4221     CV.push_back(C);
4222     CV.push_back(C);
4223     CV.push_back(C);
4224   }
4225   Constant *C = ConstantVector::get(CV);
4226   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4227   SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4228                                PseudoSourceValue::getConstantPool(), 0,
4229                                false, 16);
4230   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4231 }
4232
4233 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4234   MVT::ValueType VT = Op.getValueType();
4235   MVT::ValueType EltVT = VT;
4236   unsigned EltNum = 1;
4237   if (MVT::isVector(VT)) {
4238     EltVT = MVT::getVectorElementType(VT);
4239     EltNum = MVT::getVectorNumElements(VT);
4240   }
4241   const Type *OpNTy =  MVT::getTypeForValueType(EltVT);
4242   std::vector<Constant*> CV;
4243   if (EltVT == MVT::f64) {
4244     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4245     CV.push_back(C);
4246     CV.push_back(C);
4247   } else {
4248     Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4249     CV.push_back(C);
4250     CV.push_back(C);
4251     CV.push_back(C);
4252     CV.push_back(C);
4253   }
4254   Constant *C = ConstantVector::get(CV);
4255   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4256   SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4257                                PseudoSourceValue::getConstantPool(), 0,
4258                                false, 16);
4259   if (MVT::isVector(VT)) {
4260     return DAG.getNode(ISD::BIT_CONVERT, VT,
4261                        DAG.getNode(ISD::XOR, MVT::v2i64,
4262                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4263                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4264   } else {
4265     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4266   }
4267 }
4268
4269 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4270   SDOperand Op0 = Op.getOperand(0);
4271   SDOperand Op1 = Op.getOperand(1);
4272   MVT::ValueType VT = Op.getValueType();
4273   MVT::ValueType SrcVT = Op1.getValueType();
4274   const Type *SrcTy =  MVT::getTypeForValueType(SrcVT);
4275
4276   // If second operand is smaller, extend it first.
4277   if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4278     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4279     SrcVT = VT;
4280     SrcTy = MVT::getTypeForValueType(SrcVT);
4281   }
4282   // And if it is bigger, shrink it first.
4283   if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4284     Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4285     SrcVT = VT;
4286     SrcTy = MVT::getTypeForValueType(SrcVT);
4287   }
4288
4289   // At this point the operands and the result should have the same
4290   // type, and that won't be f80 since that is not custom lowered.
4291
4292   // First get the sign bit of second operand.
4293   std::vector<Constant*> CV;
4294   if (SrcVT == MVT::f64) {
4295     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4296     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4297   } else {
4298     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4299     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4300     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4301     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4302   }
4303   Constant *C = ConstantVector::get(CV);
4304   SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4305   SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4306                                 PseudoSourceValue::getConstantPool(), 0,
4307                                 false, 16);
4308   SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4309
4310   // Shift sign bit right or left if the two operands have different types.
4311   if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4312     // Op0 is MVT::f32, Op1 is MVT::f64.
4313     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4314     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4315                           DAG.getConstant(32, MVT::i32));
4316     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4317     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4318                           DAG.getIntPtrConstant(0));
4319   }
4320
4321   // Clear first operand sign bit.
4322   CV.clear();
4323   if (VT == MVT::f64) {
4324     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4325     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4326   } else {
4327     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4328     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4329     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4330     CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4331   }
4332   C = ConstantVector::get(CV);
4333   CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4334   SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4335                                 PseudoSourceValue::getConstantPool(), 0,
4336                                 false, 16);
4337   SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4338
4339   // Or the value with the sign bit.
4340   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4341 }
4342
4343 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4344   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4345   SDOperand Cond;
4346   SDOperand Op0 = Op.getOperand(0);
4347   SDOperand Op1 = Op.getOperand(1);
4348   SDOperand CC = Op.getOperand(2);
4349   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4350   bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4351   unsigned X86CC;
4352
4353   if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4354                      Op0, Op1, DAG)) {
4355     Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4356     return DAG.getNode(X86ISD::SETCC, MVT::i8,
4357                        DAG.getConstant(X86CC, MVT::i8), Cond);
4358   }
4359
4360   assert(isFP && "Illegal integer SetCC!");
4361
4362   Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4363   switch (SetCCOpcode) {
4364   default: assert(false && "Illegal floating point SetCC!");
4365   case ISD::SETOEQ: {  // !PF & ZF
4366     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4367                                  DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4368     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4369                                  DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4370     return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4371   }
4372   case ISD::SETUNE: {  // PF | !ZF
4373     SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4374                                  DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4375     SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4376                                  DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4377     return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4378   }
4379   }
4380 }
4381
4382
4383 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4384   bool addTest = true;
4385   SDOperand Cond  = Op.getOperand(0);
4386   SDOperand CC;
4387
4388   if (Cond.getOpcode() == ISD::SETCC)
4389     Cond = LowerSETCC(Cond, DAG);
4390
4391   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4392   // setting operand in place of the X86ISD::SETCC.
4393   if (Cond.getOpcode() == X86ISD::SETCC) {
4394     CC = Cond.getOperand(0);
4395
4396     SDOperand Cmp = Cond.getOperand(1);
4397     unsigned Opc = Cmp.getOpcode();
4398     MVT::ValueType VT = Op.getValueType();
4399     
4400     bool IllegalFPCMov = false;
4401     if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4402         !isScalarFPTypeInSSEReg(VT))  // FPStack?
4403       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4404     
4405     if ((Opc == X86ISD::CMP ||
4406          Opc == X86ISD::COMI ||
4407          Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4408       Cond = Cmp;
4409       addTest = false;
4410     }
4411   }
4412
4413   if (addTest) {
4414     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4415     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4416   }
4417
4418   const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4419                                                     MVT::Flag);
4420   SmallVector<SDOperand, 4> Ops;
4421   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4422   // condition is true.
4423   Ops.push_back(Op.getOperand(2));
4424   Ops.push_back(Op.getOperand(1));
4425   Ops.push_back(CC);
4426   Ops.push_back(Cond);
4427   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4428 }
4429
4430 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4431   bool addTest = true;
4432   SDOperand Chain = Op.getOperand(0);
4433   SDOperand Cond  = Op.getOperand(1);
4434   SDOperand Dest  = Op.getOperand(2);
4435   SDOperand CC;
4436
4437   if (Cond.getOpcode() == ISD::SETCC)
4438     Cond = LowerSETCC(Cond, DAG);
4439
4440   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4441   // setting operand in place of the X86ISD::SETCC.
4442   if (Cond.getOpcode() == X86ISD::SETCC) {
4443     CC = Cond.getOperand(0);
4444
4445     SDOperand Cmp = Cond.getOperand(1);
4446     unsigned Opc = Cmp.getOpcode();
4447     if (Opc == X86ISD::CMP ||
4448         Opc == X86ISD::COMI ||
4449         Opc == X86ISD::UCOMI) {
4450       Cond = Cmp;
4451       addTest = false;
4452     }
4453   }
4454
4455   if (addTest) {
4456     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4457     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4458   }
4459   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4460                      Chain, Op.getOperand(2), CC, Cond);
4461 }
4462
4463
4464 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4465 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4466 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4467 // that the guard pages used by the OS virtual memory manager are allocated in
4468 // correct sequence.
4469 SDOperand
4470 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4471                                            SelectionDAG &DAG) {
4472   assert(Subtarget->isTargetCygMing() &&
4473          "This should be used only on Cygwin/Mingw targets");
4474   
4475   // Get the inputs.
4476   SDOperand Chain = Op.getOperand(0);
4477   SDOperand Size  = Op.getOperand(1);
4478   // FIXME: Ensure alignment here
4479
4480   SDOperand Flag;
4481   
4482   MVT::ValueType IntPtr = getPointerTy();
4483   MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4484
4485   Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4486   Flag = Chain.getValue(1);
4487
4488   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4489   SDOperand Ops[] = { Chain,
4490                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
4491                       DAG.getRegister(X86::EAX, IntPtr),
4492                       Flag };
4493   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4494   Flag = Chain.getValue(1);
4495
4496   Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4497   
4498   std::vector<MVT::ValueType> Tys;
4499   Tys.push_back(SPTy);
4500   Tys.push_back(MVT::Other);
4501   SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4502   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4503 }
4504
4505 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4506   SDOperand InFlag(0, 0);
4507   SDOperand Chain = Op.getOperand(0);
4508   unsigned Align =
4509     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4510   if (Align == 0) Align = 1;
4511
4512   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4513   // If not DWORD aligned or size is more than the threshold, call memset.
4514   // The libc version is likely to be faster for these cases. It can use the
4515   // address value and run time information about the CPU.
4516   if ((Align & 3) != 0 ||
4517       (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4518     MVT::ValueType IntPtr = getPointerTy();
4519     const Type *IntPtrTy = getTargetData()->getIntPtrType();
4520     TargetLowering::ArgListTy Args; 
4521     TargetLowering::ArgListEntry Entry;
4522     Entry.Node = Op.getOperand(1);
4523     Entry.Ty = IntPtrTy;
4524     Args.push_back(Entry);
4525     // Extend the unsigned i8 argument to be an int value for the call.
4526     Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4527     Entry.Ty = IntPtrTy;
4528     Args.push_back(Entry);
4529     Entry.Node = Op.getOperand(3);
4530     Args.push_back(Entry);
4531     std::pair<SDOperand,SDOperand> CallResult =
4532       LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4533                   DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4534     return CallResult.second;
4535   }
4536
4537   MVT::ValueType AVT;
4538   SDOperand Count;
4539   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4540   unsigned BytesLeft = 0;
4541   bool TwoRepStos = false;
4542   if (ValC) {
4543     unsigned ValReg;
4544     uint64_t Val = ValC->getValue() & 255;
4545
4546     // If the value is a constant, then we can potentially use larger sets.
4547     switch (Align & 3) {
4548       case 2:   // WORD aligned
4549         AVT = MVT::i16;
4550         ValReg = X86::AX;
4551         Val = (Val << 8) | Val;
4552         break;
4553       case 0:  // DWORD aligned
4554         AVT = MVT::i32;
4555         ValReg = X86::EAX;
4556         Val = (Val << 8)  | Val;
4557         Val = (Val << 16) | Val;
4558         if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) {  // QWORD aligned
4559           AVT = MVT::i64;
4560           ValReg = X86::RAX;
4561           Val = (Val << 32) | Val;
4562         }
4563         break;
4564       default:  // Byte aligned
4565         AVT = MVT::i8;
4566         ValReg = X86::AL;
4567         Count = Op.getOperand(3);
4568         break;
4569     }
4570
4571     if (AVT > MVT::i8) {
4572       if (I) {
4573         unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4574         Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4575         BytesLeft = I->getValue() % UBytes;
4576       } else {
4577         assert(AVT >= MVT::i32 &&
4578                "Do not use rep;stos if not at least DWORD aligned");
4579         Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4580                             Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4581         TwoRepStos = true;
4582       }
4583     }
4584
4585     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4586                               InFlag);
4587     InFlag = Chain.getValue(1);
4588   } else {
4589     AVT = MVT::i8;
4590     Count  = Op.getOperand(3);
4591     Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4592     InFlag = Chain.getValue(1);
4593   }
4594
4595   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4596                             Count, InFlag);
4597   InFlag = Chain.getValue(1);
4598   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4599                             Op.getOperand(1), InFlag);
4600   InFlag = Chain.getValue(1);
4601
4602   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4603   SmallVector<SDOperand, 8> Ops;
4604   Ops.push_back(Chain);
4605   Ops.push_back(DAG.getValueType(AVT));
4606   Ops.push_back(InFlag);
4607   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4608
4609   if (TwoRepStos) {
4610     InFlag = Chain.getValue(1);
4611     Count = Op.getOperand(3);
4612     MVT::ValueType CVT = Count.getValueType();
4613     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4614                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4615     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4616                               Left, InFlag);
4617     InFlag = Chain.getValue(1);
4618     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4619     Ops.clear();
4620     Ops.push_back(Chain);
4621     Ops.push_back(DAG.getValueType(MVT::i8));
4622     Ops.push_back(InFlag);
4623     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4624   } else if (BytesLeft) {
4625     // Issue stores for the last 1 - 7 bytes.
4626     SDOperand Value;
4627     unsigned Val = ValC->getValue() & 255;
4628     unsigned Offset = I->getValue() - BytesLeft;
4629     SDOperand DstAddr = Op.getOperand(1);
4630     MVT::ValueType AddrVT = DstAddr.getValueType();
4631     if (BytesLeft >= 4) {
4632       Val = (Val << 8)  | Val;
4633       Val = (Val << 16) | Val;
4634       Value = DAG.getConstant(Val, MVT::i32);
4635       Chain = DAG.getStore(Chain, Value,
4636                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4637                                        DAG.getConstant(Offset, AddrVT)),
4638                            NULL, 0);
4639       BytesLeft -= 4;
4640       Offset += 4;
4641     }
4642     if (BytesLeft >= 2) {
4643       Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4644       Chain = DAG.getStore(Chain, Value,
4645                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4646                                        DAG.getConstant(Offset, AddrVT)),
4647                            NULL, 0);
4648       BytesLeft -= 2;
4649       Offset += 2;
4650     }
4651     if (BytesLeft == 1) {
4652       Value = DAG.getConstant(Val, MVT::i8);
4653       Chain = DAG.getStore(Chain, Value,
4654                            DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4655                                        DAG.getConstant(Offset, AddrVT)),
4656                            NULL, 0);
4657     }
4658   }
4659
4660   return Chain;
4661 }
4662
4663 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4664                                                SDOperand Dest,
4665                                                SDOperand Source,
4666                                                unsigned Size,
4667                                                unsigned Align,
4668                                                SelectionDAG &DAG) {
4669   MVT::ValueType AVT;
4670   unsigned BytesLeft = 0;
4671   switch (Align & 3) {
4672     case 2:   // WORD aligned
4673       AVT = MVT::i16;
4674       break;
4675     case 0:  // DWORD aligned
4676       AVT = MVT::i32;
4677       if (Subtarget->is64Bit() && ((Align & 0xF) == 0))  // QWORD aligned
4678         AVT = MVT::i64;
4679       break;
4680     default:  // Byte aligned
4681       AVT = MVT::i8;
4682       break;
4683   }
4684
4685   unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4686   SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4687   BytesLeft = Size % UBytes;
4688
4689   SDOperand InFlag(0, 0);
4690   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4691                             Count, InFlag);
4692   InFlag = Chain.getValue(1);
4693   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4694                             Dest, InFlag);
4695   InFlag = Chain.getValue(1);
4696   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4697                             Source, InFlag);
4698   InFlag = Chain.getValue(1);
4699
4700   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4701   SmallVector<SDOperand, 8> Ops;
4702   Ops.push_back(Chain);
4703   Ops.push_back(DAG.getValueType(AVT));
4704   Ops.push_back(InFlag);
4705   Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4706
4707   if (BytesLeft) {
4708     // Issue loads and stores for the last 1 - 7 bytes.
4709     unsigned Offset = Size - BytesLeft;
4710     SDOperand DstAddr = Dest;
4711     MVT::ValueType DstVT = DstAddr.getValueType();
4712     SDOperand SrcAddr = Source;
4713     MVT::ValueType SrcVT = SrcAddr.getValueType();
4714     SDOperand Value;
4715     if (BytesLeft >= 4) {
4716       Value = DAG.getLoad(MVT::i32, Chain,
4717                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4718                                       DAG.getConstant(Offset, SrcVT)),
4719                           NULL, 0);
4720       Chain = Value.getValue(1);
4721       Chain = DAG.getStore(Chain, Value,
4722                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
4723                                        DAG.getConstant(Offset, DstVT)),
4724                            NULL, 0);
4725       BytesLeft -= 4;
4726       Offset += 4;
4727     }
4728     if (BytesLeft >= 2) {
4729       Value = DAG.getLoad(MVT::i16, Chain,
4730                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4731                                       DAG.getConstant(Offset, SrcVT)),
4732                           NULL, 0);
4733       Chain = Value.getValue(1);
4734       Chain = DAG.getStore(Chain, Value,
4735                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
4736                                        DAG.getConstant(Offset, DstVT)),
4737                            NULL, 0);
4738       BytesLeft -= 2;
4739       Offset += 2;
4740     }
4741
4742     if (BytesLeft == 1) {
4743       Value = DAG.getLoad(MVT::i8, Chain,
4744                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4745                                       DAG.getConstant(Offset, SrcVT)),
4746                           NULL, 0);
4747       Chain = Value.getValue(1);
4748       Chain = DAG.getStore(Chain, Value,
4749                            DAG.getNode(ISD::ADD, DstVT, DstAddr,
4750                                        DAG.getConstant(Offset, DstVT)),
4751                            NULL, 0);
4752     }
4753   }
4754
4755   return Chain;
4756 }
4757
4758 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4759 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4760   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4761   SDOperand TheChain = N->getOperand(0);
4762   SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4763   if (Subtarget->is64Bit()) {
4764     SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4765     SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4766                                        MVT::i64, rax.getValue(2));
4767     SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4768                                 DAG.getConstant(32, MVT::i8));
4769     SDOperand Ops[] = {
4770       DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4771     };
4772     
4773     Tys = DAG.getVTList(MVT::i64, MVT::Other);
4774     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4775   }
4776   
4777   SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4778   SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4779                                        MVT::i32, eax.getValue(2));
4780   // Use a buildpair to merge the two 32-bit values into a 64-bit one. 
4781   SDOperand Ops[] = { eax, edx };
4782   Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4783
4784   // Use a MERGE_VALUES to return the value and chain.
4785   Ops[1] = edx.getValue(1);
4786   Tys = DAG.getVTList(MVT::i64, MVT::Other);
4787   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4788 }
4789
4790 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4791   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4792
4793   if (!Subtarget->is64Bit()) {
4794     // vastart just stores the address of the VarArgsFrameIndex slot into the
4795     // memory location argument.
4796     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4797     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4798   }
4799
4800   // __va_list_tag:
4801   //   gp_offset         (0 - 6 * 8)
4802   //   fp_offset         (48 - 48 + 8 * 16)
4803   //   overflow_arg_area (point to parameters coming in memory).
4804   //   reg_save_area
4805   SmallVector<SDOperand, 8> MemOps;
4806   SDOperand FIN = Op.getOperand(1);
4807   // Store gp_offset
4808   SDOperand Store = DAG.getStore(Op.getOperand(0),
4809                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
4810                                  FIN, SV, 0);
4811   MemOps.push_back(Store);
4812
4813   // Store fp_offset
4814   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4815   Store = DAG.getStore(Op.getOperand(0),
4816                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
4817                        FIN, SV, 0);
4818   MemOps.push_back(Store);
4819
4820   // Store ptr to overflow_arg_area
4821   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4822   SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4823   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4824   MemOps.push_back(Store);
4825
4826   // Store ptr to reg_save_area.
4827   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4828   SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4829   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4830   MemOps.push_back(Store);
4831   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4832 }
4833
4834 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4835   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4836   SDOperand Chain = Op.getOperand(0);
4837   SDOperand DstPtr = Op.getOperand(1);
4838   SDOperand SrcPtr = Op.getOperand(2);
4839   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4840   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4841
4842   SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4843   Chain = SrcPtr.getValue(1);
4844   for (unsigned i = 0; i < 3; ++i) {
4845     SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4846     Chain = Val.getValue(1);
4847     Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4848     if (i == 2)
4849       break;
4850     SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr, 
4851                          DAG.getIntPtrConstant(8));
4852     DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr, 
4853                          DAG.getIntPtrConstant(8));
4854   }
4855   return Chain;
4856 }
4857
4858 SDOperand
4859 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4860   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4861   switch (IntNo) {
4862   default: return SDOperand();    // Don't custom lower most intrinsics.
4863     // Comparison intrinsics.
4864   case Intrinsic::x86_sse_comieq_ss:
4865   case Intrinsic::x86_sse_comilt_ss:
4866   case Intrinsic::x86_sse_comile_ss:
4867   case Intrinsic::x86_sse_comigt_ss:
4868   case Intrinsic::x86_sse_comige_ss:
4869   case Intrinsic::x86_sse_comineq_ss:
4870   case Intrinsic::x86_sse_ucomieq_ss:
4871   case Intrinsic::x86_sse_ucomilt_ss:
4872   case Intrinsic::x86_sse_ucomile_ss:
4873   case Intrinsic::x86_sse_ucomigt_ss:
4874   case Intrinsic::x86_sse_ucomige_ss:
4875   case Intrinsic::x86_sse_ucomineq_ss:
4876   case Intrinsic::x86_sse2_comieq_sd:
4877   case Intrinsic::x86_sse2_comilt_sd:
4878   case Intrinsic::x86_sse2_comile_sd:
4879   case Intrinsic::x86_sse2_comigt_sd:
4880   case Intrinsic::x86_sse2_comige_sd:
4881   case Intrinsic::x86_sse2_comineq_sd:
4882   case Intrinsic::x86_sse2_ucomieq_sd:
4883   case Intrinsic::x86_sse2_ucomilt_sd:
4884   case Intrinsic::x86_sse2_ucomile_sd:
4885   case Intrinsic::x86_sse2_ucomigt_sd:
4886   case Intrinsic::x86_sse2_ucomige_sd:
4887   case Intrinsic::x86_sse2_ucomineq_sd: {
4888     unsigned Opc = 0;
4889     ISD::CondCode CC = ISD::SETCC_INVALID;
4890     switch (IntNo) {
4891     default: break;
4892     case Intrinsic::x86_sse_comieq_ss:
4893     case Intrinsic::x86_sse2_comieq_sd:
4894       Opc = X86ISD::COMI;
4895       CC = ISD::SETEQ;
4896       break;
4897     case Intrinsic::x86_sse_comilt_ss:
4898     case Intrinsic::x86_sse2_comilt_sd:
4899       Opc = X86ISD::COMI;
4900       CC = ISD::SETLT;
4901       break;
4902     case Intrinsic::x86_sse_comile_ss:
4903     case Intrinsic::x86_sse2_comile_sd:
4904       Opc = X86ISD::COMI;
4905       CC = ISD::SETLE;
4906       break;
4907     case Intrinsic::x86_sse_comigt_ss:
4908     case Intrinsic::x86_sse2_comigt_sd:
4909       Opc = X86ISD::COMI;
4910       CC = ISD::SETGT;
4911       break;
4912     case Intrinsic::x86_sse_comige_ss:
4913     case Intrinsic::x86_sse2_comige_sd:
4914       Opc = X86ISD::COMI;
4915       CC = ISD::SETGE;
4916       break;
4917     case Intrinsic::x86_sse_comineq_ss:
4918     case Intrinsic::x86_sse2_comineq_sd:
4919       Opc = X86ISD::COMI;
4920       CC = ISD::SETNE;
4921       break;
4922     case Intrinsic::x86_sse_ucomieq_ss:
4923     case Intrinsic::x86_sse2_ucomieq_sd:
4924       Opc = X86ISD::UCOMI;
4925       CC = ISD::SETEQ;
4926       break;
4927     case Intrinsic::x86_sse_ucomilt_ss:
4928     case Intrinsic::x86_sse2_ucomilt_sd:
4929       Opc = X86ISD::UCOMI;
4930       CC = ISD::SETLT;
4931       break;
4932     case Intrinsic::x86_sse_ucomile_ss:
4933     case Intrinsic::x86_sse2_ucomile_sd:
4934       Opc = X86ISD::UCOMI;
4935       CC = ISD::SETLE;
4936       break;
4937     case Intrinsic::x86_sse_ucomigt_ss:
4938     case Intrinsic::x86_sse2_ucomigt_sd:
4939       Opc = X86ISD::UCOMI;
4940       CC = ISD::SETGT;
4941       break;
4942     case Intrinsic::x86_sse_ucomige_ss:
4943     case Intrinsic::x86_sse2_ucomige_sd:
4944       Opc = X86ISD::UCOMI;
4945       CC = ISD::SETGE;
4946       break;
4947     case Intrinsic::x86_sse_ucomineq_ss:
4948     case Intrinsic::x86_sse2_ucomineq_sd:
4949       Opc = X86ISD::UCOMI;
4950       CC = ISD::SETNE;
4951       break;
4952     }
4953
4954     unsigned X86CC;
4955     SDOperand LHS = Op.getOperand(1);
4956     SDOperand RHS = Op.getOperand(2);
4957     translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4958
4959     SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4960     SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4961                                   DAG.getConstant(X86CC, MVT::i8), Cond);
4962     return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4963   }
4964   }
4965 }
4966
4967 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4968   // Depths > 0 not supported yet!
4969   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4970     return SDOperand();
4971   
4972   // Just load the return address
4973   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4974   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4975 }
4976
4977 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4978   // Depths > 0 not supported yet!
4979   if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4980     return SDOperand();
4981     
4982   SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4983   return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI, 
4984                      DAG.getIntPtrConstant(4));
4985 }
4986
4987 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4988                                                        SelectionDAG &DAG) {
4989   // Is not yet supported on x86-64
4990   if (Subtarget->is64Bit())
4991     return SDOperand();
4992   
4993   return DAG.getIntPtrConstant(8);
4994 }
4995
4996 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4997 {
4998   assert(!Subtarget->is64Bit() &&
4999          "Lowering of eh_return builtin is not supported yet on x86-64");
5000     
5001   MachineFunction &MF = DAG.getMachineFunction();
5002   SDOperand Chain     = Op.getOperand(0);
5003   SDOperand Offset    = Op.getOperand(1);
5004   SDOperand Handler   = Op.getOperand(2);
5005
5006   SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5007                                     getPointerTy());
5008
5009   SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5010                                     DAG.getIntPtrConstant(-4UL));
5011   StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5012   Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5013   Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5014   MF.getRegInfo().addLiveOut(X86::ECX);
5015
5016   return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5017                      Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5018 }
5019
5020 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5021                                              SelectionDAG &DAG) {
5022   SDOperand Root = Op.getOperand(0);
5023   SDOperand Trmp = Op.getOperand(1); // trampoline
5024   SDOperand FPtr = Op.getOperand(2); // nested function
5025   SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5026
5027   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5028
5029   const X86InstrInfo *TII =
5030     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5031
5032   if (Subtarget->is64Bit()) {
5033     SDOperand OutChains[6];
5034
5035     // Large code-model.
5036
5037     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
5038     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5039
5040     const unsigned char N86R10 =
5041       ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5042     const unsigned char N86R11 =
5043       ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5044
5045     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5046
5047     // Load the pointer to the nested function into R11.
5048     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5049     SDOperand Addr = Trmp;
5050     OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5051                                 TrmpAddr, 0);
5052
5053     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5054     OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5055
5056     // Load the 'nest' parameter value into R10.
5057     // R10 is specified in X86CallingConv.td
5058     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5059     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5060     OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5061                                 TrmpAddr, 10);
5062
5063     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5064     OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5065
5066     // Jump to the nested function.
5067     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5068     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5069     OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5070                                 TrmpAddr, 20);
5071
5072     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5073     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5074     OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5075                                 TrmpAddr, 22);
5076
5077     SDOperand Ops[] =
5078       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5079     return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5080   } else {
5081     const Function *Func =
5082       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5083     unsigned CC = Func->getCallingConv();
5084     unsigned NestReg;
5085
5086     switch (CC) {
5087     default:
5088       assert(0 && "Unsupported calling convention");
5089     case CallingConv::C:
5090     case CallingConv::X86_StdCall: {
5091       // Pass 'nest' parameter in ECX.
5092       // Must be kept in sync with X86CallingConv.td
5093       NestReg = X86::ECX;
5094
5095       // Check that ECX wasn't needed by an 'inreg' parameter.
5096       const FunctionType *FTy = Func->getFunctionType();
5097       const ParamAttrsList *Attrs = Func->getParamAttrs();
5098
5099       if (Attrs && !Func->isVarArg()) {
5100         unsigned InRegCount = 0;
5101         unsigned Idx = 1;
5102
5103         for (FunctionType::param_iterator I = FTy->param_begin(),
5104              E = FTy->param_end(); I != E; ++I, ++Idx)
5105           if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5106             // FIXME: should only count parameters that are lowered to integers.
5107             InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5108
5109         if (InRegCount > 2) {
5110           cerr << "Nest register in use - reduce number of inreg parameters!\n";
5111           abort();
5112         }
5113       }
5114       break;
5115     }
5116     case CallingConv::X86_FastCall:
5117       // Pass 'nest' parameter in EAX.
5118       // Must be kept in sync with X86CallingConv.td
5119       NestReg = X86::EAX;
5120       break;
5121     }
5122
5123     SDOperand OutChains[4];
5124     SDOperand Addr, Disp;
5125
5126     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5127     Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5128
5129     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5130     const unsigned char N86Reg =
5131       ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5132     OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5133                                 Trmp, TrmpAddr, 0);
5134
5135     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5136     OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5137
5138     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5139     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5140     OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5141                                 TrmpAddr, 5, false, 1);
5142
5143     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5144     OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5145
5146     SDOperand Ops[] =
5147       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5148     return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5149   }
5150 }
5151
5152 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5153   /*
5154    The rounding mode is in bits 11:10 of FPSR, and has the following
5155    settings:
5156      00 Round to nearest
5157      01 Round to -inf
5158      10 Round to +inf
5159      11 Round to 0
5160
5161   FLT_ROUNDS, on the other hand, expects the following:
5162     -1 Undefined
5163      0 Round to 0
5164      1 Round to nearest
5165      2 Round to +inf
5166      3 Round to -inf
5167
5168   To perform the conversion, we do:
5169     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5170   */
5171
5172   MachineFunction &MF = DAG.getMachineFunction();
5173   const TargetMachine &TM = MF.getTarget();
5174   const TargetFrameInfo &TFI = *TM.getFrameInfo();
5175   unsigned StackAlignment = TFI.getStackAlignment();
5176   MVT::ValueType VT = Op.getValueType();
5177
5178   // Save FP Control Word to stack slot
5179   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5180   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5181
5182   SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5183                                 DAG.getEntryNode(), StackSlot);
5184
5185   // Load FP Control Word from stack slot
5186   SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5187
5188   // Transform as necessary
5189   SDOperand CWD1 =
5190     DAG.getNode(ISD::SRL, MVT::i16,
5191                 DAG.getNode(ISD::AND, MVT::i16,
5192                             CWD, DAG.getConstant(0x800, MVT::i16)),
5193                 DAG.getConstant(11, MVT::i8));
5194   SDOperand CWD2 =
5195     DAG.getNode(ISD::SRL, MVT::i16,
5196                 DAG.getNode(ISD::AND, MVT::i16,
5197                             CWD, DAG.getConstant(0x400, MVT::i16)),
5198                 DAG.getConstant(9, MVT::i8));
5199
5200   SDOperand RetVal =
5201     DAG.getNode(ISD::AND, MVT::i16,
5202                 DAG.getNode(ISD::ADD, MVT::i16,
5203                             DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5204                             DAG.getConstant(1, MVT::i16)),
5205                 DAG.getConstant(3, MVT::i16));
5206
5207
5208   return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5209                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5210 }
5211
5212 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5213   MVT::ValueType VT = Op.getValueType();
5214   MVT::ValueType OpVT = VT;
5215   unsigned NumBits = MVT::getSizeInBits(VT);
5216
5217   Op = Op.getOperand(0);
5218   if (VT == MVT::i8) {
5219     // Zero extend to i32 since there is not an i8 bsr.
5220     OpVT = MVT::i32;
5221     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5222   }
5223
5224   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5225   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5226   Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5227
5228   // If src is zero (i.e. bsr sets ZF), returns NumBits.
5229   SmallVector<SDOperand, 4> Ops;
5230   Ops.push_back(Op);
5231   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5232   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5233   Ops.push_back(Op.getValue(1));
5234   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5235
5236   // Finally xor with NumBits-1.
5237   Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5238
5239   if (VT == MVT::i8)
5240     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5241   return Op;
5242 }
5243
5244 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5245   MVT::ValueType VT = Op.getValueType();
5246   MVT::ValueType OpVT = VT;
5247   unsigned NumBits = MVT::getSizeInBits(VT);
5248
5249   Op = Op.getOperand(0);
5250   if (VT == MVT::i8) {
5251     OpVT = MVT::i32;
5252     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5253   }
5254
5255   // Issue a bsf (scan bits forward) which also sets EFLAGS.
5256   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5257   Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5258
5259   // If src is zero (i.e. bsf sets ZF), returns NumBits.
5260   SmallVector<SDOperand, 4> Ops;
5261   Ops.push_back(Op);
5262   Ops.push_back(DAG.getConstant(NumBits, OpVT));
5263   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5264   Ops.push_back(Op.getValue(1));
5265   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5266
5267   if (VT == MVT::i8)
5268     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5269   return Op;
5270 }
5271
5272 /// LowerOperation - Provide custom lowering hooks for some operations.
5273 ///
5274 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5275   switch (Op.getOpcode()) {
5276   default: assert(0 && "Should not custom lower this!");
5277   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5278   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5279   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5280   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
5281   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5282   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5283   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5284   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5285   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
5286   case ISD::SHL_PARTS:
5287   case ISD::SRA_PARTS:
5288   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
5289   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5290   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
5291   case ISD::FABS:               return LowerFABS(Op, DAG);
5292   case ISD::FNEG:               return LowerFNEG(Op, DAG);
5293   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
5294   case ISD::SETCC:              return LowerSETCC(Op, DAG);
5295   case ISD::SELECT:             return LowerSELECT(Op, DAG);
5296   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
5297   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5298   case ISD::CALL:               return LowerCALL(Op, DAG);
5299   case ISD::RET:                return LowerRET(Op, DAG);
5300   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
5301   case ISD::MEMSET:             return LowerMEMSET(Op, DAG);
5302   case ISD::MEMCPY:             return LowerMEMCPY(Op, DAG);
5303   case ISD::VASTART:            return LowerVASTART(Op, DAG);
5304   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
5305   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5306   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
5307   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
5308   case ISD::FRAME_TO_ARGS_OFFSET:
5309                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5310   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5311   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
5312   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
5313   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
5314   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
5315   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
5316       
5317   // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5318   case ISD::READCYCLECOUNTER:
5319     return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5320   }
5321 }
5322
5323 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5324 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5325   switch (N->getOpcode()) {
5326   default: assert(0 && "Should not custom lower this!");
5327   case ISD::FP_TO_SINT:         return ExpandFP_TO_SINT(N, DAG);
5328   case ISD::READCYCLECOUNTER:   return ExpandREADCYCLECOUNTER(N, DAG);
5329   }
5330 }
5331
5332 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5333   switch (Opcode) {
5334   default: return NULL;
5335   case X86ISD::BSF:                return "X86ISD::BSF";
5336   case X86ISD::BSR:                return "X86ISD::BSR";
5337   case X86ISD::SHLD:               return "X86ISD::SHLD";
5338   case X86ISD::SHRD:               return "X86ISD::SHRD";
5339   case X86ISD::FAND:               return "X86ISD::FAND";
5340   case X86ISD::FOR:                return "X86ISD::FOR";
5341   case X86ISD::FXOR:               return "X86ISD::FXOR";
5342   case X86ISD::FSRL:               return "X86ISD::FSRL";
5343   case X86ISD::FILD:               return "X86ISD::FILD";
5344   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
5345   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5346   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5347   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5348   case X86ISD::FLD:                return "X86ISD::FLD";
5349   case X86ISD::FST:                return "X86ISD::FST";
5350   case X86ISD::FP_GET_RESULT:      return "X86ISD::FP_GET_RESULT";
5351   case X86ISD::FP_GET_RESULT2:     return "X86ISD::FP_GET_RESULT2";
5352   case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
5353   case X86ISD::CALL:               return "X86ISD::CALL";
5354   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
5355   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
5356   case X86ISD::CMP:                return "X86ISD::CMP";
5357   case X86ISD::COMI:               return "X86ISD::COMI";
5358   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
5359   case X86ISD::SETCC:              return "X86ISD::SETCC";
5360   case X86ISD::CMOV:               return "X86ISD::CMOV";
5361   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
5362   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
5363   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
5364   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
5365   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
5366   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
5367   case X86ISD::S2VEC:              return "X86ISD::S2VEC";
5368   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
5369   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
5370   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
5371   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
5372   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
5373   case X86ISD::FMAX:               return "X86ISD::FMAX";
5374   case X86ISD::FMIN:               return "X86ISD::FMIN";
5375   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
5376   case X86ISD::FRCP:               return "X86ISD::FRCP";
5377   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
5378   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
5379   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
5380   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
5381   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
5382   }
5383 }
5384
5385 // isLegalAddressingMode - Return true if the addressing mode represented
5386 // by AM is legal for this target, for a load/store of the specified type.
5387 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
5388                                               const Type *Ty) const {
5389   // X86 supports extremely general addressing modes.
5390   
5391   // X86 allows a sign-extended 32-bit immediate field as a displacement.
5392   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5393     return false;
5394   
5395   if (AM.BaseGV) {
5396     // We can only fold this if we don't need an extra load.
5397     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5398       return false;
5399
5400     // X86-64 only supports addr of globals in small code model.
5401     if (Subtarget->is64Bit()) {
5402       if (getTargetMachine().getCodeModel() != CodeModel::Small)
5403         return false;
5404       // If lower 4G is not available, then we must use rip-relative addressing.
5405       if (AM.BaseOffs || AM.Scale > 1)
5406         return false;
5407     }
5408   }
5409   
5410   switch (AM.Scale) {
5411   case 0:
5412   case 1:
5413   case 2:
5414   case 4:
5415   case 8:
5416     // These scales always work.
5417     break;
5418   case 3:
5419   case 5:
5420   case 9:
5421     // These scales are formed with basereg+scalereg.  Only accept if there is
5422     // no basereg yet.
5423     if (AM.HasBaseReg)
5424       return false;
5425     break;
5426   default:  // Other stuff never works.
5427     return false;
5428   }
5429   
5430   return true;
5431 }
5432
5433
5434 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5435   if (!Ty1->isInteger() || !Ty2->isInteger())
5436     return false;
5437   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5438   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5439   if (NumBits1 <= NumBits2)
5440     return false;
5441   return Subtarget->is64Bit() || NumBits1 < 64;
5442 }
5443
5444 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5445                                        MVT::ValueType VT2) const {
5446   if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5447     return false;
5448   unsigned NumBits1 = MVT::getSizeInBits(VT1);
5449   unsigned NumBits2 = MVT::getSizeInBits(VT2);
5450   if (NumBits1 <= NumBits2)
5451     return false;
5452   return Subtarget->is64Bit() || NumBits1 < 64;
5453 }
5454
5455 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5456 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5457 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5458 /// are assumed to be legal.
5459 bool
5460 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5461   // Only do shuffles on 128-bit vector types for now.
5462   if (MVT::getSizeInBits(VT) == 64) return false;
5463   return (Mask.Val->getNumOperands() <= 4 ||
5464           isIdentityMask(Mask.Val) ||
5465           isIdentityMask(Mask.Val, true) ||
5466           isSplatMask(Mask.Val)  ||
5467           isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5468           X86::isUNPCKLMask(Mask.Val) ||
5469           X86::isUNPCKHMask(Mask.Val) ||
5470           X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5471           X86::isUNPCKH_v_undef_Mask(Mask.Val));
5472 }
5473
5474 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5475                                                MVT::ValueType EVT,
5476                                                SelectionDAG &DAG) const {
5477   unsigned NumElts = BVOps.size();
5478   // Only do shuffles on 128-bit vector types for now.
5479   if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5480   if (NumElts == 2) return true;
5481   if (NumElts == 4) {
5482     return (isMOVLMask(&BVOps[0], 4)  ||
5483             isCommutedMOVL(&BVOps[0], 4, true) ||
5484             isSHUFPMask(&BVOps[0], 4) || 
5485             isCommutedSHUFP(&BVOps[0], 4));
5486   }
5487   return false;
5488 }
5489
5490 //===----------------------------------------------------------------------===//
5491 //                           X86 Scheduler Hooks
5492 //===----------------------------------------------------------------------===//
5493
5494 MachineBasicBlock *
5495 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5496                                                MachineBasicBlock *BB) {
5497   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5498   switch (MI->getOpcode()) {
5499   default: assert(false && "Unexpected instr type to insert");
5500   case X86::CMOV_FR32:
5501   case X86::CMOV_FR64:
5502   case X86::CMOV_V4F32:
5503   case X86::CMOV_V2F64:
5504   case X86::CMOV_V2I64: {
5505     // To "insert" a SELECT_CC instruction, we actually have to insert the
5506     // diamond control-flow pattern.  The incoming instruction knows the
5507     // destination vreg to set, the condition code register to branch on, the
5508     // true/false values to select between, and a branch opcode to use.
5509     const BasicBlock *LLVM_BB = BB->getBasicBlock();
5510     ilist<MachineBasicBlock>::iterator It = BB;
5511     ++It;
5512
5513     //  thisMBB:
5514     //  ...
5515     //   TrueVal = ...
5516     //   cmpTY ccX, r1, r2
5517     //   bCC copy1MBB
5518     //   fallthrough --> copy0MBB
5519     MachineBasicBlock *thisMBB = BB;
5520     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5521     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5522     unsigned Opc =
5523       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5524     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5525     MachineFunction *F = BB->getParent();
5526     F->getBasicBlockList().insert(It, copy0MBB);
5527     F->getBasicBlockList().insert(It, sinkMBB);
5528     // Update machine-CFG edges by first adding all successors of the current
5529     // block to the new block which will contain the Phi node for the select.
5530     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5531         e = BB->succ_end(); i != e; ++i)
5532       sinkMBB->addSuccessor(*i);
5533     // Next, remove all successors of the current block, and add the true
5534     // and fallthrough blocks as its successors.
5535     while(!BB->succ_empty())
5536       BB->removeSuccessor(BB->succ_begin());
5537     BB->addSuccessor(copy0MBB);
5538     BB->addSuccessor(sinkMBB);
5539
5540     //  copy0MBB:
5541     //   %FalseValue = ...
5542     //   # fallthrough to sinkMBB
5543     BB = copy0MBB;
5544
5545     // Update machine-CFG edges
5546     BB->addSuccessor(sinkMBB);
5547
5548     //  sinkMBB:
5549     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5550     //  ...
5551     BB = sinkMBB;
5552     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5553       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5554       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5555
5556     delete MI;   // The pseudo instruction is gone now.
5557     return BB;
5558   }
5559
5560   case X86::FP32_TO_INT16_IN_MEM:
5561   case X86::FP32_TO_INT32_IN_MEM:
5562   case X86::FP32_TO_INT64_IN_MEM:
5563   case X86::FP64_TO_INT16_IN_MEM:
5564   case X86::FP64_TO_INT32_IN_MEM:
5565   case X86::FP64_TO_INT64_IN_MEM:
5566   case X86::FP80_TO_INT16_IN_MEM:
5567   case X86::FP80_TO_INT32_IN_MEM:
5568   case X86::FP80_TO_INT64_IN_MEM: {
5569     // Change the floating point control register to use "round towards zero"
5570     // mode when truncating to an integer value.
5571     MachineFunction *F = BB->getParent();
5572     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5573     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5574
5575     // Load the old value of the high byte of the control word...
5576     unsigned OldCW =
5577       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5578     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5579
5580     // Set the high part to be round to zero...
5581     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5582       .addImm(0xC7F);
5583
5584     // Reload the modified control word now...
5585     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5586
5587     // Restore the memory image of control word to original value
5588     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5589       .addReg(OldCW);
5590
5591     // Get the X86 opcode to use.
5592     unsigned Opc;
5593     switch (MI->getOpcode()) {
5594     default: assert(0 && "illegal opcode!");
5595     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5596     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5597     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5598     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5599     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5600     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5601     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5602     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5603     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5604     }
5605
5606     X86AddressMode AM;
5607     MachineOperand &Op = MI->getOperand(0);
5608     if (Op.isRegister()) {
5609       AM.BaseType = X86AddressMode::RegBase;
5610       AM.Base.Reg = Op.getReg();
5611     } else {
5612       AM.BaseType = X86AddressMode::FrameIndexBase;
5613       AM.Base.FrameIndex = Op.getIndex();
5614     }
5615     Op = MI->getOperand(1);
5616     if (Op.isImmediate())
5617       AM.Scale = Op.getImm();
5618     Op = MI->getOperand(2);
5619     if (Op.isImmediate())
5620       AM.IndexReg = Op.getImm();
5621     Op = MI->getOperand(3);
5622     if (Op.isGlobalAddress()) {
5623       AM.GV = Op.getGlobal();
5624     } else {
5625       AM.Disp = Op.getImm();
5626     }
5627     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5628                       .addReg(MI->getOperand(4).getReg());
5629
5630     // Reload the original control word now.
5631     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5632
5633     delete MI;   // The pseudo instruction is gone now.
5634     return BB;
5635   }
5636   }
5637 }
5638
5639 //===----------------------------------------------------------------------===//
5640 //                           X86 Optimization Hooks
5641 //===----------------------------------------------------------------------===//
5642
5643 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5644                                                        uint64_t Mask,
5645                                                        uint64_t &KnownZero,
5646                                                        uint64_t &KnownOne,
5647                                                        const SelectionDAG &DAG,
5648                                                        unsigned Depth) const {
5649   unsigned Opc = Op.getOpcode();
5650   assert((Opc >= ISD::BUILTIN_OP_END ||
5651           Opc == ISD::INTRINSIC_WO_CHAIN ||
5652           Opc == ISD::INTRINSIC_W_CHAIN ||
5653           Opc == ISD::INTRINSIC_VOID) &&
5654          "Should use MaskedValueIsZero if you don't know whether Op"
5655          " is a target node!");
5656
5657   KnownZero = KnownOne = 0;   // Don't know anything.
5658   switch (Opc) {
5659   default: break;
5660   case X86ISD::SETCC:
5661     KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5662     break;
5663   }
5664 }
5665
5666 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5667 /// element of the result of the vector shuffle.
5668 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5669   MVT::ValueType VT = N->getValueType(0);
5670   SDOperand PermMask = N->getOperand(2);
5671   unsigned NumElems = PermMask.getNumOperands();
5672   SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5673   i %= NumElems;
5674   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5675     return (i == 0)
5676      ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5677   } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5678     SDOperand Idx = PermMask.getOperand(i);
5679     if (Idx.getOpcode() == ISD::UNDEF)
5680       return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5681     return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5682   }
5683   return SDOperand();
5684 }
5685
5686 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5687 /// node is a GlobalAddress + an offset.
5688 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5689   unsigned Opc = N->getOpcode();
5690   if (Opc == X86ISD::Wrapper) {
5691     if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5692       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5693       return true;
5694     }
5695   } else if (Opc == ISD::ADD) {
5696     SDOperand N1 = N->getOperand(0);
5697     SDOperand N2 = N->getOperand(1);
5698     if (isGAPlusOffset(N1.Val, GA, Offset)) {
5699       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5700       if (V) {
5701         Offset += V->getSignExtended();
5702         return true;
5703       }
5704     } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5705       ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5706       if (V) {
5707         Offset += V->getSignExtended();
5708         return true;
5709       }
5710     }
5711   }
5712   return false;
5713 }
5714
5715 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5716 /// + Dist * Size.
5717 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5718                               MachineFrameInfo *MFI) {
5719   if (N->getOperand(0).Val != Base->getOperand(0).Val)
5720     return false;
5721
5722   SDOperand Loc = N->getOperand(1);
5723   SDOperand BaseLoc = Base->getOperand(1);
5724   if (Loc.getOpcode() == ISD::FrameIndex) {
5725     if (BaseLoc.getOpcode() != ISD::FrameIndex)
5726       return false;
5727     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
5728     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5729     int FS  = MFI->getObjectSize(FI);
5730     int BFS = MFI->getObjectSize(BFI);
5731     if (FS != BFS || FS != Size) return false;
5732     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5733   } else {
5734     GlobalValue *GV1 = NULL;
5735     GlobalValue *GV2 = NULL;
5736     int64_t Offset1 = 0;
5737     int64_t Offset2 = 0;
5738     bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5739     bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5740     if (isGA1 && isGA2 && GV1 == GV2)
5741       return Offset1 == (Offset2 + Dist*Size);
5742   }
5743
5744   return false;
5745 }
5746
5747 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5748                               const X86Subtarget *Subtarget) {
5749   GlobalValue *GV;
5750   int64_t Offset = 0;
5751   if (isGAPlusOffset(Base, GV, Offset))
5752     return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5753   // DAG combine handles the stack object case.
5754   return false;
5755 }
5756
5757
5758 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5759 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5760 /// if the load addresses are consecutive, non-overlapping, and in the right
5761 /// order.
5762 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5763                                        const X86Subtarget *Subtarget) {
5764   MachineFunction &MF = DAG.getMachineFunction();
5765   MachineFrameInfo *MFI = MF.getFrameInfo();
5766   MVT::ValueType VT = N->getValueType(0);
5767   MVT::ValueType EVT = MVT::getVectorElementType(VT);
5768   SDOperand PermMask = N->getOperand(2);
5769   int NumElems = (int)PermMask.getNumOperands();
5770   SDNode *Base = NULL;
5771   for (int i = 0; i < NumElems; ++i) {
5772     SDOperand Idx = PermMask.getOperand(i);
5773     if (Idx.getOpcode() == ISD::UNDEF) {
5774       if (!Base) return SDOperand();
5775     } else {
5776       SDOperand Arg =
5777         getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5778       if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5779         return SDOperand();
5780       if (!Base)
5781         Base = Arg.Val;
5782       else if (!isConsecutiveLoad(Arg.Val, Base,
5783                                   i, MVT::getSizeInBits(EVT)/8,MFI))
5784         return SDOperand();
5785     }
5786   }
5787
5788   bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5789   LoadSDNode *LD = cast<LoadSDNode>(Base);
5790   if (isAlign16) {
5791     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5792                        LD->getSrcValueOffset(), LD->isVolatile());
5793   } else {
5794     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5795                        LD->getSrcValueOffset(), LD->isVolatile(),
5796                        LD->getAlignment());
5797   }
5798 }
5799
5800 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5801 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5802                                       const X86Subtarget *Subtarget) {
5803   SDOperand Cond = N->getOperand(0);
5804
5805   // If we have SSE[12] support, try to form min/max nodes.
5806   if (Subtarget->hasSSE2() &&
5807       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5808     if (Cond.getOpcode() == ISD::SETCC) {
5809       // Get the LHS/RHS of the select.
5810       SDOperand LHS = N->getOperand(1);
5811       SDOperand RHS = N->getOperand(2);
5812       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5813
5814       unsigned Opcode = 0;
5815       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5816         switch (CC) {
5817         default: break;
5818         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5819         case ISD::SETULE:
5820         case ISD::SETLE:
5821           if (!UnsafeFPMath) break;
5822           // FALL THROUGH.
5823         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
5824         case ISD::SETLT:
5825           Opcode = X86ISD::FMIN;
5826           break;
5827
5828         case ISD::SETOGT: // (X > Y) ? X : Y -> max
5829         case ISD::SETUGT:
5830         case ISD::SETGT:
5831           if (!UnsafeFPMath) break;
5832           // FALL THROUGH.
5833         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
5834         case ISD::SETGE:
5835           Opcode = X86ISD::FMAX;
5836           break;
5837         }
5838       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5839         switch (CC) {
5840         default: break;
5841         case ISD::SETOGT: // (X > Y) ? Y : X -> min
5842         case ISD::SETUGT:
5843         case ISD::SETGT:
5844           if (!UnsafeFPMath) break;
5845           // FALL THROUGH.
5846         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
5847         case ISD::SETGE:
5848           Opcode = X86ISD::FMIN;
5849           break;
5850
5851         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
5852         case ISD::SETULE:
5853         case ISD::SETLE:
5854           if (!UnsafeFPMath) break;
5855           // FALL THROUGH.
5856         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
5857         case ISD::SETLT:
5858           Opcode = X86ISD::FMAX;
5859           break;
5860         }
5861       }
5862
5863       if (Opcode)
5864         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5865     }
5866
5867   }
5868
5869   return SDOperand();
5870 }
5871
5872 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
5873 /// X86ISD::FXOR nodes.
5874 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
5875   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
5876   // F[X]OR(0.0, x) -> x
5877   // F[X]OR(x, 0.0) -> x
5878   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5879     if (C->getValueAPF().isPosZero())
5880       return N->getOperand(1);
5881   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5882     if (C->getValueAPF().isPosZero())
5883       return N->getOperand(0);
5884   return SDOperand();
5885 }
5886
5887 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
5888 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
5889   // FAND(0.0, x) -> 0.0
5890   // FAND(x, 0.0) -> 0.0
5891   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5892     if (C->getValueAPF().isPosZero())
5893       return N->getOperand(0);
5894   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5895     if (C->getValueAPF().isPosZero())
5896       return N->getOperand(1);
5897   return SDOperand();
5898 }
5899
5900
5901 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5902                                                DAGCombinerInfo &DCI) const {
5903   SelectionDAG &DAG = DCI.DAG;
5904   switch (N->getOpcode()) {
5905   default: break;
5906   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
5907   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
5908   case X86ISD::FXOR:
5909   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
5910   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
5911   }
5912
5913   return SDOperand();
5914 }
5915
5916 //===----------------------------------------------------------------------===//
5917 //                           X86 Inline Assembly Support
5918 //===----------------------------------------------------------------------===//
5919
5920 /// getConstraintType - Given a constraint letter, return the type of
5921 /// constraint it is for this target.
5922 X86TargetLowering::ConstraintType
5923 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5924   if (Constraint.size() == 1) {
5925     switch (Constraint[0]) {
5926     case 'A':
5927     case 'r':
5928     case 'R':
5929     case 'l':
5930     case 'q':
5931     case 'Q':
5932     case 'x':
5933     case 'Y':
5934       return C_RegisterClass;
5935     default:
5936       break;
5937     }
5938   }
5939   return TargetLowering::getConstraintType(Constraint);
5940 }
5941
5942 /// LowerXConstraint - try to replace an X constraint, which matches anything,
5943 /// with another that has more specific requirements based on the type of the
5944 /// corresponding operand.
5945 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT, 
5946                                          std::string& s) const {
5947   if (MVT::isFloatingPoint(ConstraintVT)) {
5948     if (Subtarget->hasSSE2())
5949       s = "Y";
5950     else if (Subtarget->hasSSE1())
5951       s = "x";
5952     else
5953       s = "f";
5954   } else
5955     return TargetLowering::lowerXConstraint(ConstraintVT, s);
5956 }
5957
5958 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5959 /// vector.  If it is invalid, don't add anything to Ops.
5960 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5961                                                      char Constraint,
5962                                                      std::vector<SDOperand>&Ops,
5963                                                      SelectionDAG &DAG) {
5964   SDOperand Result(0, 0);
5965   
5966   switch (Constraint) {
5967   default: break;
5968   case 'I':
5969     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5970       if (C->getValue() <= 31) {
5971         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5972         break;
5973       }
5974     }
5975     return;
5976   case 'N':
5977     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5978       if (C->getValue() <= 255) {
5979         Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5980         break;
5981       }
5982     }
5983     return;
5984   case 'i': {
5985     // Literal immediates are always ok.
5986     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5987       Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5988       break;
5989     }
5990
5991     // If we are in non-pic codegen mode, we allow the address of a global (with
5992     // an optional displacement) to be used with 'i'.
5993     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5994     int64_t Offset = 0;
5995     
5996     // Match either (GA) or (GA+C)
5997     if (GA) {
5998       Offset = GA->getOffset();
5999     } else if (Op.getOpcode() == ISD::ADD) {
6000       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6001       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6002       if (C && GA) {
6003         Offset = GA->getOffset()+C->getValue();
6004       } else {
6005         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6006         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6007         if (C && GA)
6008           Offset = GA->getOffset()+C->getValue();
6009         else
6010           C = 0, GA = 0;
6011       }
6012     }
6013     
6014     if (GA) {
6015       // If addressing this global requires a load (e.g. in PIC mode), we can't
6016       // match.
6017       if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6018                                          false))
6019         return;
6020
6021       Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6022                                       Offset);
6023       Result = Op;
6024       break;
6025     }
6026
6027     // Otherwise, not valid for this mode.
6028     return;
6029   }
6030   }
6031   
6032   if (Result.Val) {
6033     Ops.push_back(Result);
6034     return;
6035   }
6036   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6037 }
6038
6039 std::vector<unsigned> X86TargetLowering::
6040 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6041                                   MVT::ValueType VT) const {
6042   if (Constraint.size() == 1) {
6043     // FIXME: not handling fp-stack yet!
6044     switch (Constraint[0]) {      // GCC X86 Constraint Letters
6045     default: break;  // Unknown constraint letter
6046     case 'A':   // EAX/EDX
6047       if (VT == MVT::i32 || VT == MVT::i64)
6048         return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6049       break;
6050     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
6051     case 'Q':   // Q_REGS
6052       if (VT == MVT::i32)
6053         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6054       else if (VT == MVT::i16)
6055         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6056       else if (VT == MVT::i8)
6057         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6058       else if (VT == MVT::i64)
6059         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6060       break;
6061     }
6062   }
6063
6064   return std::vector<unsigned>();
6065 }
6066
6067 std::pair<unsigned, const TargetRegisterClass*>
6068 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6069                                                 MVT::ValueType VT) const {
6070   // First, see if this is a constraint that directly corresponds to an LLVM
6071   // register class.
6072   if (Constraint.size() == 1) {
6073     // GCC Constraint Letters
6074     switch (Constraint[0]) {
6075     default: break;
6076     case 'r':   // GENERAL_REGS
6077     case 'R':   // LEGACY_REGS
6078     case 'l':   // INDEX_REGS
6079       if (VT == MVT::i64 && Subtarget->is64Bit())
6080         return std::make_pair(0U, X86::GR64RegisterClass);
6081       if (VT == MVT::i32)
6082         return std::make_pair(0U, X86::GR32RegisterClass);
6083       else if (VT == MVT::i16)
6084         return std::make_pair(0U, X86::GR16RegisterClass);
6085       else if (VT == MVT::i8)
6086         return std::make_pair(0U, X86::GR8RegisterClass);
6087       break;
6088     case 'y':   // MMX_REGS if MMX allowed.
6089       if (!Subtarget->hasMMX()) break;
6090       return std::make_pair(0U, X86::VR64RegisterClass);
6091       break;
6092     case 'Y':   // SSE_REGS if SSE2 allowed
6093       if (!Subtarget->hasSSE2()) break;
6094       // FALL THROUGH.
6095     case 'x':   // SSE_REGS if SSE1 allowed
6096       if (!Subtarget->hasSSE1()) break;
6097       
6098       switch (VT) {
6099       default: break;
6100       // Scalar SSE types.
6101       case MVT::f32:
6102       case MVT::i32:
6103         return std::make_pair(0U, X86::FR32RegisterClass);
6104       case MVT::f64:
6105       case MVT::i64:
6106         return std::make_pair(0U, X86::FR64RegisterClass);
6107       // Vector types.
6108       case MVT::v16i8:
6109       case MVT::v8i16:
6110       case MVT::v4i32:
6111       case MVT::v2i64:
6112       case MVT::v4f32:
6113       case MVT::v2f64:
6114         return std::make_pair(0U, X86::VR128RegisterClass);
6115       }
6116       break;
6117     }
6118   }
6119   
6120   // Use the default implementation in TargetLowering to convert the register
6121   // constraint into a member of a register class.
6122   std::pair<unsigned, const TargetRegisterClass*> Res;
6123   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6124
6125   // Not found as a standard register?
6126   if (Res.second == 0) {
6127     // GCC calls "st(0)" just plain "st".
6128     if (StringsEqualNoCase("{st}", Constraint)) {
6129       Res.first = X86::ST0;
6130       Res.second = X86::RFP80RegisterClass;
6131     }
6132
6133     return Res;
6134   }
6135
6136   // Otherwise, check to see if this is a register class of the wrong value
6137   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6138   // turn into {ax},{dx}.
6139   if (Res.second->hasType(VT))
6140     return Res;   // Correct type already, nothing to do.
6141
6142   // All of the single-register GCC register classes map their values onto
6143   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
6144   // really want an 8-bit or 32-bit register, map to the appropriate register
6145   // class and return the appropriate register.
6146   if (Res.second != X86::GR16RegisterClass)
6147     return Res;
6148
6149   if (VT == MVT::i8) {
6150     unsigned DestReg = 0;
6151     switch (Res.first) {
6152     default: break;
6153     case X86::AX: DestReg = X86::AL; break;
6154     case X86::DX: DestReg = X86::DL; break;
6155     case X86::CX: DestReg = X86::CL; break;
6156     case X86::BX: DestReg = X86::BL; break;
6157     }
6158     if (DestReg) {
6159       Res.first = DestReg;
6160       Res.second = Res.second = X86::GR8RegisterClass;
6161     }
6162   } else if (VT == MVT::i32) {
6163     unsigned DestReg = 0;
6164     switch (Res.first) {
6165     default: break;
6166     case X86::AX: DestReg = X86::EAX; break;
6167     case X86::DX: DestReg = X86::EDX; break;
6168     case X86::CX: DestReg = X86::ECX; break;
6169     case X86::BX: DestReg = X86::EBX; break;
6170     case X86::SI: DestReg = X86::ESI; break;
6171     case X86::DI: DestReg = X86::EDI; break;
6172     case X86::BP: DestReg = X86::EBP; break;
6173     case X86::SP: DestReg = X86::ESP; break;
6174     }
6175     if (DestReg) {
6176       Res.first = DestReg;
6177       Res.second = Res.second = X86::GR32RegisterClass;
6178     }
6179   } else if (VT == MVT::i64) {
6180     unsigned DestReg = 0;
6181     switch (Res.first) {
6182     default: break;
6183     case X86::AX: DestReg = X86::RAX; break;
6184     case X86::DX: DestReg = X86::RDX; break;
6185     case X86::CX: DestReg = X86::RCX; break;
6186     case X86::BX: DestReg = X86::RBX; break;
6187     case X86::SI: DestReg = X86::RSI; break;
6188     case X86::DI: DestReg = X86::RDI; break;
6189     case X86::BP: DestReg = X86::RBP; break;
6190     case X86::SP: DestReg = X86::RSP; break;
6191     }
6192     if (DestReg) {
6193       Res.first = DestReg;
6194       Res.second = Res.second = X86::GR64RegisterClass;
6195     }
6196   }
6197
6198   return Res;
6199 }