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