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