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