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