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