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