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