X86ISelLowering.cpp revision fbad25e12073e2cbe192b2c4cc4f0bbb26148c9c
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#define DEBUG_TYPE "x86-isel"
16#include "X86.h"
17#include "X86InstrBuilder.h"
18#include "X86ISelLowering.h"
19#include "X86TargetMachine.h"
20#include "X86TargetObjectFile.h"
21#include "Utils/X86ShuffleDecode.h"
22#include "llvm/CallingConv.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/GlobalAlias.h"
26#include "llvm/GlobalVariable.h"
27#include "llvm/Function.h"
28#include "llvm/Instructions.h"
29#include "llvm/Intrinsics.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/CodeGen/IntrinsicLowering.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/PseudoSourceValue.h"
39#include "llvm/MC/MCAsmInfo.h"
40#include "llvm/MC/MCContext.h"
41#include "llvm/MC/MCExpr.h"
42#include "llvm/MC/MCSymbol.h"
43#include "llvm/ADT/BitVector.h"
44#include "llvm/ADT/SmallSet.h"
45#include "llvm/ADT/Statistic.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/ADT/VectorExtras.h"
48#include "llvm/Support/CallSite.h"
49#include "llvm/Support/Debug.h"
50#include "llvm/Support/Dwarf.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Target/TargetOptions.h"
55using namespace llvm;
56using namespace dwarf;
57
58STATISTIC(NumTailCalls, "Number of tail calls");
59
60// Forward declarations.
61static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                       SDValue V2);
63
64static SDValue Insert128BitVector(SDValue Result,
65                                  SDValue Vec,
66                                  SDValue Idx,
67                                  SelectionDAG &DAG,
68                                  DebugLoc dl);
69
70static SDValue Extract128BitVector(SDValue Vec,
71                                   SDValue Idx,
72                                   SelectionDAG &DAG,
73                                   DebugLoc dl);
74
75/// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76/// sets things up to match to an AVX VEXTRACTF128 instruction or a
77/// simple subregister reference.  Idx is an index in the 128 bits we
78/// want.  It need not be aligned to a 128-bit bounday.  That makes
79/// lowering EXTRACT_VECTOR_ELT operations easier.
80static SDValue Extract128BitVector(SDValue Vec,
81                                   SDValue Idx,
82                                   SelectionDAG &DAG,
83                                   DebugLoc dl) {
84  EVT VT = Vec.getValueType();
85  assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86  EVT ElVT = VT.getVectorElementType();
87  int Factor = VT.getSizeInBits()/128;
88  EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                  VT.getVectorNumElements()/Factor);
90
91  // Extract from UNDEF is UNDEF.
92  if (Vec.getOpcode() == ISD::UNDEF)
93    return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94
95  if (isa<ConstantSDNode>(Idx)) {
96    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97
98    // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
99    // we can match to VEXTRACTF128.
100    unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101
102    // This is the index of the first element of the 128-bit chunk
103    // we want.
104    unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
105                                 * ElemsPerChunk);
106
107    SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108    SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                 VecIdx);
110
111    return Result;
112  }
113
114  return SDValue();
115}
116
117/// Generate a DAG to put 128-bits into a vector > 128 bits.  This
118/// sets things up to match to an AVX VINSERTF128 instruction or a
119/// simple superregister reference.  Idx is an index in the 128 bits
120/// we want.  It need not be aligned to a 128-bit bounday.  That makes
121/// lowering INSERT_VECTOR_ELT operations easier.
122static SDValue Insert128BitVector(SDValue Result,
123                                  SDValue Vec,
124                                  SDValue Idx,
125                                  SelectionDAG &DAG,
126                                  DebugLoc dl) {
127  if (isa<ConstantSDNode>(Idx)) {
128    EVT VT = Vec.getValueType();
129    assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130
131    EVT ElVT = VT.getVectorElementType();
132    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133    EVT ResultVT = Result.getValueType();
134
135    // Insert the relevant 128 bits.
136    unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137
138    // This is the index of the first element of the 128-bit chunk
139    // we want.
140    unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
141                                 * ElemsPerChunk);
142
143    SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144    Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
145                         VecIdx);
146    return Result;
147  }
148
149  return SDValue();
150}
151
152static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154  bool is64Bit = Subtarget->is64Bit();
155
156  if (Subtarget->isTargetEnvMacho()) {
157    if (is64Bit)
158      return new X8664_MachoTargetObjectFile();
159    return new TargetLoweringObjectFileMachO();
160  }
161
162  if (Subtarget->isTargetELF())
163    return new TargetLoweringObjectFileELF();
164  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165    return new TargetLoweringObjectFileCOFF();
166  llvm_unreachable("unknown subtarget type");
167}
168
169X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170  : TargetLowering(TM, createTLOF(TM)) {
171  Subtarget = &TM.getSubtarget<X86Subtarget>();
172  X86ScalarSSEf64 = Subtarget->hasXMMInt() || Subtarget->hasAVX();
173  X86ScalarSSEf32 = Subtarget->hasXMM() || Subtarget->hasAVX();
174  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175
176  RegInfo = TM.getRegisterInfo();
177  TD = getTargetData();
178
179  // Set up the TargetLowering object.
180  static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181
182  // X86 is weird, it always uses i8 for shift amounts and setcc results.
183  setBooleanContents(ZeroOrOneBooleanContent);
184  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186
187  // For 64-bit since we have so many registers use the ILP scheduler, for
188  // 32-bit code use the register pressure specific scheduling.
189  if (Subtarget->is64Bit())
190    setSchedulingPreference(Sched::ILP);
191  else
192    setSchedulingPreference(Sched::RegPressure);
193  setStackPointerRegisterToSaveRestore(X86StackPtr);
194
195  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196    // Setup Windows compiler runtime calls.
197    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199    setLibcallName(RTLIB::SREM_I64, "_allrem");
200    setLibcallName(RTLIB::UREM_I64, "_aullrem");
201    setLibcallName(RTLIB::MUL_I64, "_allmul");
202    setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203    setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
211  }
212
213  if (Subtarget->isTargetDarwin()) {
214    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215    setUseUnderscoreSetJmp(false);
216    setUseUnderscoreLongJmp(false);
217  } else if (Subtarget->isTargetMingw()) {
218    // MS runtime is weird: it exports _setjmp, but longjmp!
219    setUseUnderscoreSetJmp(true);
220    setUseUnderscoreLongJmp(false);
221  } else {
222    setUseUnderscoreSetJmp(true);
223    setUseUnderscoreLongJmp(true);
224  }
225
226  // Set up the register classes.
227  addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228  addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229  addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230  if (Subtarget->is64Bit())
231    addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232
233  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234
235  // We don't accept any truncstore of integer registers.
236  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
242
243  // SETOEQ and SETUNE require checking two conditions.
244  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250
251  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252  // operation.
253  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
254  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
255  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
256
257  if (Subtarget->is64Bit()) {
258    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
259    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
260  } else if (!UseSoftFloat) {
261    // We have an algorithm for SSE2->double, and we turn this into a
262    // 64-bit FILD followed by conditional FADD for other targets.
263    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264    // We have an algorithm for SSE2, and we turn this into a 64-bit
265    // FILD for other targets.
266    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
267  }
268
269  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270  // this operation.
271  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
272  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
273
274  if (!UseSoftFloat) {
275    // SSE has no i16 to fp conversion, only i32
276    if (X86ScalarSSEf32) {
277      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278      // f32 and f64 cases are Legal, f80 case is not
279      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280    } else {
281      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
282      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
283    }
284  } else {
285    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
286    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
287  }
288
289  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
290  // are Legal, f80 is custom lowered.
291  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
292  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
293
294  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295  // this operation.
296  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
297  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
298
299  if (X86ScalarSSEf32) {
300    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
301    // f32 and f64 cases are Legal, f80 case is not
302    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303  } else {
304    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
305    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
306  }
307
308  // Handle FP_TO_UINT by promoting the destination to a larger signed
309  // conversion.
310  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
311  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
312  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
313
314  if (Subtarget->is64Bit()) {
315    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
316    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
317  } else if (!UseSoftFloat) {
318    if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
319      // Expand FP_TO_UINT into a select.
320      // FIXME: We would like to use a Custom expander here eventually to do
321      // the optimal thing for SSE vs. the default expansion in the legalizer.
322      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
323    else
324      // With SSE3 we can use fisttpll to convert to a signed i64; without
325      // SSE, we're stuck with a fistpll.
326      setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
327  }
328
329  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330  if (!X86ScalarSSEf64) {
331    setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332    setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333    if (Subtarget->is64Bit()) {
334      setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335      // Without SSE, i64->f64 goes through memory.
336      setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337    }
338  }
339
340  // Scalar integer divide and remainder are lowered to use operations that
341  // produce two results, to match the available instructions. This exposes
342  // the two-result form to trivial CSE, which is able to combine x/y and x%y
343  // into a single instruction.
344  //
345  // Scalar integer multiply-high is also lowered to use two-result
346  // operations, to match the available instructions. However, plain multiply
347  // (low) operations are left as Legal, as there are single-result
348  // instructions for this in x86. Using the two-result multiply instructions
349  // when both high and low results are needed must be arranged by dagcombine.
350  for (unsigned i = 0, e = 4; i != e; ++i) {
351    MVT VT = IntVTs[i];
352    setOperationAction(ISD::MULHS, VT, Expand);
353    setOperationAction(ISD::MULHU, VT, Expand);
354    setOperationAction(ISD::SDIV, VT, Expand);
355    setOperationAction(ISD::UDIV, VT, Expand);
356    setOperationAction(ISD::SREM, VT, Expand);
357    setOperationAction(ISD::UREM, VT, Expand);
358
359    // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360    setOperationAction(ISD::ADDC, VT, Custom);
361    setOperationAction(ISD::ADDE, VT, Custom);
362    setOperationAction(ISD::SUBC, VT, Custom);
363    setOperationAction(ISD::SUBE, VT, Custom);
364  }
365
366  setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367  setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368  setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369  setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370  if (Subtarget->is64Bit())
371    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375  setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376  setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377  setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378  setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379  setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381  setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
382  setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
383  setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
384  setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
385  setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
386  setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
387  if (Subtarget->is64Bit()) {
388    setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
389    setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
390  }
391
392  if (Subtarget->hasPOPCNT()) {
393    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
394  } else {
395    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
396    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
397    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
398    if (Subtarget->is64Bit())
399      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
400  }
401
402  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
403  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
404
405  // These should be promoted to a larger select which is supported.
406  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
407  // X86 wants to expand cmov itself.
408  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
409  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
410  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
411  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
412  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
413  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
414  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
415  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
416  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
417  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
418  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
419  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
420  if (Subtarget->is64Bit()) {
421    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
422    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
423  }
424  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
425
426  // Darwin ABI issue.
427  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
428  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
429  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
430  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
431  if (Subtarget->is64Bit())
432    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
433  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
434  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
435  if (Subtarget->is64Bit()) {
436    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
437    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
438    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
439    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
440    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
441  }
442  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
443  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
444  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
445  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
446  if (Subtarget->is64Bit()) {
447    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
448    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
449    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
450  }
451
452  if (Subtarget->hasXMM())
453    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
454
455  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
456  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458  // On X86 and X86-64, atomic operations are lowered to locked instructions.
459  // Locked instructions, in turn, have implicit fence semantics (all memory
460  // operations are flushed before issuing the locked instruction, and they
461  // are not buffered), so we can fold away the common pattern of
462  // fence-atomic-fence.
463  setShouldFoldAtomicFences(true);
464
465  // Expand certain atomics
466  for (unsigned i = 0, e = 4; i != e; ++i) {
467    MVT VT = IntVTs[i];
468    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
469    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
470    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
471  }
472
473  if (!Subtarget->is64Bit()) {
474    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
475    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
476    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
477    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
478    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
479    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
480    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
481    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
482  }
483
484  if (Subtarget->hasCmpxchg16b()) {
485    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
486  }
487
488  // FIXME - use subtarget debug flags
489  if (!Subtarget->isTargetDarwin() &&
490      !Subtarget->isTargetELF() &&
491      !Subtarget->isTargetCygMing()) {
492    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
493  }
494
495  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
496  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
497  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
498  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
499  if (Subtarget->is64Bit()) {
500    setExceptionPointerRegister(X86::RAX);
501    setExceptionSelectorRegister(X86::RDX);
502  } else {
503    setExceptionPointerRegister(X86::EAX);
504    setExceptionSelectorRegister(X86::EDX);
505  }
506  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
507  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
508
509  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
510  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
511
512  setOperationAction(ISD::TRAP, MVT::Other, Legal);
513
514  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
515  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
516  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
517  if (Subtarget->is64Bit()) {
518    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
519    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
520  } else {
521    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
522    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
523  }
524
525  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
526  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
527
528  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
529    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
530                       MVT::i64 : MVT::i32, Custom);
531  else if (EnableSegmentedStacks)
532    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
533                       MVT::i64 : MVT::i32, Custom);
534  else
535    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
536                       MVT::i64 : MVT::i32, Expand);
537
538  if (!UseSoftFloat && X86ScalarSSEf64) {
539    // f32 and f64 use SSE.
540    // Set up the FP register classes.
541    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
542    addRegisterClass(MVT::f64, X86::FR64RegisterClass);
543
544    // Use ANDPD to simulate FABS.
545    setOperationAction(ISD::FABS , MVT::f64, Custom);
546    setOperationAction(ISD::FABS , MVT::f32, Custom);
547
548    // Use XORP to simulate FNEG.
549    setOperationAction(ISD::FNEG , MVT::f64, Custom);
550    setOperationAction(ISD::FNEG , MVT::f32, Custom);
551
552    // Use ANDPD and ORPD to simulate FCOPYSIGN.
553    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
554    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
555
556    // Lower this to FGETSIGNx86 plus an AND.
557    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
558    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
559
560    // We don't support sin/cos/fmod
561    setOperationAction(ISD::FSIN , MVT::f64, Expand);
562    setOperationAction(ISD::FCOS , MVT::f64, Expand);
563    setOperationAction(ISD::FSIN , MVT::f32, Expand);
564    setOperationAction(ISD::FCOS , MVT::f32, Expand);
565
566    // Expand FP immediates into loads from the stack, except for the special
567    // cases we handle.
568    addLegalFPImmediate(APFloat(+0.0)); // xorpd
569    addLegalFPImmediate(APFloat(+0.0f)); // xorps
570  } else if (!UseSoftFloat && X86ScalarSSEf32) {
571    // Use SSE for f32, x87 for f64.
572    // Set up the FP register classes.
573    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
574    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
575
576    // Use ANDPS to simulate FABS.
577    setOperationAction(ISD::FABS , MVT::f32, Custom);
578
579    // Use XORP to simulate FNEG.
580    setOperationAction(ISD::FNEG , MVT::f32, Custom);
581
582    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
583
584    // Use ANDPS and ORPS to simulate FCOPYSIGN.
585    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
586    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
587
588    // We don't support sin/cos/fmod
589    setOperationAction(ISD::FSIN , MVT::f32, Expand);
590    setOperationAction(ISD::FCOS , MVT::f32, Expand);
591
592    // Special cases we handle for FP constants.
593    addLegalFPImmediate(APFloat(+0.0f)); // xorps
594    addLegalFPImmediate(APFloat(+0.0)); // FLD0
595    addLegalFPImmediate(APFloat(+1.0)); // FLD1
596    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
597    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
598
599    if (!UnsafeFPMath) {
600      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
601      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
602    }
603  } else if (!UseSoftFloat) {
604    // f32 and f64 in x87.
605    // Set up the FP register classes.
606    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
607    addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
608
609    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
610    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
611    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
612    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
613
614    if (!UnsafeFPMath) {
615      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
616      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
617    }
618    addLegalFPImmediate(APFloat(+0.0)); // FLD0
619    addLegalFPImmediate(APFloat(+1.0)); // FLD1
620    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
621    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
622    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
623    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
624    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
625    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
626  }
627
628  // We don't support FMA.
629  setOperationAction(ISD::FMA, MVT::f64, Expand);
630  setOperationAction(ISD::FMA, MVT::f32, Expand);
631
632  // Long double always uses X87.
633  if (!UseSoftFloat) {
634    addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
635    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
636    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
637    {
638      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
639      addLegalFPImmediate(TmpFlt);  // FLD0
640      TmpFlt.changeSign();
641      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
642
643      bool ignored;
644      APFloat TmpFlt2(+1.0);
645      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
646                      &ignored);
647      addLegalFPImmediate(TmpFlt2);  // FLD1
648      TmpFlt2.changeSign();
649      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
650    }
651
652    if (!UnsafeFPMath) {
653      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
654      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
655    }
656
657    setOperationAction(ISD::FMA, MVT::f80, Expand);
658  }
659
660  // Always use a library call for pow.
661  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
662  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
663  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
664
665  setOperationAction(ISD::FLOG, MVT::f80, Expand);
666  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
667  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
668  setOperationAction(ISD::FEXP, MVT::f80, Expand);
669  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
670
671  // First set operation action for all vector types to either promote
672  // (for widening) or expand (for scalarization). Then we will selectively
673  // turn on ones that can be effectively codegen'd.
674  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
675       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
676    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
677    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
678    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
679    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
680    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
681    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
682    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
683    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
684    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
685    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
686    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
687    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
688    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
689    setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
690    setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
691    setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
692    setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
693    setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
694    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
695    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
696    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
697    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
698    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
699    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
700    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
701    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
702    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
703    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
704    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
705    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
706    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
707    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
708    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
709    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
710    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
711    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
712    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
713    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
714    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
715    setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
716    setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
717    setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
718    setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
719    setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
720    setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
721    setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
722    setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
723    setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
724    setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
725    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
726    setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
727    setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
728    setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
729    setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
730    for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
731         InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
732      setTruncStoreAction((MVT::SimpleValueType)VT,
733                          (MVT::SimpleValueType)InnerVT, Expand);
734    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
735    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
736    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
737  }
738
739  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
740  // with -msoft-float, disable use of MMX as well.
741  if (!UseSoftFloat && Subtarget->hasMMX()) {
742    addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
743    // No operations on x86mmx supported, everything uses intrinsics.
744  }
745
746  // MMX-sized vectors (other than x86mmx) are expected to be expanded
747  // into smaller operations.
748  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
749  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
750  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
751  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
752  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
753  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
754  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
755  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
756  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
757  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
758  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
759  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
760  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
761  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
762  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
763  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
764  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
765  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
766  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
767  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
768  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
769  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
770  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
771  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
772  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
773  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
774  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
775  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
776  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
777
778  if (!UseSoftFloat && Subtarget->hasXMM()) {
779    addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
780
781    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
782    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
783    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
784    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
785    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
786    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
787    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
788    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
789    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
790    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
791    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
792    setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
793  }
794
795  if (!UseSoftFloat && Subtarget->hasXMMInt()) {
796    addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
797
798    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
799    // registers cannot be used even for integer operations.
800    addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
801    addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
802    addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
803    addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
804
805    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
806    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
807    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
808    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
809    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
810    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
811    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
812    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
813    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
814    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
815    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
816    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
817    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
818    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
819    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
820    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
821
822    setOperationAction(ISD::SETCC,              MVT::v2f64, Custom);
823    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
824    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
825    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
826
827    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
828    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
829    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
830    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
831    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
832
833    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
834    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
835    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
836    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
837    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
838
839    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
840    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
841      EVT VT = (MVT::SimpleValueType)i;
842      // Do not attempt to custom lower non-power-of-2 vectors
843      if (!isPowerOf2_32(VT.getVectorNumElements()))
844        continue;
845      // Do not attempt to custom lower non-128-bit vectors
846      if (!VT.is128BitVector())
847        continue;
848      setOperationAction(ISD::BUILD_VECTOR,
849                         VT.getSimpleVT().SimpleTy, Custom);
850      setOperationAction(ISD::VECTOR_SHUFFLE,
851                         VT.getSimpleVT().SimpleTy, Custom);
852      setOperationAction(ISD::EXTRACT_VECTOR_ELT,
853                         VT.getSimpleVT().SimpleTy, Custom);
854    }
855
856    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
857    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
858    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
859    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
860    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
861    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
862
863    if (Subtarget->is64Bit()) {
864      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
865      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
866    }
867
868    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
869    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
870      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
871      EVT VT = SVT;
872
873      // Do not attempt to promote non-128-bit vectors
874      if (!VT.is128BitVector())
875        continue;
876
877      setOperationAction(ISD::AND,    SVT, Promote);
878      AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
879      setOperationAction(ISD::OR,     SVT, Promote);
880      AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
881      setOperationAction(ISD::XOR,    SVT, Promote);
882      AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
883      setOperationAction(ISD::LOAD,   SVT, Promote);
884      AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
885      setOperationAction(ISD::SELECT, SVT, Promote);
886      AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
887    }
888
889    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
890
891    // Custom lower v2i64 and v2f64 selects.
892    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
893    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
894    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
895    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
896
897    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
898    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
899  }
900
901  if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
902    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
903    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
904    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
905    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
906    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
907    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
908    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
909    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
910    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
911    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
912
913    // FIXME: Do we need to handle scalar-to-vector here?
914    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
915
916    // Can turn SHL into an integer multiply.
917    setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
918    setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
919
920    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
921    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
922    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
923    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
924    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
925
926    // i8 and i16 vectors are custom , because the source register and source
927    // source memory operand types are not the same width.  f32 vectors are
928    // custom since the immediate controlling the insert encodes additional
929    // information.
930    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
931    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
932    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
933    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
934
935    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
936    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
937    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
938    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
939
940    if (Subtarget->is64Bit()) {
941      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
942      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
943    }
944  }
945
946  if (Subtarget->hasSSE2() || Subtarget->hasAVX()) {
947    setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
948    setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
949    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
950    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
951
952    setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
953    setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
954    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
955
956    setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
957    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
958  }
959
960  if (Subtarget->hasSSE42() || Subtarget->hasAVX())
961    setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
962
963  if (!UseSoftFloat && Subtarget->hasAVX()) {
964    addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
965    addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
966    addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
967    addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
968    addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
969    addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
970
971    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
972    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
973    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
974
975    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
976    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
977    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
978    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
979    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
980    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
981
982    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
983    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
984    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
985    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
986    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
987    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
988
989    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
990    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
991    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
992
993    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
994    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
995    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
996    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
997    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
998    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
999
1000    setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1001    setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1002    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1003    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1004
1005    setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1006    setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1007    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1008    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1009
1010    setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1011    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1012
1013    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1014    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1015    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1016    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1017
1018    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1019    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1020    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1021
1022    setOperationAction(ISD::VSELECT,            MVT::v4f64, Legal);
1023    setOperationAction(ISD::VSELECT,            MVT::v4i64, Legal);
1024    setOperationAction(ISD::VSELECT,            MVT::v8i32, Legal);
1025    setOperationAction(ISD::VSELECT,            MVT::v8f32, Legal);
1026
1027    setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1028    setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1029    setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1030    setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1031
1032    setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1033    setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1034    setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1035    setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1036
1037    setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1038    setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1039    setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1040    // Don't lower v32i8 because there is no 128-bit byte mul
1041
1042    // Custom lower several nodes for 256-bit types.
1043    for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1044                  i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1045      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1046      EVT VT = SVT;
1047
1048      // Extract subvector is special because the value type
1049      // (result) is 128-bit but the source is 256-bit wide.
1050      if (VT.is128BitVector())
1051        setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1052
1053      // Do not attempt to custom lower other non-256-bit vectors
1054      if (!VT.is256BitVector())
1055        continue;
1056
1057      setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1058      setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1059      setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1060      setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1061      setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1062      setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1063    }
1064
1065    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1066    for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1067      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1068      EVT VT = SVT;
1069
1070      // Do not attempt to promote non-256-bit vectors
1071      if (!VT.is256BitVector())
1072        continue;
1073
1074      setOperationAction(ISD::AND,    SVT, Promote);
1075      AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1076      setOperationAction(ISD::OR,     SVT, Promote);
1077      AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1078      setOperationAction(ISD::XOR,    SVT, Promote);
1079      AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1080      setOperationAction(ISD::LOAD,   SVT, Promote);
1081      AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1082      setOperationAction(ISD::SELECT, SVT, Promote);
1083      AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1084    }
1085  }
1086
1087  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1088  // of this type with custom code.
1089  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1090         VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1091    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1092  }
1093
1094  // We want to custom lower some of our intrinsics.
1095  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1096
1097
1098  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1099  // handle type legalization for these operations here.
1100  //
1101  // FIXME: We really should do custom legalization for addition and
1102  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1103  // than generic legalization for 64-bit multiplication-with-overflow, though.
1104  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1105    // Add/Sub/Mul with overflow operations are custom lowered.
1106    MVT VT = IntVTs[i];
1107    setOperationAction(ISD::SADDO, VT, Custom);
1108    setOperationAction(ISD::UADDO, VT, Custom);
1109    setOperationAction(ISD::SSUBO, VT, Custom);
1110    setOperationAction(ISD::USUBO, VT, Custom);
1111    setOperationAction(ISD::SMULO, VT, Custom);
1112    setOperationAction(ISD::UMULO, VT, Custom);
1113  }
1114
1115  // There are no 8-bit 3-address imul/mul instructions
1116  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1117  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1118
1119  if (!Subtarget->is64Bit()) {
1120    // These libcalls are not available in 32-bit.
1121    setLibcallName(RTLIB::SHL_I128, 0);
1122    setLibcallName(RTLIB::SRL_I128, 0);
1123    setLibcallName(RTLIB::SRA_I128, 0);
1124  }
1125
1126  // We have target-specific dag combine patterns for the following nodes:
1127  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1128  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1129  setTargetDAGCombine(ISD::BUILD_VECTOR);
1130  setTargetDAGCombine(ISD::SELECT);
1131  setTargetDAGCombine(ISD::SHL);
1132  setTargetDAGCombine(ISD::SRA);
1133  setTargetDAGCombine(ISD::SRL);
1134  setTargetDAGCombine(ISD::OR);
1135  setTargetDAGCombine(ISD::AND);
1136  setTargetDAGCombine(ISD::ADD);
1137  setTargetDAGCombine(ISD::SUB);
1138  setTargetDAGCombine(ISD::STORE);
1139  setTargetDAGCombine(ISD::ZERO_EXTEND);
1140  setTargetDAGCombine(ISD::SINT_TO_FP);
1141  if (Subtarget->is64Bit())
1142    setTargetDAGCombine(ISD::MUL);
1143
1144  computeRegisterProperties();
1145
1146  // On Darwin, -Os means optimize for size without hurting performance,
1147  // do not reduce the limit.
1148  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1149  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1150  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1151  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1152  maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1153  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1154  setPrefLoopAlignment(16);
1155  benefitFromCodePlacementOpt = true;
1156
1157  setPrefFunctionAlignment(4);
1158}
1159
1160
1161EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1162  if (!VT.isVector()) return MVT::i8;
1163  return VT.changeVectorElementTypeToInteger();
1164}
1165
1166
1167/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1168/// the desired ByVal argument alignment.
1169static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1170  if (MaxAlign == 16)
1171    return;
1172  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1173    if (VTy->getBitWidth() == 128)
1174      MaxAlign = 16;
1175  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1176    unsigned EltAlign = 0;
1177    getMaxByValAlign(ATy->getElementType(), EltAlign);
1178    if (EltAlign > MaxAlign)
1179      MaxAlign = EltAlign;
1180  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1181    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1182      unsigned EltAlign = 0;
1183      getMaxByValAlign(STy->getElementType(i), EltAlign);
1184      if (EltAlign > MaxAlign)
1185        MaxAlign = EltAlign;
1186      if (MaxAlign == 16)
1187        break;
1188    }
1189  }
1190  return;
1191}
1192
1193/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1194/// function arguments in the caller parameter area. For X86, aggregates
1195/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1196/// are at 4-byte boundaries.
1197unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1198  if (Subtarget->is64Bit()) {
1199    // Max of 8 and alignment of type.
1200    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1201    if (TyAlign > 8)
1202      return TyAlign;
1203    return 8;
1204  }
1205
1206  unsigned Align = 4;
1207  if (Subtarget->hasXMM())
1208    getMaxByValAlign(Ty, Align);
1209  return Align;
1210}
1211
1212/// getOptimalMemOpType - Returns the target specific optimal type for load
1213/// and store operations as a result of memset, memcpy, and memmove
1214/// lowering. If DstAlign is zero that means it's safe to destination
1215/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1216/// means there isn't a need to check it against alignment requirement,
1217/// probably because the source does not need to be loaded. If
1218/// 'NonScalarIntSafe' is true, that means it's safe to return a
1219/// non-scalar-integer type, e.g. empty string source, constant, or loaded
1220/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1221/// constant so it does not need to be loaded.
1222/// It returns EVT::Other if the type should be determined using generic
1223/// target-independent logic.
1224EVT
1225X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1226                                       unsigned DstAlign, unsigned SrcAlign,
1227                                       bool NonScalarIntSafe,
1228                                       bool MemcpyStrSrc,
1229                                       MachineFunction &MF) const {
1230  // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1231  // linux.  This is because the stack realignment code can't handle certain
1232  // cases like PR2962.  This should be removed when PR2962 is fixed.
1233  const Function *F = MF.getFunction();
1234  if (NonScalarIntSafe &&
1235      !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1236    if (Size >= 16 &&
1237        (Subtarget->isUnalignedMemAccessFast() ||
1238         ((DstAlign == 0 || DstAlign >= 16) &&
1239          (SrcAlign == 0 || SrcAlign >= 16))) &&
1240        Subtarget->getStackAlignment() >= 16) {
1241      if (Subtarget->hasSSE2())
1242        return MVT::v4i32;
1243      if (Subtarget->hasSSE1())
1244        return MVT::v4f32;
1245    } else if (!MemcpyStrSrc && Size >= 8 &&
1246               !Subtarget->is64Bit() &&
1247               Subtarget->getStackAlignment() >= 8 &&
1248               Subtarget->hasXMMInt()) {
1249      // Do not use f64 to lower memcpy if source is string constant. It's
1250      // better to use i32 to avoid the loads.
1251      return MVT::f64;
1252    }
1253  }
1254  if (Subtarget->is64Bit() && Size >= 8)
1255    return MVT::i64;
1256  return MVT::i32;
1257}
1258
1259/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1260/// current function.  The returned value is a member of the
1261/// MachineJumpTableInfo::JTEntryKind enum.
1262unsigned X86TargetLowering::getJumpTableEncoding() const {
1263  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1264  // symbol.
1265  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1266      Subtarget->isPICStyleGOT())
1267    return MachineJumpTableInfo::EK_Custom32;
1268
1269  // Otherwise, use the normal jump table encoding heuristics.
1270  return TargetLowering::getJumpTableEncoding();
1271}
1272
1273const MCExpr *
1274X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1275                                             const MachineBasicBlock *MBB,
1276                                             unsigned uid,MCContext &Ctx) const{
1277  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1278         Subtarget->isPICStyleGOT());
1279  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1280  // entries.
1281  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1282                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1283}
1284
1285/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1286/// jumptable.
1287SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1288                                                    SelectionDAG &DAG) const {
1289  if (!Subtarget->is64Bit())
1290    // This doesn't have DebugLoc associated with it, but is not really the
1291    // same as a Register.
1292    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1293  return Table;
1294}
1295
1296/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1297/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1298/// MCExpr.
1299const MCExpr *X86TargetLowering::
1300getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1301                             MCContext &Ctx) const {
1302  // X86-64 uses RIP relative addressing based on the jump table label.
1303  if (Subtarget->isPICStyleRIPRel())
1304    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1305
1306  // Otherwise, the reference is relative to the PIC base.
1307  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1308}
1309
1310// FIXME: Why this routine is here? Move to RegInfo!
1311std::pair<const TargetRegisterClass*, uint8_t>
1312X86TargetLowering::findRepresentativeClass(EVT VT) const{
1313  const TargetRegisterClass *RRC = 0;
1314  uint8_t Cost = 1;
1315  switch (VT.getSimpleVT().SimpleTy) {
1316  default:
1317    return TargetLowering::findRepresentativeClass(VT);
1318  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1319    RRC = (Subtarget->is64Bit()
1320           ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1321    break;
1322  case MVT::x86mmx:
1323    RRC = X86::VR64RegisterClass;
1324    break;
1325  case MVT::f32: case MVT::f64:
1326  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1327  case MVT::v4f32: case MVT::v2f64:
1328  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1329  case MVT::v4f64:
1330    RRC = X86::VR128RegisterClass;
1331    break;
1332  }
1333  return std::make_pair(RRC, Cost);
1334}
1335
1336bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1337                                               unsigned &Offset) const {
1338  if (!Subtarget->isTargetLinux())
1339    return false;
1340
1341  if (Subtarget->is64Bit()) {
1342    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1343    Offset = 0x28;
1344    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1345      AddressSpace = 256;
1346    else
1347      AddressSpace = 257;
1348  } else {
1349    // %gs:0x14 on i386
1350    Offset = 0x14;
1351    AddressSpace = 256;
1352  }
1353  return true;
1354}
1355
1356
1357//===----------------------------------------------------------------------===//
1358//               Return Value Calling Convention Implementation
1359//===----------------------------------------------------------------------===//
1360
1361#include "X86GenCallingConv.inc"
1362
1363bool
1364X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1365				  MachineFunction &MF, bool isVarArg,
1366                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1367                        LLVMContext &Context) const {
1368  SmallVector<CCValAssign, 16> RVLocs;
1369  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1370                 RVLocs, Context);
1371  return CCInfo.CheckReturn(Outs, RetCC_X86);
1372}
1373
1374SDValue
1375X86TargetLowering::LowerReturn(SDValue Chain,
1376                               CallingConv::ID CallConv, bool isVarArg,
1377                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1378                               const SmallVectorImpl<SDValue> &OutVals,
1379                               DebugLoc dl, SelectionDAG &DAG) const {
1380  MachineFunction &MF = DAG.getMachineFunction();
1381  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1382
1383  SmallVector<CCValAssign, 16> RVLocs;
1384  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1385                 RVLocs, *DAG.getContext());
1386  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1387
1388  // Add the regs to the liveout set for the function.
1389  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1390  for (unsigned i = 0; i != RVLocs.size(); ++i)
1391    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1392      MRI.addLiveOut(RVLocs[i].getLocReg());
1393
1394  SDValue Flag;
1395
1396  SmallVector<SDValue, 6> RetOps;
1397  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1398  // Operand #1 = Bytes To Pop
1399  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1400                   MVT::i16));
1401
1402  // Copy the result values into the output registers.
1403  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1404    CCValAssign &VA = RVLocs[i];
1405    assert(VA.isRegLoc() && "Can only return in registers!");
1406    SDValue ValToCopy = OutVals[i];
1407    EVT ValVT = ValToCopy.getValueType();
1408
1409    // If this is x86-64, and we disabled SSE, we can't return FP values,
1410    // or SSE or MMX vectors.
1411    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1412         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1413          (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1414      report_fatal_error("SSE register return with SSE disabled");
1415    }
1416    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1417    // llvm-gcc has never done it right and no one has noticed, so this
1418    // should be OK for now.
1419    if (ValVT == MVT::f64 &&
1420        (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1421      report_fatal_error("SSE2 register return with SSE2 disabled");
1422
1423    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1424    // the RET instruction and handled by the FP Stackifier.
1425    if (VA.getLocReg() == X86::ST0 ||
1426        VA.getLocReg() == X86::ST1) {
1427      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1428      // change the value to the FP stack register class.
1429      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1430        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1431      RetOps.push_back(ValToCopy);
1432      // Don't emit a copytoreg.
1433      continue;
1434    }
1435
1436    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1437    // which is returned in RAX / RDX.
1438    if (Subtarget->is64Bit()) {
1439      if (ValVT == MVT::x86mmx) {
1440        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1441          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1442          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1443                                  ValToCopy);
1444          // If we don't have SSE2 available, convert to v4f32 so the generated
1445          // register is legal.
1446          if (!Subtarget->hasSSE2())
1447            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1448        }
1449      }
1450    }
1451
1452    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1453    Flag = Chain.getValue(1);
1454  }
1455
1456  // The x86-64 ABI for returning structs by value requires that we copy
1457  // the sret argument into %rax for the return. We saved the argument into
1458  // a virtual register in the entry block, so now we copy the value out
1459  // and into %rax.
1460  if (Subtarget->is64Bit() &&
1461      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1462    MachineFunction &MF = DAG.getMachineFunction();
1463    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1464    unsigned Reg = FuncInfo->getSRetReturnReg();
1465    assert(Reg &&
1466           "SRetReturnReg should have been set in LowerFormalArguments().");
1467    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1468
1469    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1470    Flag = Chain.getValue(1);
1471
1472    // RAX now acts like a return value.
1473    MRI.addLiveOut(X86::RAX);
1474  }
1475
1476  RetOps[0] = Chain;  // Update chain.
1477
1478  // Add the flag if we have it.
1479  if (Flag.getNode())
1480    RetOps.push_back(Flag);
1481
1482  return DAG.getNode(X86ISD::RET_FLAG, dl,
1483                     MVT::Other, &RetOps[0], RetOps.size());
1484}
1485
1486bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1487  if (N->getNumValues() != 1)
1488    return false;
1489  if (!N->hasNUsesOfValue(1, 0))
1490    return false;
1491
1492  SDNode *Copy = *N->use_begin();
1493  if (Copy->getOpcode() != ISD::CopyToReg &&
1494      Copy->getOpcode() != ISD::FP_EXTEND)
1495    return false;
1496
1497  bool HasRet = false;
1498  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1499       UI != UE; ++UI) {
1500    if (UI->getOpcode() != X86ISD::RET_FLAG)
1501      return false;
1502    HasRet = true;
1503  }
1504
1505  return HasRet;
1506}
1507
1508EVT
1509X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1510                                            ISD::NodeType ExtendKind) const {
1511  MVT ReturnMVT;
1512  // TODO: Is this also valid on 32-bit?
1513  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1514    ReturnMVT = MVT::i8;
1515  else
1516    ReturnMVT = MVT::i32;
1517
1518  EVT MinVT = getRegisterType(Context, ReturnMVT);
1519  return VT.bitsLT(MinVT) ? MinVT : VT;
1520}
1521
1522/// LowerCallResult - Lower the result values of a call into the
1523/// appropriate copies out of appropriate physical registers.
1524///
1525SDValue
1526X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1527                                   CallingConv::ID CallConv, bool isVarArg,
1528                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1529                                   DebugLoc dl, SelectionDAG &DAG,
1530                                   SmallVectorImpl<SDValue> &InVals) const {
1531
1532  // Assign locations to each value returned by this call.
1533  SmallVector<CCValAssign, 16> RVLocs;
1534  bool Is64Bit = Subtarget->is64Bit();
1535  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1536		 getTargetMachine(), RVLocs, *DAG.getContext());
1537  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1538
1539  // Copy all of the result registers out of their specified physreg.
1540  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1541    CCValAssign &VA = RVLocs[i];
1542    EVT CopyVT = VA.getValVT();
1543
1544    // If this is x86-64, and we disabled SSE, we can't return FP values
1545    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1546        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1547      report_fatal_error("SSE register return with SSE disabled");
1548    }
1549
1550    SDValue Val;
1551
1552    // If this is a call to a function that returns an fp value on the floating
1553    // point stack, we must guarantee the the value is popped from the stack, so
1554    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1555    // if the return value is not used. We use the FpPOP_RETVAL instruction
1556    // instead.
1557    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1558      // If we prefer to use the value in xmm registers, copy it out as f80 and
1559      // use a truncate to move it from fp stack reg to xmm reg.
1560      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1561      SDValue Ops[] = { Chain, InFlag };
1562      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1563                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1564      Val = Chain.getValue(0);
1565
1566      // Round the f80 to the right size, which also moves it to the appropriate
1567      // xmm register.
1568      if (CopyVT != VA.getValVT())
1569        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1570                          // This truncation won't change the value.
1571                          DAG.getIntPtrConstant(1));
1572    } else {
1573      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1574                                 CopyVT, InFlag).getValue(1);
1575      Val = Chain.getValue(0);
1576    }
1577    InFlag = Chain.getValue(2);
1578    InVals.push_back(Val);
1579  }
1580
1581  return Chain;
1582}
1583
1584
1585//===----------------------------------------------------------------------===//
1586//                C & StdCall & Fast Calling Convention implementation
1587//===----------------------------------------------------------------------===//
1588//  StdCall calling convention seems to be standard for many Windows' API
1589//  routines and around. It differs from C calling convention just a little:
1590//  callee should clean up the stack, not caller. Symbols should be also
1591//  decorated in some fancy way :) It doesn't support any vector arguments.
1592//  For info on fast calling convention see Fast Calling Convention (tail call)
1593//  implementation LowerX86_32FastCCCallTo.
1594
1595/// CallIsStructReturn - Determines whether a call uses struct return
1596/// semantics.
1597static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1598  if (Outs.empty())
1599    return false;
1600
1601  return Outs[0].Flags.isSRet();
1602}
1603
1604/// ArgsAreStructReturn - Determines whether a function uses struct
1605/// return semantics.
1606static bool
1607ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1608  if (Ins.empty())
1609    return false;
1610
1611  return Ins[0].Flags.isSRet();
1612}
1613
1614/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1615/// by "Src" to address "Dst" with size and alignment information specified by
1616/// the specific parameter attribute. The copy will be passed as a byval
1617/// function parameter.
1618static SDValue
1619CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1620                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1621                          DebugLoc dl) {
1622  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1623
1624  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1625                       /*isVolatile*/false, /*AlwaysInline=*/true,
1626                       MachinePointerInfo(), MachinePointerInfo());
1627}
1628
1629/// IsTailCallConvention - Return true if the calling convention is one that
1630/// supports tail call optimization.
1631static bool IsTailCallConvention(CallingConv::ID CC) {
1632  return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1633}
1634
1635bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1636  if (!CI->isTailCall())
1637    return false;
1638
1639  CallSite CS(CI);
1640  CallingConv::ID CalleeCC = CS.getCallingConv();
1641  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1642    return false;
1643
1644  return true;
1645}
1646
1647/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1648/// a tailcall target by changing its ABI.
1649static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1650  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1651}
1652
1653SDValue
1654X86TargetLowering::LowerMemArgument(SDValue Chain,
1655                                    CallingConv::ID CallConv,
1656                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1657                                    DebugLoc dl, SelectionDAG &DAG,
1658                                    const CCValAssign &VA,
1659                                    MachineFrameInfo *MFI,
1660                                    unsigned i) const {
1661  // Create the nodes corresponding to a load from this parameter slot.
1662  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1663  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1664  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1665  EVT ValVT;
1666
1667  // If value is passed by pointer we have address passed instead of the value
1668  // itself.
1669  if (VA.getLocInfo() == CCValAssign::Indirect)
1670    ValVT = VA.getLocVT();
1671  else
1672    ValVT = VA.getValVT();
1673
1674  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1675  // changed with more analysis.
1676  // In case of tail call optimization mark all arguments mutable. Since they
1677  // could be overwritten by lowering of arguments in case of a tail call.
1678  if (Flags.isByVal()) {
1679    unsigned Bytes = Flags.getByValSize();
1680    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1681    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1682    return DAG.getFrameIndex(FI, getPointerTy());
1683  } else {
1684    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1685                                    VA.getLocMemOffset(), isImmutable);
1686    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1687    return DAG.getLoad(ValVT, dl, Chain, FIN,
1688                       MachinePointerInfo::getFixedStack(FI),
1689                       false, false, 0);
1690  }
1691}
1692
1693SDValue
1694X86TargetLowering::LowerFormalArguments(SDValue Chain,
1695                                        CallingConv::ID CallConv,
1696                                        bool isVarArg,
1697                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1698                                        DebugLoc dl,
1699                                        SelectionDAG &DAG,
1700                                        SmallVectorImpl<SDValue> &InVals)
1701                                          const {
1702  MachineFunction &MF = DAG.getMachineFunction();
1703  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1704
1705  const Function* Fn = MF.getFunction();
1706  if (Fn->hasExternalLinkage() &&
1707      Subtarget->isTargetCygMing() &&
1708      Fn->getName() == "main")
1709    FuncInfo->setForceFramePointer(true);
1710
1711  MachineFrameInfo *MFI = MF.getFrameInfo();
1712  bool Is64Bit = Subtarget->is64Bit();
1713  bool IsWin64 = Subtarget->isTargetWin64();
1714
1715  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1716         "Var args not supported with calling convention fastcc or ghc");
1717
1718  // Assign locations to all of the incoming arguments.
1719  SmallVector<CCValAssign, 16> ArgLocs;
1720  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1721                 ArgLocs, *DAG.getContext());
1722
1723  // Allocate shadow area for Win64
1724  if (IsWin64) {
1725    CCInfo.AllocateStack(32, 8);
1726  }
1727
1728  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1729
1730  unsigned LastVal = ~0U;
1731  SDValue ArgValue;
1732  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1733    CCValAssign &VA = ArgLocs[i];
1734    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1735    // places.
1736    assert(VA.getValNo() != LastVal &&
1737           "Don't support value assigned to multiple locs yet");
1738    LastVal = VA.getValNo();
1739
1740    if (VA.isRegLoc()) {
1741      EVT RegVT = VA.getLocVT();
1742      TargetRegisterClass *RC = NULL;
1743      if (RegVT == MVT::i32)
1744        RC = X86::GR32RegisterClass;
1745      else if (Is64Bit && RegVT == MVT::i64)
1746        RC = X86::GR64RegisterClass;
1747      else if (RegVT == MVT::f32)
1748        RC = X86::FR32RegisterClass;
1749      else if (RegVT == MVT::f64)
1750        RC = X86::FR64RegisterClass;
1751      else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1752        RC = X86::VR256RegisterClass;
1753      else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1754        RC = X86::VR128RegisterClass;
1755      else if (RegVT == MVT::x86mmx)
1756        RC = X86::VR64RegisterClass;
1757      else
1758        llvm_unreachable("Unknown argument type!");
1759
1760      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1761      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1762
1763      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1764      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1765      // right size.
1766      if (VA.getLocInfo() == CCValAssign::SExt)
1767        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1768                               DAG.getValueType(VA.getValVT()));
1769      else if (VA.getLocInfo() == CCValAssign::ZExt)
1770        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1771                               DAG.getValueType(VA.getValVT()));
1772      else if (VA.getLocInfo() == CCValAssign::BCvt)
1773        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1774
1775      if (VA.isExtInLoc()) {
1776        // Handle MMX values passed in XMM regs.
1777        if (RegVT.isVector()) {
1778          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1779                                 ArgValue);
1780        } else
1781          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1782      }
1783    } else {
1784      assert(VA.isMemLoc());
1785      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1786    }
1787
1788    // If value is passed via pointer - do a load.
1789    if (VA.getLocInfo() == CCValAssign::Indirect)
1790      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1791                             MachinePointerInfo(), false, false, 0);
1792
1793    InVals.push_back(ArgValue);
1794  }
1795
1796  // The x86-64 ABI for returning structs by value requires that we copy
1797  // the sret argument into %rax for the return. Save the argument into
1798  // a virtual register so that we can access it from the return points.
1799  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1800    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1801    unsigned Reg = FuncInfo->getSRetReturnReg();
1802    if (!Reg) {
1803      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1804      FuncInfo->setSRetReturnReg(Reg);
1805    }
1806    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1807    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1808  }
1809
1810  unsigned StackSize = CCInfo.getNextStackOffset();
1811  // Align stack specially for tail calls.
1812  if (FuncIsMadeTailCallSafe(CallConv))
1813    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1814
1815  // If the function takes variable number of arguments, make a frame index for
1816  // the start of the first vararg value... for expansion of llvm.va_start.
1817  if (isVarArg) {
1818    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1819                    CallConv != CallingConv::X86_ThisCall)) {
1820      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1821    }
1822    if (Is64Bit) {
1823      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1824
1825      // FIXME: We should really autogenerate these arrays
1826      static const unsigned GPR64ArgRegsWin64[] = {
1827        X86::RCX, X86::RDX, X86::R8,  X86::R9
1828      };
1829      static const unsigned GPR64ArgRegs64Bit[] = {
1830        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1831      };
1832      static const unsigned XMMArgRegs64Bit[] = {
1833        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1834        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1835      };
1836      const unsigned *GPR64ArgRegs;
1837      unsigned NumXMMRegs = 0;
1838
1839      if (IsWin64) {
1840        // The XMM registers which might contain var arg parameters are shadowed
1841        // in their paired GPR.  So we only need to save the GPR to their home
1842        // slots.
1843        TotalNumIntRegs = 4;
1844        GPR64ArgRegs = GPR64ArgRegsWin64;
1845      } else {
1846        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1847        GPR64ArgRegs = GPR64ArgRegs64Bit;
1848
1849        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1850      }
1851      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1852                                                       TotalNumIntRegs);
1853
1854      bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1855      assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1856             "SSE register cannot be used when SSE is disabled!");
1857      assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1858             "SSE register cannot be used when SSE is disabled!");
1859      if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1860        // Kernel mode asks for SSE to be disabled, so don't push them
1861        // on the stack.
1862        TotalNumXMMRegs = 0;
1863
1864      if (IsWin64) {
1865        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1866        // Get to the caller-allocated home save location.  Add 8 to account
1867        // for the return address.
1868        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1869        FuncInfo->setRegSaveFrameIndex(
1870          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1871        // Fixup to set vararg frame on shadow area (4 x i64).
1872        if (NumIntRegs < 4)
1873          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1874      } else {
1875        // For X86-64, if there are vararg parameters that are passed via
1876        // registers, then we must store them to their spots on the stack so they
1877        // may be loaded by deferencing the result of va_next.
1878        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1879        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1880        FuncInfo->setRegSaveFrameIndex(
1881          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1882                               false));
1883      }
1884
1885      // Store the integer parameter registers.
1886      SmallVector<SDValue, 8> MemOps;
1887      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1888                                        getPointerTy());
1889      unsigned Offset = FuncInfo->getVarArgsGPOffset();
1890      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1891        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1892                                  DAG.getIntPtrConstant(Offset));
1893        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1894                                     X86::GR64RegisterClass);
1895        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1896        SDValue Store =
1897          DAG.getStore(Val.getValue(1), dl, Val, FIN,
1898                       MachinePointerInfo::getFixedStack(
1899                         FuncInfo->getRegSaveFrameIndex(), Offset),
1900                       false, false, 0);
1901        MemOps.push_back(Store);
1902        Offset += 8;
1903      }
1904
1905      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1906        // Now store the XMM (fp + vector) parameter registers.
1907        SmallVector<SDValue, 11> SaveXMMOps;
1908        SaveXMMOps.push_back(Chain);
1909
1910        unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1911        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1912        SaveXMMOps.push_back(ALVal);
1913
1914        SaveXMMOps.push_back(DAG.getIntPtrConstant(
1915                               FuncInfo->getRegSaveFrameIndex()));
1916        SaveXMMOps.push_back(DAG.getIntPtrConstant(
1917                               FuncInfo->getVarArgsFPOffset()));
1918
1919        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1920          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1921                                       X86::VR128RegisterClass);
1922          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1923          SaveXMMOps.push_back(Val);
1924        }
1925        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1926                                     MVT::Other,
1927                                     &SaveXMMOps[0], SaveXMMOps.size()));
1928      }
1929
1930      if (!MemOps.empty())
1931        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1932                            &MemOps[0], MemOps.size());
1933    }
1934  }
1935
1936  // Some CCs need callee pop.
1937  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1938    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1939  } else {
1940    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1941    // If this is an sret function, the return should pop the hidden pointer.
1942    if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1943      FuncInfo->setBytesToPopOnReturn(4);
1944  }
1945
1946  if (!Is64Bit) {
1947    // RegSaveFrameIndex is X86-64 only.
1948    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1949    if (CallConv == CallingConv::X86_FastCall ||
1950        CallConv == CallingConv::X86_ThisCall)
1951      // fastcc functions can't have varargs.
1952      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1953  }
1954
1955  FuncInfo->setArgumentStackSize(StackSize);
1956
1957  return Chain;
1958}
1959
1960SDValue
1961X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1962                                    SDValue StackPtr, SDValue Arg,
1963                                    DebugLoc dl, SelectionDAG &DAG,
1964                                    const CCValAssign &VA,
1965                                    ISD::ArgFlagsTy Flags) const {
1966  unsigned LocMemOffset = VA.getLocMemOffset();
1967  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1968  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1969  if (Flags.isByVal())
1970    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1971
1972  return DAG.getStore(Chain, dl, Arg, PtrOff,
1973                      MachinePointerInfo::getStack(LocMemOffset),
1974                      false, false, 0);
1975}
1976
1977/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1978/// optimization is performed and it is required.
1979SDValue
1980X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1981                                           SDValue &OutRetAddr, SDValue Chain,
1982                                           bool IsTailCall, bool Is64Bit,
1983                                           int FPDiff, DebugLoc dl) const {
1984  // Adjust the Return address stack slot.
1985  EVT VT = getPointerTy();
1986  OutRetAddr = getReturnAddressFrameIndex(DAG);
1987
1988  // Load the "old" Return address.
1989  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1990                           false, false, 0);
1991  return SDValue(OutRetAddr.getNode(), 1);
1992}
1993
1994/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1995/// optimization is performed and it is required (FPDiff!=0).
1996static SDValue
1997EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1998                         SDValue Chain, SDValue RetAddrFrIdx,
1999                         bool Is64Bit, int FPDiff, DebugLoc dl) {
2000  // Store the return address to the appropriate stack slot.
2001  if (!FPDiff) return Chain;
2002  // Calculate the new stack slot for the return address.
2003  int SlotSize = Is64Bit ? 8 : 4;
2004  int NewReturnAddrFI =
2005    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2006  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2007  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2008  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2009                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2010                       false, false, 0);
2011  return Chain;
2012}
2013
2014SDValue
2015X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2016                             CallingConv::ID CallConv, bool isVarArg,
2017                             bool &isTailCall,
2018                             const SmallVectorImpl<ISD::OutputArg> &Outs,
2019                             const SmallVectorImpl<SDValue> &OutVals,
2020                             const SmallVectorImpl<ISD::InputArg> &Ins,
2021                             DebugLoc dl, SelectionDAG &DAG,
2022                             SmallVectorImpl<SDValue> &InVals) const {
2023  MachineFunction &MF = DAG.getMachineFunction();
2024  bool Is64Bit        = Subtarget->is64Bit();
2025  bool IsWin64        = Subtarget->isTargetWin64();
2026  bool IsStructRet    = CallIsStructReturn(Outs);
2027  bool IsSibcall      = false;
2028
2029  if (isTailCall) {
2030    // Check if it's really possible to do a tail call.
2031    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2032                    isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2033                                                   Outs, OutVals, Ins, DAG);
2034
2035    // Sibcalls are automatically detected tailcalls which do not require
2036    // ABI changes.
2037    if (!GuaranteedTailCallOpt && isTailCall)
2038      IsSibcall = true;
2039
2040    if (isTailCall)
2041      ++NumTailCalls;
2042  }
2043
2044  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2045         "Var args not supported with calling convention fastcc or ghc");
2046
2047  // Analyze operands of the call, assigning locations to each operand.
2048  SmallVector<CCValAssign, 16> ArgLocs;
2049  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2050                 ArgLocs, *DAG.getContext());
2051
2052  // Allocate shadow area for Win64
2053  if (IsWin64) {
2054    CCInfo.AllocateStack(32, 8);
2055  }
2056
2057  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2058
2059  // Get a count of how many bytes are to be pushed on the stack.
2060  unsigned NumBytes = CCInfo.getNextStackOffset();
2061  if (IsSibcall)
2062    // This is a sibcall. The memory operands are available in caller's
2063    // own caller's stack.
2064    NumBytes = 0;
2065  else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2066    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2067
2068  int FPDiff = 0;
2069  if (isTailCall && !IsSibcall) {
2070    // Lower arguments at fp - stackoffset + fpdiff.
2071    unsigned NumBytesCallerPushed =
2072      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2073    FPDiff = NumBytesCallerPushed - NumBytes;
2074
2075    // Set the delta of movement of the returnaddr stackslot.
2076    // But only set if delta is greater than previous delta.
2077    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2078      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2079  }
2080
2081  if (!IsSibcall)
2082    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2083
2084  SDValue RetAddrFrIdx;
2085  // Load return address for tail calls.
2086  if (isTailCall && FPDiff)
2087    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2088                                    Is64Bit, FPDiff, dl);
2089
2090  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2091  SmallVector<SDValue, 8> MemOpChains;
2092  SDValue StackPtr;
2093
2094  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2095  // of tail call optimization arguments are handle later.
2096  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2097    CCValAssign &VA = ArgLocs[i];
2098    EVT RegVT = VA.getLocVT();
2099    SDValue Arg = OutVals[i];
2100    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2101    bool isByVal = Flags.isByVal();
2102
2103    // Promote the value if needed.
2104    switch (VA.getLocInfo()) {
2105    default: llvm_unreachable("Unknown loc info!");
2106    case CCValAssign::Full: break;
2107    case CCValAssign::SExt:
2108      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2109      break;
2110    case CCValAssign::ZExt:
2111      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2112      break;
2113    case CCValAssign::AExt:
2114      if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2115        // Special case: passing MMX values in XMM registers.
2116        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2117        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2118        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2119      } else
2120        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2121      break;
2122    case CCValAssign::BCvt:
2123      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2124      break;
2125    case CCValAssign::Indirect: {
2126      // Store the argument.
2127      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2128      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2129      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2130                           MachinePointerInfo::getFixedStack(FI),
2131                           false, false, 0);
2132      Arg = SpillSlot;
2133      break;
2134    }
2135    }
2136
2137    if (VA.isRegLoc()) {
2138      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2139      if (isVarArg && IsWin64) {
2140        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2141        // shadow reg if callee is a varargs function.
2142        unsigned ShadowReg = 0;
2143        switch (VA.getLocReg()) {
2144        case X86::XMM0: ShadowReg = X86::RCX; break;
2145        case X86::XMM1: ShadowReg = X86::RDX; break;
2146        case X86::XMM2: ShadowReg = X86::R8; break;
2147        case X86::XMM3: ShadowReg = X86::R9; break;
2148        }
2149        if (ShadowReg)
2150          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2151      }
2152    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2153      assert(VA.isMemLoc());
2154      if (StackPtr.getNode() == 0)
2155        StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2156      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2157                                             dl, DAG, VA, Flags));
2158    }
2159  }
2160
2161  if (!MemOpChains.empty())
2162    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2163                        &MemOpChains[0], MemOpChains.size());
2164
2165  // Build a sequence of copy-to-reg nodes chained together with token chain
2166  // and flag operands which copy the outgoing args into registers.
2167  SDValue InFlag;
2168  // Tail call byval lowering might overwrite argument registers so in case of
2169  // tail call optimization the copies to registers are lowered later.
2170  if (!isTailCall)
2171    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2172      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2173                               RegsToPass[i].second, InFlag);
2174      InFlag = Chain.getValue(1);
2175    }
2176
2177  if (Subtarget->isPICStyleGOT()) {
2178    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2179    // GOT pointer.
2180    if (!isTailCall) {
2181      Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2182                               DAG.getNode(X86ISD::GlobalBaseReg,
2183                                           DebugLoc(), getPointerTy()),
2184                               InFlag);
2185      InFlag = Chain.getValue(1);
2186    } else {
2187      // If we are tail calling and generating PIC/GOT style code load the
2188      // address of the callee into ECX. The value in ecx is used as target of
2189      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2190      // for tail calls on PIC/GOT architectures. Normally we would just put the
2191      // address of GOT into ebx and then call target@PLT. But for tail calls
2192      // ebx would be restored (since ebx is callee saved) before jumping to the
2193      // target@PLT.
2194
2195      // Note: The actual moving to ECX is done further down.
2196      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2197      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2198          !G->getGlobal()->hasProtectedVisibility())
2199        Callee = LowerGlobalAddress(Callee, DAG);
2200      else if (isa<ExternalSymbolSDNode>(Callee))
2201        Callee = LowerExternalSymbol(Callee, DAG);
2202    }
2203  }
2204
2205  if (Is64Bit && isVarArg && !IsWin64) {
2206    // From AMD64 ABI document:
2207    // For calls that may call functions that use varargs or stdargs
2208    // (prototype-less calls or calls to functions containing ellipsis (...) in
2209    // the declaration) %al is used as hidden argument to specify the number
2210    // of SSE registers used. The contents of %al do not need to match exactly
2211    // the number of registers, but must be an ubound on the number of SSE
2212    // registers used and is in the range 0 - 8 inclusive.
2213
2214    // Count the number of XMM registers allocated.
2215    static const unsigned XMMArgRegs[] = {
2216      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2217      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2218    };
2219    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2220    assert((Subtarget->hasXMM() || !NumXMMRegs)
2221           && "SSE registers cannot be used when SSE is disabled");
2222
2223    Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2224                             DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2225    InFlag = Chain.getValue(1);
2226  }
2227
2228
2229  // For tail calls lower the arguments to the 'real' stack slot.
2230  if (isTailCall) {
2231    // Force all the incoming stack arguments to be loaded from the stack
2232    // before any new outgoing arguments are stored to the stack, because the
2233    // outgoing stack slots may alias the incoming argument stack slots, and
2234    // the alias isn't otherwise explicit. This is slightly more conservative
2235    // than necessary, because it means that each store effectively depends
2236    // on every argument instead of just those arguments it would clobber.
2237    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2238
2239    SmallVector<SDValue, 8> MemOpChains2;
2240    SDValue FIN;
2241    int FI = 0;
2242    // Do not flag preceding copytoreg stuff together with the following stuff.
2243    InFlag = SDValue();
2244    if (GuaranteedTailCallOpt) {
2245      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2246        CCValAssign &VA = ArgLocs[i];
2247        if (VA.isRegLoc())
2248          continue;
2249        assert(VA.isMemLoc());
2250        SDValue Arg = OutVals[i];
2251        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2252        // Create frame index.
2253        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2254        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2255        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2256        FIN = DAG.getFrameIndex(FI, getPointerTy());
2257
2258        if (Flags.isByVal()) {
2259          // Copy relative to framepointer.
2260          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2261          if (StackPtr.getNode() == 0)
2262            StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2263                                          getPointerTy());
2264          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2265
2266          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2267                                                           ArgChain,
2268                                                           Flags, DAG, dl));
2269        } else {
2270          // Store relative to framepointer.
2271          MemOpChains2.push_back(
2272            DAG.getStore(ArgChain, dl, Arg, FIN,
2273                         MachinePointerInfo::getFixedStack(FI),
2274                         false, false, 0));
2275        }
2276      }
2277    }
2278
2279    if (!MemOpChains2.empty())
2280      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2281                          &MemOpChains2[0], MemOpChains2.size());
2282
2283    // Copy arguments to their registers.
2284    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2285      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2286                               RegsToPass[i].second, InFlag);
2287      InFlag = Chain.getValue(1);
2288    }
2289    InFlag =SDValue();
2290
2291    // Store the return address to the appropriate stack slot.
2292    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2293                                     FPDiff, dl);
2294  }
2295
2296  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2297    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2298    // In the 64-bit large code model, we have to make all calls
2299    // through a register, since the call instruction's 32-bit
2300    // pc-relative offset may not be large enough to hold the whole
2301    // address.
2302  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2303    // If the callee is a GlobalAddress node (quite common, every direct call
2304    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2305    // it.
2306
2307    // We should use extra load for direct calls to dllimported functions in
2308    // non-JIT mode.
2309    const GlobalValue *GV = G->getGlobal();
2310    if (!GV->hasDLLImportLinkage()) {
2311      unsigned char OpFlags = 0;
2312      bool ExtraLoad = false;
2313      unsigned WrapperKind = ISD::DELETED_NODE;
2314
2315      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2316      // external symbols most go through the PLT in PIC mode.  If the symbol
2317      // has hidden or protected visibility, or if it is static or local, then
2318      // we don't need to use the PLT - we can directly call it.
2319      if (Subtarget->isTargetELF() &&
2320          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2321          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2322        OpFlags = X86II::MO_PLT;
2323      } else if (Subtarget->isPICStyleStubAny() &&
2324                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2325                 (!Subtarget->getTargetTriple().isMacOSX() ||
2326                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2327        // PC-relative references to external symbols should go through $stub,
2328        // unless we're building with the leopard linker or later, which
2329        // automatically synthesizes these stubs.
2330        OpFlags = X86II::MO_DARWIN_STUB;
2331      } else if (Subtarget->isPICStyleRIPRel() &&
2332                 isa<Function>(GV) &&
2333                 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2334        // If the function is marked as non-lazy, generate an indirect call
2335        // which loads from the GOT directly. This avoids runtime overhead
2336        // at the cost of eager binding (and one extra byte of encoding).
2337        OpFlags = X86II::MO_GOTPCREL;
2338        WrapperKind = X86ISD::WrapperRIP;
2339        ExtraLoad = true;
2340      }
2341
2342      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2343                                          G->getOffset(), OpFlags);
2344
2345      // Add a wrapper if needed.
2346      if (WrapperKind != ISD::DELETED_NODE)
2347        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2348      // Add extra indirection if needed.
2349      if (ExtraLoad)
2350        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2351                             MachinePointerInfo::getGOT(),
2352                             false, false, 0);
2353    }
2354  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2355    unsigned char OpFlags = 0;
2356
2357    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2358    // external symbols should go through the PLT.
2359    if (Subtarget->isTargetELF() &&
2360        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2361      OpFlags = X86II::MO_PLT;
2362    } else if (Subtarget->isPICStyleStubAny() &&
2363               (!Subtarget->getTargetTriple().isMacOSX() ||
2364                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2365      // PC-relative references to external symbols should go through $stub,
2366      // unless we're building with the leopard linker or later, which
2367      // automatically synthesizes these stubs.
2368      OpFlags = X86II::MO_DARWIN_STUB;
2369    }
2370
2371    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2372                                         OpFlags);
2373  }
2374
2375  // Returns a chain & a flag for retval copy to use.
2376  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2377  SmallVector<SDValue, 8> Ops;
2378
2379  if (!IsSibcall && isTailCall) {
2380    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2381                           DAG.getIntPtrConstant(0, true), InFlag);
2382    InFlag = Chain.getValue(1);
2383  }
2384
2385  Ops.push_back(Chain);
2386  Ops.push_back(Callee);
2387
2388  if (isTailCall)
2389    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2390
2391  // Add argument registers to the end of the list so that they are known live
2392  // into the call.
2393  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2394    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2395                                  RegsToPass[i].second.getValueType()));
2396
2397  // Add an implicit use GOT pointer in EBX.
2398  if (!isTailCall && Subtarget->isPICStyleGOT())
2399    Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2400
2401  // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2402  if (Is64Bit && isVarArg && !IsWin64)
2403    Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2404
2405  if (InFlag.getNode())
2406    Ops.push_back(InFlag);
2407
2408  if (isTailCall) {
2409    // We used to do:
2410    //// If this is the first return lowered for this function, add the regs
2411    //// to the liveout set for the function.
2412    // This isn't right, although it's probably harmless on x86; liveouts
2413    // should be computed from returns not tail calls.  Consider a void
2414    // function making a tail call to a function returning int.
2415    return DAG.getNode(X86ISD::TC_RETURN, dl,
2416                       NodeTys, &Ops[0], Ops.size());
2417  }
2418
2419  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2420  InFlag = Chain.getValue(1);
2421
2422  // Create the CALLSEQ_END node.
2423  unsigned NumBytesForCalleeToPush;
2424  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2425    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2426  else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2427    // If this is a call to a struct-return function, the callee
2428    // pops the hidden struct pointer, so we have to push it back.
2429    // This is common for Darwin/X86, Linux & Mingw32 targets.
2430    NumBytesForCalleeToPush = 4;
2431  else
2432    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2433
2434  // Returns a flag for retval copy to use.
2435  if (!IsSibcall) {
2436    Chain = DAG.getCALLSEQ_END(Chain,
2437                               DAG.getIntPtrConstant(NumBytes, true),
2438                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2439                                                     true),
2440                               InFlag);
2441    InFlag = Chain.getValue(1);
2442  }
2443
2444  // Handle result values, copying them out of physregs into vregs that we
2445  // return.
2446  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2447                         Ins, dl, DAG, InVals);
2448}
2449
2450
2451//===----------------------------------------------------------------------===//
2452//                Fast Calling Convention (tail call) implementation
2453//===----------------------------------------------------------------------===//
2454
2455//  Like std call, callee cleans arguments, convention except that ECX is
2456//  reserved for storing the tail called function address. Only 2 registers are
2457//  free for argument passing (inreg). Tail call optimization is performed
2458//  provided:
2459//                * tailcallopt is enabled
2460//                * caller/callee are fastcc
2461//  On X86_64 architecture with GOT-style position independent code only local
2462//  (within module) calls are supported at the moment.
2463//  To keep the stack aligned according to platform abi the function
2464//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2465//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2466//  If a tail called function callee has more arguments than the caller the
2467//  caller needs to make sure that there is room to move the RETADDR to. This is
2468//  achieved by reserving an area the size of the argument delta right after the
2469//  original REtADDR, but before the saved framepointer or the spilled registers
2470//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2471//  stack layout:
2472//    arg1
2473//    arg2
2474//    RETADDR
2475//    [ new RETADDR
2476//      move area ]
2477//    (possible EBP)
2478//    ESI
2479//    EDI
2480//    local1 ..
2481
2482/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2483/// for a 16 byte align requirement.
2484unsigned
2485X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2486                                               SelectionDAG& DAG) const {
2487  MachineFunction &MF = DAG.getMachineFunction();
2488  const TargetMachine &TM = MF.getTarget();
2489  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2490  unsigned StackAlignment = TFI.getStackAlignment();
2491  uint64_t AlignMask = StackAlignment - 1;
2492  int64_t Offset = StackSize;
2493  uint64_t SlotSize = TD->getPointerSize();
2494  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2495    // Number smaller than 12 so just add the difference.
2496    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2497  } else {
2498    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2499    Offset = ((~AlignMask) & Offset) + StackAlignment +
2500      (StackAlignment-SlotSize);
2501  }
2502  return Offset;
2503}
2504
2505/// MatchingStackOffset - Return true if the given stack call argument is
2506/// already available in the same position (relatively) of the caller's
2507/// incoming argument stack.
2508static
2509bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2510                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2511                         const X86InstrInfo *TII) {
2512  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2513  int FI = INT_MAX;
2514  if (Arg.getOpcode() == ISD::CopyFromReg) {
2515    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2516    if (!TargetRegisterInfo::isVirtualRegister(VR))
2517      return false;
2518    MachineInstr *Def = MRI->getVRegDef(VR);
2519    if (!Def)
2520      return false;
2521    if (!Flags.isByVal()) {
2522      if (!TII->isLoadFromStackSlot(Def, FI))
2523        return false;
2524    } else {
2525      unsigned Opcode = Def->getOpcode();
2526      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2527          Def->getOperand(1).isFI()) {
2528        FI = Def->getOperand(1).getIndex();
2529        Bytes = Flags.getByValSize();
2530      } else
2531        return false;
2532    }
2533  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2534    if (Flags.isByVal())
2535      // ByVal argument is passed in as a pointer but it's now being
2536      // dereferenced. e.g.
2537      // define @foo(%struct.X* %A) {
2538      //   tail call @bar(%struct.X* byval %A)
2539      // }
2540      return false;
2541    SDValue Ptr = Ld->getBasePtr();
2542    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2543    if (!FINode)
2544      return false;
2545    FI = FINode->getIndex();
2546  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2547    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2548    FI = FINode->getIndex();
2549    Bytes = Flags.getByValSize();
2550  } else
2551    return false;
2552
2553  assert(FI != INT_MAX);
2554  if (!MFI->isFixedObjectIndex(FI))
2555    return false;
2556  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2557}
2558
2559/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2560/// for tail call optimization. Targets which want to do tail call
2561/// optimization should implement this function.
2562bool
2563X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2564                                                     CallingConv::ID CalleeCC,
2565                                                     bool isVarArg,
2566                                                     bool isCalleeStructRet,
2567                                                     bool isCallerStructRet,
2568                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2569                                    const SmallVectorImpl<SDValue> &OutVals,
2570                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2571                                                     SelectionDAG& DAG) const {
2572  if (!IsTailCallConvention(CalleeCC) &&
2573      CalleeCC != CallingConv::C)
2574    return false;
2575
2576  // If -tailcallopt is specified, make fastcc functions tail-callable.
2577  const MachineFunction &MF = DAG.getMachineFunction();
2578  const Function *CallerF = DAG.getMachineFunction().getFunction();
2579  CallingConv::ID CallerCC = CallerF->getCallingConv();
2580  bool CCMatch = CallerCC == CalleeCC;
2581
2582  if (GuaranteedTailCallOpt) {
2583    if (IsTailCallConvention(CalleeCC) && CCMatch)
2584      return true;
2585    return false;
2586  }
2587
2588  // Look for obvious safe cases to perform tail call optimization that do not
2589  // require ABI changes. This is what gcc calls sibcall.
2590
2591  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2592  // emit a special epilogue.
2593  if (RegInfo->needsStackRealignment(MF))
2594    return false;
2595
2596  // Also avoid sibcall optimization if either caller or callee uses struct
2597  // return semantics.
2598  if (isCalleeStructRet || isCallerStructRet)
2599    return false;
2600
2601  // An stdcall caller is expected to clean up its arguments; the callee
2602  // isn't going to do that.
2603  if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2604    return false;
2605
2606  // Do not sibcall optimize vararg calls unless all arguments are passed via
2607  // registers.
2608  if (isVarArg && !Outs.empty()) {
2609
2610    // Optimizing for varargs on Win64 is unlikely to be safe without
2611    // additional testing.
2612    if (Subtarget->isTargetWin64())
2613      return false;
2614
2615    SmallVector<CCValAssign, 16> ArgLocs;
2616    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2617		   getTargetMachine(), ArgLocs, *DAG.getContext());
2618
2619    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2620    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2621      if (!ArgLocs[i].isRegLoc())
2622        return false;
2623  }
2624
2625  // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2626  // Therefore if it's not used by the call it is not safe to optimize this into
2627  // a sibcall.
2628  bool Unused = false;
2629  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2630    if (!Ins[i].Used) {
2631      Unused = true;
2632      break;
2633    }
2634  }
2635  if (Unused) {
2636    SmallVector<CCValAssign, 16> RVLocs;
2637    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2638		   getTargetMachine(), RVLocs, *DAG.getContext());
2639    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2640    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2641      CCValAssign &VA = RVLocs[i];
2642      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2643        return false;
2644    }
2645  }
2646
2647  // If the calling conventions do not match, then we'd better make sure the
2648  // results are returned in the same way as what the caller expects.
2649  if (!CCMatch) {
2650    SmallVector<CCValAssign, 16> RVLocs1;
2651    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2652		    getTargetMachine(), RVLocs1, *DAG.getContext());
2653    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2654
2655    SmallVector<CCValAssign, 16> RVLocs2;
2656    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2657		    getTargetMachine(), RVLocs2, *DAG.getContext());
2658    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2659
2660    if (RVLocs1.size() != RVLocs2.size())
2661      return false;
2662    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2663      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2664        return false;
2665      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2666        return false;
2667      if (RVLocs1[i].isRegLoc()) {
2668        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2669          return false;
2670      } else {
2671        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2672          return false;
2673      }
2674    }
2675  }
2676
2677  // If the callee takes no arguments then go on to check the results of the
2678  // call.
2679  if (!Outs.empty()) {
2680    // Check if stack adjustment is needed. For now, do not do this if any
2681    // argument is passed on the stack.
2682    SmallVector<CCValAssign, 16> ArgLocs;
2683    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2684		   getTargetMachine(), ArgLocs, *DAG.getContext());
2685
2686    // Allocate shadow area for Win64
2687    if (Subtarget->isTargetWin64()) {
2688      CCInfo.AllocateStack(32, 8);
2689    }
2690
2691    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2692    if (CCInfo.getNextStackOffset()) {
2693      MachineFunction &MF = DAG.getMachineFunction();
2694      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2695        return false;
2696
2697      // Check if the arguments are already laid out in the right way as
2698      // the caller's fixed stack objects.
2699      MachineFrameInfo *MFI = MF.getFrameInfo();
2700      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2701      const X86InstrInfo *TII =
2702        ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2703      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2704        CCValAssign &VA = ArgLocs[i];
2705        SDValue Arg = OutVals[i];
2706        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2707        if (VA.getLocInfo() == CCValAssign::Indirect)
2708          return false;
2709        if (!VA.isRegLoc()) {
2710          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2711                                   MFI, MRI, TII))
2712            return false;
2713        }
2714      }
2715    }
2716
2717    // If the tailcall address may be in a register, then make sure it's
2718    // possible to register allocate for it. In 32-bit, the call address can
2719    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2720    // callee-saved registers are restored. These happen to be the same
2721    // registers used to pass 'inreg' arguments so watch out for those.
2722    if (!Subtarget->is64Bit() &&
2723        !isa<GlobalAddressSDNode>(Callee) &&
2724        !isa<ExternalSymbolSDNode>(Callee)) {
2725      unsigned NumInRegs = 0;
2726      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2727        CCValAssign &VA = ArgLocs[i];
2728        if (!VA.isRegLoc())
2729          continue;
2730        unsigned Reg = VA.getLocReg();
2731        switch (Reg) {
2732        default: break;
2733        case X86::EAX: case X86::EDX: case X86::ECX:
2734          if (++NumInRegs == 3)
2735            return false;
2736          break;
2737        }
2738      }
2739    }
2740  }
2741
2742  return true;
2743}
2744
2745FastISel *
2746X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2747  return X86::createFastISel(funcInfo);
2748}
2749
2750
2751//===----------------------------------------------------------------------===//
2752//                           Other Lowering Hooks
2753//===----------------------------------------------------------------------===//
2754
2755static bool MayFoldLoad(SDValue Op) {
2756  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2757}
2758
2759static bool MayFoldIntoStore(SDValue Op) {
2760  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2761}
2762
2763static bool isTargetShuffle(unsigned Opcode) {
2764  switch(Opcode) {
2765  default: return false;
2766  case X86ISD::PSHUFD:
2767  case X86ISD::PSHUFHW:
2768  case X86ISD::PSHUFLW:
2769  case X86ISD::SHUFPD:
2770  case X86ISD::PALIGN:
2771  case X86ISD::SHUFPS:
2772  case X86ISD::MOVLHPS:
2773  case X86ISD::MOVLHPD:
2774  case X86ISD::MOVHLPS:
2775  case X86ISD::MOVLPS:
2776  case X86ISD::MOVLPD:
2777  case X86ISD::MOVSHDUP:
2778  case X86ISD::MOVSLDUP:
2779  case X86ISD::MOVDDUP:
2780  case X86ISD::MOVSS:
2781  case X86ISD::MOVSD:
2782  case X86ISD::UNPCKLPS:
2783  case X86ISD::UNPCKLPD:
2784  case X86ISD::VUNPCKLPSY:
2785  case X86ISD::VUNPCKLPDY:
2786  case X86ISD::PUNPCKLWD:
2787  case X86ISD::PUNPCKLBW:
2788  case X86ISD::PUNPCKLDQ:
2789  case X86ISD::PUNPCKLQDQ:
2790  case X86ISD::UNPCKHPS:
2791  case X86ISD::UNPCKHPD:
2792  case X86ISD::VUNPCKHPSY:
2793  case X86ISD::VUNPCKHPDY:
2794  case X86ISD::PUNPCKHWD:
2795  case X86ISD::PUNPCKHBW:
2796  case X86ISD::PUNPCKHDQ:
2797  case X86ISD::PUNPCKHQDQ:
2798  case X86ISD::VPERMILPS:
2799  case X86ISD::VPERMILPSY:
2800  case X86ISD::VPERMILPD:
2801  case X86ISD::VPERMILPDY:
2802  case X86ISD::VPERM2F128:
2803    return true;
2804  }
2805  return false;
2806}
2807
2808static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2809                                               SDValue V1, SelectionDAG &DAG) {
2810  switch(Opc) {
2811  default: llvm_unreachable("Unknown x86 shuffle node");
2812  case X86ISD::MOVSHDUP:
2813  case X86ISD::MOVSLDUP:
2814  case X86ISD::MOVDDUP:
2815    return DAG.getNode(Opc, dl, VT, V1);
2816  }
2817
2818  return SDValue();
2819}
2820
2821static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2822                          SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2823  switch(Opc) {
2824  default: llvm_unreachable("Unknown x86 shuffle node");
2825  case X86ISD::PSHUFD:
2826  case X86ISD::PSHUFHW:
2827  case X86ISD::PSHUFLW:
2828  case X86ISD::VPERMILPS:
2829  case X86ISD::VPERMILPSY:
2830  case X86ISD::VPERMILPD:
2831  case X86ISD::VPERMILPDY:
2832    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2833  }
2834
2835  return SDValue();
2836}
2837
2838static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2839               SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2840  switch(Opc) {
2841  default: llvm_unreachable("Unknown x86 shuffle node");
2842  case X86ISD::PALIGN:
2843  case X86ISD::SHUFPD:
2844  case X86ISD::SHUFPS:
2845  case X86ISD::VPERM2F128:
2846    return DAG.getNode(Opc, dl, VT, V1, V2,
2847                       DAG.getConstant(TargetMask, MVT::i8));
2848  }
2849  return SDValue();
2850}
2851
2852static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2853                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
2854  switch(Opc) {
2855  default: llvm_unreachable("Unknown x86 shuffle node");
2856  case X86ISD::MOVLHPS:
2857  case X86ISD::MOVLHPD:
2858  case X86ISD::MOVHLPS:
2859  case X86ISD::MOVLPS:
2860  case X86ISD::MOVLPD:
2861  case X86ISD::MOVSS:
2862  case X86ISD::MOVSD:
2863  case X86ISD::UNPCKLPS:
2864  case X86ISD::UNPCKLPD:
2865  case X86ISD::VUNPCKLPSY:
2866  case X86ISD::VUNPCKLPDY:
2867  case X86ISD::PUNPCKLWD:
2868  case X86ISD::PUNPCKLBW:
2869  case X86ISD::PUNPCKLDQ:
2870  case X86ISD::PUNPCKLQDQ:
2871  case X86ISD::UNPCKHPS:
2872  case X86ISD::UNPCKHPD:
2873  case X86ISD::VUNPCKHPSY:
2874  case X86ISD::VUNPCKHPDY:
2875  case X86ISD::PUNPCKHWD:
2876  case X86ISD::PUNPCKHBW:
2877  case X86ISD::PUNPCKHDQ:
2878  case X86ISD::PUNPCKHQDQ:
2879    return DAG.getNode(Opc, dl, VT, V1, V2);
2880  }
2881  return SDValue();
2882}
2883
2884SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2885  MachineFunction &MF = DAG.getMachineFunction();
2886  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2887  int ReturnAddrIndex = FuncInfo->getRAIndex();
2888
2889  if (ReturnAddrIndex == 0) {
2890    // Set up a frame object for the return address.
2891    uint64_t SlotSize = TD->getPointerSize();
2892    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2893                                                           false);
2894    FuncInfo->setRAIndex(ReturnAddrIndex);
2895  }
2896
2897  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2898}
2899
2900
2901bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2902                                       bool hasSymbolicDisplacement) {
2903  // Offset should fit into 32 bit immediate field.
2904  if (!isInt<32>(Offset))
2905    return false;
2906
2907  // If we don't have a symbolic displacement - we don't have any extra
2908  // restrictions.
2909  if (!hasSymbolicDisplacement)
2910    return true;
2911
2912  // FIXME: Some tweaks might be needed for medium code model.
2913  if (M != CodeModel::Small && M != CodeModel::Kernel)
2914    return false;
2915
2916  // For small code model we assume that latest object is 16MB before end of 31
2917  // bits boundary. We may also accept pretty large negative constants knowing
2918  // that all objects are in the positive half of address space.
2919  if (M == CodeModel::Small && Offset < 16*1024*1024)
2920    return true;
2921
2922  // For kernel code model we know that all object resist in the negative half
2923  // of 32bits address space. We may not accept negative offsets, since they may
2924  // be just off and we may accept pretty large positive ones.
2925  if (M == CodeModel::Kernel && Offset > 0)
2926    return true;
2927
2928  return false;
2929}
2930
2931/// isCalleePop - Determines whether the callee is required to pop its
2932/// own arguments. Callee pop is necessary to support tail calls.
2933bool X86::isCalleePop(CallingConv::ID CallingConv,
2934                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2935  if (IsVarArg)
2936    return false;
2937
2938  switch (CallingConv) {
2939  default:
2940    return false;
2941  case CallingConv::X86_StdCall:
2942    return !is64Bit;
2943  case CallingConv::X86_FastCall:
2944    return !is64Bit;
2945  case CallingConv::X86_ThisCall:
2946    return !is64Bit;
2947  case CallingConv::Fast:
2948    return TailCallOpt;
2949  case CallingConv::GHC:
2950    return TailCallOpt;
2951  }
2952}
2953
2954/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2955/// specific condition code, returning the condition code and the LHS/RHS of the
2956/// comparison to make.
2957static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2958                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2959  if (!isFP) {
2960    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2961      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2962        // X > -1   -> X == 0, jump !sign.
2963        RHS = DAG.getConstant(0, RHS.getValueType());
2964        return X86::COND_NS;
2965      } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2966        // X < 0   -> X == 0, jump on sign.
2967        return X86::COND_S;
2968      } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2969        // X < 1   -> X <= 0
2970        RHS = DAG.getConstant(0, RHS.getValueType());
2971        return X86::COND_LE;
2972      }
2973    }
2974
2975    switch (SetCCOpcode) {
2976    default: llvm_unreachable("Invalid integer condition!");
2977    case ISD::SETEQ:  return X86::COND_E;
2978    case ISD::SETGT:  return X86::COND_G;
2979    case ISD::SETGE:  return X86::COND_GE;
2980    case ISD::SETLT:  return X86::COND_L;
2981    case ISD::SETLE:  return X86::COND_LE;
2982    case ISD::SETNE:  return X86::COND_NE;
2983    case ISD::SETULT: return X86::COND_B;
2984    case ISD::SETUGT: return X86::COND_A;
2985    case ISD::SETULE: return X86::COND_BE;
2986    case ISD::SETUGE: return X86::COND_AE;
2987    }
2988  }
2989
2990  // First determine if it is required or is profitable to flip the operands.
2991
2992  // If LHS is a foldable load, but RHS is not, flip the condition.
2993  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2994      !ISD::isNON_EXTLoad(RHS.getNode())) {
2995    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2996    std::swap(LHS, RHS);
2997  }
2998
2999  switch (SetCCOpcode) {
3000  default: break;
3001  case ISD::SETOLT:
3002  case ISD::SETOLE:
3003  case ISD::SETUGT:
3004  case ISD::SETUGE:
3005    std::swap(LHS, RHS);
3006    break;
3007  }
3008
3009  // On a floating point condition, the flags are set as follows:
3010  // ZF  PF  CF   op
3011  //  0 | 0 | 0 | X > Y
3012  //  0 | 0 | 1 | X < Y
3013  //  1 | 0 | 0 | X == Y
3014  //  1 | 1 | 1 | unordered
3015  switch (SetCCOpcode) {
3016  default: llvm_unreachable("Condcode should be pre-legalized away");
3017  case ISD::SETUEQ:
3018  case ISD::SETEQ:   return X86::COND_E;
3019  case ISD::SETOLT:              // flipped
3020  case ISD::SETOGT:
3021  case ISD::SETGT:   return X86::COND_A;
3022  case ISD::SETOLE:              // flipped
3023  case ISD::SETOGE:
3024  case ISD::SETGE:   return X86::COND_AE;
3025  case ISD::SETUGT:              // flipped
3026  case ISD::SETULT:
3027  case ISD::SETLT:   return X86::COND_B;
3028  case ISD::SETUGE:              // flipped
3029  case ISD::SETULE:
3030  case ISD::SETLE:   return X86::COND_BE;
3031  case ISD::SETONE:
3032  case ISD::SETNE:   return X86::COND_NE;
3033  case ISD::SETUO:   return X86::COND_P;
3034  case ISD::SETO:    return X86::COND_NP;
3035  case ISD::SETOEQ:
3036  case ISD::SETUNE:  return X86::COND_INVALID;
3037  }
3038}
3039
3040/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3041/// code. Current x86 isa includes the following FP cmov instructions:
3042/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3043static bool hasFPCMov(unsigned X86CC) {
3044  switch (X86CC) {
3045  default:
3046    return false;
3047  case X86::COND_B:
3048  case X86::COND_BE:
3049  case X86::COND_E:
3050  case X86::COND_P:
3051  case X86::COND_A:
3052  case X86::COND_AE:
3053  case X86::COND_NE:
3054  case X86::COND_NP:
3055    return true;
3056  }
3057}
3058
3059/// isFPImmLegal - Returns true if the target can instruction select the
3060/// specified FP immediate natively. If false, the legalizer will
3061/// materialize the FP immediate as a load from a constant pool.
3062bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3063  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3064    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3065      return true;
3066  }
3067  return false;
3068}
3069
3070/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3071/// the specified range (L, H].
3072static bool isUndefOrInRange(int Val, int Low, int Hi) {
3073  return (Val < 0) || (Val >= Low && Val < Hi);
3074}
3075
3076/// isUndefOrInRange - Return true if every element in Mask, begining
3077/// from position Pos and ending in Pos+Size, falls within the specified
3078/// range (L, L+Pos]. or is undef.
3079static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3080                             int Pos, int Size, int Low, int Hi) {
3081  for (int i = Pos, e = Pos+Size; i != e; ++i)
3082    if (!isUndefOrInRange(Mask[i], Low, Hi))
3083      return false;
3084  return true;
3085}
3086
3087/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3088/// specified value.
3089static bool isUndefOrEqual(int Val, int CmpVal) {
3090  if (Val < 0 || Val == CmpVal)
3091    return true;
3092  return false;
3093}
3094
3095/// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3096/// from position Pos and ending in Pos+Size, falls within the specified
3097/// sequential range (L, L+Pos]. or is undef.
3098static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3099                                       int Pos, int Size, int Low) {
3100  for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3101    if (!isUndefOrEqual(Mask[i], Low))
3102      return false;
3103  return true;
3104}
3105
3106/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3107/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3108/// the second operand.
3109static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3110  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3111    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3112  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3113    return (Mask[0] < 2 && Mask[1] < 2);
3114  return false;
3115}
3116
3117bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3118  SmallVector<int, 8> M;
3119  N->getMask(M);
3120  return ::isPSHUFDMask(M, N->getValueType(0));
3121}
3122
3123/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3124/// is suitable for input to PSHUFHW.
3125static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3126  if (VT != MVT::v8i16)
3127    return false;
3128
3129  // Lower quadword copied in order or undef.
3130  for (int i = 0; i != 4; ++i)
3131    if (Mask[i] >= 0 && Mask[i] != i)
3132      return false;
3133
3134  // Upper quadword shuffled.
3135  for (int i = 4; i != 8; ++i)
3136    if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3137      return false;
3138
3139  return true;
3140}
3141
3142bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3143  SmallVector<int, 8> M;
3144  N->getMask(M);
3145  return ::isPSHUFHWMask(M, N->getValueType(0));
3146}
3147
3148/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3149/// is suitable for input to PSHUFLW.
3150static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3151  if (VT != MVT::v8i16)
3152    return false;
3153
3154  // Upper quadword copied in order.
3155  for (int i = 4; i != 8; ++i)
3156    if (Mask[i] >= 0 && Mask[i] != i)
3157      return false;
3158
3159  // Lower quadword shuffled.
3160  for (int i = 0; i != 4; ++i)
3161    if (Mask[i] >= 4)
3162      return false;
3163
3164  return true;
3165}
3166
3167bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3168  SmallVector<int, 8> M;
3169  N->getMask(M);
3170  return ::isPSHUFLWMask(M, N->getValueType(0));
3171}
3172
3173/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3174/// is suitable for input to PALIGNR.
3175static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3176                          bool hasSSSE3) {
3177  int i, e = VT.getVectorNumElements();
3178  if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3179    return false;
3180
3181  // Do not handle v2i64 / v2f64 shuffles with palignr.
3182  if (e < 4 || !hasSSSE3)
3183    return false;
3184
3185  for (i = 0; i != e; ++i)
3186    if (Mask[i] >= 0)
3187      break;
3188
3189  // All undef, not a palignr.
3190  if (i == e)
3191    return false;
3192
3193  // Make sure we're shifting in the right direction.
3194  if (Mask[i] <= i)
3195    return false;
3196
3197  int s = Mask[i] - i;
3198
3199  // Check the rest of the elements to see if they are consecutive.
3200  for (++i; i != e; ++i) {
3201    int m = Mask[i];
3202    if (m >= 0 && m != s+i)
3203      return false;
3204  }
3205  return true;
3206}
3207
3208/// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3209/// specifies a shuffle of elements that is suitable for input to 256-bit
3210/// VSHUFPSY.
3211static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3212                          const X86Subtarget *Subtarget) {
3213  int NumElems = VT.getVectorNumElements();
3214
3215  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3216    return false;
3217
3218  if (NumElems != 8)
3219    return false;
3220
3221  // VSHUFPSY divides the resulting vector into 4 chunks.
3222  // The sources are also splitted into 4 chunks, and each destination
3223  // chunk must come from a different source chunk.
3224  //
3225  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3226  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3227  //
3228  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3229  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3230  //
3231  int QuarterSize = NumElems/4;
3232  int HalfSize = QuarterSize*2;
3233  for (int i = 0; i < QuarterSize; ++i)
3234    if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3235      return false;
3236  for (int i = QuarterSize; i < QuarterSize*2; ++i)
3237    if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3238      return false;
3239
3240  // The mask of the second half must be the same as the first but with
3241  // the appropriate offsets. This works in the same way as VPERMILPS
3242  // works with masks.
3243  for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3244    if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3245      return false;
3246    int FstHalfIdx = i-HalfSize;
3247    if (Mask[FstHalfIdx] < 0)
3248      continue;
3249    if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3250      return false;
3251  }
3252  for (int i = QuarterSize*3; i < NumElems; ++i) {
3253    if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3254      return false;
3255    int FstHalfIdx = i-HalfSize;
3256    if (Mask[FstHalfIdx] < 0)
3257      continue;
3258    if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3259      return false;
3260
3261  }
3262
3263  return true;
3264}
3265
3266/// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3267/// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3268static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3269  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3270  EVT VT = SVOp->getValueType(0);
3271  int NumElems = VT.getVectorNumElements();
3272
3273  assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3274         "Only supports v8i32 and v8f32 types");
3275
3276  int HalfSize = NumElems/2;
3277  unsigned Mask = 0;
3278  for (int i = 0; i != NumElems ; ++i) {
3279    if (SVOp->getMaskElt(i) < 0)
3280      continue;
3281    // The mask of the first half must be equal to the second one.
3282    unsigned Shamt = (i%HalfSize)*2;
3283    unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3284    Mask |= Elt << Shamt;
3285  }
3286
3287  return Mask;
3288}
3289
3290/// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3291/// specifies a shuffle of elements that is suitable for input to 256-bit
3292/// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3293/// version and the mask of the second half isn't binded with the first
3294/// one.
3295static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3296                           const X86Subtarget *Subtarget) {
3297  int NumElems = VT.getVectorNumElements();
3298
3299  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3300    return false;
3301
3302  if (NumElems != 4)
3303    return false;
3304
3305  // VSHUFPSY divides the resulting vector into 4 chunks.
3306  // The sources are also splitted into 4 chunks, and each destination
3307  // chunk must come from a different source chunk.
3308  //
3309  //  SRC1 =>      X3       X2       X1       X0
3310  //  SRC2 =>      Y3       Y2       Y1       Y0
3311  //
3312  //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3313  //
3314  int QuarterSize = NumElems/4;
3315  int HalfSize = QuarterSize*2;
3316  for (int i = 0; i < QuarterSize; ++i)
3317    if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3318      return false;
3319  for (int i = QuarterSize; i < QuarterSize*2; ++i)
3320    if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3321      return false;
3322  for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3323    if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3324      return false;
3325  for (int i = QuarterSize*3; i < NumElems; ++i)
3326    if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3327      return false;
3328
3329  return true;
3330}
3331
3332/// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3333/// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3334static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3335  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3336  EVT VT = SVOp->getValueType(0);
3337  int NumElems = VT.getVectorNumElements();
3338
3339  assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3340         "Only supports v4i64 and v4f64 types");
3341
3342  int HalfSize = NumElems/2;
3343  unsigned Mask = 0;
3344  for (int i = 0; i != NumElems ; ++i) {
3345    if (SVOp->getMaskElt(i) < 0)
3346      continue;
3347    int Elt = SVOp->getMaskElt(i) % HalfSize;
3348    Mask |= Elt << i;
3349  }
3350
3351  return Mask;
3352}
3353
3354/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3355/// specifies a shuffle of elements that is suitable for input to 128-bit
3356/// SHUFPS and SHUFPD.
3357static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3358  int NumElems = VT.getVectorNumElements();
3359
3360  if (VT.getSizeInBits() != 128)
3361    return false;
3362
3363  if (NumElems != 2 && NumElems != 4)
3364    return false;
3365
3366  int Half = NumElems / 2;
3367  for (int i = 0; i < Half; ++i)
3368    if (!isUndefOrInRange(Mask[i], 0, NumElems))
3369      return false;
3370  for (int i = Half; i < NumElems; ++i)
3371    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3372      return false;
3373
3374  return true;
3375}
3376
3377bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3378  SmallVector<int, 8> M;
3379  N->getMask(M);
3380  return ::isSHUFPMask(M, N->getValueType(0));
3381}
3382
3383/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3384/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3385/// half elements to come from vector 1 (which would equal the dest.) and
3386/// the upper half to come from vector 2.
3387static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3388  int NumElems = VT.getVectorNumElements();
3389
3390  if (NumElems != 2 && NumElems != 4)
3391    return false;
3392
3393  int Half = NumElems / 2;
3394  for (int i = 0; i < Half; ++i)
3395    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3396      return false;
3397  for (int i = Half; i < NumElems; ++i)
3398    if (!isUndefOrInRange(Mask[i], 0, NumElems))
3399      return false;
3400  return true;
3401}
3402
3403static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3404  SmallVector<int, 8> M;
3405  N->getMask(M);
3406  return isCommutedSHUFPMask(M, N->getValueType(0));
3407}
3408
3409/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3410/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3411bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3412  EVT VT = N->getValueType(0);
3413  unsigned NumElems = VT.getVectorNumElements();
3414
3415  if (VT.getSizeInBits() != 128)
3416    return false;
3417
3418  if (NumElems != 4)
3419    return false;
3420
3421  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3422  return isUndefOrEqual(N->getMaskElt(0), 6) &&
3423         isUndefOrEqual(N->getMaskElt(1), 7) &&
3424         isUndefOrEqual(N->getMaskElt(2), 2) &&
3425         isUndefOrEqual(N->getMaskElt(3), 3);
3426}
3427
3428/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3429/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3430/// <2, 3, 2, 3>
3431bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3432  EVT VT = N->getValueType(0);
3433  unsigned NumElems = VT.getVectorNumElements();
3434
3435  if (VT.getSizeInBits() != 128)
3436    return false;
3437
3438  if (NumElems != 4)
3439    return false;
3440
3441  return isUndefOrEqual(N->getMaskElt(0), 2) &&
3442         isUndefOrEqual(N->getMaskElt(1), 3) &&
3443         isUndefOrEqual(N->getMaskElt(2), 2) &&
3444         isUndefOrEqual(N->getMaskElt(3), 3);
3445}
3446
3447/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3448/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3449bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3450  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3451
3452  if (NumElems != 2 && NumElems != 4)
3453    return false;
3454
3455  for (unsigned i = 0; i < NumElems/2; ++i)
3456    if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3457      return false;
3458
3459  for (unsigned i = NumElems/2; i < NumElems; ++i)
3460    if (!isUndefOrEqual(N->getMaskElt(i), i))
3461      return false;
3462
3463  return true;
3464}
3465
3466/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3467/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3468bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3469  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3470
3471  if ((NumElems != 2 && NumElems != 4)
3472      || N->getValueType(0).getSizeInBits() > 128)
3473    return false;
3474
3475  for (unsigned i = 0; i < NumElems/2; ++i)
3476    if (!isUndefOrEqual(N->getMaskElt(i), i))
3477      return false;
3478
3479  for (unsigned i = 0; i < NumElems/2; ++i)
3480    if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3481      return false;
3482
3483  return true;
3484}
3485
3486/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3487/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3488static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3489                         bool V2IsSplat = false) {
3490  int NumElts = VT.getVectorNumElements();
3491
3492  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3493         "Unsupported vector type for unpckh");
3494
3495  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3496    return false;
3497
3498  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3499  // independently on 128-bit lanes.
3500  unsigned NumLanes = VT.getSizeInBits()/128;
3501  unsigned NumLaneElts = NumElts/NumLanes;
3502
3503  unsigned Start = 0;
3504  unsigned End = NumLaneElts;
3505  for (unsigned s = 0; s < NumLanes; ++s) {
3506    for (unsigned i = Start, j = s * NumLaneElts;
3507         i != End;
3508         i += 2, ++j) {
3509      int BitI  = Mask[i];
3510      int BitI1 = Mask[i+1];
3511      if (!isUndefOrEqual(BitI, j))
3512        return false;
3513      if (V2IsSplat) {
3514        if (!isUndefOrEqual(BitI1, NumElts))
3515          return false;
3516      } else {
3517        if (!isUndefOrEqual(BitI1, j + NumElts))
3518          return false;
3519      }
3520    }
3521    // Process the next 128 bits.
3522    Start += NumLaneElts;
3523    End += NumLaneElts;
3524  }
3525
3526  return true;
3527}
3528
3529bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3530  SmallVector<int, 8> M;
3531  N->getMask(M);
3532  return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3533}
3534
3535/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3536/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3537static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3538                         bool V2IsSplat = false) {
3539  int NumElts = VT.getVectorNumElements();
3540
3541  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3542         "Unsupported vector type for unpckh");
3543
3544  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3545    return false;
3546
3547  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3548  // independently on 128-bit lanes.
3549  unsigned NumLanes = VT.getSizeInBits()/128;
3550  unsigned NumLaneElts = NumElts/NumLanes;
3551
3552  unsigned Start = 0;
3553  unsigned End = NumLaneElts;
3554  for (unsigned l = 0; l != NumLanes; ++l) {
3555    for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3556                             i != End; i += 2, ++j) {
3557      int BitI  = Mask[i];
3558      int BitI1 = Mask[i+1];
3559      if (!isUndefOrEqual(BitI, j))
3560        return false;
3561      if (V2IsSplat) {
3562        if (isUndefOrEqual(BitI1, NumElts))
3563          return false;
3564      } else {
3565        if (!isUndefOrEqual(BitI1, j+NumElts))
3566          return false;
3567      }
3568    }
3569    // Process the next 128 bits.
3570    Start += NumLaneElts;
3571    End += NumLaneElts;
3572  }
3573  return true;
3574}
3575
3576bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3577  SmallVector<int, 8> M;
3578  N->getMask(M);
3579  return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3580}
3581
3582/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3583/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3584/// <0, 0, 1, 1>
3585static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3586  int NumElems = VT.getVectorNumElements();
3587  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3588    return false;
3589
3590  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3591  // FIXME: Need a better way to get rid of this, there's no latency difference
3592  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3593  // the former later. We should also remove the "_undef" special mask.
3594  if (NumElems == 4 && VT.getSizeInBits() == 256)
3595    return false;
3596
3597  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3598  // independently on 128-bit lanes.
3599  unsigned NumLanes = VT.getSizeInBits() / 128;
3600  unsigned NumLaneElts = NumElems / NumLanes;
3601
3602  for (unsigned s = 0; s < NumLanes; ++s) {
3603    for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3604         i != NumLaneElts * (s + 1);
3605         i += 2, ++j) {
3606      int BitI  = Mask[i];
3607      int BitI1 = Mask[i+1];
3608
3609      if (!isUndefOrEqual(BitI, j))
3610        return false;
3611      if (!isUndefOrEqual(BitI1, j))
3612        return false;
3613    }
3614  }
3615
3616  return true;
3617}
3618
3619bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3620  SmallVector<int, 8> M;
3621  N->getMask(M);
3622  return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3623}
3624
3625/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3626/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3627/// <2, 2, 3, 3>
3628static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3629  int NumElems = VT.getVectorNumElements();
3630  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3631    return false;
3632
3633  for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3634    int BitI  = Mask[i];
3635    int BitI1 = Mask[i+1];
3636    if (!isUndefOrEqual(BitI, j))
3637      return false;
3638    if (!isUndefOrEqual(BitI1, j))
3639      return false;
3640  }
3641  return true;
3642}
3643
3644bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3645  SmallVector<int, 8> M;
3646  N->getMask(M);
3647  return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3648}
3649
3650/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3651/// specifies a shuffle of elements that is suitable for input to MOVSS,
3652/// MOVSD, and MOVD, i.e. setting the lowest element.
3653static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3654  if (VT.getVectorElementType().getSizeInBits() < 32)
3655    return false;
3656
3657  int NumElts = VT.getVectorNumElements();
3658
3659  if (!isUndefOrEqual(Mask[0], NumElts))
3660    return false;
3661
3662  for (int i = 1; i < NumElts; ++i)
3663    if (!isUndefOrEqual(Mask[i], i))
3664      return false;
3665
3666  return true;
3667}
3668
3669bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3670  SmallVector<int, 8> M;
3671  N->getMask(M);
3672  return ::isMOVLMask(M, N->getValueType(0));
3673}
3674
3675/// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3676/// as permutations between 128-bit chunks or halves. As an example: this
3677/// shuffle bellow:
3678///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3679/// The first half comes from the second half of V1 and the second half from the
3680/// the second half of V2.
3681static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3682                             const X86Subtarget *Subtarget) {
3683  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3684    return false;
3685
3686  // The shuffle result is divided into half A and half B. In total the two
3687  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3688  // B must come from C, D, E or F.
3689  int HalfSize = VT.getVectorNumElements()/2;
3690  bool MatchA = false, MatchB = false;
3691
3692  // Check if A comes from one of C, D, E, F.
3693  for (int Half = 0; Half < 4; ++Half) {
3694    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3695      MatchA = true;
3696      break;
3697    }
3698  }
3699
3700  // Check if B comes from one of C, D, E, F.
3701  for (int Half = 0; Half < 4; ++Half) {
3702    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3703      MatchB = true;
3704      break;
3705    }
3706  }
3707
3708  return MatchA && MatchB;
3709}
3710
3711/// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3712/// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3713static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3714  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3715  EVT VT = SVOp->getValueType(0);
3716
3717  int HalfSize = VT.getVectorNumElements()/2;
3718
3719  int FstHalf = 0, SndHalf = 0;
3720  for (int i = 0; i < HalfSize; ++i) {
3721    if (SVOp->getMaskElt(i) > 0) {
3722      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3723      break;
3724    }
3725  }
3726  for (int i = HalfSize; i < HalfSize*2; ++i) {
3727    if (SVOp->getMaskElt(i) > 0) {
3728      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3729      break;
3730    }
3731  }
3732
3733  return (FstHalf | (SndHalf << 4));
3734}
3735
3736/// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3737/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3738/// Note that VPERMIL mask matching is different depending whether theunderlying
3739/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3740/// to the same elements of the low, but to the higher half of the source.
3741/// In VPERMILPD the two lanes could be shuffled independently of each other
3742/// with the same restriction that lanes can't be crossed.
3743static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3744                            const X86Subtarget *Subtarget) {
3745  int NumElts = VT.getVectorNumElements();
3746  int NumLanes = VT.getSizeInBits()/128;
3747
3748  if (!Subtarget->hasAVX())
3749    return false;
3750
3751  // Match any permutation of 128-bit vector with 64-bit types
3752  if (NumLanes == 1 && NumElts != 2)
3753    return false;
3754
3755  // Only match 256-bit with 32 types
3756  if (VT.getSizeInBits() == 256 && NumElts != 4)
3757    return false;
3758
3759  // The mask on the high lane is independent of the low. Both can match
3760  // any element in inside its own lane, but can't cross.
3761  int LaneSize = NumElts/NumLanes;
3762  for (int l = 0; l < NumLanes; ++l)
3763    for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3764      int LaneStart = l*LaneSize;
3765      if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3766        return false;
3767    }
3768
3769  return true;
3770}
3771
3772/// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3773/// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3774/// Note that VPERMIL mask matching is different depending whether theunderlying
3775/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3776/// to the same elements of the low, but to the higher half of the source.
3777/// In VPERMILPD the two lanes could be shuffled independently of each other
3778/// with the same restriction that lanes can't be crossed.
3779static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3780                            const X86Subtarget *Subtarget) {
3781  unsigned NumElts = VT.getVectorNumElements();
3782  unsigned NumLanes = VT.getSizeInBits()/128;
3783
3784  if (!Subtarget->hasAVX())
3785    return false;
3786
3787  // Match any permutation of 128-bit vector with 32-bit types
3788  if (NumLanes == 1 && NumElts != 4)
3789    return false;
3790
3791  // Only match 256-bit with 32 types
3792  if (VT.getSizeInBits() == 256 && NumElts != 8)
3793    return false;
3794
3795  // The mask on the high lane should be the same as the low. Actually,
3796  // they can differ if any of the corresponding index in a lane is undef
3797  // and the other stays in range.
3798  int LaneSize = NumElts/NumLanes;
3799  for (int i = 0; i < LaneSize; ++i) {
3800    int HighElt = i+LaneSize;
3801    bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3802    bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3803
3804    if (!HighValid || !LowValid)
3805      return false;
3806    if (Mask[i] < 0 || Mask[HighElt] < 0)
3807      continue;
3808    if (Mask[HighElt]-Mask[i] != LaneSize)
3809      return false;
3810  }
3811
3812  return true;
3813}
3814
3815/// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3816/// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3817static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3818  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3819  EVT VT = SVOp->getValueType(0);
3820
3821  int NumElts = VT.getVectorNumElements();
3822  int NumLanes = VT.getSizeInBits()/128;
3823  int LaneSize = NumElts/NumLanes;
3824
3825  // Although the mask is equal for both lanes do it twice to get the cases
3826  // where a mask will match because the same mask element is undef on the
3827  // first half but valid on the second. This would get pathological cases
3828  // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3829  unsigned Mask = 0;
3830  for (int l = 0; l < NumLanes; ++l) {
3831    for (int i = 0; i < LaneSize; ++i) {
3832      int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3833      if (MaskElt < 0)
3834        continue;
3835      if (MaskElt >= LaneSize)
3836        MaskElt -= LaneSize;
3837      Mask |= MaskElt << (i*2);
3838    }
3839  }
3840
3841  return Mask;
3842}
3843
3844/// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3845/// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3846static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3847  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3848  EVT VT = SVOp->getValueType(0);
3849
3850  int NumElts = VT.getVectorNumElements();
3851  int NumLanes = VT.getSizeInBits()/128;
3852
3853  unsigned Mask = 0;
3854  int LaneSize = NumElts/NumLanes;
3855  for (int l = 0; l < NumLanes; ++l)
3856    for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3857      int MaskElt = SVOp->getMaskElt(i);
3858      if (MaskElt < 0)
3859        continue;
3860      Mask |= (MaskElt-l*LaneSize) << i;
3861    }
3862
3863  return Mask;
3864}
3865
3866/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3867/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3868/// element of vector 2 and the other elements to come from vector 1 in order.
3869static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3870                               bool V2IsSplat = false, bool V2IsUndef = false) {
3871  int NumOps = VT.getVectorNumElements();
3872  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3873    return false;
3874
3875  if (!isUndefOrEqual(Mask[0], 0))
3876    return false;
3877
3878  for (int i = 1; i < NumOps; ++i)
3879    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3880          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3881          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3882      return false;
3883
3884  return true;
3885}
3886
3887static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3888                           bool V2IsUndef = false) {
3889  SmallVector<int, 8> M;
3890  N->getMask(M);
3891  return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3892}
3893
3894/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3895/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3896/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3897bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3898                         const X86Subtarget *Subtarget) {
3899  if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3900    return false;
3901
3902  // The second vector must be undef
3903  if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3904    return false;
3905
3906  EVT VT = N->getValueType(0);
3907  unsigned NumElems = VT.getVectorNumElements();
3908
3909  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3910      (VT.getSizeInBits() == 256 && NumElems != 8))
3911    return false;
3912
3913  // "i+1" is the value the indexed mask element must have
3914  for (unsigned i = 0; i < NumElems; i += 2)
3915    if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3916        !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3917      return false;
3918
3919  return true;
3920}
3921
3922/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3923/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3924/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3925bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3926                         const X86Subtarget *Subtarget) {
3927  if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3928    return false;
3929
3930  // The second vector must be undef
3931  if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3932    return false;
3933
3934  EVT VT = N->getValueType(0);
3935  unsigned NumElems = VT.getVectorNumElements();
3936
3937  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3938      (VT.getSizeInBits() == 256 && NumElems != 8))
3939    return false;
3940
3941  // "i" is the value the indexed mask element must have
3942  for (unsigned i = 0; i < NumElems; i += 2)
3943    if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3944        !isUndefOrEqual(N->getMaskElt(i+1), i))
3945      return false;
3946
3947  return true;
3948}
3949
3950/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3951/// specifies a shuffle of elements that is suitable for input to 256-bit
3952/// version of MOVDDUP.
3953static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3954                           const X86Subtarget *Subtarget) {
3955  EVT VT = N->getValueType(0);
3956  int NumElts = VT.getVectorNumElements();
3957  bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3958
3959  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3960      !V2IsUndef || NumElts != 4)
3961    return false;
3962
3963  for (int i = 0; i != NumElts/2; ++i)
3964    if (!isUndefOrEqual(N->getMaskElt(i), 0))
3965      return false;
3966  for (int i = NumElts/2; i != NumElts; ++i)
3967    if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3968      return false;
3969  return true;
3970}
3971
3972/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3973/// specifies a shuffle of elements that is suitable for input to 128-bit
3974/// version of MOVDDUP.
3975bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3976  EVT VT = N->getValueType(0);
3977
3978  if (VT.getSizeInBits() != 128)
3979    return false;
3980
3981  int e = VT.getVectorNumElements() / 2;
3982  for (int i = 0; i < e; ++i)
3983    if (!isUndefOrEqual(N->getMaskElt(i), i))
3984      return false;
3985  for (int i = 0; i < e; ++i)
3986    if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3987      return false;
3988  return true;
3989}
3990
3991/// isVEXTRACTF128Index - Return true if the specified
3992/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3993/// suitable for input to VEXTRACTF128.
3994bool X86::isVEXTRACTF128Index(SDNode *N) {
3995  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3996    return false;
3997
3998  // The index should be aligned on a 128-bit boundary.
3999  uint64_t Index =
4000    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4001
4002  unsigned VL = N->getValueType(0).getVectorNumElements();
4003  unsigned VBits = N->getValueType(0).getSizeInBits();
4004  unsigned ElSize = VBits / VL;
4005  bool Result = (Index * ElSize) % 128 == 0;
4006
4007  return Result;
4008}
4009
4010/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4011/// operand specifies a subvector insert that is suitable for input to
4012/// VINSERTF128.
4013bool X86::isVINSERTF128Index(SDNode *N) {
4014  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4015    return false;
4016
4017  // The index should be aligned on a 128-bit boundary.
4018  uint64_t Index =
4019    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4020
4021  unsigned VL = N->getValueType(0).getVectorNumElements();
4022  unsigned VBits = N->getValueType(0).getSizeInBits();
4023  unsigned ElSize = VBits / VL;
4024  bool Result = (Index * ElSize) % 128 == 0;
4025
4026  return Result;
4027}
4028
4029/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4030/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4031unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4032  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4033  int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4034
4035  unsigned Shift = (NumOperands == 4) ? 2 : 1;
4036  unsigned Mask = 0;
4037  for (int i = 0; i < NumOperands; ++i) {
4038    int Val = SVOp->getMaskElt(NumOperands-i-1);
4039    if (Val < 0) Val = 0;
4040    if (Val >= NumOperands) Val -= NumOperands;
4041    Mask |= Val;
4042    if (i != NumOperands - 1)
4043      Mask <<= Shift;
4044  }
4045  return Mask;
4046}
4047
4048/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4049/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4050unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4051  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4052  unsigned Mask = 0;
4053  // 8 nodes, but we only care about the last 4.
4054  for (unsigned i = 7; i >= 4; --i) {
4055    int Val = SVOp->getMaskElt(i);
4056    if (Val >= 0)
4057      Mask |= (Val - 4);
4058    if (i != 4)
4059      Mask <<= 2;
4060  }
4061  return Mask;
4062}
4063
4064/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4065/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4066unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4067  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4068  unsigned Mask = 0;
4069  // 8 nodes, but we only care about the first 4.
4070  for (int i = 3; i >= 0; --i) {
4071    int Val = SVOp->getMaskElt(i);
4072    if (Val >= 0)
4073      Mask |= Val;
4074    if (i != 0)
4075      Mask <<= 2;
4076  }
4077  return Mask;
4078}
4079
4080/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4081/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4082unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4083  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4084  EVT VVT = N->getValueType(0);
4085  unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4086  int Val = 0;
4087
4088  unsigned i, e;
4089  for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4090    Val = SVOp->getMaskElt(i);
4091    if (Val >= 0)
4092      break;
4093  }
4094  assert(Val - i > 0 && "PALIGNR imm should be positive");
4095  return (Val - i) * EltSize;
4096}
4097
4098/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4099/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4100/// instructions.
4101unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4102  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4103    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4104
4105  uint64_t Index =
4106    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4107
4108  EVT VecVT = N->getOperand(0).getValueType();
4109  EVT ElVT = VecVT.getVectorElementType();
4110
4111  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4112  return Index / NumElemsPerChunk;
4113}
4114
4115/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4116/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4117/// instructions.
4118unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4119  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4120    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4121
4122  uint64_t Index =
4123    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4124
4125  EVT VecVT = N->getValueType(0);
4126  EVT ElVT = VecVT.getVectorElementType();
4127
4128  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4129  return Index / NumElemsPerChunk;
4130}
4131
4132/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4133/// constant +0.0.
4134bool X86::isZeroNode(SDValue Elt) {
4135  return ((isa<ConstantSDNode>(Elt) &&
4136           cast<ConstantSDNode>(Elt)->isNullValue()) ||
4137          (isa<ConstantFPSDNode>(Elt) &&
4138           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4139}
4140
4141/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4142/// their permute mask.
4143static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4144                                    SelectionDAG &DAG) {
4145  EVT VT = SVOp->getValueType(0);
4146  unsigned NumElems = VT.getVectorNumElements();
4147  SmallVector<int, 8> MaskVec;
4148
4149  for (unsigned i = 0; i != NumElems; ++i) {
4150    int idx = SVOp->getMaskElt(i);
4151    if (idx < 0)
4152      MaskVec.push_back(idx);
4153    else if (idx < (int)NumElems)
4154      MaskVec.push_back(idx + NumElems);
4155    else
4156      MaskVec.push_back(idx - NumElems);
4157  }
4158  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4159                              SVOp->getOperand(0), &MaskVec[0]);
4160}
4161
4162/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4163/// the two vector operands have swapped position.
4164static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4165  unsigned NumElems = VT.getVectorNumElements();
4166  for (unsigned i = 0; i != NumElems; ++i) {
4167    int idx = Mask[i];
4168    if (idx < 0)
4169      continue;
4170    else if (idx < (int)NumElems)
4171      Mask[i] = idx + NumElems;
4172    else
4173      Mask[i] = idx - NumElems;
4174  }
4175}
4176
4177/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4178/// match movhlps. The lower half elements should come from upper half of
4179/// V1 (and in order), and the upper half elements should come from the upper
4180/// half of V2 (and in order).
4181static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4182  EVT VT = Op->getValueType(0);
4183  if (VT.getSizeInBits() != 128)
4184    return false;
4185  if (VT.getVectorNumElements() != 4)
4186    return false;
4187  for (unsigned i = 0, e = 2; i != e; ++i)
4188    if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4189      return false;
4190  for (unsigned i = 2; i != 4; ++i)
4191    if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4192      return false;
4193  return true;
4194}
4195
4196/// isScalarLoadToVector - Returns true if the node is a scalar load that
4197/// is promoted to a vector. It also returns the LoadSDNode by reference if
4198/// required.
4199static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4200  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4201    return false;
4202  N = N->getOperand(0).getNode();
4203  if (!ISD::isNON_EXTLoad(N))
4204    return false;
4205  if (LD)
4206    *LD = cast<LoadSDNode>(N);
4207  return true;
4208}
4209
4210/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4211/// match movlp{s|d}. The lower half elements should come from lower half of
4212/// V1 (and in order), and the upper half elements should come from the upper
4213/// half of V2 (and in order). And since V1 will become the source of the
4214/// MOVLP, it must be either a vector load or a scalar load to vector.
4215static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4216                               ShuffleVectorSDNode *Op) {
4217  EVT VT = Op->getValueType(0);
4218  if (VT.getSizeInBits() != 128)
4219    return false;
4220
4221  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4222    return false;
4223  // Is V2 is a vector load, don't do this transformation. We will try to use
4224  // load folding shufps op.
4225  if (ISD::isNON_EXTLoad(V2))
4226    return false;
4227
4228  unsigned NumElems = VT.getVectorNumElements();
4229
4230  if (NumElems != 2 && NumElems != 4)
4231    return false;
4232  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4233    if (!isUndefOrEqual(Op->getMaskElt(i), i))
4234      return false;
4235  for (unsigned i = NumElems/2; i != NumElems; ++i)
4236    if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4237      return false;
4238  return true;
4239}
4240
4241/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4242/// all the same.
4243static bool isSplatVector(SDNode *N) {
4244  if (N->getOpcode() != ISD::BUILD_VECTOR)
4245    return false;
4246
4247  SDValue SplatValue = N->getOperand(0);
4248  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4249    if (N->getOperand(i) != SplatValue)
4250      return false;
4251  return true;
4252}
4253
4254/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4255/// to an zero vector.
4256/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4257static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4258  SDValue V1 = N->getOperand(0);
4259  SDValue V2 = N->getOperand(1);
4260  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4261  for (unsigned i = 0; i != NumElems; ++i) {
4262    int Idx = N->getMaskElt(i);
4263    if (Idx >= (int)NumElems) {
4264      unsigned Opc = V2.getOpcode();
4265      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4266        continue;
4267      if (Opc != ISD::BUILD_VECTOR ||
4268          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4269        return false;
4270    } else if (Idx >= 0) {
4271      unsigned Opc = V1.getOpcode();
4272      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4273        continue;
4274      if (Opc != ISD::BUILD_VECTOR ||
4275          !X86::isZeroNode(V1.getOperand(Idx)))
4276        return false;
4277    }
4278  }
4279  return true;
4280}
4281
4282/// getZeroVector - Returns a vector of specified type with all zero elements.
4283///
4284static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
4285                             DebugLoc dl) {
4286  assert(VT.isVector() && "Expected a vector type");
4287
4288  // Always build SSE zero vectors as <4 x i32> bitcasted
4289  // to their dest type. This ensures they get CSE'd.
4290  SDValue Vec;
4291  if (VT.getSizeInBits() == 128) {  // SSE
4292    if (HasSSE2) {  // SSE2
4293      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4294      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4295    } else { // SSE1
4296      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4297      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4298    }
4299  } else if (VT.getSizeInBits() == 256) { // AVX
4300    // 256-bit logic and arithmetic instructions in AVX are
4301    // all floating-point, no support for integer ops. Default
4302    // to emitting fp zeroed vectors then.
4303    SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4304    SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4305    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4306  }
4307  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4308}
4309
4310/// getOnesVector - Returns a vector of specified type with all bits set.
4311/// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4312/// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4313/// original type, ensuring they get CSE'd.
4314static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4315  assert(VT.isVector() && "Expected a vector type");
4316  assert((VT.is128BitVector() || VT.is256BitVector())
4317         && "Expected a 128-bit or 256-bit vector type");
4318
4319  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4320  SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4321                            Cst, Cst, Cst, Cst);
4322
4323  if (VT.is256BitVector()) {
4324    SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4325                              Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4326    Vec = Insert128BitVector(InsV, Vec,
4327                  DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4328  }
4329
4330  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4331}
4332
4333/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4334/// that point to V2 points to its first element.
4335static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4336  EVT VT = SVOp->getValueType(0);
4337  unsigned NumElems = VT.getVectorNumElements();
4338
4339  bool Changed = false;
4340  SmallVector<int, 8> MaskVec;
4341  SVOp->getMask(MaskVec);
4342
4343  for (unsigned i = 0; i != NumElems; ++i) {
4344    if (MaskVec[i] > (int)NumElems) {
4345      MaskVec[i] = NumElems;
4346      Changed = true;
4347    }
4348  }
4349  if (Changed)
4350    return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4351                                SVOp->getOperand(1), &MaskVec[0]);
4352  return SDValue(SVOp, 0);
4353}
4354
4355/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4356/// operation of specified width.
4357static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4358                       SDValue V2) {
4359  unsigned NumElems = VT.getVectorNumElements();
4360  SmallVector<int, 8> Mask;
4361  Mask.push_back(NumElems);
4362  for (unsigned i = 1; i != NumElems; ++i)
4363    Mask.push_back(i);
4364  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4365}
4366
4367/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4368static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4369                          SDValue V2) {
4370  unsigned NumElems = VT.getVectorNumElements();
4371  SmallVector<int, 8> Mask;
4372  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4373    Mask.push_back(i);
4374    Mask.push_back(i + NumElems);
4375  }
4376  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4377}
4378
4379/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4380static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4381                          SDValue V2) {
4382  unsigned NumElems = VT.getVectorNumElements();
4383  unsigned Half = NumElems/2;
4384  SmallVector<int, 8> Mask;
4385  for (unsigned i = 0; i != Half; ++i) {
4386    Mask.push_back(i + Half);
4387    Mask.push_back(i + NumElems + Half);
4388  }
4389  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4390}
4391
4392// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4393// a generic shuffle instruction because the target has no such instructions.
4394// Generate shuffles which repeat i16 and i8 several times until they can be
4395// represented by v4f32 and then be manipulated by target suported shuffles.
4396static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4397  EVT VT = V.getValueType();
4398  int NumElems = VT.getVectorNumElements();
4399  DebugLoc dl = V.getDebugLoc();
4400
4401  while (NumElems > 4) {
4402    if (EltNo < NumElems/2) {
4403      V = getUnpackl(DAG, dl, VT, V, V);
4404    } else {
4405      V = getUnpackh(DAG, dl, VT, V, V);
4406      EltNo -= NumElems/2;
4407    }
4408    NumElems >>= 1;
4409  }
4410  return V;
4411}
4412
4413/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4414static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4415  EVT VT = V.getValueType();
4416  DebugLoc dl = V.getDebugLoc();
4417  assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4418         && "Vector size not supported");
4419
4420  if (VT.getSizeInBits() == 128) {
4421    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4422    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4423    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4424                             &SplatMask[0]);
4425  } else {
4426    // To use VPERMILPS to splat scalars, the second half of indicies must
4427    // refer to the higher part, which is a duplication of the lower one,
4428    // because VPERMILPS can only handle in-lane permutations.
4429    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4430                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4431
4432    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4433    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4434                             &SplatMask[0]);
4435  }
4436
4437  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4438}
4439
4440/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4441static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4442  EVT SrcVT = SV->getValueType(0);
4443  SDValue V1 = SV->getOperand(0);
4444  DebugLoc dl = SV->getDebugLoc();
4445
4446  int EltNo = SV->getSplatIndex();
4447  int NumElems = SrcVT.getVectorNumElements();
4448  unsigned Size = SrcVT.getSizeInBits();
4449
4450  assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4451          "Unknown how to promote splat for type");
4452
4453  // Extract the 128-bit part containing the splat element and update
4454  // the splat element index when it refers to the higher register.
4455  if (Size == 256) {
4456    unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4457    V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4458    if (Idx > 0)
4459      EltNo -= NumElems/2;
4460  }
4461
4462  // All i16 and i8 vector types can't be used directly by a generic shuffle
4463  // instruction because the target has no such instruction. Generate shuffles
4464  // which repeat i16 and i8 several times until they fit in i32, and then can
4465  // be manipulated by target suported shuffles.
4466  EVT EltVT = SrcVT.getVectorElementType();
4467  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4468    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4469
4470  // Recreate the 256-bit vector and place the same 128-bit vector
4471  // into the low and high part. This is necessary because we want
4472  // to use VPERM* to shuffle the vectors
4473  if (Size == 256) {
4474    SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4475                         DAG.getConstant(0, MVT::i32), DAG, dl);
4476    V1 = Insert128BitVector(InsV, V1,
4477               DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4478  }
4479
4480  return getLegalSplat(DAG, V1, EltNo);
4481}
4482
4483/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4484/// vector of zero or undef vector.  This produces a shuffle where the low
4485/// element of V2 is swizzled into the zero/undef vector, landing at element
4486/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4487static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4488                                             bool isZero, bool HasSSE2,
4489                                             SelectionDAG &DAG) {
4490  EVT VT = V2.getValueType();
4491  SDValue V1 = isZero
4492    ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4493  unsigned NumElems = VT.getVectorNumElements();
4494  SmallVector<int, 16> MaskVec;
4495  for (unsigned i = 0; i != NumElems; ++i)
4496    // If this is the insertion idx, put the low elt of V2 here.
4497    MaskVec.push_back(i == Idx ? NumElems : i);
4498  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4499}
4500
4501/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4502/// element of the result of the vector shuffle.
4503static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4504                                   unsigned Depth) {
4505  if (Depth == 6)
4506    return SDValue();  // Limit search depth.
4507
4508  SDValue V = SDValue(N, 0);
4509  EVT VT = V.getValueType();
4510  unsigned Opcode = V.getOpcode();
4511
4512  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4513  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4514    Index = SV->getMaskElt(Index);
4515
4516    if (Index < 0)
4517      return DAG.getUNDEF(VT.getVectorElementType());
4518
4519    int NumElems = VT.getVectorNumElements();
4520    SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4521    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4522  }
4523
4524  // Recurse into target specific vector shuffles to find scalars.
4525  if (isTargetShuffle(Opcode)) {
4526    int NumElems = VT.getVectorNumElements();
4527    SmallVector<unsigned, 16> ShuffleMask;
4528    SDValue ImmN;
4529
4530    switch(Opcode) {
4531    case X86ISD::SHUFPS:
4532    case X86ISD::SHUFPD:
4533      ImmN = N->getOperand(N->getNumOperands()-1);
4534      DecodeSHUFPSMask(NumElems,
4535                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4536                       ShuffleMask);
4537      break;
4538    case X86ISD::PUNPCKHBW:
4539    case X86ISD::PUNPCKHWD:
4540    case X86ISD::PUNPCKHDQ:
4541    case X86ISD::PUNPCKHQDQ:
4542      DecodePUNPCKHMask(NumElems, ShuffleMask);
4543      break;
4544    case X86ISD::UNPCKHPS:
4545    case X86ISD::UNPCKHPD:
4546    case X86ISD::VUNPCKHPSY:
4547    case X86ISD::VUNPCKHPDY:
4548      DecodeUNPCKHPMask(NumElems, ShuffleMask);
4549      break;
4550    case X86ISD::PUNPCKLBW:
4551    case X86ISD::PUNPCKLWD:
4552    case X86ISD::PUNPCKLDQ:
4553    case X86ISD::PUNPCKLQDQ:
4554      DecodePUNPCKLMask(VT, ShuffleMask);
4555      break;
4556    case X86ISD::UNPCKLPS:
4557    case X86ISD::UNPCKLPD:
4558    case X86ISD::VUNPCKLPSY:
4559    case X86ISD::VUNPCKLPDY:
4560      DecodeUNPCKLPMask(VT, ShuffleMask);
4561      break;
4562    case X86ISD::MOVHLPS:
4563      DecodeMOVHLPSMask(NumElems, ShuffleMask);
4564      break;
4565    case X86ISD::MOVLHPS:
4566      DecodeMOVLHPSMask(NumElems, ShuffleMask);
4567      break;
4568    case X86ISD::PSHUFD:
4569      ImmN = N->getOperand(N->getNumOperands()-1);
4570      DecodePSHUFMask(NumElems,
4571                      cast<ConstantSDNode>(ImmN)->getZExtValue(),
4572                      ShuffleMask);
4573      break;
4574    case X86ISD::PSHUFHW:
4575      ImmN = N->getOperand(N->getNumOperands()-1);
4576      DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4577                        ShuffleMask);
4578      break;
4579    case X86ISD::PSHUFLW:
4580      ImmN = N->getOperand(N->getNumOperands()-1);
4581      DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4582                        ShuffleMask);
4583      break;
4584    case X86ISD::MOVSS:
4585    case X86ISD::MOVSD: {
4586      // The index 0 always comes from the first element of the second source,
4587      // this is why MOVSS and MOVSD are used in the first place. The other
4588      // elements come from the other positions of the first source vector.
4589      unsigned OpNum = (Index == 0) ? 1 : 0;
4590      return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4591                                 Depth+1);
4592    }
4593    case X86ISD::VPERMILPS:
4594      ImmN = N->getOperand(N->getNumOperands()-1);
4595      DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4596                        ShuffleMask);
4597      break;
4598    case X86ISD::VPERMILPSY:
4599      ImmN = N->getOperand(N->getNumOperands()-1);
4600      DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4601                        ShuffleMask);
4602      break;
4603    case X86ISD::VPERMILPD:
4604      ImmN = N->getOperand(N->getNumOperands()-1);
4605      DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4606                        ShuffleMask);
4607      break;
4608    case X86ISD::VPERMILPDY:
4609      ImmN = N->getOperand(N->getNumOperands()-1);
4610      DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4611                        ShuffleMask);
4612      break;
4613    case X86ISD::VPERM2F128:
4614      ImmN = N->getOperand(N->getNumOperands()-1);
4615      DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4616                           ShuffleMask);
4617      break;
4618    case X86ISD::MOVDDUP:
4619    case X86ISD::MOVLHPD:
4620    case X86ISD::MOVLPD:
4621    case X86ISD::MOVLPS:
4622    case X86ISD::MOVSHDUP:
4623    case X86ISD::MOVSLDUP:
4624    case X86ISD::PALIGN:
4625      return SDValue(); // Not yet implemented.
4626    default:
4627      assert(0 && "unknown target shuffle node");
4628      return SDValue();
4629    }
4630
4631    Index = ShuffleMask[Index];
4632    if (Index < 0)
4633      return DAG.getUNDEF(VT.getVectorElementType());
4634
4635    SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4636    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4637                               Depth+1);
4638  }
4639
4640  // Actual nodes that may contain scalar elements
4641  if (Opcode == ISD::BITCAST) {
4642    V = V.getOperand(0);
4643    EVT SrcVT = V.getValueType();
4644    unsigned NumElems = VT.getVectorNumElements();
4645
4646    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4647      return SDValue();
4648  }
4649
4650  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4651    return (Index == 0) ? V.getOperand(0)
4652                          : DAG.getUNDEF(VT.getVectorElementType());
4653
4654  if (V.getOpcode() == ISD::BUILD_VECTOR)
4655    return V.getOperand(Index);
4656
4657  return SDValue();
4658}
4659
4660/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4661/// shuffle operation which come from a consecutively from a zero. The
4662/// search can start in two different directions, from left or right.
4663static
4664unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4665                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4666  int i = 0;
4667
4668  while (i < NumElems) {
4669    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4670    SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4671    if (!(Elt.getNode() &&
4672         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4673      break;
4674    ++i;
4675  }
4676
4677  return i;
4678}
4679
4680/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4681/// MaskE correspond consecutively to elements from one of the vector operands,
4682/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4683static
4684bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4685                              int OpIdx, int NumElems, unsigned &OpNum) {
4686  bool SeenV1 = false;
4687  bool SeenV2 = false;
4688
4689  for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4690    int Idx = SVOp->getMaskElt(i);
4691    // Ignore undef indicies
4692    if (Idx < 0)
4693      continue;
4694
4695    if (Idx < NumElems)
4696      SeenV1 = true;
4697    else
4698      SeenV2 = true;
4699
4700    // Only accept consecutive elements from the same vector
4701    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4702      return false;
4703  }
4704
4705  OpNum = SeenV1 ? 0 : 1;
4706  return true;
4707}
4708
4709/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4710/// logical left shift of a vector.
4711static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4712                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4713  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4714  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4715              false /* check zeros from right */, DAG);
4716  unsigned OpSrc;
4717
4718  if (!NumZeros)
4719    return false;
4720
4721  // Considering the elements in the mask that are not consecutive zeros,
4722  // check if they consecutively come from only one of the source vectors.
4723  //
4724  //               V1 = {X, A, B, C}     0
4725  //                         \  \  \    /
4726  //   vector_shuffle V1, V2 <1, 2, 3, X>
4727  //
4728  if (!isShuffleMaskConsecutive(SVOp,
4729            0,                   // Mask Start Index
4730            NumElems-NumZeros-1, // Mask End Index
4731            NumZeros,            // Where to start looking in the src vector
4732            NumElems,            // Number of elements in vector
4733            OpSrc))              // Which source operand ?
4734    return false;
4735
4736  isLeft = false;
4737  ShAmt = NumZeros;
4738  ShVal = SVOp->getOperand(OpSrc);
4739  return true;
4740}
4741
4742/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4743/// logical left shift of a vector.
4744static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4745                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4746  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4747  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4748              true /* check zeros from left */, DAG);
4749  unsigned OpSrc;
4750
4751  if (!NumZeros)
4752    return false;
4753
4754  // Considering the elements in the mask that are not consecutive zeros,
4755  // check if they consecutively come from only one of the source vectors.
4756  //
4757  //                           0    { A, B, X, X } = V2
4758  //                          / \    /  /
4759  //   vector_shuffle V1, V2 <X, X, 4, 5>
4760  //
4761  if (!isShuffleMaskConsecutive(SVOp,
4762            NumZeros,     // Mask Start Index
4763            NumElems-1,   // Mask End Index
4764            0,            // Where to start looking in the src vector
4765            NumElems,     // Number of elements in vector
4766            OpSrc))       // Which source operand ?
4767    return false;
4768
4769  isLeft = true;
4770  ShAmt = NumZeros;
4771  ShVal = SVOp->getOperand(OpSrc);
4772  return true;
4773}
4774
4775/// isVectorShift - Returns true if the shuffle can be implemented as a
4776/// logical left or right shift of a vector.
4777static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4778                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4779  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4780      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4781    return true;
4782
4783  return false;
4784}
4785
4786/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4787///
4788static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4789                                       unsigned NumNonZero, unsigned NumZero,
4790                                       SelectionDAG &DAG,
4791                                       const TargetLowering &TLI) {
4792  if (NumNonZero > 8)
4793    return SDValue();
4794
4795  DebugLoc dl = Op.getDebugLoc();
4796  SDValue V(0, 0);
4797  bool First = true;
4798  for (unsigned i = 0; i < 16; ++i) {
4799    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4800    if (ThisIsNonZero && First) {
4801      if (NumZero)
4802        V = getZeroVector(MVT::v8i16, true, DAG, dl);
4803      else
4804        V = DAG.getUNDEF(MVT::v8i16);
4805      First = false;
4806    }
4807
4808    if ((i & 1) != 0) {
4809      SDValue ThisElt(0, 0), LastElt(0, 0);
4810      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4811      if (LastIsNonZero) {
4812        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4813                              MVT::i16, Op.getOperand(i-1));
4814      }
4815      if (ThisIsNonZero) {
4816        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4817        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4818                              ThisElt, DAG.getConstant(8, MVT::i8));
4819        if (LastIsNonZero)
4820          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4821      } else
4822        ThisElt = LastElt;
4823
4824      if (ThisElt.getNode())
4825        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4826                        DAG.getIntPtrConstant(i/2));
4827    }
4828  }
4829
4830  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4831}
4832
4833/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4834///
4835static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4836                                     unsigned NumNonZero, unsigned NumZero,
4837                                     SelectionDAG &DAG,
4838                                     const TargetLowering &TLI) {
4839  if (NumNonZero > 4)
4840    return SDValue();
4841
4842  DebugLoc dl = Op.getDebugLoc();
4843  SDValue V(0, 0);
4844  bool First = true;
4845  for (unsigned i = 0; i < 8; ++i) {
4846    bool isNonZero = (NonZeros & (1 << i)) != 0;
4847    if (isNonZero) {
4848      if (First) {
4849        if (NumZero)
4850          V = getZeroVector(MVT::v8i16, true, DAG, dl);
4851        else
4852          V = DAG.getUNDEF(MVT::v8i16);
4853        First = false;
4854      }
4855      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4856                      MVT::v8i16, V, Op.getOperand(i),
4857                      DAG.getIntPtrConstant(i));
4858    }
4859  }
4860
4861  return V;
4862}
4863
4864/// getVShift - Return a vector logical shift node.
4865///
4866static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4867                         unsigned NumBits, SelectionDAG &DAG,
4868                         const TargetLowering &TLI, DebugLoc dl) {
4869  EVT ShVT = MVT::v2i64;
4870  unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4871  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4872  return DAG.getNode(ISD::BITCAST, dl, VT,
4873                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4874                             DAG.getConstant(NumBits,
4875                                  TLI.getShiftAmountTy(SrcOp.getValueType()))));
4876}
4877
4878SDValue
4879X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4880                                          SelectionDAG &DAG) const {
4881
4882  // Check if the scalar load can be widened into a vector load. And if
4883  // the address is "base + cst" see if the cst can be "absorbed" into
4884  // the shuffle mask.
4885  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4886    SDValue Ptr = LD->getBasePtr();
4887    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4888      return SDValue();
4889    EVT PVT = LD->getValueType(0);
4890    if (PVT != MVT::i32 && PVT != MVT::f32)
4891      return SDValue();
4892
4893    int FI = -1;
4894    int64_t Offset = 0;
4895    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4896      FI = FINode->getIndex();
4897      Offset = 0;
4898    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4899               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4900      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4901      Offset = Ptr.getConstantOperandVal(1);
4902      Ptr = Ptr.getOperand(0);
4903    } else {
4904      return SDValue();
4905    }
4906
4907    // FIXME: 256-bit vector instructions don't require a strict alignment,
4908    // improve this code to support it better.
4909    unsigned RequiredAlign = VT.getSizeInBits()/8;
4910    SDValue Chain = LD->getChain();
4911    // Make sure the stack object alignment is at least 16 or 32.
4912    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4913    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4914      if (MFI->isFixedObjectIndex(FI)) {
4915        // Can't change the alignment. FIXME: It's possible to compute
4916        // the exact stack offset and reference FI + adjust offset instead.
4917        // If someone *really* cares about this. That's the way to implement it.
4918        return SDValue();
4919      } else {
4920        MFI->setObjectAlignment(FI, RequiredAlign);
4921      }
4922    }
4923
4924    // (Offset % 16 or 32) must be multiple of 4. Then address is then
4925    // Ptr + (Offset & ~15).
4926    if (Offset < 0)
4927      return SDValue();
4928    if ((Offset % RequiredAlign) & 3)
4929      return SDValue();
4930    int64_t StartOffset = Offset & ~(RequiredAlign-1);
4931    if (StartOffset)
4932      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4933                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4934
4935    int EltNo = (Offset - StartOffset) >> 2;
4936    int NumElems = VT.getVectorNumElements();
4937
4938    EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4939    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4940    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4941                             LD->getPointerInfo().getWithOffset(StartOffset),
4942                             false, false, 0);
4943
4944    // Canonicalize it to a v4i32 or v8i32 shuffle.
4945    SmallVector<int, 8> Mask;
4946    for (int i = 0; i < NumElems; ++i)
4947      Mask.push_back(EltNo);
4948
4949    V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4950    return DAG.getNode(ISD::BITCAST, dl, NVT,
4951                       DAG.getVectorShuffle(CanonVT, dl, V1,
4952                                            DAG.getUNDEF(CanonVT),&Mask[0]));
4953  }
4954
4955  return SDValue();
4956}
4957
4958/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4959/// vector of type 'VT', see if the elements can be replaced by a single large
4960/// load which has the same value as a build_vector whose operands are 'elts'.
4961///
4962/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4963///
4964/// FIXME: we'd also like to handle the case where the last elements are zero
4965/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4966/// There's even a handy isZeroNode for that purpose.
4967static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4968                                        DebugLoc &DL, SelectionDAG &DAG) {
4969  EVT EltVT = VT.getVectorElementType();
4970  unsigned NumElems = Elts.size();
4971
4972  LoadSDNode *LDBase = NULL;
4973  unsigned LastLoadedElt = -1U;
4974
4975  // For each element in the initializer, see if we've found a load or an undef.
4976  // If we don't find an initial load element, or later load elements are
4977  // non-consecutive, bail out.
4978  for (unsigned i = 0; i < NumElems; ++i) {
4979    SDValue Elt = Elts[i];
4980
4981    if (!Elt.getNode() ||
4982        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4983      return SDValue();
4984    if (!LDBase) {
4985      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4986        return SDValue();
4987      LDBase = cast<LoadSDNode>(Elt.getNode());
4988      LastLoadedElt = i;
4989      continue;
4990    }
4991    if (Elt.getOpcode() == ISD::UNDEF)
4992      continue;
4993
4994    LoadSDNode *LD = cast<LoadSDNode>(Elt);
4995    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4996      return SDValue();
4997    LastLoadedElt = i;
4998  }
4999
5000  // If we have found an entire vector of loads and undefs, then return a large
5001  // load of the entire vector width starting at the base pointer.  If we found
5002  // consecutive loads for the low half, generate a vzext_load node.
5003  if (LastLoadedElt == NumElems - 1) {
5004    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5005      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5006                         LDBase->getPointerInfo(),
5007                         LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5008    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5009                       LDBase->getPointerInfo(),
5010                       LDBase->isVolatile(), LDBase->isNonTemporal(),
5011                       LDBase->getAlignment());
5012  } else if (NumElems == 4 && LastLoadedElt == 1 &&
5013             DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5014    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5015    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5016    SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
5017                                              Ops, 2, MVT::i32,
5018                                              LDBase->getMemOperand());
5019    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5020  }
5021  return SDValue();
5022}
5023
5024SDValue
5025X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5026  DebugLoc dl = Op.getDebugLoc();
5027
5028  EVT VT = Op.getValueType();
5029  EVT ExtVT = VT.getVectorElementType();
5030  unsigned NumElems = Op.getNumOperands();
5031
5032  // Vectors containing all zeros can be matched by pxor and xorps later
5033  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5034    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5035    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5036    if (Op.getValueType() == MVT::v4i32 ||
5037        Op.getValueType() == MVT::v8i32)
5038      return Op;
5039
5040    return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
5041  }
5042
5043  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5044  // vectors or broken into v4i32 operations on 256-bit vectors.
5045  if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5046    if (Op.getValueType() == MVT::v4i32)
5047      return Op;
5048
5049    return getOnesVector(Op.getValueType(), DAG, dl);
5050  }
5051
5052  unsigned EVTBits = ExtVT.getSizeInBits();
5053
5054  unsigned NumZero  = 0;
5055  unsigned NumNonZero = 0;
5056  unsigned NonZeros = 0;
5057  bool IsAllConstants = true;
5058  SmallSet<SDValue, 8> Values;
5059  for (unsigned i = 0; i < NumElems; ++i) {
5060    SDValue Elt = Op.getOperand(i);
5061    if (Elt.getOpcode() == ISD::UNDEF)
5062      continue;
5063    Values.insert(Elt);
5064    if (Elt.getOpcode() != ISD::Constant &&
5065        Elt.getOpcode() != ISD::ConstantFP)
5066      IsAllConstants = false;
5067    if (X86::isZeroNode(Elt))
5068      NumZero++;
5069    else {
5070      NonZeros |= (1 << i);
5071      NumNonZero++;
5072    }
5073  }
5074
5075  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5076  if (NumNonZero == 0)
5077    return DAG.getUNDEF(VT);
5078
5079  // Special case for single non-zero, non-undef, element.
5080  if (NumNonZero == 1) {
5081    unsigned Idx = CountTrailingZeros_32(NonZeros);
5082    SDValue Item = Op.getOperand(Idx);
5083
5084    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5085    // the value are obviously zero, truncate the value to i32 and do the
5086    // insertion that way.  Only do this if the value is non-constant or if the
5087    // value is a constant being inserted into element 0.  It is cheaper to do
5088    // a constant pool load than it is to do a movd + shuffle.
5089    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5090        (!IsAllConstants || Idx == 0)) {
5091      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5092        // Handle SSE only.
5093        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5094        EVT VecVT = MVT::v4i32;
5095        unsigned VecElts = 4;
5096
5097        // Truncate the value (which may itself be a constant) to i32, and
5098        // convert it to a vector with movd (S2V+shuffle to zero extend).
5099        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5100        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5101        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5102                                           Subtarget->hasSSE2(), DAG);
5103
5104        // Now we have our 32-bit value zero extended in the low element of
5105        // a vector.  If Idx != 0, swizzle it into place.
5106        if (Idx != 0) {
5107          SmallVector<int, 4> Mask;
5108          Mask.push_back(Idx);
5109          for (unsigned i = 1; i != VecElts; ++i)
5110            Mask.push_back(i);
5111          Item = DAG.getVectorShuffle(VecVT, dl, Item,
5112                                      DAG.getUNDEF(Item.getValueType()),
5113                                      &Mask[0]);
5114        }
5115        return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5116      }
5117    }
5118
5119    // If we have a constant or non-constant insertion into the low element of
5120    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5121    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5122    // depending on what the source datatype is.
5123    if (Idx == 0) {
5124      if (NumZero == 0) {
5125        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5126      } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5127          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5128        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5129        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5130        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
5131                                           DAG);
5132      } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5133        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5134        assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5135        EVT MiddleVT = MVT::v4i32;
5136        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5137        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5138                                           Subtarget->hasSSE2(), DAG);
5139        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5140      }
5141    }
5142
5143    // Is it a vector logical left shift?
5144    if (NumElems == 2 && Idx == 1 &&
5145        X86::isZeroNode(Op.getOperand(0)) &&
5146        !X86::isZeroNode(Op.getOperand(1))) {
5147      unsigned NumBits = VT.getSizeInBits();
5148      return getVShift(true, VT,
5149                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5150                                   VT, Op.getOperand(1)),
5151                       NumBits/2, DAG, *this, dl);
5152    }
5153
5154    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5155      return SDValue();
5156
5157    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5158    // is a non-constant being inserted into an element other than the low one,
5159    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5160    // movd/movss) to move this into the low element, then shuffle it into
5161    // place.
5162    if (EVTBits == 32) {
5163      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5164
5165      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5166      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5167                                         Subtarget->hasSSE2(), DAG);
5168      SmallVector<int, 8> MaskVec;
5169      for (unsigned i = 0; i < NumElems; i++)
5170        MaskVec.push_back(i == Idx ? 0 : 1);
5171      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5172    }
5173  }
5174
5175  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5176  if (Values.size() == 1) {
5177    if (EVTBits == 32) {
5178      // Instead of a shuffle like this:
5179      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5180      // Check if it's possible to issue this instead.
5181      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5182      unsigned Idx = CountTrailingZeros_32(NonZeros);
5183      SDValue Item = Op.getOperand(Idx);
5184      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5185        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5186    }
5187    return SDValue();
5188  }
5189
5190  // A vector full of immediates; various special cases are already
5191  // handled, so this is best done with a single constant-pool load.
5192  if (IsAllConstants)
5193    return SDValue();
5194
5195  // For AVX-length vectors, build the individual 128-bit pieces and use
5196  // shuffles to put them in place.
5197  if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5198    SmallVector<SDValue, 32> V;
5199    for (unsigned i = 0; i < NumElems; ++i)
5200      V.push_back(Op.getOperand(i));
5201
5202    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5203
5204    // Build both the lower and upper subvector.
5205    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5206    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5207                                NumElems/2);
5208
5209    // Recreate the wider vector with the lower and upper part.
5210    SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5211                                DAG.getConstant(0, MVT::i32), DAG, dl);
5212    return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5213                              DAG, dl);
5214  }
5215
5216  // Let legalizer expand 2-wide build_vectors.
5217  if (EVTBits == 64) {
5218    if (NumNonZero == 1) {
5219      // One half is zero or undef.
5220      unsigned Idx = CountTrailingZeros_32(NonZeros);
5221      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5222                                 Op.getOperand(Idx));
5223      return getShuffleVectorZeroOrUndef(V2, Idx, true,
5224                                         Subtarget->hasSSE2(), DAG);
5225    }
5226    return SDValue();
5227  }
5228
5229  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5230  if (EVTBits == 8 && NumElems == 16) {
5231    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5232                                        *this);
5233    if (V.getNode()) return V;
5234  }
5235
5236  if (EVTBits == 16 && NumElems == 8) {
5237    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5238                                      *this);
5239    if (V.getNode()) return V;
5240  }
5241
5242  // If element VT is == 32 bits, turn it into a number of shuffles.
5243  SmallVector<SDValue, 8> V;
5244  V.resize(NumElems);
5245  if (NumElems == 4 && NumZero > 0) {
5246    for (unsigned i = 0; i < 4; ++i) {
5247      bool isZero = !(NonZeros & (1 << i));
5248      if (isZero)
5249        V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5250      else
5251        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5252    }
5253
5254    for (unsigned i = 0; i < 2; ++i) {
5255      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5256        default: break;
5257        case 0:
5258          V[i] = V[i*2];  // Must be a zero vector.
5259          break;
5260        case 1:
5261          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5262          break;
5263        case 2:
5264          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5265          break;
5266        case 3:
5267          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5268          break;
5269      }
5270    }
5271
5272    SmallVector<int, 8> MaskVec;
5273    bool Reverse = (NonZeros & 0x3) == 2;
5274    for (unsigned i = 0; i < 2; ++i)
5275      MaskVec.push_back(Reverse ? 1-i : i);
5276    Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5277    for (unsigned i = 0; i < 2; ++i)
5278      MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5279    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5280  }
5281
5282  if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5283    // Check for a build vector of consecutive loads.
5284    for (unsigned i = 0; i < NumElems; ++i)
5285      V[i] = Op.getOperand(i);
5286
5287    // Check for elements which are consecutive loads.
5288    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5289    if (LD.getNode())
5290      return LD;
5291
5292    // For SSE 4.1, use insertps to put the high elements into the low element.
5293    if (getSubtarget()->hasSSE41()) {
5294      SDValue Result;
5295      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5296        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5297      else
5298        Result = DAG.getUNDEF(VT);
5299
5300      for (unsigned i = 1; i < NumElems; ++i) {
5301        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5302        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5303                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5304      }
5305      return Result;
5306    }
5307
5308    // Otherwise, expand into a number of unpckl*, start by extending each of
5309    // our (non-undef) elements to the full vector width with the element in the
5310    // bottom slot of the vector (which generates no code for SSE).
5311    for (unsigned i = 0; i < NumElems; ++i) {
5312      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5313        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5314      else
5315        V[i] = DAG.getUNDEF(VT);
5316    }
5317
5318    // Next, we iteratively mix elements, e.g. for v4f32:
5319    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5320    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5321    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5322    unsigned EltStride = NumElems >> 1;
5323    while (EltStride != 0) {
5324      for (unsigned i = 0; i < EltStride; ++i) {
5325        // If V[i+EltStride] is undef and this is the first round of mixing,
5326        // then it is safe to just drop this shuffle: V[i] is already in the
5327        // right place, the one element (since it's the first round) being
5328        // inserted as undef can be dropped.  This isn't safe for successive
5329        // rounds because they will permute elements within both vectors.
5330        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5331            EltStride == NumElems/2)
5332          continue;
5333
5334        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5335      }
5336      EltStride >>= 1;
5337    }
5338    return V[0];
5339  }
5340  return SDValue();
5341}
5342
5343// LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5344// them in a MMX register.  This is better than doing a stack convert.
5345static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5346  DebugLoc dl = Op.getDebugLoc();
5347  EVT ResVT = Op.getValueType();
5348
5349  assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5350         ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5351  int Mask[2];
5352  SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5353  SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5354  InVec = Op.getOperand(1);
5355  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5356    unsigned NumElts = ResVT.getVectorNumElements();
5357    VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5358    VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5359                       InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5360  } else {
5361    InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5362    SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5363    Mask[0] = 0; Mask[1] = 2;
5364    VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5365  }
5366  return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5367}
5368
5369// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5370// to create 256-bit vectors from two other 128-bit ones.
5371static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5372  DebugLoc dl = Op.getDebugLoc();
5373  EVT ResVT = Op.getValueType();
5374
5375  assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5376
5377  SDValue V1 = Op.getOperand(0);
5378  SDValue V2 = Op.getOperand(1);
5379  unsigned NumElems = ResVT.getVectorNumElements();
5380
5381  SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5382                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5383  return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5384                            DAG, dl);
5385}
5386
5387SDValue
5388X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5389  EVT ResVT = Op.getValueType();
5390
5391  assert(Op.getNumOperands() == 2);
5392  assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5393         "Unsupported CONCAT_VECTORS for value type");
5394
5395  // We support concatenate two MMX registers and place them in a MMX register.
5396  // This is better than doing a stack convert.
5397  if (ResVT.is128BitVector())
5398    return LowerMMXCONCAT_VECTORS(Op, DAG);
5399
5400  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5401  // from two other 128-bit ones.
5402  return LowerAVXCONCAT_VECTORS(Op, DAG);
5403}
5404
5405// v8i16 shuffles - Prefer shuffles in the following order:
5406// 1. [all]   pshuflw, pshufhw, optional move
5407// 2. [ssse3] 1 x pshufb
5408// 3. [ssse3] 2 x pshufb + 1 x por
5409// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5410SDValue
5411X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5412                                            SelectionDAG &DAG) const {
5413  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5414  SDValue V1 = SVOp->getOperand(0);
5415  SDValue V2 = SVOp->getOperand(1);
5416  DebugLoc dl = SVOp->getDebugLoc();
5417  SmallVector<int, 8> MaskVals;
5418
5419  // Determine if more than 1 of the words in each of the low and high quadwords
5420  // of the result come from the same quadword of one of the two inputs.  Undef
5421  // mask values count as coming from any quadword, for better codegen.
5422  SmallVector<unsigned, 4> LoQuad(4);
5423  SmallVector<unsigned, 4> HiQuad(4);
5424  BitVector InputQuads(4);
5425  for (unsigned i = 0; i < 8; ++i) {
5426    SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5427    int EltIdx = SVOp->getMaskElt(i);
5428    MaskVals.push_back(EltIdx);
5429    if (EltIdx < 0) {
5430      ++Quad[0];
5431      ++Quad[1];
5432      ++Quad[2];
5433      ++Quad[3];
5434      continue;
5435    }
5436    ++Quad[EltIdx / 4];
5437    InputQuads.set(EltIdx / 4);
5438  }
5439
5440  int BestLoQuad = -1;
5441  unsigned MaxQuad = 1;
5442  for (unsigned i = 0; i < 4; ++i) {
5443    if (LoQuad[i] > MaxQuad) {
5444      BestLoQuad = i;
5445      MaxQuad = LoQuad[i];
5446    }
5447  }
5448
5449  int BestHiQuad = -1;
5450  MaxQuad = 1;
5451  for (unsigned i = 0; i < 4; ++i) {
5452    if (HiQuad[i] > MaxQuad) {
5453      BestHiQuad = i;
5454      MaxQuad = HiQuad[i];
5455    }
5456  }
5457
5458  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5459  // of the two input vectors, shuffle them into one input vector so only a
5460  // single pshufb instruction is necessary. If There are more than 2 input
5461  // quads, disable the next transformation since it does not help SSSE3.
5462  bool V1Used = InputQuads[0] || InputQuads[1];
5463  bool V2Used = InputQuads[2] || InputQuads[3];
5464  if (Subtarget->hasSSSE3()) {
5465    if (InputQuads.count() == 2 && V1Used && V2Used) {
5466      BestLoQuad = InputQuads.find_first();
5467      BestHiQuad = InputQuads.find_next(BestLoQuad);
5468    }
5469    if (InputQuads.count() > 2) {
5470      BestLoQuad = -1;
5471      BestHiQuad = -1;
5472    }
5473  }
5474
5475  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5476  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5477  // words from all 4 input quadwords.
5478  SDValue NewV;
5479  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5480    SmallVector<int, 8> MaskV;
5481    MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5482    MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5483    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5484                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5485                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5486    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5487
5488    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5489    // source words for the shuffle, to aid later transformations.
5490    bool AllWordsInNewV = true;
5491    bool InOrder[2] = { true, true };
5492    for (unsigned i = 0; i != 8; ++i) {
5493      int idx = MaskVals[i];
5494      if (idx != (int)i)
5495        InOrder[i/4] = false;
5496      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5497        continue;
5498      AllWordsInNewV = false;
5499      break;
5500    }
5501
5502    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5503    if (AllWordsInNewV) {
5504      for (int i = 0; i != 8; ++i) {
5505        int idx = MaskVals[i];
5506        if (idx < 0)
5507          continue;
5508        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5509        if ((idx != i) && idx < 4)
5510          pshufhw = false;
5511        if ((idx != i) && idx > 3)
5512          pshuflw = false;
5513      }
5514      V1 = NewV;
5515      V2Used = false;
5516      BestLoQuad = 0;
5517      BestHiQuad = 1;
5518    }
5519
5520    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5521    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5522    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5523      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5524      unsigned TargetMask = 0;
5525      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5526                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5527      TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5528                             X86::getShufflePSHUFLWImmediate(NewV.getNode());
5529      V1 = NewV.getOperand(0);
5530      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5531    }
5532  }
5533
5534  // If we have SSSE3, and all words of the result are from 1 input vector,
5535  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5536  // is present, fall back to case 4.
5537  if (Subtarget->hasSSSE3()) {
5538    SmallVector<SDValue,16> pshufbMask;
5539
5540    // If we have elements from both input vectors, set the high bit of the
5541    // shuffle mask element to zero out elements that come from V2 in the V1
5542    // mask, and elements that come from V1 in the V2 mask, so that the two
5543    // results can be OR'd together.
5544    bool TwoInputs = V1Used && V2Used;
5545    for (unsigned i = 0; i != 8; ++i) {
5546      int EltIdx = MaskVals[i] * 2;
5547      if (TwoInputs && (EltIdx >= 16)) {
5548        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5549        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5550        continue;
5551      }
5552      pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5553      pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5554    }
5555    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5556    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5557                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5558                                 MVT::v16i8, &pshufbMask[0], 16));
5559    if (!TwoInputs)
5560      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5561
5562    // Calculate the shuffle mask for the second input, shuffle it, and
5563    // OR it with the first shuffled input.
5564    pshufbMask.clear();
5565    for (unsigned i = 0; i != 8; ++i) {
5566      int EltIdx = MaskVals[i] * 2;
5567      if (EltIdx < 16) {
5568        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5569        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5570        continue;
5571      }
5572      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5573      pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5574    }
5575    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5576    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5577                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5578                                 MVT::v16i8, &pshufbMask[0], 16));
5579    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5580    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5581  }
5582
5583  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5584  // and update MaskVals with new element order.
5585  BitVector InOrder(8);
5586  if (BestLoQuad >= 0) {
5587    SmallVector<int, 8> MaskV;
5588    for (int i = 0; i != 4; ++i) {
5589      int idx = MaskVals[i];
5590      if (idx < 0) {
5591        MaskV.push_back(-1);
5592        InOrder.set(i);
5593      } else if ((idx / 4) == BestLoQuad) {
5594        MaskV.push_back(idx & 3);
5595        InOrder.set(i);
5596      } else {
5597        MaskV.push_back(-1);
5598      }
5599    }
5600    for (unsigned i = 4; i != 8; ++i)
5601      MaskV.push_back(i);
5602    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5603                                &MaskV[0]);
5604
5605    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5606      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5607                               NewV.getOperand(0),
5608                               X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5609                               DAG);
5610  }
5611
5612  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5613  // and update MaskVals with the new element order.
5614  if (BestHiQuad >= 0) {
5615    SmallVector<int, 8> MaskV;
5616    for (unsigned i = 0; i != 4; ++i)
5617      MaskV.push_back(i);
5618    for (unsigned i = 4; i != 8; ++i) {
5619      int idx = MaskVals[i];
5620      if (idx < 0) {
5621        MaskV.push_back(-1);
5622        InOrder.set(i);
5623      } else if ((idx / 4) == BestHiQuad) {
5624        MaskV.push_back((idx & 3) + 4);
5625        InOrder.set(i);
5626      } else {
5627        MaskV.push_back(-1);
5628      }
5629    }
5630    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5631                                &MaskV[0]);
5632
5633    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5634      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5635                              NewV.getOperand(0),
5636                              X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5637                              DAG);
5638  }
5639
5640  // In case BestHi & BestLo were both -1, which means each quadword has a word
5641  // from each of the four input quadwords, calculate the InOrder bitvector now
5642  // before falling through to the insert/extract cleanup.
5643  if (BestLoQuad == -1 && BestHiQuad == -1) {
5644    NewV = V1;
5645    for (int i = 0; i != 8; ++i)
5646      if (MaskVals[i] < 0 || MaskVals[i] == i)
5647        InOrder.set(i);
5648  }
5649
5650  // The other elements are put in the right place using pextrw and pinsrw.
5651  for (unsigned i = 0; i != 8; ++i) {
5652    if (InOrder[i])
5653      continue;
5654    int EltIdx = MaskVals[i];
5655    if (EltIdx < 0)
5656      continue;
5657    SDValue ExtOp = (EltIdx < 8)
5658    ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5659                  DAG.getIntPtrConstant(EltIdx))
5660    : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5661                  DAG.getIntPtrConstant(EltIdx - 8));
5662    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5663                       DAG.getIntPtrConstant(i));
5664  }
5665  return NewV;
5666}
5667
5668// v16i8 shuffles - Prefer shuffles in the following order:
5669// 1. [ssse3] 1 x pshufb
5670// 2. [ssse3] 2 x pshufb + 1 x por
5671// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5672static
5673SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5674                                 SelectionDAG &DAG,
5675                                 const X86TargetLowering &TLI) {
5676  SDValue V1 = SVOp->getOperand(0);
5677  SDValue V2 = SVOp->getOperand(1);
5678  DebugLoc dl = SVOp->getDebugLoc();
5679  SmallVector<int, 16> MaskVals;
5680  SVOp->getMask(MaskVals);
5681
5682  // If we have SSSE3, case 1 is generated when all result bytes come from
5683  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5684  // present, fall back to case 3.
5685  // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5686  bool V1Only = true;
5687  bool V2Only = true;
5688  for (unsigned i = 0; i < 16; ++i) {
5689    int EltIdx = MaskVals[i];
5690    if (EltIdx < 0)
5691      continue;
5692    if (EltIdx < 16)
5693      V2Only = false;
5694    else
5695      V1Only = false;
5696  }
5697
5698  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5699  if (TLI.getSubtarget()->hasSSSE3()) {
5700    SmallVector<SDValue,16> pshufbMask;
5701
5702    // If all result elements are from one input vector, then only translate
5703    // undef mask values to 0x80 (zero out result) in the pshufb mask.
5704    //
5705    // Otherwise, we have elements from both input vectors, and must zero out
5706    // elements that come from V2 in the first mask, and V1 in the second mask
5707    // so that we can OR them together.
5708    bool TwoInputs = !(V1Only || V2Only);
5709    for (unsigned i = 0; i != 16; ++i) {
5710      int EltIdx = MaskVals[i];
5711      if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5712        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5713        continue;
5714      }
5715      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5716    }
5717    // If all the elements are from V2, assign it to V1 and return after
5718    // building the first pshufb.
5719    if (V2Only)
5720      V1 = V2;
5721    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5722                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5723                                 MVT::v16i8, &pshufbMask[0], 16));
5724    if (!TwoInputs)
5725      return V1;
5726
5727    // Calculate the shuffle mask for the second input, shuffle it, and
5728    // OR it with the first shuffled input.
5729    pshufbMask.clear();
5730    for (unsigned i = 0; i != 16; ++i) {
5731      int EltIdx = MaskVals[i];
5732      if (EltIdx < 16) {
5733        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5734        continue;
5735      }
5736      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5737    }
5738    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5739                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5740                                 MVT::v16i8, &pshufbMask[0], 16));
5741    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5742  }
5743
5744  // No SSSE3 - Calculate in place words and then fix all out of place words
5745  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5746  // the 16 different words that comprise the two doublequadword input vectors.
5747  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5748  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5749  SDValue NewV = V2Only ? V2 : V1;
5750  for (int i = 0; i != 8; ++i) {
5751    int Elt0 = MaskVals[i*2];
5752    int Elt1 = MaskVals[i*2+1];
5753
5754    // This word of the result is all undef, skip it.
5755    if (Elt0 < 0 && Elt1 < 0)
5756      continue;
5757
5758    // This word of the result is already in the correct place, skip it.
5759    if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5760      continue;
5761    if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5762      continue;
5763
5764    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5765    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5766    SDValue InsElt;
5767
5768    // If Elt0 and Elt1 are defined, are consecutive, and can be load
5769    // using a single extract together, load it and store it.
5770    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5771      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5772                           DAG.getIntPtrConstant(Elt1 / 2));
5773      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5774                        DAG.getIntPtrConstant(i));
5775      continue;
5776    }
5777
5778    // If Elt1 is defined, extract it from the appropriate source.  If the
5779    // source byte is not also odd, shift the extracted word left 8 bits
5780    // otherwise clear the bottom 8 bits if we need to do an or.
5781    if (Elt1 >= 0) {
5782      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5783                           DAG.getIntPtrConstant(Elt1 / 2));
5784      if ((Elt1 & 1) == 0)
5785        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5786                             DAG.getConstant(8,
5787                                  TLI.getShiftAmountTy(InsElt.getValueType())));
5788      else if (Elt0 >= 0)
5789        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5790                             DAG.getConstant(0xFF00, MVT::i16));
5791    }
5792    // If Elt0 is defined, extract it from the appropriate source.  If the
5793    // source byte is not also even, shift the extracted word right 8 bits. If
5794    // Elt1 was also defined, OR the extracted values together before
5795    // inserting them in the result.
5796    if (Elt0 >= 0) {
5797      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5798                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5799      if ((Elt0 & 1) != 0)
5800        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5801                              DAG.getConstant(8,
5802                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
5803      else if (Elt1 >= 0)
5804        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5805                             DAG.getConstant(0x00FF, MVT::i16));
5806      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5807                         : InsElt0;
5808    }
5809    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5810                       DAG.getIntPtrConstant(i));
5811  }
5812  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5813}
5814
5815/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5816/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5817/// done when every pair / quad of shuffle mask elements point to elements in
5818/// the right sequence. e.g.
5819/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5820static
5821SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5822                                 SelectionDAG &DAG, DebugLoc dl) {
5823  EVT VT = SVOp->getValueType(0);
5824  SDValue V1 = SVOp->getOperand(0);
5825  SDValue V2 = SVOp->getOperand(1);
5826  unsigned NumElems = VT.getVectorNumElements();
5827  unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5828  EVT NewVT;
5829  switch (VT.getSimpleVT().SimpleTy) {
5830  default: assert(false && "Unexpected!");
5831  case MVT::v4f32: NewVT = MVT::v2f64; break;
5832  case MVT::v4i32: NewVT = MVT::v2i64; break;
5833  case MVT::v8i16: NewVT = MVT::v4i32; break;
5834  case MVT::v16i8: NewVT = MVT::v4i32; break;
5835  }
5836
5837  int Scale = NumElems / NewWidth;
5838  SmallVector<int, 8> MaskVec;
5839  for (unsigned i = 0; i < NumElems; i += Scale) {
5840    int StartIdx = -1;
5841    for (int j = 0; j < Scale; ++j) {
5842      int EltIdx = SVOp->getMaskElt(i+j);
5843      if (EltIdx < 0)
5844        continue;
5845      if (StartIdx == -1)
5846        StartIdx = EltIdx - (EltIdx % Scale);
5847      if (EltIdx != StartIdx + j)
5848        return SDValue();
5849    }
5850    if (StartIdx == -1)
5851      MaskVec.push_back(-1);
5852    else
5853      MaskVec.push_back(StartIdx / Scale);
5854  }
5855
5856  V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5857  V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5858  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5859}
5860
5861/// getVZextMovL - Return a zero-extending vector move low node.
5862///
5863static SDValue getVZextMovL(EVT VT, EVT OpVT,
5864                            SDValue SrcOp, SelectionDAG &DAG,
5865                            const X86Subtarget *Subtarget, DebugLoc dl) {
5866  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5867    LoadSDNode *LD = NULL;
5868    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5869      LD = dyn_cast<LoadSDNode>(SrcOp);
5870    if (!LD) {
5871      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5872      // instead.
5873      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5874      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5875          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5876          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5877          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5878        // PR2108
5879        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5880        return DAG.getNode(ISD::BITCAST, dl, VT,
5881                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5882                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5883                                                   OpVT,
5884                                                   SrcOp.getOperand(0)
5885                                                          .getOperand(0))));
5886      }
5887    }
5888  }
5889
5890  return DAG.getNode(ISD::BITCAST, dl, VT,
5891                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5892                                 DAG.getNode(ISD::BITCAST, dl,
5893                                             OpVT, SrcOp)));
5894}
5895
5896/// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5897/// shuffle node referes to only one lane in the sources.
5898static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5899  EVT VT = SVOp->getValueType(0);
5900  int NumElems = VT.getVectorNumElements();
5901  int HalfSize = NumElems/2;
5902  SmallVector<int, 16> M;
5903  SVOp->getMask(M);
5904  bool MatchA = false, MatchB = false;
5905
5906  for (int l = 0; l < NumElems*2; l += HalfSize) {
5907    if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5908      MatchA = true;
5909      break;
5910    }
5911  }
5912
5913  for (int l = 0; l < NumElems*2; l += HalfSize) {
5914    if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5915      MatchB = true;
5916      break;
5917    }
5918  }
5919
5920  return MatchA && MatchB;
5921}
5922
5923/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5924/// which could not be matched by any known target speficic shuffle
5925static SDValue
5926LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5927  if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5928    // If each half of a vector shuffle node referes to only one lane in the
5929    // source vectors, extract each used 128-bit lane and shuffle them using
5930    // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5931    // the work to the legalizer.
5932    DebugLoc dl = SVOp->getDebugLoc();
5933    EVT VT = SVOp->getValueType(0);
5934    int NumElems = VT.getVectorNumElements();
5935    int HalfSize = NumElems/2;
5936
5937    // Extract the reference for each half
5938    int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5939    int FstVecOpNum = 0, SndVecOpNum = 0;
5940    for (int i = 0; i < HalfSize; ++i) {
5941      int Elt = SVOp->getMaskElt(i);
5942      if (SVOp->getMaskElt(i) < 0)
5943        continue;
5944      FstVecOpNum = Elt/NumElems;
5945      FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5946      break;
5947    }
5948    for (int i = HalfSize; i < NumElems; ++i) {
5949      int Elt = SVOp->getMaskElt(i);
5950      if (SVOp->getMaskElt(i) < 0)
5951        continue;
5952      SndVecOpNum = Elt/NumElems;
5953      SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5954      break;
5955    }
5956
5957    // Extract the subvectors
5958    SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5959                      DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5960    SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5961                      DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5962
5963    // Generate 128-bit shuffles
5964    SmallVector<int, 16> MaskV1, MaskV2;
5965    for (int i = 0; i < HalfSize; ++i) {
5966      int Elt = SVOp->getMaskElt(i);
5967      MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5968    }
5969    for (int i = HalfSize; i < NumElems; ++i) {
5970      int Elt = SVOp->getMaskElt(i);
5971      MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5972    }
5973
5974    EVT NVT = V1.getValueType();
5975    V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5976    V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5977
5978    // Concatenate the result back
5979    SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5980                                   DAG.getConstant(0, MVT::i32), DAG, dl);
5981    return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5982                              DAG, dl);
5983  }
5984
5985  return SDValue();
5986}
5987
5988/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5989/// 4 elements, and match them with several different shuffle types.
5990static SDValue
5991LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5992  SDValue V1 = SVOp->getOperand(0);
5993  SDValue V2 = SVOp->getOperand(1);
5994  DebugLoc dl = SVOp->getDebugLoc();
5995  EVT VT = SVOp->getValueType(0);
5996
5997  assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5998
5999  SmallVector<std::pair<int, int>, 8> Locs;
6000  Locs.resize(4);
6001  SmallVector<int, 8> Mask1(4U, -1);
6002  SmallVector<int, 8> PermMask;
6003  SVOp->getMask(PermMask);
6004
6005  unsigned NumHi = 0;
6006  unsigned NumLo = 0;
6007  for (unsigned i = 0; i != 4; ++i) {
6008    int Idx = PermMask[i];
6009    if (Idx < 0) {
6010      Locs[i] = std::make_pair(-1, -1);
6011    } else {
6012      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6013      if (Idx < 4) {
6014        Locs[i] = std::make_pair(0, NumLo);
6015        Mask1[NumLo] = Idx;
6016        NumLo++;
6017      } else {
6018        Locs[i] = std::make_pair(1, NumHi);
6019        if (2+NumHi < 4)
6020          Mask1[2+NumHi] = Idx;
6021        NumHi++;
6022      }
6023    }
6024  }
6025
6026  if (NumLo <= 2 && NumHi <= 2) {
6027    // If no more than two elements come from either vector. This can be
6028    // implemented with two shuffles. First shuffle gather the elements.
6029    // The second shuffle, which takes the first shuffle as both of its
6030    // vector operands, put the elements into the right order.
6031    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6032
6033    SmallVector<int, 8> Mask2(4U, -1);
6034
6035    for (unsigned i = 0; i != 4; ++i) {
6036      if (Locs[i].first == -1)
6037        continue;
6038      else {
6039        unsigned Idx = (i < 2) ? 0 : 4;
6040        Idx += Locs[i].first * 2 + Locs[i].second;
6041        Mask2[i] = Idx;
6042      }
6043    }
6044
6045    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6046  } else if (NumLo == 3 || NumHi == 3) {
6047    // Otherwise, we must have three elements from one vector, call it X, and
6048    // one element from the other, call it Y.  First, use a shufps to build an
6049    // intermediate vector with the one element from Y and the element from X
6050    // that will be in the same half in the final destination (the indexes don't
6051    // matter). Then, use a shufps to build the final vector, taking the half
6052    // containing the element from Y from the intermediate, and the other half
6053    // from X.
6054    if (NumHi == 3) {
6055      // Normalize it so the 3 elements come from V1.
6056      CommuteVectorShuffleMask(PermMask, VT);
6057      std::swap(V1, V2);
6058    }
6059
6060    // Find the element from V2.
6061    unsigned HiIndex;
6062    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6063      int Val = PermMask[HiIndex];
6064      if (Val < 0)
6065        continue;
6066      if (Val >= 4)
6067        break;
6068    }
6069
6070    Mask1[0] = PermMask[HiIndex];
6071    Mask1[1] = -1;
6072    Mask1[2] = PermMask[HiIndex^1];
6073    Mask1[3] = -1;
6074    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6075
6076    if (HiIndex >= 2) {
6077      Mask1[0] = PermMask[0];
6078      Mask1[1] = PermMask[1];
6079      Mask1[2] = HiIndex & 1 ? 6 : 4;
6080      Mask1[3] = HiIndex & 1 ? 4 : 6;
6081      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6082    } else {
6083      Mask1[0] = HiIndex & 1 ? 2 : 0;
6084      Mask1[1] = HiIndex & 1 ? 0 : 2;
6085      Mask1[2] = PermMask[2];
6086      Mask1[3] = PermMask[3];
6087      if (Mask1[2] >= 0)
6088        Mask1[2] += 4;
6089      if (Mask1[3] >= 0)
6090        Mask1[3] += 4;
6091      return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6092    }
6093  }
6094
6095  // Break it into (shuffle shuffle_hi, shuffle_lo).
6096  Locs.clear();
6097  Locs.resize(4);
6098  SmallVector<int,8> LoMask(4U, -1);
6099  SmallVector<int,8> HiMask(4U, -1);
6100
6101  SmallVector<int,8> *MaskPtr = &LoMask;
6102  unsigned MaskIdx = 0;
6103  unsigned LoIdx = 0;
6104  unsigned HiIdx = 2;
6105  for (unsigned i = 0; i != 4; ++i) {
6106    if (i == 2) {
6107      MaskPtr = &HiMask;
6108      MaskIdx = 1;
6109      LoIdx = 0;
6110      HiIdx = 2;
6111    }
6112    int Idx = PermMask[i];
6113    if (Idx < 0) {
6114      Locs[i] = std::make_pair(-1, -1);
6115    } else if (Idx < 4) {
6116      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6117      (*MaskPtr)[LoIdx] = Idx;
6118      LoIdx++;
6119    } else {
6120      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6121      (*MaskPtr)[HiIdx] = Idx;
6122      HiIdx++;
6123    }
6124  }
6125
6126  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6127  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6128  SmallVector<int, 8> MaskOps;
6129  for (unsigned i = 0; i != 4; ++i) {
6130    if (Locs[i].first == -1) {
6131      MaskOps.push_back(-1);
6132    } else {
6133      unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6134      MaskOps.push_back(Idx);
6135    }
6136  }
6137  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6138}
6139
6140static bool MayFoldVectorLoad(SDValue V) {
6141  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6142    V = V.getOperand(0);
6143  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6144    V = V.getOperand(0);
6145  if (MayFoldLoad(V))
6146    return true;
6147  return false;
6148}
6149
6150// FIXME: the version above should always be used. Since there's
6151// a bug where several vector shuffles can't be folded because the
6152// DAG is not updated during lowering and a node claims to have two
6153// uses while it only has one, use this version, and let isel match
6154// another instruction if the load really happens to have more than
6155// one use. Remove this version after this bug get fixed.
6156// rdar://8434668, PR8156
6157static bool RelaxedMayFoldVectorLoad(SDValue V) {
6158  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6159    V = V.getOperand(0);
6160  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6161    V = V.getOperand(0);
6162  if (ISD::isNormalLoad(V.getNode()))
6163    return true;
6164  return false;
6165}
6166
6167/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6168/// a vector extract, and if both can be later optimized into a single load.
6169/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6170/// here because otherwise a target specific shuffle node is going to be
6171/// emitted for this shuffle, and the optimization not done.
6172/// FIXME: This is probably not the best approach, but fix the problem
6173/// until the right path is decided.
6174static
6175bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6176                                         const TargetLowering &TLI) {
6177  EVT VT = V.getValueType();
6178  ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6179
6180  // Be sure that the vector shuffle is present in a pattern like this:
6181  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6182  if (!V.hasOneUse())
6183    return false;
6184
6185  SDNode *N = *V.getNode()->use_begin();
6186  if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6187    return false;
6188
6189  SDValue EltNo = N->getOperand(1);
6190  if (!isa<ConstantSDNode>(EltNo))
6191    return false;
6192
6193  // If the bit convert changed the number of elements, it is unsafe
6194  // to examine the mask.
6195  bool HasShuffleIntoBitcast = false;
6196  if (V.getOpcode() == ISD::BITCAST) {
6197    EVT SrcVT = V.getOperand(0).getValueType();
6198    if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6199      return false;
6200    V = V.getOperand(0);
6201    HasShuffleIntoBitcast = true;
6202  }
6203
6204  // Select the input vector, guarding against out of range extract vector.
6205  unsigned NumElems = VT.getVectorNumElements();
6206  unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6207  int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6208  V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6209
6210  // Skip one more bit_convert if necessary
6211  if (V.getOpcode() == ISD::BITCAST)
6212    V = V.getOperand(0);
6213
6214  if (ISD::isNormalLoad(V.getNode())) {
6215    // Is the original load suitable?
6216    LoadSDNode *LN0 = cast<LoadSDNode>(V);
6217
6218    // FIXME: avoid the multi-use bug that is preventing lots of
6219    // of foldings to be detected, this is still wrong of course, but
6220    // give the temporary desired behavior, and if it happens that
6221    // the load has real more uses, during isel it will not fold, and
6222    // will generate poor code.
6223    if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6224      return false;
6225
6226    if (!HasShuffleIntoBitcast)
6227      return true;
6228
6229    // If there's a bitcast before the shuffle, check if the load type and
6230    // alignment is valid.
6231    unsigned Align = LN0->getAlignment();
6232    unsigned NewAlign =
6233      TLI.getTargetData()->getABITypeAlignment(
6234                                    VT.getTypeForEVT(*DAG.getContext()));
6235
6236    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6237      return false;
6238  }
6239
6240  return true;
6241}
6242
6243static
6244SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6245  EVT VT = Op.getValueType();
6246
6247  // Canonizalize to v2f64.
6248  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6249  return DAG.getNode(ISD::BITCAST, dl, VT,
6250                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6251                                          V1, DAG));
6252}
6253
6254static
6255SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6256                        bool HasSSE2) {
6257  SDValue V1 = Op.getOperand(0);
6258  SDValue V2 = Op.getOperand(1);
6259  EVT VT = Op.getValueType();
6260
6261  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6262
6263  if (HasSSE2 && VT == MVT::v2f64)
6264    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6265
6266  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6267  return DAG.getNode(ISD::BITCAST, dl, VT,
6268                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6269                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6270                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6271}
6272
6273static
6274SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6275  SDValue V1 = Op.getOperand(0);
6276  SDValue V2 = Op.getOperand(1);
6277  EVT VT = Op.getValueType();
6278
6279  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6280         "unsupported shuffle type");
6281
6282  if (V2.getOpcode() == ISD::UNDEF)
6283    V2 = V1;
6284
6285  // v4i32 or v4f32
6286  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6287}
6288
6289static inline unsigned getSHUFPOpcode(EVT VT) {
6290  switch(VT.getSimpleVT().SimpleTy) {
6291  case MVT::v8i32: // Use fp unit for int unpack.
6292  case MVT::v8f32:
6293  case MVT::v4i32: // Use fp unit for int unpack.
6294  case MVT::v4f32: return X86ISD::SHUFPS;
6295  case MVT::v4i64: // Use fp unit for int unpack.
6296  case MVT::v4f64:
6297  case MVT::v2i64: // Use fp unit for int unpack.
6298  case MVT::v2f64: return X86ISD::SHUFPD;
6299  default:
6300    llvm_unreachable("Unknown type for shufp*");
6301  }
6302  return 0;
6303}
6304
6305static
6306SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6307  SDValue V1 = Op.getOperand(0);
6308  SDValue V2 = Op.getOperand(1);
6309  EVT VT = Op.getValueType();
6310  unsigned NumElems = VT.getVectorNumElements();
6311
6312  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6313  // operand of these instructions is only memory, so check if there's a
6314  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6315  // same masks.
6316  bool CanFoldLoad = false;
6317
6318  // Trivial case, when V2 comes from a load.
6319  if (MayFoldVectorLoad(V2))
6320    CanFoldLoad = true;
6321
6322  // When V1 is a load, it can be folded later into a store in isel, example:
6323  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6324  //    turns into:
6325  //  (MOVLPSmr addr:$src1, VR128:$src2)
6326  // So, recognize this potential and also use MOVLPS or MOVLPD
6327  if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6328    CanFoldLoad = true;
6329
6330  // Both of them can't be memory operations though.
6331  if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6332    CanFoldLoad = false;
6333
6334  if (CanFoldLoad) {
6335    if (HasSSE2 && NumElems == 2)
6336      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6337
6338    if (NumElems == 4)
6339      return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6340  }
6341
6342  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6343  // movl and movlp will both match v2i64, but v2i64 is never matched by
6344  // movl earlier because we make it strict to avoid messing with the movlp load
6345  // folding logic (see the code above getMOVLP call). Match it here then,
6346  // this is horrible, but will stay like this until we move all shuffle
6347  // matching to x86 specific nodes. Note that for the 1st condition all
6348  // types are matched with movsd.
6349  if (HasSSE2) {
6350    if (NumElems == 2)
6351      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6352    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6353  }
6354
6355  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6356
6357  // Invert the operand order and use SHUFPS to match it.
6358  return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6359                              X86::getShuffleSHUFImmediate(SVOp), DAG);
6360}
6361
6362static inline unsigned getUNPCKLOpcode(EVT VT) {
6363  switch(VT.getSimpleVT().SimpleTy) {
6364  case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6365  case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6366  case MVT::v4f32: return X86ISD::UNPCKLPS;
6367  case MVT::v2f64: return X86ISD::UNPCKLPD;
6368  case MVT::v8i32: // Use fp unit for int unpack.
6369  case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6370  case MVT::v4i64: // Use fp unit for int unpack.
6371  case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6372  case MVT::v16i8: return X86ISD::PUNPCKLBW;
6373  case MVT::v8i16: return X86ISD::PUNPCKLWD;
6374  default:
6375    llvm_unreachable("Unknown type for unpckl");
6376  }
6377  return 0;
6378}
6379
6380static inline unsigned getUNPCKHOpcode(EVT VT) {
6381  switch(VT.getSimpleVT().SimpleTy) {
6382  case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6383  case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6384  case MVT::v4f32: return X86ISD::UNPCKHPS;
6385  case MVT::v2f64: return X86ISD::UNPCKHPD;
6386  case MVT::v8i32: // Use fp unit for int unpack.
6387  case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6388  case MVT::v4i64: // Use fp unit for int unpack.
6389  case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6390  case MVT::v16i8: return X86ISD::PUNPCKHBW;
6391  case MVT::v8i16: return X86ISD::PUNPCKHWD;
6392  default:
6393    llvm_unreachable("Unknown type for unpckh");
6394  }
6395  return 0;
6396}
6397
6398static inline unsigned getVPERMILOpcode(EVT VT) {
6399  switch(VT.getSimpleVT().SimpleTy) {
6400  case MVT::v4i32:
6401  case MVT::v4f32: return X86ISD::VPERMILPS;
6402  case MVT::v2i64:
6403  case MVT::v2f64: return X86ISD::VPERMILPD;
6404  case MVT::v8i32:
6405  case MVT::v8f32: return X86ISD::VPERMILPSY;
6406  case MVT::v4i64:
6407  case MVT::v4f64: return X86ISD::VPERMILPDY;
6408  default:
6409    llvm_unreachable("Unknown type for vpermil");
6410  }
6411  return 0;
6412}
6413
6414/// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6415/// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6416/// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6417static bool isVectorBroadcast(SDValue &Op) {
6418  EVT VT = Op.getValueType();
6419  bool Is256 = VT.getSizeInBits() == 256;
6420
6421  assert((VT.getSizeInBits() == 128 || Is256) &&
6422         "Unsupported type for vbroadcast node");
6423
6424  SDValue V = Op;
6425  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6426    V = V.getOperand(0);
6427
6428  if (Is256 && !(V.hasOneUse() &&
6429                 V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6430                 V.getOperand(0).getOpcode() == ISD::UNDEF))
6431    return false;
6432
6433  if (Is256)
6434    V = V.getOperand(1);
6435
6436  if (!V.hasOneUse())
6437    return false;
6438
6439  // Check the source scalar_to_vector type. 256-bit broadcasts are
6440  // supported for 32/64-bit sizes, while 128-bit ones are only supported
6441  // for 32-bit scalars.
6442  if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6443    return false;
6444
6445  unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6446  if (ScalarSize != 32 && ScalarSize != 64)
6447    return false;
6448  if (!Is256 && ScalarSize == 64)
6449    return false;
6450
6451  V = V.getOperand(0);
6452  if (!MayFoldLoad(V))
6453    return false;
6454
6455  // Return the load node
6456  Op = V;
6457  return true;
6458}
6459
6460static
6461SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6462                               const TargetLowering &TLI,
6463                               const X86Subtarget *Subtarget) {
6464  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6465  EVT VT = Op.getValueType();
6466  DebugLoc dl = Op.getDebugLoc();
6467  SDValue V1 = Op.getOperand(0);
6468  SDValue V2 = Op.getOperand(1);
6469
6470  if (isZeroShuffle(SVOp))
6471    return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
6472
6473  // Handle splat operations
6474  if (SVOp->isSplat()) {
6475    unsigned NumElem = VT.getVectorNumElements();
6476    int Size = VT.getSizeInBits();
6477    // Special case, this is the only place now where it's allowed to return
6478    // a vector_shuffle operation without using a target specific node, because
6479    // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6480    // this be moved to DAGCombine instead?
6481    if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6482      return Op;
6483
6484    // Use vbroadcast whenever the splat comes from a foldable load
6485    if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6486      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6487
6488    // Handle splats by matching through known shuffle masks
6489    if ((Size == 128 && NumElem <= 4) ||
6490        (Size == 256 && NumElem < 8))
6491      return SDValue();
6492
6493    // All remaning splats are promoted to target supported vector shuffles.
6494    return PromoteSplat(SVOp, DAG);
6495  }
6496
6497  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6498  // do it!
6499  if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6500    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6501    if (NewOp.getNode())
6502      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6503  } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6504    // FIXME: Figure out a cleaner way to do this.
6505    // Try to make use of movq to zero out the top part.
6506    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6507      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6508      if (NewOp.getNode()) {
6509        if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6510          return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6511                              DAG, Subtarget, dl);
6512      }
6513    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6514      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6515      if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6516        return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6517                            DAG, Subtarget, dl);
6518    }
6519  }
6520  return SDValue();
6521}
6522
6523SDValue
6524X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6525  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6526  SDValue V1 = Op.getOperand(0);
6527  SDValue V2 = Op.getOperand(1);
6528  EVT VT = Op.getValueType();
6529  DebugLoc dl = Op.getDebugLoc();
6530  unsigned NumElems = VT.getVectorNumElements();
6531  bool isMMX = VT.getSizeInBits() == 64;
6532  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6533  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6534  bool V1IsSplat = false;
6535  bool V2IsSplat = false;
6536  bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
6537  bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
6538  bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
6539  MachineFunction &MF = DAG.getMachineFunction();
6540  bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6541
6542  // Shuffle operations on MMX not supported.
6543  if (isMMX)
6544    return Op;
6545
6546  // Vector shuffle lowering takes 3 steps:
6547  //
6548  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6549  //    narrowing and commutation of operands should be handled.
6550  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6551  //    shuffle nodes.
6552  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6553  //    so the shuffle can be broken into other shuffles and the legalizer can
6554  //    try the lowering again.
6555  //
6556  // The general ideia is that no vector_shuffle operation should be left to
6557  // be matched during isel, all of them must be converted to a target specific
6558  // node here.
6559
6560  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6561  // narrowing and commutation of operands should be handled. The actual code
6562  // doesn't include all of those, work in progress...
6563  SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6564  if (NewOp.getNode())
6565    return NewOp;
6566
6567  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6568  // unpckh_undef). Only use pshufd if speed is more important than size.
6569  if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6570    return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6571  if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6572    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6573
6574  if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
6575      RelaxedMayFoldVectorLoad(V1))
6576    return getMOVDDup(Op, dl, V1, DAG);
6577
6578  if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6579    return getMOVHighToLow(Op, dl, DAG);
6580
6581  // Use to match splats
6582  if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6583      (VT == MVT::v2f64 || VT == MVT::v2i64))
6584    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6585
6586  if (X86::isPSHUFDMask(SVOp)) {
6587    // The actual implementation will match the mask in the if above and then
6588    // during isel it can match several different instructions, not only pshufd
6589    // as its name says, sad but true, emulate the behavior for now...
6590    if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6591        return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6592
6593    unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6594
6595    if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6596      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6597
6598    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6599                                TargetMask, DAG);
6600  }
6601
6602  // Check if this can be converted into a logical shift.
6603  bool isLeft = false;
6604  unsigned ShAmt = 0;
6605  SDValue ShVal;
6606  bool isShift = getSubtarget()->hasSSE2() &&
6607    isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6608  if (isShift && ShVal.hasOneUse()) {
6609    // If the shifted value has multiple uses, it may be cheaper to use
6610    // v_set0 + movlhps or movhlps, etc.
6611    EVT EltVT = VT.getVectorElementType();
6612    ShAmt *= EltVT.getSizeInBits();
6613    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6614  }
6615
6616  if (X86::isMOVLMask(SVOp)) {
6617    if (V1IsUndef)
6618      return V2;
6619    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6620      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6621    if (!X86::isMOVLPMask(SVOp)) {
6622      if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6623        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6624
6625      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6626        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6627    }
6628  }
6629
6630  // FIXME: fold these into legal mask.
6631  if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6632    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6633
6634  if (X86::isMOVHLPSMask(SVOp))
6635    return getMOVHighToLow(Op, dl, DAG);
6636
6637  if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6638    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6639
6640  if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6641    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6642
6643  if (X86::isMOVLPMask(SVOp))
6644    return getMOVLP(Op, dl, DAG, HasSSE2);
6645
6646  if (ShouldXformToMOVHLPS(SVOp) ||
6647      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6648    return CommuteVectorShuffle(SVOp, DAG);
6649
6650  if (isShift) {
6651    // No better options. Use a vshl / vsrl.
6652    EVT EltVT = VT.getVectorElementType();
6653    ShAmt *= EltVT.getSizeInBits();
6654    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6655  }
6656
6657  bool Commuted = false;
6658  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6659  // 1,1,1,1 -> v8i16 though.
6660  V1IsSplat = isSplatVector(V1.getNode());
6661  V2IsSplat = isSplatVector(V2.getNode());
6662
6663  // Canonicalize the splat or undef, if present, to be on the RHS.
6664  if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6665    Op = CommuteVectorShuffle(SVOp, DAG);
6666    SVOp = cast<ShuffleVectorSDNode>(Op);
6667    V1 = SVOp->getOperand(0);
6668    V2 = SVOp->getOperand(1);
6669    std::swap(V1IsSplat, V2IsSplat);
6670    std::swap(V1IsUndef, V2IsUndef);
6671    Commuted = true;
6672  }
6673
6674  if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6675    // Shuffling low element of v1 into undef, just return v1.
6676    if (V2IsUndef)
6677      return V1;
6678    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6679    // the instruction selector will not match, so get a canonical MOVL with
6680    // swapped operands to undo the commute.
6681    return getMOVL(DAG, dl, VT, V2, V1);
6682  }
6683
6684  if (X86::isUNPCKLMask(SVOp))
6685    return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6686
6687  if (X86::isUNPCKHMask(SVOp))
6688    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6689
6690  if (V2IsSplat) {
6691    // Normalize mask so all entries that point to V2 points to its first
6692    // element then try to match unpck{h|l} again. If match, return a
6693    // new vector_shuffle with the corrected mask.
6694    SDValue NewMask = NormalizeMask(SVOp, DAG);
6695    ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6696    if (NSVOp != SVOp) {
6697      if (X86::isUNPCKLMask(NSVOp, true)) {
6698        return NewMask;
6699      } else if (X86::isUNPCKHMask(NSVOp, true)) {
6700        return NewMask;
6701      }
6702    }
6703  }
6704
6705  if (Commuted) {
6706    // Commute is back and try unpck* again.
6707    // FIXME: this seems wrong.
6708    SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6709    ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6710
6711    if (X86::isUNPCKLMask(NewSVOp))
6712      return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6713
6714    if (X86::isUNPCKHMask(NewSVOp))
6715      return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6716  }
6717
6718  // Normalize the node to match x86 shuffle ops if needed
6719  if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6720    return CommuteVectorShuffle(SVOp, DAG);
6721
6722  // The checks below are all present in isShuffleMaskLegal, but they are
6723  // inlined here right now to enable us to directly emit target specific
6724  // nodes, and remove one by one until they don't return Op anymore.
6725  SmallVector<int, 16> M;
6726  SVOp->getMask(M);
6727
6728  if (isPALIGNRMask(M, VT, HasSSSE3))
6729    return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6730                                X86::getShufflePALIGNRImmediate(SVOp),
6731                                DAG);
6732
6733  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6734      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6735    if (VT == MVT::v2f64)
6736      return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6737    if (VT == MVT::v2i64)
6738      return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6739  }
6740
6741  if (isPSHUFHWMask(M, VT))
6742    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6743                                X86::getShufflePSHUFHWImmediate(SVOp),
6744                                DAG);
6745
6746  if (isPSHUFLWMask(M, VT))
6747    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6748                                X86::getShufflePSHUFLWImmediate(SVOp),
6749                                DAG);
6750
6751  if (isSHUFPMask(M, VT))
6752    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6753                                X86::getShuffleSHUFImmediate(SVOp), DAG);
6754
6755  if (X86::isUNPCKL_v_undef_Mask(SVOp))
6756    return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6757  if (X86::isUNPCKH_v_undef_Mask(SVOp))
6758    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6759
6760  //===--------------------------------------------------------------------===//
6761  // Generate target specific nodes for 128 or 256-bit shuffles only
6762  // supported in the AVX instruction set.
6763  //
6764
6765  // Handle VMOVDDUPY permutations
6766  if (isMOVDDUPYMask(SVOp, Subtarget))
6767    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6768
6769  // Handle VPERMILPS* permutations
6770  if (isVPERMILPSMask(M, VT, Subtarget))
6771    return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6772                                getShuffleVPERMILPSImmediate(SVOp), DAG);
6773
6774  // Handle VPERMILPD* permutations
6775  if (isVPERMILPDMask(M, VT, Subtarget))
6776    return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6777                                getShuffleVPERMILPDImmediate(SVOp), DAG);
6778
6779  // Handle VPERM2F128 permutations
6780  if (isVPERM2F128Mask(M, VT, Subtarget))
6781    return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6782                                getShuffleVPERM2F128Immediate(SVOp), DAG);
6783
6784  // Handle VSHUFPSY permutations
6785  if (isVSHUFPSYMask(M, VT, Subtarget))
6786    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6787                                getShuffleVSHUFPSYImmediate(SVOp), DAG);
6788
6789  // Handle VSHUFPDY permutations
6790  if (isVSHUFPDYMask(M, VT, Subtarget))
6791    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6792                                getShuffleVSHUFPDYImmediate(SVOp), DAG);
6793
6794  //===--------------------------------------------------------------------===//
6795  // Since no target specific shuffle was selected for this generic one,
6796  // lower it into other known shuffles. FIXME: this isn't true yet, but
6797  // this is the plan.
6798  //
6799
6800  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6801  if (VT == MVT::v8i16) {
6802    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6803    if (NewOp.getNode())
6804      return NewOp;
6805  }
6806
6807  if (VT == MVT::v16i8) {
6808    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6809    if (NewOp.getNode())
6810      return NewOp;
6811  }
6812
6813  // Handle all 128-bit wide vectors with 4 elements, and match them with
6814  // several different shuffle types.
6815  if (NumElems == 4 && VT.getSizeInBits() == 128)
6816    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6817
6818  // Handle general 256-bit shuffles
6819  if (VT.is256BitVector())
6820    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6821
6822  return SDValue();
6823}
6824
6825SDValue
6826X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6827                                                SelectionDAG &DAG) const {
6828  EVT VT = Op.getValueType();
6829  DebugLoc dl = Op.getDebugLoc();
6830
6831  if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6832    return SDValue();
6833
6834  if (VT.getSizeInBits() == 8) {
6835    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6836                                    Op.getOperand(0), Op.getOperand(1));
6837    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6838                                    DAG.getValueType(VT));
6839    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6840  } else if (VT.getSizeInBits() == 16) {
6841    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6842    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6843    if (Idx == 0)
6844      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6845                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6846                                     DAG.getNode(ISD::BITCAST, dl,
6847                                                 MVT::v4i32,
6848                                                 Op.getOperand(0)),
6849                                     Op.getOperand(1)));
6850    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6851                                    Op.getOperand(0), Op.getOperand(1));
6852    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6853                                    DAG.getValueType(VT));
6854    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6855  } else if (VT == MVT::f32) {
6856    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6857    // the result back to FR32 register. It's only worth matching if the
6858    // result has a single use which is a store or a bitcast to i32.  And in
6859    // the case of a store, it's not worth it if the index is a constant 0,
6860    // because a MOVSSmr can be used instead, which is smaller and faster.
6861    if (!Op.hasOneUse())
6862      return SDValue();
6863    SDNode *User = *Op.getNode()->use_begin();
6864    if ((User->getOpcode() != ISD::STORE ||
6865         (isa<ConstantSDNode>(Op.getOperand(1)) &&
6866          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6867        (User->getOpcode() != ISD::BITCAST ||
6868         User->getValueType(0) != MVT::i32))
6869      return SDValue();
6870    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6871                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6872                                              Op.getOperand(0)),
6873                                              Op.getOperand(1));
6874    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6875  } else if (VT == MVT::i32) {
6876    // ExtractPS works with constant index.
6877    if (isa<ConstantSDNode>(Op.getOperand(1)))
6878      return Op;
6879  }
6880  return SDValue();
6881}
6882
6883
6884SDValue
6885X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6886                                           SelectionDAG &DAG) const {
6887  if (!isa<ConstantSDNode>(Op.getOperand(1)))
6888    return SDValue();
6889
6890  SDValue Vec = Op.getOperand(0);
6891  EVT VecVT = Vec.getValueType();
6892
6893  // If this is a 256-bit vector result, first extract the 128-bit vector and
6894  // then extract the element from the 128-bit vector.
6895  if (VecVT.getSizeInBits() == 256) {
6896    DebugLoc dl = Op.getNode()->getDebugLoc();
6897    unsigned NumElems = VecVT.getVectorNumElements();
6898    SDValue Idx = Op.getOperand(1);
6899    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6900
6901    // Get the 128-bit vector.
6902    bool Upper = IdxVal >= NumElems/2;
6903    Vec = Extract128BitVector(Vec,
6904                    DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6905
6906    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6907                    Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6908  }
6909
6910  assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6911
6912  if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6913    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6914    if (Res.getNode())
6915      return Res;
6916  }
6917
6918  EVT VT = Op.getValueType();
6919  DebugLoc dl = Op.getDebugLoc();
6920  // TODO: handle v16i8.
6921  if (VT.getSizeInBits() == 16) {
6922    SDValue Vec = Op.getOperand(0);
6923    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6924    if (Idx == 0)
6925      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6926                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6927                                     DAG.getNode(ISD::BITCAST, dl,
6928                                                 MVT::v4i32, Vec),
6929                                     Op.getOperand(1)));
6930    // Transform it so it match pextrw which produces a 32-bit result.
6931    EVT EltVT = MVT::i32;
6932    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6933                                    Op.getOperand(0), Op.getOperand(1));
6934    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6935                                    DAG.getValueType(VT));
6936    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6937  } else if (VT.getSizeInBits() == 32) {
6938    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6939    if (Idx == 0)
6940      return Op;
6941
6942    // SHUFPS the element to the lowest double word, then movss.
6943    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6944    EVT VVT = Op.getOperand(0).getValueType();
6945    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6946                                       DAG.getUNDEF(VVT), Mask);
6947    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6948                       DAG.getIntPtrConstant(0));
6949  } else if (VT.getSizeInBits() == 64) {
6950    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6951    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6952    //        to match extract_elt for f64.
6953    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6954    if (Idx == 0)
6955      return Op;
6956
6957    // UNPCKHPD the element to the lowest double word, then movsd.
6958    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6959    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6960    int Mask[2] = { 1, -1 };
6961    EVT VVT = Op.getOperand(0).getValueType();
6962    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6963                                       DAG.getUNDEF(VVT), Mask);
6964    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6965                       DAG.getIntPtrConstant(0));
6966  }
6967
6968  return SDValue();
6969}
6970
6971SDValue
6972X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6973                                               SelectionDAG &DAG) const {
6974  EVT VT = Op.getValueType();
6975  EVT EltVT = VT.getVectorElementType();
6976  DebugLoc dl = Op.getDebugLoc();
6977
6978  SDValue N0 = Op.getOperand(0);
6979  SDValue N1 = Op.getOperand(1);
6980  SDValue N2 = Op.getOperand(2);
6981
6982  if (VT.getSizeInBits() == 256)
6983    return SDValue();
6984
6985  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6986      isa<ConstantSDNode>(N2)) {
6987    unsigned Opc;
6988    if (VT == MVT::v8i16)
6989      Opc = X86ISD::PINSRW;
6990    else if (VT == MVT::v16i8)
6991      Opc = X86ISD::PINSRB;
6992    else
6993      Opc = X86ISD::PINSRB;
6994
6995    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6996    // argument.
6997    if (N1.getValueType() != MVT::i32)
6998      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6999    if (N2.getValueType() != MVT::i32)
7000      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7001    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7002  } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7003    // Bits [7:6] of the constant are the source select.  This will always be
7004    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7005    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7006    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7007    // Bits [5:4] of the constant are the destination select.  This is the
7008    //  value of the incoming immediate.
7009    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7010    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7011    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7012    // Create this as a scalar to vector..
7013    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7014    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7015  } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7016    // PINSR* works with constant index.
7017    return Op;
7018  }
7019  return SDValue();
7020}
7021
7022SDValue
7023X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7024  EVT VT = Op.getValueType();
7025  EVT EltVT = VT.getVectorElementType();
7026
7027  DebugLoc dl = Op.getDebugLoc();
7028  SDValue N0 = Op.getOperand(0);
7029  SDValue N1 = Op.getOperand(1);
7030  SDValue N2 = Op.getOperand(2);
7031
7032  // If this is a 256-bit vector result, first extract the 128-bit vector,
7033  // insert the element into the extracted half and then place it back.
7034  if (VT.getSizeInBits() == 256) {
7035    if (!isa<ConstantSDNode>(N2))
7036      return SDValue();
7037
7038    // Get the desired 128-bit vector half.
7039    unsigned NumElems = VT.getVectorNumElements();
7040    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7041    bool Upper = IdxVal >= NumElems/2;
7042    SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7043    SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7044
7045    // Insert the element into the desired half.
7046    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7047                 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7048
7049    // Insert the changed part back to the 256-bit vector
7050    return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7051  }
7052
7053  if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7054    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7055
7056  if (EltVT == MVT::i8)
7057    return SDValue();
7058
7059  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7060    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7061    // as its second argument.
7062    if (N1.getValueType() != MVT::i32)
7063      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7064    if (N2.getValueType() != MVT::i32)
7065      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7066    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7067  }
7068  return SDValue();
7069}
7070
7071SDValue
7072X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7073  LLVMContext *Context = DAG.getContext();
7074  DebugLoc dl = Op.getDebugLoc();
7075  EVT OpVT = Op.getValueType();
7076
7077  // If this is a 256-bit vector result, first insert into a 128-bit
7078  // vector and then insert into the 256-bit vector.
7079  if (OpVT.getSizeInBits() > 128) {
7080    // Insert into a 128-bit vector.
7081    EVT VT128 = EVT::getVectorVT(*Context,
7082                                 OpVT.getVectorElementType(),
7083                                 OpVT.getVectorNumElements() / 2);
7084
7085    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7086
7087    // Insert the 128-bit vector.
7088    return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7089                              DAG.getConstant(0, MVT::i32),
7090                              DAG, dl);
7091  }
7092
7093  if (Op.getValueType() == MVT::v1i64 &&
7094      Op.getOperand(0).getValueType() == MVT::i64)
7095    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7096
7097  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7098  assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7099         "Expected an SSE type!");
7100  return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7101                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7102}
7103
7104// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7105// a simple subregister reference or explicit instructions to grab
7106// upper bits of a vector.
7107SDValue
7108X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7109  if (Subtarget->hasAVX()) {
7110    DebugLoc dl = Op.getNode()->getDebugLoc();
7111    SDValue Vec = Op.getNode()->getOperand(0);
7112    SDValue Idx = Op.getNode()->getOperand(1);
7113
7114    if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7115        && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7116        return Extract128BitVector(Vec, Idx, DAG, dl);
7117    }
7118  }
7119  return SDValue();
7120}
7121
7122// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7123// simple superregister reference or explicit instructions to insert
7124// the upper bits of a vector.
7125SDValue
7126X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7127  if (Subtarget->hasAVX()) {
7128    DebugLoc dl = Op.getNode()->getDebugLoc();
7129    SDValue Vec = Op.getNode()->getOperand(0);
7130    SDValue SubVec = Op.getNode()->getOperand(1);
7131    SDValue Idx = Op.getNode()->getOperand(2);
7132
7133    if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7134        && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7135      return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7136    }
7137  }
7138  return SDValue();
7139}
7140
7141// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7142// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7143// one of the above mentioned nodes. It has to be wrapped because otherwise
7144// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7145// be used to form addressing mode. These wrapped nodes will be selected
7146// into MOV32ri.
7147SDValue
7148X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7149  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7150
7151  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7152  // global base reg.
7153  unsigned char OpFlag = 0;
7154  unsigned WrapperKind = X86ISD::Wrapper;
7155  CodeModel::Model M = getTargetMachine().getCodeModel();
7156
7157  if (Subtarget->isPICStyleRIPRel() &&
7158      (M == CodeModel::Small || M == CodeModel::Kernel))
7159    WrapperKind = X86ISD::WrapperRIP;
7160  else if (Subtarget->isPICStyleGOT())
7161    OpFlag = X86II::MO_GOTOFF;
7162  else if (Subtarget->isPICStyleStubPIC())
7163    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7164
7165  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7166                                             CP->getAlignment(),
7167                                             CP->getOffset(), OpFlag);
7168  DebugLoc DL = CP->getDebugLoc();
7169  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7170  // With PIC, the address is actually $g + Offset.
7171  if (OpFlag) {
7172    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7173                         DAG.getNode(X86ISD::GlobalBaseReg,
7174                                     DebugLoc(), getPointerTy()),
7175                         Result);
7176  }
7177
7178  return Result;
7179}
7180
7181SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7182  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7183
7184  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7185  // global base reg.
7186  unsigned char OpFlag = 0;
7187  unsigned WrapperKind = X86ISD::Wrapper;
7188  CodeModel::Model M = getTargetMachine().getCodeModel();
7189
7190  if (Subtarget->isPICStyleRIPRel() &&
7191      (M == CodeModel::Small || M == CodeModel::Kernel))
7192    WrapperKind = X86ISD::WrapperRIP;
7193  else if (Subtarget->isPICStyleGOT())
7194    OpFlag = X86II::MO_GOTOFF;
7195  else if (Subtarget->isPICStyleStubPIC())
7196    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7197
7198  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7199                                          OpFlag);
7200  DebugLoc DL = JT->getDebugLoc();
7201  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7202
7203  // With PIC, the address is actually $g + Offset.
7204  if (OpFlag)
7205    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7206                         DAG.getNode(X86ISD::GlobalBaseReg,
7207                                     DebugLoc(), getPointerTy()),
7208                         Result);
7209
7210  return Result;
7211}
7212
7213SDValue
7214X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7215  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7216
7217  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7218  // global base reg.
7219  unsigned char OpFlag = 0;
7220  unsigned WrapperKind = X86ISD::Wrapper;
7221  CodeModel::Model M = getTargetMachine().getCodeModel();
7222
7223  if (Subtarget->isPICStyleRIPRel() &&
7224      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7225    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7226      OpFlag = X86II::MO_GOTPCREL;
7227    WrapperKind = X86ISD::WrapperRIP;
7228  } else if (Subtarget->isPICStyleGOT()) {
7229    OpFlag = X86II::MO_GOT;
7230  } else if (Subtarget->isPICStyleStubPIC()) {
7231    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7232  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7233    OpFlag = X86II::MO_DARWIN_NONLAZY;
7234  }
7235
7236  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7237
7238  DebugLoc DL = Op.getDebugLoc();
7239  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7240
7241
7242  // With PIC, the address is actually $g + Offset.
7243  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7244      !Subtarget->is64Bit()) {
7245    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7246                         DAG.getNode(X86ISD::GlobalBaseReg,
7247                                     DebugLoc(), getPointerTy()),
7248                         Result);
7249  }
7250
7251  // For symbols that require a load from a stub to get the address, emit the
7252  // load.
7253  if (isGlobalStubReference(OpFlag))
7254    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7255                         MachinePointerInfo::getGOT(), false, false, 0);
7256
7257  return Result;
7258}
7259
7260SDValue
7261X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7262  // Create the TargetBlockAddressAddress node.
7263  unsigned char OpFlags =
7264    Subtarget->ClassifyBlockAddressReference();
7265  CodeModel::Model M = getTargetMachine().getCodeModel();
7266  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7267  DebugLoc dl = Op.getDebugLoc();
7268  SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7269                                       /*isTarget=*/true, OpFlags);
7270
7271  if (Subtarget->isPICStyleRIPRel() &&
7272      (M == CodeModel::Small || M == CodeModel::Kernel))
7273    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7274  else
7275    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7276
7277  // With PIC, the address is actually $g + Offset.
7278  if (isGlobalRelativeToPICBase(OpFlags)) {
7279    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7280                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7281                         Result);
7282  }
7283
7284  return Result;
7285}
7286
7287SDValue
7288X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7289                                      int64_t Offset,
7290                                      SelectionDAG &DAG) const {
7291  // Create the TargetGlobalAddress node, folding in the constant
7292  // offset if it is legal.
7293  unsigned char OpFlags =
7294    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7295  CodeModel::Model M = getTargetMachine().getCodeModel();
7296  SDValue Result;
7297  if (OpFlags == X86II::MO_NO_FLAG &&
7298      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7299    // A direct static reference to a global.
7300    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7301    Offset = 0;
7302  } else {
7303    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7304  }
7305
7306  if (Subtarget->isPICStyleRIPRel() &&
7307      (M == CodeModel::Small || M == CodeModel::Kernel))
7308    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7309  else
7310    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7311
7312  // With PIC, the address is actually $g + Offset.
7313  if (isGlobalRelativeToPICBase(OpFlags)) {
7314    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7315                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7316                         Result);
7317  }
7318
7319  // For globals that require a load from a stub to get the address, emit the
7320  // load.
7321  if (isGlobalStubReference(OpFlags))
7322    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7323                         MachinePointerInfo::getGOT(), false, false, 0);
7324
7325  // If there was a non-zero offset that we didn't fold, create an explicit
7326  // addition for it.
7327  if (Offset != 0)
7328    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7329                         DAG.getConstant(Offset, getPointerTy()));
7330
7331  return Result;
7332}
7333
7334SDValue
7335X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7336  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7337  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7338  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7339}
7340
7341static SDValue
7342GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7343           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7344           unsigned char OperandFlags) {
7345  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7346  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7347  DebugLoc dl = GA->getDebugLoc();
7348  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7349                                           GA->getValueType(0),
7350                                           GA->getOffset(),
7351                                           OperandFlags);
7352  if (InFlag) {
7353    SDValue Ops[] = { Chain,  TGA, *InFlag };
7354    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7355  } else {
7356    SDValue Ops[]  = { Chain, TGA };
7357    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7358  }
7359
7360  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7361  MFI->setAdjustsStack(true);
7362
7363  SDValue Flag = Chain.getValue(1);
7364  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7365}
7366
7367// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7368static SDValue
7369LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7370                                const EVT PtrVT) {
7371  SDValue InFlag;
7372  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7373  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7374                                     DAG.getNode(X86ISD::GlobalBaseReg,
7375                                                 DebugLoc(), PtrVT), InFlag);
7376  InFlag = Chain.getValue(1);
7377
7378  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7379}
7380
7381// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7382static SDValue
7383LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7384                                const EVT PtrVT) {
7385  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7386                    X86::RAX, X86II::MO_TLSGD);
7387}
7388
7389// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7390// "local exec" model.
7391static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7392                                   const EVT PtrVT, TLSModel::Model model,
7393                                   bool is64Bit) {
7394  DebugLoc dl = GA->getDebugLoc();
7395
7396  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7397  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7398                                                         is64Bit ? 257 : 256));
7399
7400  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7401                                      DAG.getIntPtrConstant(0),
7402                                      MachinePointerInfo(Ptr), false, false, 0);
7403
7404  unsigned char OperandFlags = 0;
7405  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7406  // initialexec.
7407  unsigned WrapperKind = X86ISD::Wrapper;
7408  if (model == TLSModel::LocalExec) {
7409    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7410  } else if (is64Bit) {
7411    assert(model == TLSModel::InitialExec);
7412    OperandFlags = X86II::MO_GOTTPOFF;
7413    WrapperKind = X86ISD::WrapperRIP;
7414  } else {
7415    assert(model == TLSModel::InitialExec);
7416    OperandFlags = X86II::MO_INDNTPOFF;
7417  }
7418
7419  // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7420  // exec)
7421  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7422                                           GA->getValueType(0),
7423                                           GA->getOffset(), OperandFlags);
7424  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7425
7426  if (model == TLSModel::InitialExec)
7427    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7428                         MachinePointerInfo::getGOT(), false, false, 0);
7429
7430  // The address of the thread local variable is the add of the thread
7431  // pointer with the offset of the variable.
7432  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7433}
7434
7435SDValue
7436X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7437
7438  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7439  const GlobalValue *GV = GA->getGlobal();
7440
7441  if (Subtarget->isTargetELF()) {
7442    // TODO: implement the "local dynamic" model
7443    // TODO: implement the "initial exec"model for pic executables
7444
7445    // If GV is an alias then use the aliasee for determining
7446    // thread-localness.
7447    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7448      GV = GA->resolveAliasedGlobal(false);
7449
7450    TLSModel::Model model
7451      = getTLSModel(GV, getTargetMachine().getRelocationModel());
7452
7453    switch (model) {
7454      case TLSModel::GeneralDynamic:
7455      case TLSModel::LocalDynamic: // not implemented
7456        if (Subtarget->is64Bit())
7457          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7458        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7459
7460      case TLSModel::InitialExec:
7461      case TLSModel::LocalExec:
7462        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7463                                   Subtarget->is64Bit());
7464    }
7465  } else if (Subtarget->isTargetDarwin()) {
7466    // Darwin only has one model of TLS.  Lower to that.
7467    unsigned char OpFlag = 0;
7468    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7469                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7470
7471    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7472    // global base reg.
7473    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7474                  !Subtarget->is64Bit();
7475    if (PIC32)
7476      OpFlag = X86II::MO_TLVP_PIC_BASE;
7477    else
7478      OpFlag = X86II::MO_TLVP;
7479    DebugLoc DL = Op.getDebugLoc();
7480    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7481                                                GA->getValueType(0),
7482                                                GA->getOffset(), OpFlag);
7483    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7484
7485    // With PIC32, the address is actually $g + Offset.
7486    if (PIC32)
7487      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7488                           DAG.getNode(X86ISD::GlobalBaseReg,
7489                                       DebugLoc(), getPointerTy()),
7490                           Offset);
7491
7492    // Lowering the machine isd will make sure everything is in the right
7493    // location.
7494    SDValue Chain = DAG.getEntryNode();
7495    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7496    SDValue Args[] = { Chain, Offset };
7497    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7498
7499    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7500    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7501    MFI->setAdjustsStack(true);
7502
7503    // And our return value (tls address) is in the standard call return value
7504    // location.
7505    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7506    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7507  }
7508
7509  assert(false &&
7510         "TLS not implemented for this target.");
7511
7512  llvm_unreachable("Unreachable");
7513  return SDValue();
7514}
7515
7516
7517/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7518/// take a 2 x i32 value to shift plus a shift amount.
7519SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7520  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7521  EVT VT = Op.getValueType();
7522  unsigned VTBits = VT.getSizeInBits();
7523  DebugLoc dl = Op.getDebugLoc();
7524  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7525  SDValue ShOpLo = Op.getOperand(0);
7526  SDValue ShOpHi = Op.getOperand(1);
7527  SDValue ShAmt  = Op.getOperand(2);
7528  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7529                                     DAG.getConstant(VTBits - 1, MVT::i8))
7530                       : DAG.getConstant(0, VT);
7531
7532  SDValue Tmp2, Tmp3;
7533  if (Op.getOpcode() == ISD::SHL_PARTS) {
7534    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7535    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7536  } else {
7537    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7538    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7539  }
7540
7541  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7542                                DAG.getConstant(VTBits, MVT::i8));
7543  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7544                             AndNode, DAG.getConstant(0, MVT::i8));
7545
7546  SDValue Hi, Lo;
7547  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7548  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7549  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7550
7551  if (Op.getOpcode() == ISD::SHL_PARTS) {
7552    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7553    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7554  } else {
7555    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7556    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7557  }
7558
7559  SDValue Ops[2] = { Lo, Hi };
7560  return DAG.getMergeValues(Ops, 2, dl);
7561}
7562
7563SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7564                                           SelectionDAG &DAG) const {
7565  EVT SrcVT = Op.getOperand(0).getValueType();
7566
7567  if (SrcVT.isVector())
7568    return SDValue();
7569
7570  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7571         "Unknown SINT_TO_FP to lower!");
7572
7573  // These are really Legal; return the operand so the caller accepts it as
7574  // Legal.
7575  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7576    return Op;
7577  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7578      Subtarget->is64Bit()) {
7579    return Op;
7580  }
7581
7582  DebugLoc dl = Op.getDebugLoc();
7583  unsigned Size = SrcVT.getSizeInBits()/8;
7584  MachineFunction &MF = DAG.getMachineFunction();
7585  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7586  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7587  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7588                               StackSlot,
7589                               MachinePointerInfo::getFixedStack(SSFI),
7590                               false, false, 0);
7591  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7592}
7593
7594SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7595                                     SDValue StackSlot,
7596                                     SelectionDAG &DAG) const {
7597  // Build the FILD
7598  DebugLoc DL = Op.getDebugLoc();
7599  SDVTList Tys;
7600  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7601  if (useSSE)
7602    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7603  else
7604    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7605
7606  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7607
7608  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7609  MachineMemOperand *MMO;
7610  if (FI) {
7611    int SSFI = FI->getIndex();
7612    MMO =
7613      DAG.getMachineFunction()
7614      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7615                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7616  } else {
7617    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7618    StackSlot = StackSlot.getOperand(1);
7619  }
7620  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7621  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7622                                           X86ISD::FILD, DL,
7623                                           Tys, Ops, array_lengthof(Ops),
7624                                           SrcVT, MMO);
7625
7626  if (useSSE) {
7627    Chain = Result.getValue(1);
7628    SDValue InFlag = Result.getValue(2);
7629
7630    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7631    // shouldn't be necessary except that RFP cannot be live across
7632    // multiple blocks. When stackifier is fixed, they can be uncoupled.
7633    MachineFunction &MF = DAG.getMachineFunction();
7634    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7635    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7636    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7637    Tys = DAG.getVTList(MVT::Other);
7638    SDValue Ops[] = {
7639      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7640    };
7641    MachineMemOperand *MMO =
7642      DAG.getMachineFunction()
7643      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7644                            MachineMemOperand::MOStore, SSFISize, SSFISize);
7645
7646    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7647                                    Ops, array_lengthof(Ops),
7648                                    Op.getValueType(), MMO);
7649    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7650                         MachinePointerInfo::getFixedStack(SSFI),
7651                         false, false, 0);
7652  }
7653
7654  return Result;
7655}
7656
7657// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7658SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7659                                               SelectionDAG &DAG) const {
7660  // This algorithm is not obvious. Here it is in C code, more or less:
7661  /*
7662    double uint64_to_double( uint32_t hi, uint32_t lo ) {
7663      static const __m128i exp = { 0x4330000045300000ULL, 0 };
7664      static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7665
7666      // Copy ints to xmm registers.
7667      __m128i xh = _mm_cvtsi32_si128( hi );
7668      __m128i xl = _mm_cvtsi32_si128( lo );
7669
7670      // Combine into low half of a single xmm register.
7671      __m128i x = _mm_unpacklo_epi32( xh, xl );
7672      __m128d d;
7673      double sd;
7674
7675      // Merge in appropriate exponents to give the integer bits the right
7676      // magnitude.
7677      x = _mm_unpacklo_epi32( x, exp );
7678
7679      // Subtract away the biases to deal with the IEEE-754 double precision
7680      // implicit 1.
7681      d = _mm_sub_pd( (__m128d) x, bias );
7682
7683      // All conversions up to here are exact. The correctly rounded result is
7684      // calculated using the current rounding mode using the following
7685      // horizontal add.
7686      d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7687      _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7688                                // store doesn't really need to be here (except
7689                                // maybe to zero the other double)
7690      return sd;
7691    }
7692  */
7693
7694  DebugLoc dl = Op.getDebugLoc();
7695  LLVMContext *Context = DAG.getContext();
7696
7697  // Build some magic constants.
7698  std::vector<Constant*> CV0;
7699  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7700  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7701  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7702  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7703  Constant *C0 = ConstantVector::get(CV0);
7704  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7705
7706  std::vector<Constant*> CV1;
7707  CV1.push_back(
7708    ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7709  CV1.push_back(
7710    ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7711  Constant *C1 = ConstantVector::get(CV1);
7712  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7713
7714  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7715                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7716                                        Op.getOperand(0),
7717                                        DAG.getIntPtrConstant(1)));
7718  SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7719                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7720                                        Op.getOperand(0),
7721                                        DAG.getIntPtrConstant(0)));
7722  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7723  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7724                              MachinePointerInfo::getConstantPool(),
7725                              false, false, 16);
7726  SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7727  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7728  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7729                              MachinePointerInfo::getConstantPool(),
7730                              false, false, 16);
7731  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7732
7733  // Add the halves; easiest way is to swap them into another reg first.
7734  int ShufMask[2] = { 1, -1 };
7735  SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7736                                      DAG.getUNDEF(MVT::v2f64), ShufMask);
7737  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7738  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7739                     DAG.getIntPtrConstant(0));
7740}
7741
7742// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7743SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7744                                               SelectionDAG &DAG) const {
7745  DebugLoc dl = Op.getDebugLoc();
7746  // FP constant to bias correct the final result.
7747  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7748                                   MVT::f64);
7749
7750  // Load the 32-bit value into an XMM register.
7751  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7752                             Op.getOperand(0));
7753
7754  // Zero out the upper parts of the register.
7755  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasSSE2(), DAG);
7756
7757  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7758                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7759                     DAG.getIntPtrConstant(0));
7760
7761  // Or the load with the bias.
7762  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7763                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7764                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7765                                                   MVT::v2f64, Load)),
7766                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7767                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7768                                                   MVT::v2f64, Bias)));
7769  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7770                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7771                   DAG.getIntPtrConstant(0));
7772
7773  // Subtract the bias.
7774  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7775
7776  // Handle final rounding.
7777  EVT DestVT = Op.getValueType();
7778
7779  if (DestVT.bitsLT(MVT::f64)) {
7780    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7781                       DAG.getIntPtrConstant(0));
7782  } else if (DestVT.bitsGT(MVT::f64)) {
7783    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7784  }
7785
7786  // Handle final rounding.
7787  return Sub;
7788}
7789
7790SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7791                                           SelectionDAG &DAG) const {
7792  SDValue N0 = Op.getOperand(0);
7793  DebugLoc dl = Op.getDebugLoc();
7794
7795  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7796  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7797  // the optimization here.
7798  if (DAG.SignBitIsZero(N0))
7799    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7800
7801  EVT SrcVT = N0.getValueType();
7802  EVT DstVT = Op.getValueType();
7803  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7804    return LowerUINT_TO_FP_i64(Op, DAG);
7805  else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7806    return LowerUINT_TO_FP_i32(Op, DAG);
7807
7808  // Make a 64-bit buffer, and use it to build an FILD.
7809  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7810  if (SrcVT == MVT::i32) {
7811    SDValue WordOff = DAG.getConstant(4, getPointerTy());
7812    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7813                                     getPointerTy(), StackSlot, WordOff);
7814    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7815                                  StackSlot, MachinePointerInfo(),
7816                                  false, false, 0);
7817    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7818                                  OffsetSlot, MachinePointerInfo(),
7819                                  false, false, 0);
7820    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7821    return Fild;
7822  }
7823
7824  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7825  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7826                                StackSlot, MachinePointerInfo(),
7827                               false, false, 0);
7828  // For i64 source, we need to add the appropriate power of 2 if the input
7829  // was negative.  This is the same as the optimization in
7830  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7831  // we must be careful to do the computation in x87 extended precision, not
7832  // in SSE. (The generic code can't know it's OK to do this, or how to.)
7833  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7834  MachineMemOperand *MMO =
7835    DAG.getMachineFunction()
7836    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7837                          MachineMemOperand::MOLoad, 8, 8);
7838
7839  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7840  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7841  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7842                                         MVT::i64, MMO);
7843
7844  APInt FF(32, 0x5F800000ULL);
7845
7846  // Check whether the sign bit is set.
7847  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7848                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7849                                 ISD::SETLT);
7850
7851  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7852  SDValue FudgePtr = DAG.getConstantPool(
7853                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7854                                         getPointerTy());
7855
7856  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7857  SDValue Zero = DAG.getIntPtrConstant(0);
7858  SDValue Four = DAG.getIntPtrConstant(4);
7859  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7860                               Zero, Four);
7861  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7862
7863  // Load the value out, extending it from f32 to f80.
7864  // FIXME: Avoid the extend by constructing the right constant pool?
7865  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7866                                 FudgePtr, MachinePointerInfo::getConstantPool(),
7867                                 MVT::f32, false, false, 4);
7868  // Extend everything to 80 bits to force it to be done on x87.
7869  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7870  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7871}
7872
7873std::pair<SDValue,SDValue> X86TargetLowering::
7874FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7875  DebugLoc DL = Op.getDebugLoc();
7876
7877  EVT DstTy = Op.getValueType();
7878
7879  if (!IsSigned) {
7880    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7881    DstTy = MVT::i64;
7882  }
7883
7884  assert(DstTy.getSimpleVT() <= MVT::i64 &&
7885         DstTy.getSimpleVT() >= MVT::i16 &&
7886         "Unknown FP_TO_SINT to lower!");
7887
7888  // These are really Legal.
7889  if (DstTy == MVT::i32 &&
7890      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7891    return std::make_pair(SDValue(), SDValue());
7892  if (Subtarget->is64Bit() &&
7893      DstTy == MVT::i64 &&
7894      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7895    return std::make_pair(SDValue(), SDValue());
7896
7897  // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7898  // stack slot.
7899  MachineFunction &MF = DAG.getMachineFunction();
7900  unsigned MemSize = DstTy.getSizeInBits()/8;
7901  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7902  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7903
7904
7905
7906  unsigned Opc;
7907  switch (DstTy.getSimpleVT().SimpleTy) {
7908  default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7909  case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7910  case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7911  case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7912  }
7913
7914  SDValue Chain = DAG.getEntryNode();
7915  SDValue Value = Op.getOperand(0);
7916  EVT TheVT = Op.getOperand(0).getValueType();
7917  if (isScalarFPTypeInSSEReg(TheVT)) {
7918    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7919    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7920                         MachinePointerInfo::getFixedStack(SSFI),
7921                         false, false, 0);
7922    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7923    SDValue Ops[] = {
7924      Chain, StackSlot, DAG.getValueType(TheVT)
7925    };
7926
7927    MachineMemOperand *MMO =
7928      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7929                              MachineMemOperand::MOLoad, MemSize, MemSize);
7930    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7931                                    DstTy, MMO);
7932    Chain = Value.getValue(1);
7933    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7934    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7935  }
7936
7937  MachineMemOperand *MMO =
7938    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7939                            MachineMemOperand::MOStore, MemSize, MemSize);
7940
7941  // Build the FP_TO_INT*_IN_MEM
7942  SDValue Ops[] = { Chain, Value, StackSlot };
7943  SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7944                                         Ops, 3, DstTy, MMO);
7945
7946  return std::make_pair(FIST, StackSlot);
7947}
7948
7949SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7950                                           SelectionDAG &DAG) const {
7951  if (Op.getValueType().isVector())
7952    return SDValue();
7953
7954  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7955  SDValue FIST = Vals.first, StackSlot = Vals.second;
7956  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7957  if (FIST.getNode() == 0) return Op;
7958
7959  // Load the result.
7960  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7961                     FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7962}
7963
7964SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7965                                           SelectionDAG &DAG) const {
7966  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7967  SDValue FIST = Vals.first, StackSlot = Vals.second;
7968  assert(FIST.getNode() && "Unexpected failure");
7969
7970  // Load the result.
7971  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7972                     FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7973}
7974
7975SDValue X86TargetLowering::LowerFABS(SDValue Op,
7976                                     SelectionDAG &DAG) const {
7977  LLVMContext *Context = DAG.getContext();
7978  DebugLoc dl = Op.getDebugLoc();
7979  EVT VT = Op.getValueType();
7980  EVT EltVT = VT;
7981  if (VT.isVector())
7982    EltVT = VT.getVectorElementType();
7983  std::vector<Constant*> CV;
7984  if (EltVT == MVT::f64) {
7985    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7986    CV.push_back(C);
7987    CV.push_back(C);
7988  } else {
7989    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7990    CV.push_back(C);
7991    CV.push_back(C);
7992    CV.push_back(C);
7993    CV.push_back(C);
7994  }
7995  Constant *C = ConstantVector::get(CV);
7996  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7997  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7998                             MachinePointerInfo::getConstantPool(),
7999                             false, false, 16);
8000  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8001}
8002
8003SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8004  LLVMContext *Context = DAG.getContext();
8005  DebugLoc dl = Op.getDebugLoc();
8006  EVT VT = Op.getValueType();
8007  EVT EltVT = VT;
8008  if (VT.isVector())
8009    EltVT = VT.getVectorElementType();
8010  std::vector<Constant*> CV;
8011  if (EltVT == MVT::f64) {
8012    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8013    CV.push_back(C);
8014    CV.push_back(C);
8015  } else {
8016    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8017    CV.push_back(C);
8018    CV.push_back(C);
8019    CV.push_back(C);
8020    CV.push_back(C);
8021  }
8022  Constant *C = ConstantVector::get(CV);
8023  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8024  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8025                             MachinePointerInfo::getConstantPool(),
8026                             false, false, 16);
8027  if (VT.isVector()) {
8028    return DAG.getNode(ISD::BITCAST, dl, VT,
8029                       DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8030                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8031                                Op.getOperand(0)),
8032                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8033  } else {
8034    return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8035  }
8036}
8037
8038SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8039  LLVMContext *Context = DAG.getContext();
8040  SDValue Op0 = Op.getOperand(0);
8041  SDValue Op1 = Op.getOperand(1);
8042  DebugLoc dl = Op.getDebugLoc();
8043  EVT VT = Op.getValueType();
8044  EVT SrcVT = Op1.getValueType();
8045
8046  // If second operand is smaller, extend it first.
8047  if (SrcVT.bitsLT(VT)) {
8048    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8049    SrcVT = VT;
8050  }
8051  // And if it is bigger, shrink it first.
8052  if (SrcVT.bitsGT(VT)) {
8053    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8054    SrcVT = VT;
8055  }
8056
8057  // At this point the operands and the result should have the same
8058  // type, and that won't be f80 since that is not custom lowered.
8059
8060  // First get the sign bit of second operand.
8061  std::vector<Constant*> CV;
8062  if (SrcVT == MVT::f64) {
8063    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8064    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8065  } else {
8066    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8067    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8068    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8069    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8070  }
8071  Constant *C = ConstantVector::get(CV);
8072  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8073  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8074                              MachinePointerInfo::getConstantPool(),
8075                              false, false, 16);
8076  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8077
8078  // Shift sign bit right or left if the two operands have different types.
8079  if (SrcVT.bitsGT(VT)) {
8080    // Op0 is MVT::f32, Op1 is MVT::f64.
8081    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8082    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8083                          DAG.getConstant(32, MVT::i32));
8084    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8085    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8086                          DAG.getIntPtrConstant(0));
8087  }
8088
8089  // Clear first operand sign bit.
8090  CV.clear();
8091  if (VT == MVT::f64) {
8092    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8093    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8094  } else {
8095    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8096    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8097    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8098    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8099  }
8100  C = ConstantVector::get(CV);
8101  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8102  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8103                              MachinePointerInfo::getConstantPool(),
8104                              false, false, 16);
8105  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8106
8107  // Or the value with the sign bit.
8108  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8109}
8110
8111SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8112  SDValue N0 = Op.getOperand(0);
8113  DebugLoc dl = Op.getDebugLoc();
8114  EVT VT = Op.getValueType();
8115
8116  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8117  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8118                                  DAG.getConstant(1, VT));
8119  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8120}
8121
8122/// Emit nodes that will be selected as "test Op0,Op0", or something
8123/// equivalent.
8124SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8125                                    SelectionDAG &DAG) const {
8126  DebugLoc dl = Op.getDebugLoc();
8127
8128  // CF and OF aren't always set the way we want. Determine which
8129  // of these we need.
8130  bool NeedCF = false;
8131  bool NeedOF = false;
8132  switch (X86CC) {
8133  default: break;
8134  case X86::COND_A: case X86::COND_AE:
8135  case X86::COND_B: case X86::COND_BE:
8136    NeedCF = true;
8137    break;
8138  case X86::COND_G: case X86::COND_GE:
8139  case X86::COND_L: case X86::COND_LE:
8140  case X86::COND_O: case X86::COND_NO:
8141    NeedOF = true;
8142    break;
8143  }
8144
8145  // See if we can use the EFLAGS value from the operand instead of
8146  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8147  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8148  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8149    // Emit a CMP with 0, which is the TEST pattern.
8150    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8151                       DAG.getConstant(0, Op.getValueType()));
8152
8153  unsigned Opcode = 0;
8154  unsigned NumOperands = 0;
8155  switch (Op.getNode()->getOpcode()) {
8156  case ISD::ADD:
8157    // Due to an isel shortcoming, be conservative if this add is likely to be
8158    // selected as part of a load-modify-store instruction. When the root node
8159    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8160    // uses of other nodes in the match, such as the ADD in this case. This
8161    // leads to the ADD being left around and reselected, with the result being
8162    // two adds in the output.  Alas, even if none our users are stores, that
8163    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8164    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8165    // climbing the DAG back to the root, and it doesn't seem to be worth the
8166    // effort.
8167    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8168           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8169      if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8170        goto default_case;
8171
8172    if (ConstantSDNode *C =
8173        dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8174      // An add of one will be selected as an INC.
8175      if (C->getAPIntValue() == 1) {
8176        Opcode = X86ISD::INC;
8177        NumOperands = 1;
8178        break;
8179      }
8180
8181      // An add of negative one (subtract of one) will be selected as a DEC.
8182      if (C->getAPIntValue().isAllOnesValue()) {
8183        Opcode = X86ISD::DEC;
8184        NumOperands = 1;
8185        break;
8186      }
8187    }
8188
8189    // Otherwise use a regular EFLAGS-setting add.
8190    Opcode = X86ISD::ADD;
8191    NumOperands = 2;
8192    break;
8193  case ISD::AND: {
8194    // If the primary and result isn't used, don't bother using X86ISD::AND,
8195    // because a TEST instruction will be better.
8196    bool NonFlagUse = false;
8197    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8198           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8199      SDNode *User = *UI;
8200      unsigned UOpNo = UI.getOperandNo();
8201      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8202        // Look pass truncate.
8203        UOpNo = User->use_begin().getOperandNo();
8204        User = *User->use_begin();
8205      }
8206
8207      if (User->getOpcode() != ISD::BRCOND &&
8208          User->getOpcode() != ISD::SETCC &&
8209          (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8210        NonFlagUse = true;
8211        break;
8212      }
8213    }
8214
8215    if (!NonFlagUse)
8216      break;
8217  }
8218    // FALL THROUGH
8219  case ISD::SUB:
8220  case ISD::OR:
8221  case ISD::XOR:
8222    // Due to the ISEL shortcoming noted above, be conservative if this op is
8223    // likely to be selected as part of a load-modify-store instruction.
8224    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8225           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8226      if (UI->getOpcode() == ISD::STORE)
8227        goto default_case;
8228
8229    // Otherwise use a regular EFLAGS-setting instruction.
8230    switch (Op.getNode()->getOpcode()) {
8231    default: llvm_unreachable("unexpected operator!");
8232    case ISD::SUB: Opcode = X86ISD::SUB; break;
8233    case ISD::OR:  Opcode = X86ISD::OR;  break;
8234    case ISD::XOR: Opcode = X86ISD::XOR; break;
8235    case ISD::AND: Opcode = X86ISD::AND; break;
8236    }
8237
8238    NumOperands = 2;
8239    break;
8240  case X86ISD::ADD:
8241  case X86ISD::SUB:
8242  case X86ISD::INC:
8243  case X86ISD::DEC:
8244  case X86ISD::OR:
8245  case X86ISD::XOR:
8246  case X86ISD::AND:
8247    return SDValue(Op.getNode(), 1);
8248  default:
8249  default_case:
8250    break;
8251  }
8252
8253  if (Opcode == 0)
8254    // Emit a CMP with 0, which is the TEST pattern.
8255    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8256                       DAG.getConstant(0, Op.getValueType()));
8257
8258  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8259  SmallVector<SDValue, 4> Ops;
8260  for (unsigned i = 0; i != NumOperands; ++i)
8261    Ops.push_back(Op.getOperand(i));
8262
8263  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8264  DAG.ReplaceAllUsesWith(Op, New);
8265  return SDValue(New.getNode(), 1);
8266}
8267
8268/// Emit nodes that will be selected as "cmp Op0,Op1", or something
8269/// equivalent.
8270SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8271                                   SelectionDAG &DAG) const {
8272  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8273    if (C->getAPIntValue() == 0)
8274      return EmitTest(Op0, X86CC, DAG);
8275
8276  DebugLoc dl = Op0.getDebugLoc();
8277  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8278}
8279
8280/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8281/// if it's possible.
8282SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8283                                     DebugLoc dl, SelectionDAG &DAG) const {
8284  SDValue Op0 = And.getOperand(0);
8285  SDValue Op1 = And.getOperand(1);
8286  if (Op0.getOpcode() == ISD::TRUNCATE)
8287    Op0 = Op0.getOperand(0);
8288  if (Op1.getOpcode() == ISD::TRUNCATE)
8289    Op1 = Op1.getOperand(0);
8290
8291  SDValue LHS, RHS;
8292  if (Op1.getOpcode() == ISD::SHL)
8293    std::swap(Op0, Op1);
8294  if (Op0.getOpcode() == ISD::SHL) {
8295    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8296      if (And00C->getZExtValue() == 1) {
8297        // If we looked past a truncate, check that it's only truncating away
8298        // known zeros.
8299        unsigned BitWidth = Op0.getValueSizeInBits();
8300        unsigned AndBitWidth = And.getValueSizeInBits();
8301        if (BitWidth > AndBitWidth) {
8302          APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8303          DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8304          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8305            return SDValue();
8306        }
8307        LHS = Op1;
8308        RHS = Op0.getOperand(1);
8309      }
8310  } else if (Op1.getOpcode() == ISD::Constant) {
8311    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8312    SDValue AndLHS = Op0;
8313    if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8314      LHS = AndLHS.getOperand(0);
8315      RHS = AndLHS.getOperand(1);
8316    }
8317  }
8318
8319  if (LHS.getNode()) {
8320    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8321    // instruction.  Since the shift amount is in-range-or-undefined, we know
8322    // that doing a bittest on the i32 value is ok.  We extend to i32 because
8323    // the encoding for the i16 version is larger than the i32 version.
8324    // Also promote i16 to i32 for performance / code size reason.
8325    if (LHS.getValueType() == MVT::i8 ||
8326        LHS.getValueType() == MVT::i16)
8327      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8328
8329    // If the operand types disagree, extend the shift amount to match.  Since
8330    // BT ignores high bits (like shifts) we can use anyextend.
8331    if (LHS.getValueType() != RHS.getValueType())
8332      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8333
8334    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8335    unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8336    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8337                       DAG.getConstant(Cond, MVT::i8), BT);
8338  }
8339
8340  return SDValue();
8341}
8342
8343SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8344
8345  if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8346
8347  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8348  SDValue Op0 = Op.getOperand(0);
8349  SDValue Op1 = Op.getOperand(1);
8350  DebugLoc dl = Op.getDebugLoc();
8351  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8352
8353  // Optimize to BT if possible.
8354  // Lower (X & (1 << N)) == 0 to BT(X, N).
8355  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8356  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8357  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8358      Op1.getOpcode() == ISD::Constant &&
8359      cast<ConstantSDNode>(Op1)->isNullValue() &&
8360      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8361    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8362    if (NewSetCC.getNode())
8363      return NewSetCC;
8364  }
8365
8366  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8367  // these.
8368  if (Op1.getOpcode() == ISD::Constant &&
8369      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8370       cast<ConstantSDNode>(Op1)->isNullValue()) &&
8371      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8372
8373    // If the input is a setcc, then reuse the input setcc or use a new one with
8374    // the inverted condition.
8375    if (Op0.getOpcode() == X86ISD::SETCC) {
8376      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8377      bool Invert = (CC == ISD::SETNE) ^
8378        cast<ConstantSDNode>(Op1)->isNullValue();
8379      if (!Invert) return Op0;
8380
8381      CCode = X86::GetOppositeBranchCondition(CCode);
8382      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8383                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8384    }
8385  }
8386
8387  bool isFP = Op1.getValueType().isFloatingPoint();
8388  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8389  if (X86CC == X86::COND_INVALID)
8390    return SDValue();
8391
8392  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8393  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8394                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8395}
8396
8397// Lower256IntVETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8398// ones, and then concatenate the result back.
8399static SDValue Lower256IntVETCC(SDValue Op, SelectionDAG &DAG) {
8400  EVT VT = Op.getValueType();
8401
8402  assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8403         "Unsupported value type for operation");
8404
8405  int NumElems = VT.getVectorNumElements();
8406  DebugLoc dl = Op.getDebugLoc();
8407  SDValue CC = Op.getOperand(2);
8408  SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8409  SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8410
8411  // Extract the LHS vectors
8412  SDValue LHS = Op.getOperand(0);
8413  SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8414  SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8415
8416  // Extract the RHS vectors
8417  SDValue RHS = Op.getOperand(1);
8418  SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8419  SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8420
8421  // Issue the operation on the smaller types and concatenate the result back
8422  MVT EltVT = VT.getVectorElementType().getSimpleVT();
8423  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8424  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8425                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8426                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8427}
8428
8429
8430SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8431  SDValue Cond;
8432  SDValue Op0 = Op.getOperand(0);
8433  SDValue Op1 = Op.getOperand(1);
8434  SDValue CC = Op.getOperand(2);
8435  EVT VT = Op.getValueType();
8436  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8437  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8438  DebugLoc dl = Op.getDebugLoc();
8439
8440  if (isFP) {
8441    unsigned SSECC = 8;
8442    EVT EltVT = Op0.getValueType().getVectorElementType();
8443    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8444
8445    unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8446    bool Swap = false;
8447
8448    switch (SetCCOpcode) {
8449    default: break;
8450    case ISD::SETOEQ:
8451    case ISD::SETEQ:  SSECC = 0; break;
8452    case ISD::SETOGT:
8453    case ISD::SETGT: Swap = true; // Fallthrough
8454    case ISD::SETLT:
8455    case ISD::SETOLT: SSECC = 1; break;
8456    case ISD::SETOGE:
8457    case ISD::SETGE: Swap = true; // Fallthrough
8458    case ISD::SETLE:
8459    case ISD::SETOLE: SSECC = 2; break;
8460    case ISD::SETUO:  SSECC = 3; break;
8461    case ISD::SETUNE:
8462    case ISD::SETNE:  SSECC = 4; break;
8463    case ISD::SETULE: Swap = true;
8464    case ISD::SETUGE: SSECC = 5; break;
8465    case ISD::SETULT: Swap = true;
8466    case ISD::SETUGT: SSECC = 6; break;
8467    case ISD::SETO:   SSECC = 7; break;
8468    }
8469    if (Swap)
8470      std::swap(Op0, Op1);
8471
8472    // In the two special cases we can't handle, emit two comparisons.
8473    if (SSECC == 8) {
8474      if (SetCCOpcode == ISD::SETUEQ) {
8475        SDValue UNORD, EQ;
8476        UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8477        EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8478        return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8479      }
8480      else if (SetCCOpcode == ISD::SETONE) {
8481        SDValue ORD, NEQ;
8482        ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8483        NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8484        return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8485      }
8486      llvm_unreachable("Illegal FP comparison");
8487    }
8488    // Handle all other FP comparisons here.
8489    return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8490  }
8491
8492  // Break 256-bit integer vector compare into smaller ones.
8493  if (!isFP && VT.getSizeInBits() == 256)
8494    return Lower256IntVETCC(Op, DAG);
8495
8496  // We are handling one of the integer comparisons here.  Since SSE only has
8497  // GT and EQ comparisons for integer, swapping operands and multiple
8498  // operations may be required for some comparisons.
8499  unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8500  bool Swap = false, Invert = false, FlipSigns = false;
8501
8502  switch (VT.getSimpleVT().SimpleTy) {
8503  default: break;
8504  case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8505  case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8506  case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8507  case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8508  }
8509
8510  switch (SetCCOpcode) {
8511  default: break;
8512  case ISD::SETNE:  Invert = true;
8513  case ISD::SETEQ:  Opc = EQOpc; break;
8514  case ISD::SETLT:  Swap = true;
8515  case ISD::SETGT:  Opc = GTOpc; break;
8516  case ISD::SETGE:  Swap = true;
8517  case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8518  case ISD::SETULT: Swap = true;
8519  case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8520  case ISD::SETUGE: Swap = true;
8521  case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8522  }
8523  if (Swap)
8524    std::swap(Op0, Op1);
8525
8526  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8527  // bits of the inputs before performing those operations.
8528  if (FlipSigns) {
8529    EVT EltVT = VT.getVectorElementType();
8530    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8531                                      EltVT);
8532    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8533    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8534                                    SignBits.size());
8535    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8536    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8537  }
8538
8539  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8540
8541  // If the logical-not of the result is required, perform that now.
8542  if (Invert)
8543    Result = DAG.getNOT(dl, Result, VT);
8544
8545  return Result;
8546}
8547
8548// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8549static bool isX86LogicalCmp(SDValue Op) {
8550  unsigned Opc = Op.getNode()->getOpcode();
8551  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8552    return true;
8553  if (Op.getResNo() == 1 &&
8554      (Opc == X86ISD::ADD ||
8555       Opc == X86ISD::SUB ||
8556       Opc == X86ISD::ADC ||
8557       Opc == X86ISD::SBB ||
8558       Opc == X86ISD::SMUL ||
8559       Opc == X86ISD::UMUL ||
8560       Opc == X86ISD::INC ||
8561       Opc == X86ISD::DEC ||
8562       Opc == X86ISD::OR ||
8563       Opc == X86ISD::XOR ||
8564       Opc == X86ISD::AND))
8565    return true;
8566
8567  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8568    return true;
8569
8570  return false;
8571}
8572
8573static bool isZero(SDValue V) {
8574  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8575  return C && C->isNullValue();
8576}
8577
8578static bool isAllOnes(SDValue V) {
8579  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8580  return C && C->isAllOnesValue();
8581}
8582
8583SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8584  bool addTest = true;
8585  SDValue Cond  = Op.getOperand(0);
8586  SDValue Op1 = Op.getOperand(1);
8587  SDValue Op2 = Op.getOperand(2);
8588  DebugLoc DL = Op.getDebugLoc();
8589  SDValue CC;
8590
8591  if (Cond.getOpcode() == ISD::SETCC) {
8592    SDValue NewCond = LowerSETCC(Cond, DAG);
8593    if (NewCond.getNode())
8594      Cond = NewCond;
8595  }
8596
8597  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8598  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8599  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8600  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8601  if (Cond.getOpcode() == X86ISD::SETCC &&
8602      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8603      isZero(Cond.getOperand(1).getOperand(1))) {
8604    SDValue Cmp = Cond.getOperand(1);
8605
8606    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8607
8608    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8609        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8610      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8611
8612      SDValue CmpOp0 = Cmp.getOperand(0);
8613      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8614                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8615
8616      SDValue Res =   // Res = 0 or -1.
8617        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8618                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8619
8620      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8621        Res = DAG.getNOT(DL, Res, Res.getValueType());
8622
8623      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8624      if (N2C == 0 || !N2C->isNullValue())
8625        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8626      return Res;
8627    }
8628  }
8629
8630  // Look past (and (setcc_carry (cmp ...)), 1).
8631  if (Cond.getOpcode() == ISD::AND &&
8632      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8633    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8634    if (C && C->getAPIntValue() == 1)
8635      Cond = Cond.getOperand(0);
8636  }
8637
8638  // If condition flag is set by a X86ISD::CMP, then use it as the condition
8639  // setting operand in place of the X86ISD::SETCC.
8640  if (Cond.getOpcode() == X86ISD::SETCC ||
8641      Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8642    CC = Cond.getOperand(0);
8643
8644    SDValue Cmp = Cond.getOperand(1);
8645    unsigned Opc = Cmp.getOpcode();
8646    EVT VT = Op.getValueType();
8647
8648    bool IllegalFPCMov = false;
8649    if (VT.isFloatingPoint() && !VT.isVector() &&
8650        !isScalarFPTypeInSSEReg(VT))  // FPStack?
8651      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8652
8653    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8654        Opc == X86ISD::BT) { // FIXME
8655      Cond = Cmp;
8656      addTest = false;
8657    }
8658  }
8659
8660  if (addTest) {
8661    // Look pass the truncate.
8662    if (Cond.getOpcode() == ISD::TRUNCATE)
8663      Cond = Cond.getOperand(0);
8664
8665    // We know the result of AND is compared against zero. Try to match
8666    // it to BT.
8667    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8668      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8669      if (NewSetCC.getNode()) {
8670        CC = NewSetCC.getOperand(0);
8671        Cond = NewSetCC.getOperand(1);
8672        addTest = false;
8673      }
8674    }
8675  }
8676
8677  if (addTest) {
8678    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8679    Cond = EmitTest(Cond, X86::COND_NE, DAG);
8680  }
8681
8682  // a <  b ? -1 :  0 -> RES = ~setcc_carry
8683  // a <  b ?  0 : -1 -> RES = setcc_carry
8684  // a >= b ? -1 :  0 -> RES = setcc_carry
8685  // a >= b ?  0 : -1 -> RES = ~setcc_carry
8686  if (Cond.getOpcode() == X86ISD::CMP) {
8687    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8688
8689    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8690        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8691      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8692                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8693      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8694        return DAG.getNOT(DL, Res, Res.getValueType());
8695      return Res;
8696    }
8697  }
8698
8699  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8700  // condition is true.
8701  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8702  SDValue Ops[] = { Op2, Op1, CC, Cond };
8703  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8704}
8705
8706// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8707// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8708// from the AND / OR.
8709static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8710  Opc = Op.getOpcode();
8711  if (Opc != ISD::OR && Opc != ISD::AND)
8712    return false;
8713  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8714          Op.getOperand(0).hasOneUse() &&
8715          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8716          Op.getOperand(1).hasOneUse());
8717}
8718
8719// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8720// 1 and that the SETCC node has a single use.
8721static bool isXor1OfSetCC(SDValue Op) {
8722  if (Op.getOpcode() != ISD::XOR)
8723    return false;
8724  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8725  if (N1C && N1C->getAPIntValue() == 1) {
8726    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8727      Op.getOperand(0).hasOneUse();
8728  }
8729  return false;
8730}
8731
8732SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8733  bool addTest = true;
8734  SDValue Chain = Op.getOperand(0);
8735  SDValue Cond  = Op.getOperand(1);
8736  SDValue Dest  = Op.getOperand(2);
8737  DebugLoc dl = Op.getDebugLoc();
8738  SDValue CC;
8739
8740  if (Cond.getOpcode() == ISD::SETCC) {
8741    SDValue NewCond = LowerSETCC(Cond, DAG);
8742    if (NewCond.getNode())
8743      Cond = NewCond;
8744  }
8745#if 0
8746  // FIXME: LowerXALUO doesn't handle these!!
8747  else if (Cond.getOpcode() == X86ISD::ADD  ||
8748           Cond.getOpcode() == X86ISD::SUB  ||
8749           Cond.getOpcode() == X86ISD::SMUL ||
8750           Cond.getOpcode() == X86ISD::UMUL)
8751    Cond = LowerXALUO(Cond, DAG);
8752#endif
8753
8754  // Look pass (and (setcc_carry (cmp ...)), 1).
8755  if (Cond.getOpcode() == ISD::AND &&
8756      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8757    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8758    if (C && C->getAPIntValue() == 1)
8759      Cond = Cond.getOperand(0);
8760  }
8761
8762  // If condition flag is set by a X86ISD::CMP, then use it as the condition
8763  // setting operand in place of the X86ISD::SETCC.
8764  if (Cond.getOpcode() == X86ISD::SETCC ||
8765      Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8766    CC = Cond.getOperand(0);
8767
8768    SDValue Cmp = Cond.getOperand(1);
8769    unsigned Opc = Cmp.getOpcode();
8770    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8771    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8772      Cond = Cmp;
8773      addTest = false;
8774    } else {
8775      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8776      default: break;
8777      case X86::COND_O:
8778      case X86::COND_B:
8779        // These can only come from an arithmetic instruction with overflow,
8780        // e.g. SADDO, UADDO.
8781        Cond = Cond.getNode()->getOperand(1);
8782        addTest = false;
8783        break;
8784      }
8785    }
8786  } else {
8787    unsigned CondOpc;
8788    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8789      SDValue Cmp = Cond.getOperand(0).getOperand(1);
8790      if (CondOpc == ISD::OR) {
8791        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8792        // two branches instead of an explicit OR instruction with a
8793        // separate test.
8794        if (Cmp == Cond.getOperand(1).getOperand(1) &&
8795            isX86LogicalCmp(Cmp)) {
8796          CC = Cond.getOperand(0).getOperand(0);
8797          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8798                              Chain, Dest, CC, Cmp);
8799          CC = Cond.getOperand(1).getOperand(0);
8800          Cond = Cmp;
8801          addTest = false;
8802        }
8803      } else { // ISD::AND
8804        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8805        // two branches instead of an explicit AND instruction with a
8806        // separate test. However, we only do this if this block doesn't
8807        // have a fall-through edge, because this requires an explicit
8808        // jmp when the condition is false.
8809        if (Cmp == Cond.getOperand(1).getOperand(1) &&
8810            isX86LogicalCmp(Cmp) &&
8811            Op.getNode()->hasOneUse()) {
8812          X86::CondCode CCode =
8813            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8814          CCode = X86::GetOppositeBranchCondition(CCode);
8815          CC = DAG.getConstant(CCode, MVT::i8);
8816          SDNode *User = *Op.getNode()->use_begin();
8817          // Look for an unconditional branch following this conditional branch.
8818          // We need this because we need to reverse the successors in order
8819          // to implement FCMP_OEQ.
8820          if (User->getOpcode() == ISD::BR) {
8821            SDValue FalseBB = User->getOperand(1);
8822            SDNode *NewBR =
8823              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8824            assert(NewBR == User);
8825            (void)NewBR;
8826            Dest = FalseBB;
8827
8828            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8829                                Chain, Dest, CC, Cmp);
8830            X86::CondCode CCode =
8831              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8832            CCode = X86::GetOppositeBranchCondition(CCode);
8833            CC = DAG.getConstant(CCode, MVT::i8);
8834            Cond = Cmp;
8835            addTest = false;
8836          }
8837        }
8838      }
8839    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8840      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8841      // It should be transformed during dag combiner except when the condition
8842      // is set by a arithmetics with overflow node.
8843      X86::CondCode CCode =
8844        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8845      CCode = X86::GetOppositeBranchCondition(CCode);
8846      CC = DAG.getConstant(CCode, MVT::i8);
8847      Cond = Cond.getOperand(0).getOperand(1);
8848      addTest = false;
8849    }
8850  }
8851
8852  if (addTest) {
8853    // Look pass the truncate.
8854    if (Cond.getOpcode() == ISD::TRUNCATE)
8855      Cond = Cond.getOperand(0);
8856
8857    // We know the result of AND is compared against zero. Try to match
8858    // it to BT.
8859    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8860      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8861      if (NewSetCC.getNode()) {
8862        CC = NewSetCC.getOperand(0);
8863        Cond = NewSetCC.getOperand(1);
8864        addTest = false;
8865      }
8866    }
8867  }
8868
8869  if (addTest) {
8870    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8871    Cond = EmitTest(Cond, X86::COND_NE, DAG);
8872  }
8873  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8874                     Chain, Dest, CC, Cond);
8875}
8876
8877
8878// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8879// Calls to _alloca is needed to probe the stack when allocating more than 4k
8880// bytes in one go. Touching the stack at 4K increments is necessary to ensure
8881// that the guard pages used by the OS virtual memory manager are allocated in
8882// correct sequence.
8883SDValue
8884X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8885                                           SelectionDAG &DAG) const {
8886  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8887          EnableSegmentedStacks) &&
8888         "This should be used only on Windows targets or when segmented stacks "
8889         "are being used");
8890  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8891  DebugLoc dl = Op.getDebugLoc();
8892
8893  // Get the inputs.
8894  SDValue Chain = Op.getOperand(0);
8895  SDValue Size  = Op.getOperand(1);
8896  // FIXME: Ensure alignment here
8897
8898  bool Is64Bit = Subtarget->is64Bit();
8899  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8900
8901  if (EnableSegmentedStacks) {
8902    MachineFunction &MF = DAG.getMachineFunction();
8903    MachineRegisterInfo &MRI = MF.getRegInfo();
8904
8905    if (Is64Bit) {
8906      // The 64 bit implementation of segmented stacks needs to clobber both r10
8907      // r11. This makes it impossible to use it along with nested parameters.
8908      const Function *F = MF.getFunction();
8909
8910      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8911           I != E; I++)
8912        if (I->hasNestAttr())
8913          report_fatal_error("Cannot use segmented stacks with functions that "
8914                             "have nested arguments.");
8915    }
8916
8917    const TargetRegisterClass *AddrRegClass =
8918      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8919    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8920    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8921    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8922                                DAG.getRegister(Vreg, SPTy));
8923    SDValue Ops1[2] = { Value, Chain };
8924    return DAG.getMergeValues(Ops1, 2, dl);
8925  } else {
8926    SDValue Flag;
8927    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8928
8929    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8930    Flag = Chain.getValue(1);
8931    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8932
8933    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8934    Flag = Chain.getValue(1);
8935
8936    Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8937
8938    SDValue Ops1[2] = { Chain.getValue(0), Chain };
8939    return DAG.getMergeValues(Ops1, 2, dl);
8940  }
8941}
8942
8943SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8944  MachineFunction &MF = DAG.getMachineFunction();
8945  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8946
8947  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8948  DebugLoc DL = Op.getDebugLoc();
8949
8950  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8951    // vastart just stores the address of the VarArgsFrameIndex slot into the
8952    // memory location argument.
8953    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8954                                   getPointerTy());
8955    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8956                        MachinePointerInfo(SV), false, false, 0);
8957  }
8958
8959  // __va_list_tag:
8960  //   gp_offset         (0 - 6 * 8)
8961  //   fp_offset         (48 - 48 + 8 * 16)
8962  //   overflow_arg_area (point to parameters coming in memory).
8963  //   reg_save_area
8964  SmallVector<SDValue, 8> MemOps;
8965  SDValue FIN = Op.getOperand(1);
8966  // Store gp_offset
8967  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8968                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8969                                               MVT::i32),
8970                               FIN, MachinePointerInfo(SV), false, false, 0);
8971  MemOps.push_back(Store);
8972
8973  // Store fp_offset
8974  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8975                    FIN, DAG.getIntPtrConstant(4));
8976  Store = DAG.getStore(Op.getOperand(0), DL,
8977                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8978                                       MVT::i32),
8979                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
8980  MemOps.push_back(Store);
8981
8982  // Store ptr to overflow_arg_area
8983  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8984                    FIN, DAG.getIntPtrConstant(4));
8985  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8986                                    getPointerTy());
8987  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8988                       MachinePointerInfo(SV, 8),
8989                       false, false, 0);
8990  MemOps.push_back(Store);
8991
8992  // Store ptr to reg_save_area.
8993  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8994                    FIN, DAG.getIntPtrConstant(8));
8995  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8996                                    getPointerTy());
8997  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8998                       MachinePointerInfo(SV, 16), false, false, 0);
8999  MemOps.push_back(Store);
9000  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9001                     &MemOps[0], MemOps.size());
9002}
9003
9004SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9005  assert(Subtarget->is64Bit() &&
9006         "LowerVAARG only handles 64-bit va_arg!");
9007  assert((Subtarget->isTargetLinux() ||
9008          Subtarget->isTargetDarwin()) &&
9009          "Unhandled target in LowerVAARG");
9010  assert(Op.getNode()->getNumOperands() == 4);
9011  SDValue Chain = Op.getOperand(0);
9012  SDValue SrcPtr = Op.getOperand(1);
9013  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9014  unsigned Align = Op.getConstantOperandVal(3);
9015  DebugLoc dl = Op.getDebugLoc();
9016
9017  EVT ArgVT = Op.getNode()->getValueType(0);
9018  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9019  uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9020  uint8_t ArgMode;
9021
9022  // Decide which area this value should be read from.
9023  // TODO: Implement the AMD64 ABI in its entirety. This simple
9024  // selection mechanism works only for the basic types.
9025  if (ArgVT == MVT::f80) {
9026    llvm_unreachable("va_arg for f80 not yet implemented");
9027  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9028    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9029  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9030    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9031  } else {
9032    llvm_unreachable("Unhandled argument type in LowerVAARG");
9033  }
9034
9035  if (ArgMode == 2) {
9036    // Sanity Check: Make sure using fp_offset makes sense.
9037    assert(!UseSoftFloat &&
9038           !(DAG.getMachineFunction()
9039                .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9040           Subtarget->hasXMM());
9041  }
9042
9043  // Insert VAARG_64 node into the DAG
9044  // VAARG_64 returns two values: Variable Argument Address, Chain
9045  SmallVector<SDValue, 11> InstOps;
9046  InstOps.push_back(Chain);
9047  InstOps.push_back(SrcPtr);
9048  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9049  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9050  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9051  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9052  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9053                                          VTs, &InstOps[0], InstOps.size(),
9054                                          MVT::i64,
9055                                          MachinePointerInfo(SV),
9056                                          /*Align=*/0,
9057                                          /*Volatile=*/false,
9058                                          /*ReadMem=*/true,
9059                                          /*WriteMem=*/true);
9060  Chain = VAARG.getValue(1);
9061
9062  // Load the next argument and return it
9063  return DAG.getLoad(ArgVT, dl,
9064                     Chain,
9065                     VAARG,
9066                     MachinePointerInfo(),
9067                     false, false, 0);
9068}
9069
9070SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9071  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9072  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9073  SDValue Chain = Op.getOperand(0);
9074  SDValue DstPtr = Op.getOperand(1);
9075  SDValue SrcPtr = Op.getOperand(2);
9076  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9077  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9078  DebugLoc DL = Op.getDebugLoc();
9079
9080  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9081                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9082                       false,
9083                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9084}
9085
9086SDValue
9087X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9088  DebugLoc dl = Op.getDebugLoc();
9089  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9090  switch (IntNo) {
9091  default: return SDValue();    // Don't custom lower most intrinsics.
9092  // Comparison intrinsics.
9093  case Intrinsic::x86_sse_comieq_ss:
9094  case Intrinsic::x86_sse_comilt_ss:
9095  case Intrinsic::x86_sse_comile_ss:
9096  case Intrinsic::x86_sse_comigt_ss:
9097  case Intrinsic::x86_sse_comige_ss:
9098  case Intrinsic::x86_sse_comineq_ss:
9099  case Intrinsic::x86_sse_ucomieq_ss:
9100  case Intrinsic::x86_sse_ucomilt_ss:
9101  case Intrinsic::x86_sse_ucomile_ss:
9102  case Intrinsic::x86_sse_ucomigt_ss:
9103  case Intrinsic::x86_sse_ucomige_ss:
9104  case Intrinsic::x86_sse_ucomineq_ss:
9105  case Intrinsic::x86_sse2_comieq_sd:
9106  case Intrinsic::x86_sse2_comilt_sd:
9107  case Intrinsic::x86_sse2_comile_sd:
9108  case Intrinsic::x86_sse2_comigt_sd:
9109  case Intrinsic::x86_sse2_comige_sd:
9110  case Intrinsic::x86_sse2_comineq_sd:
9111  case Intrinsic::x86_sse2_ucomieq_sd:
9112  case Intrinsic::x86_sse2_ucomilt_sd:
9113  case Intrinsic::x86_sse2_ucomile_sd:
9114  case Intrinsic::x86_sse2_ucomigt_sd:
9115  case Intrinsic::x86_sse2_ucomige_sd:
9116  case Intrinsic::x86_sse2_ucomineq_sd: {
9117    unsigned Opc = 0;
9118    ISD::CondCode CC = ISD::SETCC_INVALID;
9119    switch (IntNo) {
9120    default: break;
9121    case Intrinsic::x86_sse_comieq_ss:
9122    case Intrinsic::x86_sse2_comieq_sd:
9123      Opc = X86ISD::COMI;
9124      CC = ISD::SETEQ;
9125      break;
9126    case Intrinsic::x86_sse_comilt_ss:
9127    case Intrinsic::x86_sse2_comilt_sd:
9128      Opc = X86ISD::COMI;
9129      CC = ISD::SETLT;
9130      break;
9131    case Intrinsic::x86_sse_comile_ss:
9132    case Intrinsic::x86_sse2_comile_sd:
9133      Opc = X86ISD::COMI;
9134      CC = ISD::SETLE;
9135      break;
9136    case Intrinsic::x86_sse_comigt_ss:
9137    case Intrinsic::x86_sse2_comigt_sd:
9138      Opc = X86ISD::COMI;
9139      CC = ISD::SETGT;
9140      break;
9141    case Intrinsic::x86_sse_comige_ss:
9142    case Intrinsic::x86_sse2_comige_sd:
9143      Opc = X86ISD::COMI;
9144      CC = ISD::SETGE;
9145      break;
9146    case Intrinsic::x86_sse_comineq_ss:
9147    case Intrinsic::x86_sse2_comineq_sd:
9148      Opc = X86ISD::COMI;
9149      CC = ISD::SETNE;
9150      break;
9151    case Intrinsic::x86_sse_ucomieq_ss:
9152    case Intrinsic::x86_sse2_ucomieq_sd:
9153      Opc = X86ISD::UCOMI;
9154      CC = ISD::SETEQ;
9155      break;
9156    case Intrinsic::x86_sse_ucomilt_ss:
9157    case Intrinsic::x86_sse2_ucomilt_sd:
9158      Opc = X86ISD::UCOMI;
9159      CC = ISD::SETLT;
9160      break;
9161    case Intrinsic::x86_sse_ucomile_ss:
9162    case Intrinsic::x86_sse2_ucomile_sd:
9163      Opc = X86ISD::UCOMI;
9164      CC = ISD::SETLE;
9165      break;
9166    case Intrinsic::x86_sse_ucomigt_ss:
9167    case Intrinsic::x86_sse2_ucomigt_sd:
9168      Opc = X86ISD::UCOMI;
9169      CC = ISD::SETGT;
9170      break;
9171    case Intrinsic::x86_sse_ucomige_ss:
9172    case Intrinsic::x86_sse2_ucomige_sd:
9173      Opc = X86ISD::UCOMI;
9174      CC = ISD::SETGE;
9175      break;
9176    case Intrinsic::x86_sse_ucomineq_ss:
9177    case Intrinsic::x86_sse2_ucomineq_sd:
9178      Opc = X86ISD::UCOMI;
9179      CC = ISD::SETNE;
9180      break;
9181    }
9182
9183    SDValue LHS = Op.getOperand(1);
9184    SDValue RHS = Op.getOperand(2);
9185    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9186    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9187    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9188    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9189                                DAG.getConstant(X86CC, MVT::i8), Cond);
9190    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9191  }
9192  // ptest and testp intrinsics. The intrinsic these come from are designed to
9193  // return an integer value, not just an instruction so lower it to the ptest
9194  // or testp pattern and a setcc for the result.
9195  case Intrinsic::x86_sse41_ptestz:
9196  case Intrinsic::x86_sse41_ptestc:
9197  case Intrinsic::x86_sse41_ptestnzc:
9198  case Intrinsic::x86_avx_ptestz_256:
9199  case Intrinsic::x86_avx_ptestc_256:
9200  case Intrinsic::x86_avx_ptestnzc_256:
9201  case Intrinsic::x86_avx_vtestz_ps:
9202  case Intrinsic::x86_avx_vtestc_ps:
9203  case Intrinsic::x86_avx_vtestnzc_ps:
9204  case Intrinsic::x86_avx_vtestz_pd:
9205  case Intrinsic::x86_avx_vtestc_pd:
9206  case Intrinsic::x86_avx_vtestnzc_pd:
9207  case Intrinsic::x86_avx_vtestz_ps_256:
9208  case Intrinsic::x86_avx_vtestc_ps_256:
9209  case Intrinsic::x86_avx_vtestnzc_ps_256:
9210  case Intrinsic::x86_avx_vtestz_pd_256:
9211  case Intrinsic::x86_avx_vtestc_pd_256:
9212  case Intrinsic::x86_avx_vtestnzc_pd_256: {
9213    bool IsTestPacked = false;
9214    unsigned X86CC = 0;
9215    switch (IntNo) {
9216    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9217    case Intrinsic::x86_avx_vtestz_ps:
9218    case Intrinsic::x86_avx_vtestz_pd:
9219    case Intrinsic::x86_avx_vtestz_ps_256:
9220    case Intrinsic::x86_avx_vtestz_pd_256:
9221      IsTestPacked = true; // Fallthrough
9222    case Intrinsic::x86_sse41_ptestz:
9223    case Intrinsic::x86_avx_ptestz_256:
9224      // ZF = 1
9225      X86CC = X86::COND_E;
9226      break;
9227    case Intrinsic::x86_avx_vtestc_ps:
9228    case Intrinsic::x86_avx_vtestc_pd:
9229    case Intrinsic::x86_avx_vtestc_ps_256:
9230    case Intrinsic::x86_avx_vtestc_pd_256:
9231      IsTestPacked = true; // Fallthrough
9232    case Intrinsic::x86_sse41_ptestc:
9233    case Intrinsic::x86_avx_ptestc_256:
9234      // CF = 1
9235      X86CC = X86::COND_B;
9236      break;
9237    case Intrinsic::x86_avx_vtestnzc_ps:
9238    case Intrinsic::x86_avx_vtestnzc_pd:
9239    case Intrinsic::x86_avx_vtestnzc_ps_256:
9240    case Intrinsic::x86_avx_vtestnzc_pd_256:
9241      IsTestPacked = true; // Fallthrough
9242    case Intrinsic::x86_sse41_ptestnzc:
9243    case Intrinsic::x86_avx_ptestnzc_256:
9244      // ZF and CF = 0
9245      X86CC = X86::COND_A;
9246      break;
9247    }
9248
9249    SDValue LHS = Op.getOperand(1);
9250    SDValue RHS = Op.getOperand(2);
9251    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9252    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9253    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9254    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9255    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9256  }
9257
9258  // Fix vector shift instructions where the last operand is a non-immediate
9259  // i32 value.
9260  case Intrinsic::x86_sse2_pslli_w:
9261  case Intrinsic::x86_sse2_pslli_d:
9262  case Intrinsic::x86_sse2_pslli_q:
9263  case Intrinsic::x86_sse2_psrli_w:
9264  case Intrinsic::x86_sse2_psrli_d:
9265  case Intrinsic::x86_sse2_psrli_q:
9266  case Intrinsic::x86_sse2_psrai_w:
9267  case Intrinsic::x86_sse2_psrai_d:
9268  case Intrinsic::x86_mmx_pslli_w:
9269  case Intrinsic::x86_mmx_pslli_d:
9270  case Intrinsic::x86_mmx_pslli_q:
9271  case Intrinsic::x86_mmx_psrli_w:
9272  case Intrinsic::x86_mmx_psrli_d:
9273  case Intrinsic::x86_mmx_psrli_q:
9274  case Intrinsic::x86_mmx_psrai_w:
9275  case Intrinsic::x86_mmx_psrai_d: {
9276    SDValue ShAmt = Op.getOperand(2);
9277    if (isa<ConstantSDNode>(ShAmt))
9278      return SDValue();
9279
9280    unsigned NewIntNo = 0;
9281    EVT ShAmtVT = MVT::v4i32;
9282    switch (IntNo) {
9283    case Intrinsic::x86_sse2_pslli_w:
9284      NewIntNo = Intrinsic::x86_sse2_psll_w;
9285      break;
9286    case Intrinsic::x86_sse2_pslli_d:
9287      NewIntNo = Intrinsic::x86_sse2_psll_d;
9288      break;
9289    case Intrinsic::x86_sse2_pslli_q:
9290      NewIntNo = Intrinsic::x86_sse2_psll_q;
9291      break;
9292    case Intrinsic::x86_sse2_psrli_w:
9293      NewIntNo = Intrinsic::x86_sse2_psrl_w;
9294      break;
9295    case Intrinsic::x86_sse2_psrli_d:
9296      NewIntNo = Intrinsic::x86_sse2_psrl_d;
9297      break;
9298    case Intrinsic::x86_sse2_psrli_q:
9299      NewIntNo = Intrinsic::x86_sse2_psrl_q;
9300      break;
9301    case Intrinsic::x86_sse2_psrai_w:
9302      NewIntNo = Intrinsic::x86_sse2_psra_w;
9303      break;
9304    case Intrinsic::x86_sse2_psrai_d:
9305      NewIntNo = Intrinsic::x86_sse2_psra_d;
9306      break;
9307    default: {
9308      ShAmtVT = MVT::v2i32;
9309      switch (IntNo) {
9310      case Intrinsic::x86_mmx_pslli_w:
9311        NewIntNo = Intrinsic::x86_mmx_psll_w;
9312        break;
9313      case Intrinsic::x86_mmx_pslli_d:
9314        NewIntNo = Intrinsic::x86_mmx_psll_d;
9315        break;
9316      case Intrinsic::x86_mmx_pslli_q:
9317        NewIntNo = Intrinsic::x86_mmx_psll_q;
9318        break;
9319      case Intrinsic::x86_mmx_psrli_w:
9320        NewIntNo = Intrinsic::x86_mmx_psrl_w;
9321        break;
9322      case Intrinsic::x86_mmx_psrli_d:
9323        NewIntNo = Intrinsic::x86_mmx_psrl_d;
9324        break;
9325      case Intrinsic::x86_mmx_psrli_q:
9326        NewIntNo = Intrinsic::x86_mmx_psrl_q;
9327        break;
9328      case Intrinsic::x86_mmx_psrai_w:
9329        NewIntNo = Intrinsic::x86_mmx_psra_w;
9330        break;
9331      case Intrinsic::x86_mmx_psrai_d:
9332        NewIntNo = Intrinsic::x86_mmx_psra_d;
9333        break;
9334      default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9335      }
9336      break;
9337    }
9338    }
9339
9340    // The vector shift intrinsics with scalars uses 32b shift amounts but
9341    // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9342    // to be zero.
9343    SDValue ShOps[4];
9344    ShOps[0] = ShAmt;
9345    ShOps[1] = DAG.getConstant(0, MVT::i32);
9346    if (ShAmtVT == MVT::v4i32) {
9347      ShOps[2] = DAG.getUNDEF(MVT::i32);
9348      ShOps[3] = DAG.getUNDEF(MVT::i32);
9349      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9350    } else {
9351      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9352// FIXME this must be lowered to get rid of the invalid type.
9353    }
9354
9355    EVT VT = Op.getValueType();
9356    ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9357    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9358                       DAG.getConstant(NewIntNo, MVT::i32),
9359                       Op.getOperand(1), ShAmt);
9360  }
9361  }
9362}
9363
9364SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9365                                           SelectionDAG &DAG) const {
9366  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9367  MFI->setReturnAddressIsTaken(true);
9368
9369  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9370  DebugLoc dl = Op.getDebugLoc();
9371
9372  if (Depth > 0) {
9373    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9374    SDValue Offset =
9375      DAG.getConstant(TD->getPointerSize(),
9376                      Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9377    return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9378                       DAG.getNode(ISD::ADD, dl, getPointerTy(),
9379                                   FrameAddr, Offset),
9380                       MachinePointerInfo(), false, false, 0);
9381  }
9382
9383  // Just load the return address.
9384  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9385  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9386                     RetAddrFI, MachinePointerInfo(), false, false, 0);
9387}
9388
9389SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9390  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9391  MFI->setFrameAddressIsTaken(true);
9392
9393  EVT VT = Op.getValueType();
9394  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9395  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9396  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9397  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9398  while (Depth--)
9399    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9400                            MachinePointerInfo(),
9401                            false, false, 0);
9402  return FrameAddr;
9403}
9404
9405SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9406                                                     SelectionDAG &DAG) const {
9407  return DAG.getIntPtrConstant(2*TD->getPointerSize());
9408}
9409
9410SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9411  MachineFunction &MF = DAG.getMachineFunction();
9412  SDValue Chain     = Op.getOperand(0);
9413  SDValue Offset    = Op.getOperand(1);
9414  SDValue Handler   = Op.getOperand(2);
9415  DebugLoc dl       = Op.getDebugLoc();
9416
9417  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9418                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9419                                     getPointerTy());
9420  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9421
9422  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9423                                  DAG.getIntPtrConstant(TD->getPointerSize()));
9424  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9425  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9426                       false, false, 0);
9427  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9428  MF.getRegInfo().addLiveOut(StoreAddrReg);
9429
9430  return DAG.getNode(X86ISD::EH_RETURN, dl,
9431                     MVT::Other,
9432                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9433}
9434
9435SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9436                                                  SelectionDAG &DAG) const {
9437  return Op.getOperand(0);
9438}
9439
9440SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9441                                                SelectionDAG &DAG) const {
9442  SDValue Root = Op.getOperand(0);
9443  SDValue Trmp = Op.getOperand(1); // trampoline
9444  SDValue FPtr = Op.getOperand(2); // nested function
9445  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9446  DebugLoc dl  = Op.getDebugLoc();
9447
9448  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9449
9450  if (Subtarget->is64Bit()) {
9451    SDValue OutChains[6];
9452
9453    // Large code-model.
9454    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9455    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9456
9457    const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9458    const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9459
9460    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9461
9462    // Load the pointer to the nested function into R11.
9463    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9464    SDValue Addr = Trmp;
9465    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9466                                Addr, MachinePointerInfo(TrmpAddr),
9467                                false, false, 0);
9468
9469    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9470                       DAG.getConstant(2, MVT::i64));
9471    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9472                                MachinePointerInfo(TrmpAddr, 2),
9473                                false, false, 2);
9474
9475    // Load the 'nest' parameter value into R10.
9476    // R10 is specified in X86CallingConv.td
9477    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9478    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9479                       DAG.getConstant(10, MVT::i64));
9480    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9481                                Addr, MachinePointerInfo(TrmpAddr, 10),
9482                                false, false, 0);
9483
9484    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9485                       DAG.getConstant(12, MVT::i64));
9486    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9487                                MachinePointerInfo(TrmpAddr, 12),
9488                                false, false, 2);
9489
9490    // Jump to the nested function.
9491    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9492    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9493                       DAG.getConstant(20, MVT::i64));
9494    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9495                                Addr, MachinePointerInfo(TrmpAddr, 20),
9496                                false, false, 0);
9497
9498    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9499    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9500                       DAG.getConstant(22, MVT::i64));
9501    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9502                                MachinePointerInfo(TrmpAddr, 22),
9503                                false, false, 0);
9504
9505    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9506  } else {
9507    const Function *Func =
9508      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9509    CallingConv::ID CC = Func->getCallingConv();
9510    unsigned NestReg;
9511
9512    switch (CC) {
9513    default:
9514      llvm_unreachable("Unsupported calling convention");
9515    case CallingConv::C:
9516    case CallingConv::X86_StdCall: {
9517      // Pass 'nest' parameter in ECX.
9518      // Must be kept in sync with X86CallingConv.td
9519      NestReg = X86::ECX;
9520
9521      // Check that ECX wasn't needed by an 'inreg' parameter.
9522      FunctionType *FTy = Func->getFunctionType();
9523      const AttrListPtr &Attrs = Func->getAttributes();
9524
9525      if (!Attrs.isEmpty() && !Func->isVarArg()) {
9526        unsigned InRegCount = 0;
9527        unsigned Idx = 1;
9528
9529        for (FunctionType::param_iterator I = FTy->param_begin(),
9530             E = FTy->param_end(); I != E; ++I, ++Idx)
9531          if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9532            // FIXME: should only count parameters that are lowered to integers.
9533            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9534
9535        if (InRegCount > 2) {
9536          report_fatal_error("Nest register in use - reduce number of inreg"
9537                             " parameters!");
9538        }
9539      }
9540      break;
9541    }
9542    case CallingConv::X86_FastCall:
9543    case CallingConv::X86_ThisCall:
9544    case CallingConv::Fast:
9545      // Pass 'nest' parameter in EAX.
9546      // Must be kept in sync with X86CallingConv.td
9547      NestReg = X86::EAX;
9548      break;
9549    }
9550
9551    SDValue OutChains[4];
9552    SDValue Addr, Disp;
9553
9554    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9555                       DAG.getConstant(10, MVT::i32));
9556    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9557
9558    // This is storing the opcode for MOV32ri.
9559    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9560    const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9561    OutChains[0] = DAG.getStore(Root, dl,
9562                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9563                                Trmp, MachinePointerInfo(TrmpAddr),
9564                                false, false, 0);
9565
9566    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9567                       DAG.getConstant(1, MVT::i32));
9568    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9569                                MachinePointerInfo(TrmpAddr, 1),
9570                                false, false, 1);
9571
9572    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9573    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9574                       DAG.getConstant(5, MVT::i32));
9575    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9576                                MachinePointerInfo(TrmpAddr, 5),
9577                                false, false, 1);
9578
9579    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9580                       DAG.getConstant(6, MVT::i32));
9581    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9582                                MachinePointerInfo(TrmpAddr, 6),
9583                                false, false, 1);
9584
9585    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9586  }
9587}
9588
9589SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9590                                            SelectionDAG &DAG) const {
9591  /*
9592   The rounding mode is in bits 11:10 of FPSR, and has the following
9593   settings:
9594     00 Round to nearest
9595     01 Round to -inf
9596     10 Round to +inf
9597     11 Round to 0
9598
9599  FLT_ROUNDS, on the other hand, expects the following:
9600    -1 Undefined
9601     0 Round to 0
9602     1 Round to nearest
9603     2 Round to +inf
9604     3 Round to -inf
9605
9606  To perform the conversion, we do:
9607    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9608  */
9609
9610  MachineFunction &MF = DAG.getMachineFunction();
9611  const TargetMachine &TM = MF.getTarget();
9612  const TargetFrameLowering &TFI = *TM.getFrameLowering();
9613  unsigned StackAlignment = TFI.getStackAlignment();
9614  EVT VT = Op.getValueType();
9615  DebugLoc DL = Op.getDebugLoc();
9616
9617  // Save FP Control Word to stack slot
9618  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9619  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9620
9621
9622  MachineMemOperand *MMO =
9623   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9624                           MachineMemOperand::MOStore, 2, 2);
9625
9626  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9627  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9628                                          DAG.getVTList(MVT::Other),
9629                                          Ops, 2, MVT::i16, MMO);
9630
9631  // Load FP Control Word from stack slot
9632  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9633                            MachinePointerInfo(), false, false, 0);
9634
9635  // Transform as necessary
9636  SDValue CWD1 =
9637    DAG.getNode(ISD::SRL, DL, MVT::i16,
9638                DAG.getNode(ISD::AND, DL, MVT::i16,
9639                            CWD, DAG.getConstant(0x800, MVT::i16)),
9640                DAG.getConstant(11, MVT::i8));
9641  SDValue CWD2 =
9642    DAG.getNode(ISD::SRL, DL, MVT::i16,
9643                DAG.getNode(ISD::AND, DL, MVT::i16,
9644                            CWD, DAG.getConstant(0x400, MVT::i16)),
9645                DAG.getConstant(9, MVT::i8));
9646
9647  SDValue RetVal =
9648    DAG.getNode(ISD::AND, DL, MVT::i16,
9649                DAG.getNode(ISD::ADD, DL, MVT::i16,
9650                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9651                            DAG.getConstant(1, MVT::i16)),
9652                DAG.getConstant(3, MVT::i16));
9653
9654
9655  return DAG.getNode((VT.getSizeInBits() < 16 ?
9656                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9657}
9658
9659SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9660  EVT VT = Op.getValueType();
9661  EVT OpVT = VT;
9662  unsigned NumBits = VT.getSizeInBits();
9663  DebugLoc dl = Op.getDebugLoc();
9664
9665  Op = Op.getOperand(0);
9666  if (VT == MVT::i8) {
9667    // Zero extend to i32 since there is not an i8 bsr.
9668    OpVT = MVT::i32;
9669    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9670  }
9671
9672  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9673  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9674  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9675
9676  // If src is zero (i.e. bsr sets ZF), returns NumBits.
9677  SDValue Ops[] = {
9678    Op,
9679    DAG.getConstant(NumBits+NumBits-1, OpVT),
9680    DAG.getConstant(X86::COND_E, MVT::i8),
9681    Op.getValue(1)
9682  };
9683  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9684
9685  // Finally xor with NumBits-1.
9686  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9687
9688  if (VT == MVT::i8)
9689    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9690  return Op;
9691}
9692
9693SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9694  EVT VT = Op.getValueType();
9695  EVT OpVT = VT;
9696  unsigned NumBits = VT.getSizeInBits();
9697  DebugLoc dl = Op.getDebugLoc();
9698
9699  Op = Op.getOperand(0);
9700  if (VT == MVT::i8) {
9701    OpVT = MVT::i32;
9702    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9703  }
9704
9705  // Issue a bsf (scan bits forward) which also sets EFLAGS.
9706  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9707  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9708
9709  // If src is zero (i.e. bsf sets ZF), returns NumBits.
9710  SDValue Ops[] = {
9711    Op,
9712    DAG.getConstant(NumBits, OpVT),
9713    DAG.getConstant(X86::COND_E, MVT::i8),
9714    Op.getValue(1)
9715  };
9716  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9717
9718  if (VT == MVT::i8)
9719    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9720  return Op;
9721}
9722
9723// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9724// ones, and then concatenate the result back.
9725static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9726  EVT VT = Op.getValueType();
9727
9728  assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9729         "Unsupported value type for operation");
9730
9731  int NumElems = VT.getVectorNumElements();
9732  DebugLoc dl = Op.getDebugLoc();
9733  SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9734  SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9735
9736  // Extract the LHS vectors
9737  SDValue LHS = Op.getOperand(0);
9738  SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9739  SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9740
9741  // Extract the RHS vectors
9742  SDValue RHS = Op.getOperand(1);
9743  SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9744  SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9745
9746  MVT EltVT = VT.getVectorElementType().getSimpleVT();
9747  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9748
9749  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9750                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9751                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9752}
9753
9754SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9755  assert(Op.getValueType().getSizeInBits() == 256 &&
9756         Op.getValueType().isInteger() &&
9757         "Only handle AVX 256-bit vector integer operation");
9758  return Lower256IntArith(Op, DAG);
9759}
9760
9761SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9762  assert(Op.getValueType().getSizeInBits() == 256 &&
9763         Op.getValueType().isInteger() &&
9764         "Only handle AVX 256-bit vector integer operation");
9765  return Lower256IntArith(Op, DAG);
9766}
9767
9768SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9769  EVT VT = Op.getValueType();
9770
9771  // Decompose 256-bit ops into smaller 128-bit ops.
9772  if (VT.getSizeInBits() == 256)
9773    return Lower256IntArith(Op, DAG);
9774
9775  assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9776  DebugLoc dl = Op.getDebugLoc();
9777
9778  //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9779  //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9780  //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9781  //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9782  //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9783  //
9784  //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9785  //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9786  //  return AloBlo + AloBhi + AhiBlo;
9787
9788  SDValue A = Op.getOperand(0);
9789  SDValue B = Op.getOperand(1);
9790
9791  SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9792                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9793                       A, DAG.getConstant(32, MVT::i32));
9794  SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9795                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9796                       B, DAG.getConstant(32, MVT::i32));
9797  SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9798                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9799                       A, B);
9800  SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9801                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9802                       A, Bhi);
9803  SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9804                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9805                       Ahi, B);
9806  AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9807                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9808                       AloBhi, DAG.getConstant(32, MVT::i32));
9809  AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9810                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9811                       AhiBlo, DAG.getConstant(32, MVT::i32));
9812  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9813  Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9814  return Res;
9815}
9816
9817SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9818
9819  EVT VT = Op.getValueType();
9820  DebugLoc dl = Op.getDebugLoc();
9821  SDValue R = Op.getOperand(0);
9822  SDValue Amt = Op.getOperand(1);
9823  LLVMContext *Context = DAG.getContext();
9824
9825  if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
9826    return SDValue();
9827
9828  // Decompose 256-bit shifts into smaller 128-bit shifts.
9829  if (VT.getSizeInBits() == 256) {
9830    int NumElems = VT.getVectorNumElements();
9831    MVT EltVT = VT.getVectorElementType().getSimpleVT();
9832    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9833
9834    // Extract the two vectors
9835    SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9836    SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9837                                     DAG, dl);
9838
9839    // Recreate the shift amount vectors
9840    SDValue Amt1, Amt2;
9841    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9842      // Constant shift amount
9843      SmallVector<SDValue, 4> Amt1Csts;
9844      SmallVector<SDValue, 4> Amt2Csts;
9845      for (int i = 0; i < NumElems/2; ++i)
9846        Amt1Csts.push_back(Amt->getOperand(i));
9847      for (int i = NumElems/2; i < NumElems; ++i)
9848        Amt2Csts.push_back(Amt->getOperand(i));
9849
9850      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9851                                 &Amt1Csts[0], NumElems/2);
9852      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9853                                 &Amt2Csts[0], NumElems/2);
9854    } else {
9855      // Variable shift amount
9856      Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9857      Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9858                                 DAG, dl);
9859    }
9860
9861    // Issue new vector shifts for the smaller types
9862    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9863    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9864
9865    // Concatenate the result back
9866    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9867  }
9868
9869  // Optimize shl/srl/sra with constant shift amount.
9870  if (isSplatVector(Amt.getNode())) {
9871    SDValue SclrAmt = Amt->getOperand(0);
9872    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9873      uint64_t ShiftAmt = C->getZExtValue();
9874
9875      if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9876       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9877                     DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9878                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9879
9880      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9881       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9882                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9883                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9884
9885      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9886       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9887                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9888                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9889
9890      if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9891       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9892                     DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9893                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9894
9895      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9896       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9897                     DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9898                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9899
9900      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9901       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9902                     DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9903                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9904
9905      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9906       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9907                     DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9908                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9909
9910      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9911       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9912                     DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9913                     R, DAG.getConstant(ShiftAmt, MVT::i32));
9914    }
9915  }
9916
9917  // Lower SHL with variable shift amount.
9918  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9919    Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9920                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9921                     Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9922
9923    ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9924
9925    std::vector<Constant*> CV(4, CI);
9926    Constant *C = ConstantVector::get(CV);
9927    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9928    SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9929                                 MachinePointerInfo::getConstantPool(),
9930                                 false, false, 16);
9931
9932    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9933    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9934    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9935    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9936  }
9937  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9938    // a = a << 5;
9939    Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9940                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9941                     Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9942
9943    ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9944    ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9945
9946    std::vector<Constant*> CVM1(16, CM1);
9947    std::vector<Constant*> CVM2(16, CM2);
9948    Constant *C = ConstantVector::get(CVM1);
9949    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9950    SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9951                            MachinePointerInfo::getConstantPool(),
9952                            false, false, 16);
9953
9954    // r = pblendv(r, psllw(r & (char16)15, 4), a);
9955    M = DAG.getNode(ISD::AND, dl, VT, R, M);
9956    M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9957                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9958                    DAG.getConstant(4, MVT::i32));
9959    R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
9960    // a += a
9961    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9962
9963    C = ConstantVector::get(CVM2);
9964    CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9965    M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9966                    MachinePointerInfo::getConstantPool(),
9967                    false, false, 16);
9968
9969    // r = pblendv(r, psllw(r & (char16)63, 2), a);
9970    M = DAG.getNode(ISD::AND, dl, VT, R, M);
9971    M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9972                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9973                    DAG.getConstant(2, MVT::i32));
9974    R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
9975    // a += a
9976    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9977
9978    // return pblendv(r, r+r, a);
9979    R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
9980                    R, DAG.getNode(ISD::ADD, dl, VT, R, R));
9981    return R;
9982  }
9983  return SDValue();
9984}
9985
9986SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9987  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9988  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9989  // looks for this combo and may remove the "setcc" instruction if the "setcc"
9990  // has only one use.
9991  SDNode *N = Op.getNode();
9992  SDValue LHS = N->getOperand(0);
9993  SDValue RHS = N->getOperand(1);
9994  unsigned BaseOp = 0;
9995  unsigned Cond = 0;
9996  DebugLoc DL = Op.getDebugLoc();
9997  switch (Op.getOpcode()) {
9998  default: llvm_unreachable("Unknown ovf instruction!");
9999  case ISD::SADDO:
10000    // A subtract of one will be selected as a INC. Note that INC doesn't
10001    // set CF, so we can't do this for UADDO.
10002    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10003      if (C->isOne()) {
10004        BaseOp = X86ISD::INC;
10005        Cond = X86::COND_O;
10006        break;
10007      }
10008    BaseOp = X86ISD::ADD;
10009    Cond = X86::COND_O;
10010    break;
10011  case ISD::UADDO:
10012    BaseOp = X86ISD::ADD;
10013    Cond = X86::COND_B;
10014    break;
10015  case ISD::SSUBO:
10016    // A subtract of one will be selected as a DEC. Note that DEC doesn't
10017    // set CF, so we can't do this for USUBO.
10018    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10019      if (C->isOne()) {
10020        BaseOp = X86ISD::DEC;
10021        Cond = X86::COND_O;
10022        break;
10023      }
10024    BaseOp = X86ISD::SUB;
10025    Cond = X86::COND_O;
10026    break;
10027  case ISD::USUBO:
10028    BaseOp = X86ISD::SUB;
10029    Cond = X86::COND_B;
10030    break;
10031  case ISD::SMULO:
10032    BaseOp = X86ISD::SMUL;
10033    Cond = X86::COND_O;
10034    break;
10035  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10036    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10037                                 MVT::i32);
10038    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10039
10040    SDValue SetCC =
10041      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10042                  DAG.getConstant(X86::COND_O, MVT::i32),
10043                  SDValue(Sum.getNode(), 2));
10044
10045    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10046  }
10047  }
10048
10049  // Also sets EFLAGS.
10050  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10051  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10052
10053  SDValue SetCC =
10054    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10055                DAG.getConstant(Cond, MVT::i32),
10056                SDValue(Sum.getNode(), 1));
10057
10058  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10059}
10060
10061SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10062  DebugLoc dl = Op.getDebugLoc();
10063  SDNode* Node = Op.getNode();
10064  EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10065  EVT VT = Node->getValueType(0);
10066  if (Subtarget->hasSSE2() && VT.isVector()) {
10067    unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10068                        ExtraVT.getScalarType().getSizeInBits();
10069    SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10070
10071    unsigned SHLIntrinsicsID = 0;
10072    unsigned SRAIntrinsicsID = 0;
10073    switch (VT.getSimpleVT().SimpleTy) {
10074      default:
10075        return SDValue();
10076      case MVT::v2i64: {
10077        SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
10078        SRAIntrinsicsID = 0;
10079        break;
10080      }
10081      case MVT::v4i32: {
10082        SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10083        SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10084        break;
10085      }
10086      case MVT::v8i16: {
10087        SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10088        SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10089        break;
10090      }
10091    }
10092
10093    SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10094                         DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10095                         Node->getOperand(0), ShAmt);
10096
10097    // In case of 1 bit sext, no need to shr
10098    if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10099
10100    if (SRAIntrinsicsID) {
10101      Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10102                         DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10103                         Tmp1, ShAmt);
10104    }
10105    return Tmp1;
10106  }
10107
10108  return SDValue();
10109}
10110
10111
10112SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10113  DebugLoc dl = Op.getDebugLoc();
10114
10115  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10116  // There isn't any reason to disable it if the target processor supports it.
10117  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10118    SDValue Chain = Op.getOperand(0);
10119    SDValue Zero = DAG.getConstant(0, MVT::i32);
10120    SDValue Ops[] = {
10121      DAG.getRegister(X86::ESP, MVT::i32), // Base
10122      DAG.getTargetConstant(1, MVT::i8),   // Scale
10123      DAG.getRegister(0, MVT::i32),        // Index
10124      DAG.getTargetConstant(0, MVT::i32),  // Disp
10125      DAG.getRegister(0, MVT::i32),        // Segment.
10126      Zero,
10127      Chain
10128    };
10129    SDNode *Res =
10130      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10131                          array_lengthof(Ops));
10132    return SDValue(Res, 0);
10133  }
10134
10135  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10136  if (!isDev)
10137    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10138
10139  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10140  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10141  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10142  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10143
10144  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10145  if (!Op1 && !Op2 && !Op3 && Op4)
10146    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10147
10148  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10149  if (Op1 && !Op2 && !Op3 && !Op4)
10150    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10151
10152  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10153  //           (MFENCE)>;
10154  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10155}
10156
10157SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10158                                             SelectionDAG &DAG) const {
10159  DebugLoc dl = Op.getDebugLoc();
10160  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10161    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10162  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10163    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10164
10165  // The only fence that needs an instruction is a sequentially-consistent
10166  // cross-thread fence.
10167  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10168    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10169    // no-sse2). There isn't any reason to disable it if the target processor
10170    // supports it.
10171    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10172      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10173
10174    SDValue Chain = Op.getOperand(0);
10175    SDValue Zero = DAG.getConstant(0, MVT::i32);
10176    SDValue Ops[] = {
10177      DAG.getRegister(X86::ESP, MVT::i32), // Base
10178      DAG.getTargetConstant(1, MVT::i8),   // Scale
10179      DAG.getRegister(0, MVT::i32),        // Index
10180      DAG.getTargetConstant(0, MVT::i32),  // Disp
10181      DAG.getRegister(0, MVT::i32),        // Segment.
10182      Zero,
10183      Chain
10184    };
10185    SDNode *Res =
10186      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10187                         array_lengthof(Ops));
10188    return SDValue(Res, 0);
10189  }
10190
10191  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10192  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10193}
10194
10195
10196SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10197  EVT T = Op.getValueType();
10198  DebugLoc DL = Op.getDebugLoc();
10199  unsigned Reg = 0;
10200  unsigned size = 0;
10201  switch(T.getSimpleVT().SimpleTy) {
10202  default:
10203    assert(false && "Invalid value type!");
10204  case MVT::i8:  Reg = X86::AL;  size = 1; break;
10205  case MVT::i16: Reg = X86::AX;  size = 2; break;
10206  case MVT::i32: Reg = X86::EAX; size = 4; break;
10207  case MVT::i64:
10208    assert(Subtarget->is64Bit() && "Node not type legal!");
10209    Reg = X86::RAX; size = 8;
10210    break;
10211  }
10212  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10213                                    Op.getOperand(2), SDValue());
10214  SDValue Ops[] = { cpIn.getValue(0),
10215                    Op.getOperand(1),
10216                    Op.getOperand(3),
10217                    DAG.getTargetConstant(size, MVT::i8),
10218                    cpIn.getValue(1) };
10219  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10220  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10221  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10222                                           Ops, 5, T, MMO);
10223  SDValue cpOut =
10224    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10225  return cpOut;
10226}
10227
10228SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10229                                                 SelectionDAG &DAG) const {
10230  assert(Subtarget->is64Bit() && "Result not type legalized?");
10231  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10232  SDValue TheChain = Op.getOperand(0);
10233  DebugLoc dl = Op.getDebugLoc();
10234  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10235  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10236  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10237                                   rax.getValue(2));
10238  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10239                            DAG.getConstant(32, MVT::i8));
10240  SDValue Ops[] = {
10241    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10242    rdx.getValue(1)
10243  };
10244  return DAG.getMergeValues(Ops, 2, dl);
10245}
10246
10247SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10248                                            SelectionDAG &DAG) const {
10249  EVT SrcVT = Op.getOperand(0).getValueType();
10250  EVT DstVT = Op.getValueType();
10251  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10252         Subtarget->hasMMX() && "Unexpected custom BITCAST");
10253  assert((DstVT == MVT::i64 ||
10254          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10255         "Unexpected custom BITCAST");
10256  // i64 <=> MMX conversions are Legal.
10257  if (SrcVT==MVT::i64 && DstVT.isVector())
10258    return Op;
10259  if (DstVT==MVT::i64 && SrcVT.isVector())
10260    return Op;
10261  // MMX <=> MMX conversions are Legal.
10262  if (SrcVT.isVector() && DstVT.isVector())
10263    return Op;
10264  // All other conversions need to be expanded.
10265  return SDValue();
10266}
10267
10268SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10269  SDNode *Node = Op.getNode();
10270  DebugLoc dl = Node->getDebugLoc();
10271  EVT T = Node->getValueType(0);
10272  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10273                              DAG.getConstant(0, T), Node->getOperand(2));
10274  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10275                       cast<AtomicSDNode>(Node)->getMemoryVT(),
10276                       Node->getOperand(0),
10277                       Node->getOperand(1), negOp,
10278                       cast<AtomicSDNode>(Node)->getSrcValue(),
10279                       cast<AtomicSDNode>(Node)->getAlignment(),
10280                       cast<AtomicSDNode>(Node)->getOrdering(),
10281                       cast<AtomicSDNode>(Node)->getSynchScope());
10282}
10283
10284static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10285  SDNode *Node = Op.getNode();
10286  DebugLoc dl = Node->getDebugLoc();
10287  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10288
10289  // Convert seq_cst store -> xchg
10290  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10291  // FIXME: On 32-bit, store -> fist or movq would be more efficient
10292  //        (The only way to get a 16-byte store is cmpxchg16b)
10293  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10294  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10295      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10296    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10297                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
10298                                 Node->getOperand(0),
10299                                 Node->getOperand(1), Node->getOperand(2),
10300                                 cast<AtomicSDNode>(Node)->getMemOperand(),
10301                                 cast<AtomicSDNode>(Node)->getOrdering(),
10302                                 cast<AtomicSDNode>(Node)->getSynchScope());
10303    return Swap.getValue(1);
10304  }
10305  // Other atomic stores have a simple pattern.
10306  return Op;
10307}
10308
10309static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10310  EVT VT = Op.getNode()->getValueType(0);
10311
10312  // Let legalize expand this if it isn't a legal type yet.
10313  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10314    return SDValue();
10315
10316  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10317
10318  unsigned Opc;
10319  bool ExtraOp = false;
10320  switch (Op.getOpcode()) {
10321  default: assert(0 && "Invalid code");
10322  case ISD::ADDC: Opc = X86ISD::ADD; break;
10323  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10324  case ISD::SUBC: Opc = X86ISD::SUB; break;
10325  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10326  }
10327
10328  if (!ExtraOp)
10329    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10330                       Op.getOperand(1));
10331  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10332                     Op.getOperand(1), Op.getOperand(2));
10333}
10334
10335/// LowerOperation - Provide custom lowering hooks for some operations.
10336///
10337SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10338  switch (Op.getOpcode()) {
10339  default: llvm_unreachable("Should not custom lower this!");
10340  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10341  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10342  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10343  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10344  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10345  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10346  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10347  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10348  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10349  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10350  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10351  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10352  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10353  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10354  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10355  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10356  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10357  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10358  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10359  case ISD::SHL_PARTS:
10360  case ISD::SRA_PARTS:
10361  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10362  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10363  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10364  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10365  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10366  case ISD::FABS:               return LowerFABS(Op, DAG);
10367  case ISD::FNEG:               return LowerFNEG(Op, DAG);
10368  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10369  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10370  case ISD::SETCC:              return LowerSETCC(Op, DAG);
10371  case ISD::SELECT:             return LowerSELECT(Op, DAG);
10372  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10373  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10374  case ISD::VASTART:            return LowerVASTART(Op, DAG);
10375  case ISD::VAARG:              return LowerVAARG(Op, DAG);
10376  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10377  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10378  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10379  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10380  case ISD::FRAME_TO_ARGS_OFFSET:
10381                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10382  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10383  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10384  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10385  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10386  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10387  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10388  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10389  case ISD::MUL:                return LowerMUL(Op, DAG);
10390  case ISD::SRA:
10391  case ISD::SRL:
10392  case ISD::SHL:                return LowerShift(Op, DAG);
10393  case ISD::SADDO:
10394  case ISD::UADDO:
10395  case ISD::SSUBO:
10396  case ISD::USUBO:
10397  case ISD::SMULO:
10398  case ISD::UMULO:              return LowerXALUO(Op, DAG);
10399  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10400  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10401  case ISD::ADDC:
10402  case ISD::ADDE:
10403  case ISD::SUBC:
10404  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10405  case ISD::ADD:                return LowerADD(Op, DAG);
10406  case ISD::SUB:                return LowerSUB(Op, DAG);
10407  }
10408}
10409
10410static void ReplaceATOMIC_LOAD(SDNode *Node,
10411                                  SmallVectorImpl<SDValue> &Results,
10412                                  SelectionDAG &DAG) {
10413  DebugLoc dl = Node->getDebugLoc();
10414  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10415
10416  // Convert wide load -> cmpxchg8b/cmpxchg16b
10417  // FIXME: On 32-bit, load -> fild or movq would be more efficient
10418  //        (The only way to get a 16-byte load is cmpxchg16b)
10419  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10420  SDValue Zero = DAG.getConstant(0, VT);
10421  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10422                               Node->getOperand(0),
10423                               Node->getOperand(1), Zero, Zero,
10424                               cast<AtomicSDNode>(Node)->getMemOperand(),
10425                               cast<AtomicSDNode>(Node)->getOrdering(),
10426                               cast<AtomicSDNode>(Node)->getSynchScope());
10427  Results.push_back(Swap.getValue(0));
10428  Results.push_back(Swap.getValue(1));
10429}
10430
10431void X86TargetLowering::
10432ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10433                        SelectionDAG &DAG, unsigned NewOp) const {
10434  EVT T = Node->getValueType(0);
10435  DebugLoc dl = Node->getDebugLoc();
10436  assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10437
10438  SDValue Chain = Node->getOperand(0);
10439  SDValue In1 = Node->getOperand(1);
10440  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10441                             Node->getOperand(2), DAG.getIntPtrConstant(0));
10442  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10443                             Node->getOperand(2), DAG.getIntPtrConstant(1));
10444  SDValue Ops[] = { Chain, In1, In2L, In2H };
10445  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10446  SDValue Result =
10447    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10448                            cast<MemSDNode>(Node)->getMemOperand());
10449  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10450  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10451  Results.push_back(Result.getValue(2));
10452}
10453
10454/// ReplaceNodeResults - Replace a node with an illegal result type
10455/// with a new node built out of custom code.
10456void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10457                                           SmallVectorImpl<SDValue>&Results,
10458                                           SelectionDAG &DAG) const {
10459  DebugLoc dl = N->getDebugLoc();
10460  switch (N->getOpcode()) {
10461  default:
10462    assert(false && "Do not know how to custom type legalize this operation!");
10463    return;
10464  case ISD::SIGN_EXTEND_INREG:
10465  case ISD::ADDC:
10466  case ISD::ADDE:
10467  case ISD::SUBC:
10468  case ISD::SUBE:
10469    // We don't want to expand or promote these.
10470    return;
10471  case ISD::FP_TO_SINT: {
10472    std::pair<SDValue,SDValue> Vals =
10473        FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10474    SDValue FIST = Vals.first, StackSlot = Vals.second;
10475    if (FIST.getNode() != 0) {
10476      EVT VT = N->getValueType(0);
10477      // Return a load from the stack slot.
10478      Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10479                                    MachinePointerInfo(), false, false, 0));
10480    }
10481    return;
10482  }
10483  case ISD::READCYCLECOUNTER: {
10484    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10485    SDValue TheChain = N->getOperand(0);
10486    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10487    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10488                                     rd.getValue(1));
10489    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10490                                     eax.getValue(2));
10491    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10492    SDValue Ops[] = { eax, edx };
10493    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10494    Results.push_back(edx.getValue(1));
10495    return;
10496  }
10497  case ISD::ATOMIC_CMP_SWAP: {
10498    EVT T = N->getValueType(0);
10499    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10500    bool Regs64bit = T == MVT::i128;
10501    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10502    SDValue cpInL, cpInH;
10503    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10504                        DAG.getConstant(0, HalfT));
10505    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10506                        DAG.getConstant(1, HalfT));
10507    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10508                             Regs64bit ? X86::RAX : X86::EAX,
10509                             cpInL, SDValue());
10510    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10511                             Regs64bit ? X86::RDX : X86::EDX,
10512                             cpInH, cpInL.getValue(1));
10513    SDValue swapInL, swapInH;
10514    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10515                          DAG.getConstant(0, HalfT));
10516    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10517                          DAG.getConstant(1, HalfT));
10518    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10519                               Regs64bit ? X86::RBX : X86::EBX,
10520                               swapInL, cpInH.getValue(1));
10521    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10522                               Regs64bit ? X86::RCX : X86::ECX,
10523                               swapInH, swapInL.getValue(1));
10524    SDValue Ops[] = { swapInH.getValue(0),
10525                      N->getOperand(1),
10526                      swapInH.getValue(1) };
10527    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10528    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10529    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10530                                  X86ISD::LCMPXCHG8_DAG;
10531    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10532                                             Ops, 3, T, MMO);
10533    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10534                                        Regs64bit ? X86::RAX : X86::EAX,
10535                                        HalfT, Result.getValue(1));
10536    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10537                                        Regs64bit ? X86::RDX : X86::EDX,
10538                                        HalfT, cpOutL.getValue(2));
10539    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10540    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10541    Results.push_back(cpOutH.getValue(1));
10542    return;
10543  }
10544  case ISD::ATOMIC_LOAD_ADD:
10545    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10546    return;
10547  case ISD::ATOMIC_LOAD_AND:
10548    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10549    return;
10550  case ISD::ATOMIC_LOAD_NAND:
10551    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10552    return;
10553  case ISD::ATOMIC_LOAD_OR:
10554    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10555    return;
10556  case ISD::ATOMIC_LOAD_SUB:
10557    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10558    return;
10559  case ISD::ATOMIC_LOAD_XOR:
10560    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10561    return;
10562  case ISD::ATOMIC_SWAP:
10563    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10564    return;
10565  case ISD::ATOMIC_LOAD:
10566    ReplaceATOMIC_LOAD(N, Results, DAG);
10567  }
10568}
10569
10570const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10571  switch (Opcode) {
10572  default: return NULL;
10573  case X86ISD::BSF:                return "X86ISD::BSF";
10574  case X86ISD::BSR:                return "X86ISD::BSR";
10575  case X86ISD::SHLD:               return "X86ISD::SHLD";
10576  case X86ISD::SHRD:               return "X86ISD::SHRD";
10577  case X86ISD::FAND:               return "X86ISD::FAND";
10578  case X86ISD::FOR:                return "X86ISD::FOR";
10579  case X86ISD::FXOR:               return "X86ISD::FXOR";
10580  case X86ISD::FSRL:               return "X86ISD::FSRL";
10581  case X86ISD::FILD:               return "X86ISD::FILD";
10582  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10583  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10584  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10585  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10586  case X86ISD::FLD:                return "X86ISD::FLD";
10587  case X86ISD::FST:                return "X86ISD::FST";
10588  case X86ISD::CALL:               return "X86ISD::CALL";
10589  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10590  case X86ISD::BT:                 return "X86ISD::BT";
10591  case X86ISD::CMP:                return "X86ISD::CMP";
10592  case X86ISD::COMI:               return "X86ISD::COMI";
10593  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10594  case X86ISD::SETCC:              return "X86ISD::SETCC";
10595  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10596  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10597  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10598  case X86ISD::CMOV:               return "X86ISD::CMOV";
10599  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10600  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10601  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10602  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10603  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10604  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10605  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10606  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10607  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10608  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10609  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10610  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10611  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10612  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10613  case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10614  case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10615  case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10616  case X86ISD::FMAX:               return "X86ISD::FMAX";
10617  case X86ISD::FMIN:               return "X86ISD::FMIN";
10618  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10619  case X86ISD::FRCP:               return "X86ISD::FRCP";
10620  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10621  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10622  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10623  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10624  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10625  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10626  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10627  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10628  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10629  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10630  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10631  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10632  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10633  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10634  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10635  case X86ISD::VSHL:               return "X86ISD::VSHL";
10636  case X86ISD::VSRL:               return "X86ISD::VSRL";
10637  case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10638  case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10639  case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10640  case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10641  case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10642  case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10643  case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10644  case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10645  case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10646  case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10647  case X86ISD::ADD:                return "X86ISD::ADD";
10648  case X86ISD::SUB:                return "X86ISD::SUB";
10649  case X86ISD::ADC:                return "X86ISD::ADC";
10650  case X86ISD::SBB:                return "X86ISD::SBB";
10651  case X86ISD::SMUL:               return "X86ISD::SMUL";
10652  case X86ISD::UMUL:               return "X86ISD::UMUL";
10653  case X86ISD::INC:                return "X86ISD::INC";
10654  case X86ISD::DEC:                return "X86ISD::DEC";
10655  case X86ISD::OR:                 return "X86ISD::OR";
10656  case X86ISD::XOR:                return "X86ISD::XOR";
10657  case X86ISD::AND:                return "X86ISD::AND";
10658  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10659  case X86ISD::PTEST:              return "X86ISD::PTEST";
10660  case X86ISD::TESTP:              return "X86ISD::TESTP";
10661  case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10662  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10663  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10664  case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10665  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10666  case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10667  case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10668  case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10669  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10670  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10671  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10672  case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10673  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10674  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10675  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10676  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10677  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10678  case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10679  case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10680  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10681  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10682  case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10683  case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10684  case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10685  case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10686  case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10687  case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10688  case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10689  case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10690  case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10691  case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10692  case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10693  case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10694  case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10695  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10696  case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10697  case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10698  case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10699  case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10700  case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10701  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10702  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10703  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10704  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10705  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10706  }
10707}
10708
10709// isLegalAddressingMode - Return true if the addressing mode represented
10710// by AM is legal for this target, for a load/store of the specified type.
10711bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10712                                              Type *Ty) const {
10713  // X86 supports extremely general addressing modes.
10714  CodeModel::Model M = getTargetMachine().getCodeModel();
10715  Reloc::Model R = getTargetMachine().getRelocationModel();
10716
10717  // X86 allows a sign-extended 32-bit immediate field as a displacement.
10718  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10719    return false;
10720
10721  if (AM.BaseGV) {
10722    unsigned GVFlags =
10723      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10724
10725    // If a reference to this global requires an extra load, we can't fold it.
10726    if (isGlobalStubReference(GVFlags))
10727      return false;
10728
10729    // If BaseGV requires a register for the PIC base, we cannot also have a
10730    // BaseReg specified.
10731    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10732      return false;
10733
10734    // If lower 4G is not available, then we must use rip-relative addressing.
10735    if ((M != CodeModel::Small || R != Reloc::Static) &&
10736        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10737      return false;
10738  }
10739
10740  switch (AM.Scale) {
10741  case 0:
10742  case 1:
10743  case 2:
10744  case 4:
10745  case 8:
10746    // These scales always work.
10747    break;
10748  case 3:
10749  case 5:
10750  case 9:
10751    // These scales are formed with basereg+scalereg.  Only accept if there is
10752    // no basereg yet.
10753    if (AM.HasBaseReg)
10754      return false;
10755    break;
10756  default:  // Other stuff never works.
10757    return false;
10758  }
10759
10760  return true;
10761}
10762
10763
10764bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10765  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10766    return false;
10767  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10768  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10769  if (NumBits1 <= NumBits2)
10770    return false;
10771  return true;
10772}
10773
10774bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10775  if (!VT1.isInteger() || !VT2.isInteger())
10776    return false;
10777  unsigned NumBits1 = VT1.getSizeInBits();
10778  unsigned NumBits2 = VT2.getSizeInBits();
10779  if (NumBits1 <= NumBits2)
10780    return false;
10781  return true;
10782}
10783
10784bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10785  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10786  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10787}
10788
10789bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10790  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10791  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10792}
10793
10794bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10795  // i16 instructions are longer (0x66 prefix) and potentially slower.
10796  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10797}
10798
10799/// isShuffleMaskLegal - Targets can use this to indicate that they only
10800/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10801/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10802/// are assumed to be legal.
10803bool
10804X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10805                                      EVT VT) const {
10806  // Very little shuffling can be done for 64-bit vectors right now.
10807  if (VT.getSizeInBits() == 64)
10808    return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
10809
10810  // FIXME: pshufb, blends, shifts.
10811  return (VT.getVectorNumElements() == 2 ||
10812          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10813          isMOVLMask(M, VT) ||
10814          isSHUFPMask(M, VT) ||
10815          isPSHUFDMask(M, VT) ||
10816          isPSHUFHWMask(M, VT) ||
10817          isPSHUFLWMask(M, VT) ||
10818          isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
10819          isUNPCKLMask(M, VT) ||
10820          isUNPCKHMask(M, VT) ||
10821          isUNPCKL_v_undef_Mask(M, VT) ||
10822          isUNPCKH_v_undef_Mask(M, VT));
10823}
10824
10825bool
10826X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10827                                          EVT VT) const {
10828  unsigned NumElts = VT.getVectorNumElements();
10829  // FIXME: This collection of masks seems suspect.
10830  if (NumElts == 2)
10831    return true;
10832  if (NumElts == 4 && VT.getSizeInBits() == 128) {
10833    return (isMOVLMask(Mask, VT)  ||
10834            isCommutedMOVLMask(Mask, VT, true) ||
10835            isSHUFPMask(Mask, VT) ||
10836            isCommutedSHUFPMask(Mask, VT));
10837  }
10838  return false;
10839}
10840
10841//===----------------------------------------------------------------------===//
10842//                           X86 Scheduler Hooks
10843//===----------------------------------------------------------------------===//
10844
10845// private utility function
10846MachineBasicBlock *
10847X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10848                                                       MachineBasicBlock *MBB,
10849                                                       unsigned regOpc,
10850                                                       unsigned immOpc,
10851                                                       unsigned LoadOpc,
10852                                                       unsigned CXchgOpc,
10853                                                       unsigned notOpc,
10854                                                       unsigned EAXreg,
10855                                                       TargetRegisterClass *RC,
10856                                                       bool invSrc) const {
10857  // For the atomic bitwise operator, we generate
10858  //   thisMBB:
10859  //   newMBB:
10860  //     ld  t1 = [bitinstr.addr]
10861  //     op  t2 = t1, [bitinstr.val]
10862  //     mov EAX = t1
10863  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10864  //     bz  newMBB
10865  //     fallthrough -->nextMBB
10866  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10867  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10868  MachineFunction::iterator MBBIter = MBB;
10869  ++MBBIter;
10870
10871  /// First build the CFG
10872  MachineFunction *F = MBB->getParent();
10873  MachineBasicBlock *thisMBB = MBB;
10874  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10875  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10876  F->insert(MBBIter, newMBB);
10877  F->insert(MBBIter, nextMBB);
10878
10879  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10880  nextMBB->splice(nextMBB->begin(), thisMBB,
10881                  llvm::next(MachineBasicBlock::iterator(bInstr)),
10882                  thisMBB->end());
10883  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10884
10885  // Update thisMBB to fall through to newMBB
10886  thisMBB->addSuccessor(newMBB);
10887
10888  // newMBB jumps to itself and fall through to nextMBB
10889  newMBB->addSuccessor(nextMBB);
10890  newMBB->addSuccessor(newMBB);
10891
10892  // Insert instructions into newMBB based on incoming instruction
10893  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10894         "unexpected number of operands");
10895  DebugLoc dl = bInstr->getDebugLoc();
10896  MachineOperand& destOper = bInstr->getOperand(0);
10897  MachineOperand* argOpers[2 + X86::AddrNumOperands];
10898  int numArgs = bInstr->getNumOperands() - 1;
10899  for (int i=0; i < numArgs; ++i)
10900    argOpers[i] = &bInstr->getOperand(i+1);
10901
10902  // x86 address has 4 operands: base, index, scale, and displacement
10903  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10904  int valArgIndx = lastAddrIndx + 1;
10905
10906  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10907  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10908  for (int i=0; i <= lastAddrIndx; ++i)
10909    (*MIB).addOperand(*argOpers[i]);
10910
10911  unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10912  if (invSrc) {
10913    MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10914  }
10915  else
10916    tt = t1;
10917
10918  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10919  assert((argOpers[valArgIndx]->isReg() ||
10920          argOpers[valArgIndx]->isImm()) &&
10921         "invalid operand");
10922  if (argOpers[valArgIndx]->isReg())
10923    MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10924  else
10925    MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10926  MIB.addReg(tt);
10927  (*MIB).addOperand(*argOpers[valArgIndx]);
10928
10929  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10930  MIB.addReg(t1);
10931
10932  MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10933  for (int i=0; i <= lastAddrIndx; ++i)
10934    (*MIB).addOperand(*argOpers[i]);
10935  MIB.addReg(t2);
10936  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10937  (*MIB).setMemRefs(bInstr->memoperands_begin(),
10938                    bInstr->memoperands_end());
10939
10940  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10941  MIB.addReg(EAXreg);
10942
10943  // insert branch
10944  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10945
10946  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10947  return nextMBB;
10948}
10949
10950// private utility function:  64 bit atomics on 32 bit host.
10951MachineBasicBlock *
10952X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10953                                                       MachineBasicBlock *MBB,
10954                                                       unsigned regOpcL,
10955                                                       unsigned regOpcH,
10956                                                       unsigned immOpcL,
10957                                                       unsigned immOpcH,
10958                                                       bool invSrc) const {
10959  // For the atomic bitwise operator, we generate
10960  //   thisMBB (instructions are in pairs, except cmpxchg8b)
10961  //     ld t1,t2 = [bitinstr.addr]
10962  //   newMBB:
10963  //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10964  //     op  t5, t6 <- out1, out2, [bitinstr.val]
10965  //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
10966  //     mov ECX, EBX <- t5, t6
10967  //     mov EAX, EDX <- t1, t2
10968  //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
10969  //     mov t3, t4 <- EAX, EDX
10970  //     bz  newMBB
10971  //     result in out1, out2
10972  //     fallthrough -->nextMBB
10973
10974  const TargetRegisterClass *RC = X86::GR32RegisterClass;
10975  const unsigned LoadOpc = X86::MOV32rm;
10976  const unsigned NotOpc = X86::NOT32r;
10977  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10978  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10979  MachineFunction::iterator MBBIter = MBB;
10980  ++MBBIter;
10981
10982  /// First build the CFG
10983  MachineFunction *F = MBB->getParent();
10984  MachineBasicBlock *thisMBB = MBB;
10985  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10986  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10987  F->insert(MBBIter, newMBB);
10988  F->insert(MBBIter, nextMBB);
10989
10990  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10991  nextMBB->splice(nextMBB->begin(), thisMBB,
10992                  llvm::next(MachineBasicBlock::iterator(bInstr)),
10993                  thisMBB->end());
10994  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10995
10996  // Update thisMBB to fall through to newMBB
10997  thisMBB->addSuccessor(newMBB);
10998
10999  // newMBB jumps to itself and fall through to nextMBB
11000  newMBB->addSuccessor(nextMBB);
11001  newMBB->addSuccessor(newMBB);
11002
11003  DebugLoc dl = bInstr->getDebugLoc();
11004  // Insert instructions into newMBB based on incoming instruction
11005  // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11006  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11007         "unexpected number of operands");
11008  MachineOperand& dest1Oper = bInstr->getOperand(0);
11009  MachineOperand& dest2Oper = bInstr->getOperand(1);
11010  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11011  for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11012    argOpers[i] = &bInstr->getOperand(i+2);
11013
11014    // We use some of the operands multiple times, so conservatively just
11015    // clear any kill flags that might be present.
11016    if (argOpers[i]->isReg() && argOpers[i]->isUse())
11017      argOpers[i]->setIsKill(false);
11018  }
11019
11020  // x86 address has 5 operands: base, index, scale, displacement, and segment.
11021  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11022
11023  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11024  MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11025  for (int i=0; i <= lastAddrIndx; ++i)
11026    (*MIB).addOperand(*argOpers[i]);
11027  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11028  MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11029  // add 4 to displacement.
11030  for (int i=0; i <= lastAddrIndx-2; ++i)
11031    (*MIB).addOperand(*argOpers[i]);
11032  MachineOperand newOp3 = *(argOpers[3]);
11033  if (newOp3.isImm())
11034    newOp3.setImm(newOp3.getImm()+4);
11035  else
11036    newOp3.setOffset(newOp3.getOffset()+4);
11037  (*MIB).addOperand(newOp3);
11038  (*MIB).addOperand(*argOpers[lastAddrIndx]);
11039
11040  // t3/4 are defined later, at the bottom of the loop
11041  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11042  unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11043  BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11044    .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11045  BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11046    .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11047
11048  // The subsequent operations should be using the destination registers of
11049  //the PHI instructions.
11050  if (invSrc) {
11051    t1 = F->getRegInfo().createVirtualRegister(RC);
11052    t2 = F->getRegInfo().createVirtualRegister(RC);
11053    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11054    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11055  } else {
11056    t1 = dest1Oper.getReg();
11057    t2 = dest2Oper.getReg();
11058  }
11059
11060  int valArgIndx = lastAddrIndx + 1;
11061  assert((argOpers[valArgIndx]->isReg() ||
11062          argOpers[valArgIndx]->isImm()) &&
11063         "invalid operand");
11064  unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11065  unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11066  if (argOpers[valArgIndx]->isReg())
11067    MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11068  else
11069    MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11070  if (regOpcL != X86::MOV32rr)
11071    MIB.addReg(t1);
11072  (*MIB).addOperand(*argOpers[valArgIndx]);
11073  assert(argOpers[valArgIndx + 1]->isReg() ==
11074         argOpers[valArgIndx]->isReg());
11075  assert(argOpers[valArgIndx + 1]->isImm() ==
11076         argOpers[valArgIndx]->isImm());
11077  if (argOpers[valArgIndx + 1]->isReg())
11078    MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11079  else
11080    MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11081  if (regOpcH != X86::MOV32rr)
11082    MIB.addReg(t2);
11083  (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11084
11085  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11086  MIB.addReg(t1);
11087  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11088  MIB.addReg(t2);
11089
11090  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11091  MIB.addReg(t5);
11092  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11093  MIB.addReg(t6);
11094
11095  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11096  for (int i=0; i <= lastAddrIndx; ++i)
11097    (*MIB).addOperand(*argOpers[i]);
11098
11099  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11100  (*MIB).setMemRefs(bInstr->memoperands_begin(),
11101                    bInstr->memoperands_end());
11102
11103  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11104  MIB.addReg(X86::EAX);
11105  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11106  MIB.addReg(X86::EDX);
11107
11108  // insert branch
11109  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11110
11111  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11112  return nextMBB;
11113}
11114
11115// private utility function
11116MachineBasicBlock *
11117X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11118                                                      MachineBasicBlock *MBB,
11119                                                      unsigned cmovOpc) const {
11120  // For the atomic min/max operator, we generate
11121  //   thisMBB:
11122  //   newMBB:
11123  //     ld t1 = [min/max.addr]
11124  //     mov t2 = [min/max.val]
11125  //     cmp  t1, t2
11126  //     cmov[cond] t2 = t1
11127  //     mov EAX = t1
11128  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11129  //     bz   newMBB
11130  //     fallthrough -->nextMBB
11131  //
11132  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11133  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11134  MachineFunction::iterator MBBIter = MBB;
11135  ++MBBIter;
11136
11137  /// First build the CFG
11138  MachineFunction *F = MBB->getParent();
11139  MachineBasicBlock *thisMBB = MBB;
11140  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11141  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11142  F->insert(MBBIter, newMBB);
11143  F->insert(MBBIter, nextMBB);
11144
11145  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11146  nextMBB->splice(nextMBB->begin(), thisMBB,
11147                  llvm::next(MachineBasicBlock::iterator(mInstr)),
11148                  thisMBB->end());
11149  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11150
11151  // Update thisMBB to fall through to newMBB
11152  thisMBB->addSuccessor(newMBB);
11153
11154  // newMBB jumps to newMBB and fall through to nextMBB
11155  newMBB->addSuccessor(nextMBB);
11156  newMBB->addSuccessor(newMBB);
11157
11158  DebugLoc dl = mInstr->getDebugLoc();
11159  // Insert instructions into newMBB based on incoming instruction
11160  assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11161         "unexpected number of operands");
11162  MachineOperand& destOper = mInstr->getOperand(0);
11163  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11164  int numArgs = mInstr->getNumOperands() - 1;
11165  for (int i=0; i < numArgs; ++i)
11166    argOpers[i] = &mInstr->getOperand(i+1);
11167
11168  // x86 address has 4 operands: base, index, scale, and displacement
11169  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11170  int valArgIndx = lastAddrIndx + 1;
11171
11172  unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11173  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11174  for (int i=0; i <= lastAddrIndx; ++i)
11175    (*MIB).addOperand(*argOpers[i]);
11176
11177  // We only support register and immediate values
11178  assert((argOpers[valArgIndx]->isReg() ||
11179          argOpers[valArgIndx]->isImm()) &&
11180         "invalid operand");
11181
11182  unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11183  if (argOpers[valArgIndx]->isReg())
11184    MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11185  else
11186    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11187  (*MIB).addOperand(*argOpers[valArgIndx]);
11188
11189  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11190  MIB.addReg(t1);
11191
11192  MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11193  MIB.addReg(t1);
11194  MIB.addReg(t2);
11195
11196  // Generate movc
11197  unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11198  MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11199  MIB.addReg(t2);
11200  MIB.addReg(t1);
11201
11202  // Cmp and exchange if none has modified the memory location
11203  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11204  for (int i=0; i <= lastAddrIndx; ++i)
11205    (*MIB).addOperand(*argOpers[i]);
11206  MIB.addReg(t3);
11207  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11208  (*MIB).setMemRefs(mInstr->memoperands_begin(),
11209                    mInstr->memoperands_end());
11210
11211  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11212  MIB.addReg(X86::EAX);
11213
11214  // insert branch
11215  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11216
11217  mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11218  return nextMBB;
11219}
11220
11221// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11222// or XMM0_V32I8 in AVX all of this code can be replaced with that
11223// in the .td file.
11224MachineBasicBlock *
11225X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11226                            unsigned numArgs, bool memArg) const {
11227  assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11228         "Target must have SSE4.2 or AVX features enabled");
11229
11230  DebugLoc dl = MI->getDebugLoc();
11231  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11232  unsigned Opc;
11233  if (!Subtarget->hasAVX()) {
11234    if (memArg)
11235      Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11236    else
11237      Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11238  } else {
11239    if (memArg)
11240      Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11241    else
11242      Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11243  }
11244
11245  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11246  for (unsigned i = 0; i < numArgs; ++i) {
11247    MachineOperand &Op = MI->getOperand(i+1);
11248    if (!(Op.isReg() && Op.isImplicit()))
11249      MIB.addOperand(Op);
11250  }
11251  BuildMI(*BB, MI, dl,
11252    TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11253             MI->getOperand(0).getReg())
11254    .addReg(X86::XMM0);
11255
11256  MI->eraseFromParent();
11257  return BB;
11258}
11259
11260MachineBasicBlock *
11261X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11262  DebugLoc dl = MI->getDebugLoc();
11263  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11264
11265  // Address into RAX/EAX, other two args into ECX, EDX.
11266  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11267  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11268  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11269  for (int i = 0; i < X86::AddrNumOperands; ++i)
11270    MIB.addOperand(MI->getOperand(i));
11271
11272  unsigned ValOps = X86::AddrNumOperands;
11273  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11274    .addReg(MI->getOperand(ValOps).getReg());
11275  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11276    .addReg(MI->getOperand(ValOps+1).getReg());
11277
11278  // The instruction doesn't actually take any operands though.
11279  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11280
11281  MI->eraseFromParent(); // The pseudo is gone now.
11282  return BB;
11283}
11284
11285MachineBasicBlock *
11286X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11287  DebugLoc dl = MI->getDebugLoc();
11288  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11289
11290  // First arg in ECX, the second in EAX.
11291  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11292    .addReg(MI->getOperand(0).getReg());
11293  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11294    .addReg(MI->getOperand(1).getReg());
11295
11296  // The instruction doesn't actually take any operands though.
11297  BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11298
11299  MI->eraseFromParent(); // The pseudo is gone now.
11300  return BB;
11301}
11302
11303MachineBasicBlock *
11304X86TargetLowering::EmitVAARG64WithCustomInserter(
11305                   MachineInstr *MI,
11306                   MachineBasicBlock *MBB) const {
11307  // Emit va_arg instruction on X86-64.
11308
11309  // Operands to this pseudo-instruction:
11310  // 0  ) Output        : destination address (reg)
11311  // 1-5) Input         : va_list address (addr, i64mem)
11312  // 6  ) ArgSize       : Size (in bytes) of vararg type
11313  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11314  // 8  ) Align         : Alignment of type
11315  // 9  ) EFLAGS (implicit-def)
11316
11317  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11318  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11319
11320  unsigned DestReg = MI->getOperand(0).getReg();
11321  MachineOperand &Base = MI->getOperand(1);
11322  MachineOperand &Scale = MI->getOperand(2);
11323  MachineOperand &Index = MI->getOperand(3);
11324  MachineOperand &Disp = MI->getOperand(4);
11325  MachineOperand &Segment = MI->getOperand(5);
11326  unsigned ArgSize = MI->getOperand(6).getImm();
11327  unsigned ArgMode = MI->getOperand(7).getImm();
11328  unsigned Align = MI->getOperand(8).getImm();
11329
11330  // Memory Reference
11331  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11332  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11333  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11334
11335  // Machine Information
11336  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11337  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11338  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11339  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11340  DebugLoc DL = MI->getDebugLoc();
11341
11342  // struct va_list {
11343  //   i32   gp_offset
11344  //   i32   fp_offset
11345  //   i64   overflow_area (address)
11346  //   i64   reg_save_area (address)
11347  // }
11348  // sizeof(va_list) = 24
11349  // alignment(va_list) = 8
11350
11351  unsigned TotalNumIntRegs = 6;
11352  unsigned TotalNumXMMRegs = 8;
11353  bool UseGPOffset = (ArgMode == 1);
11354  bool UseFPOffset = (ArgMode == 2);
11355  unsigned MaxOffset = TotalNumIntRegs * 8 +
11356                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11357
11358  /* Align ArgSize to a multiple of 8 */
11359  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11360  bool NeedsAlign = (Align > 8);
11361
11362  MachineBasicBlock *thisMBB = MBB;
11363  MachineBasicBlock *overflowMBB;
11364  MachineBasicBlock *offsetMBB;
11365  MachineBasicBlock *endMBB;
11366
11367  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11368  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11369  unsigned OffsetReg = 0;
11370
11371  if (!UseGPOffset && !UseFPOffset) {
11372    // If we only pull from the overflow region, we don't create a branch.
11373    // We don't need to alter control flow.
11374    OffsetDestReg = 0; // unused
11375    OverflowDestReg = DestReg;
11376
11377    offsetMBB = NULL;
11378    overflowMBB = thisMBB;
11379    endMBB = thisMBB;
11380  } else {
11381    // First emit code to check if gp_offset (or fp_offset) is below the bound.
11382    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11383    // If not, pull from overflow_area. (branch to overflowMBB)
11384    //
11385    //       thisMBB
11386    //         |     .
11387    //         |        .
11388    //     offsetMBB   overflowMBB
11389    //         |        .
11390    //         |     .
11391    //        endMBB
11392
11393    // Registers for the PHI in endMBB
11394    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11395    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11396
11397    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11398    MachineFunction *MF = MBB->getParent();
11399    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11400    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11401    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11402
11403    MachineFunction::iterator MBBIter = MBB;
11404    ++MBBIter;
11405
11406    // Insert the new basic blocks
11407    MF->insert(MBBIter, offsetMBB);
11408    MF->insert(MBBIter, overflowMBB);
11409    MF->insert(MBBIter, endMBB);
11410
11411    // Transfer the remainder of MBB and its successor edges to endMBB.
11412    endMBB->splice(endMBB->begin(), thisMBB,
11413                    llvm::next(MachineBasicBlock::iterator(MI)),
11414                    thisMBB->end());
11415    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11416
11417    // Make offsetMBB and overflowMBB successors of thisMBB
11418    thisMBB->addSuccessor(offsetMBB);
11419    thisMBB->addSuccessor(overflowMBB);
11420
11421    // endMBB is a successor of both offsetMBB and overflowMBB
11422    offsetMBB->addSuccessor(endMBB);
11423    overflowMBB->addSuccessor(endMBB);
11424
11425    // Load the offset value into a register
11426    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11427    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11428      .addOperand(Base)
11429      .addOperand(Scale)
11430      .addOperand(Index)
11431      .addDisp(Disp, UseFPOffset ? 4 : 0)
11432      .addOperand(Segment)
11433      .setMemRefs(MMOBegin, MMOEnd);
11434
11435    // Check if there is enough room left to pull this argument.
11436    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11437      .addReg(OffsetReg)
11438      .addImm(MaxOffset + 8 - ArgSizeA8);
11439
11440    // Branch to "overflowMBB" if offset >= max
11441    // Fall through to "offsetMBB" otherwise
11442    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11443      .addMBB(overflowMBB);
11444  }
11445
11446  // In offsetMBB, emit code to use the reg_save_area.
11447  if (offsetMBB) {
11448    assert(OffsetReg != 0);
11449
11450    // Read the reg_save_area address.
11451    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11452    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11453      .addOperand(Base)
11454      .addOperand(Scale)
11455      .addOperand(Index)
11456      .addDisp(Disp, 16)
11457      .addOperand(Segment)
11458      .setMemRefs(MMOBegin, MMOEnd);
11459
11460    // Zero-extend the offset
11461    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11462      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11463        .addImm(0)
11464        .addReg(OffsetReg)
11465        .addImm(X86::sub_32bit);
11466
11467    // Add the offset to the reg_save_area to get the final address.
11468    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11469      .addReg(OffsetReg64)
11470      .addReg(RegSaveReg);
11471
11472    // Compute the offset for the next argument
11473    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11474    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11475      .addReg(OffsetReg)
11476      .addImm(UseFPOffset ? 16 : 8);
11477
11478    // Store it back into the va_list.
11479    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11480      .addOperand(Base)
11481      .addOperand(Scale)
11482      .addOperand(Index)
11483      .addDisp(Disp, UseFPOffset ? 4 : 0)
11484      .addOperand(Segment)
11485      .addReg(NextOffsetReg)
11486      .setMemRefs(MMOBegin, MMOEnd);
11487
11488    // Jump to endMBB
11489    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11490      .addMBB(endMBB);
11491  }
11492
11493  //
11494  // Emit code to use overflow area
11495  //
11496
11497  // Load the overflow_area address into a register.
11498  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11499  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11500    .addOperand(Base)
11501    .addOperand(Scale)
11502    .addOperand(Index)
11503    .addDisp(Disp, 8)
11504    .addOperand(Segment)
11505    .setMemRefs(MMOBegin, MMOEnd);
11506
11507  // If we need to align it, do so. Otherwise, just copy the address
11508  // to OverflowDestReg.
11509  if (NeedsAlign) {
11510    // Align the overflow address
11511    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11512    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11513
11514    // aligned_addr = (addr + (align-1)) & ~(align-1)
11515    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11516      .addReg(OverflowAddrReg)
11517      .addImm(Align-1);
11518
11519    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11520      .addReg(TmpReg)
11521      .addImm(~(uint64_t)(Align-1));
11522  } else {
11523    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11524      .addReg(OverflowAddrReg);
11525  }
11526
11527  // Compute the next overflow address after this argument.
11528  // (the overflow address should be kept 8-byte aligned)
11529  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11530  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11531    .addReg(OverflowDestReg)
11532    .addImm(ArgSizeA8);
11533
11534  // Store the new overflow address.
11535  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11536    .addOperand(Base)
11537    .addOperand(Scale)
11538    .addOperand(Index)
11539    .addDisp(Disp, 8)
11540    .addOperand(Segment)
11541    .addReg(NextAddrReg)
11542    .setMemRefs(MMOBegin, MMOEnd);
11543
11544  // If we branched, emit the PHI to the front of endMBB.
11545  if (offsetMBB) {
11546    BuildMI(*endMBB, endMBB->begin(), DL,
11547            TII->get(X86::PHI), DestReg)
11548      .addReg(OffsetDestReg).addMBB(offsetMBB)
11549      .addReg(OverflowDestReg).addMBB(overflowMBB);
11550  }
11551
11552  // Erase the pseudo instruction
11553  MI->eraseFromParent();
11554
11555  return endMBB;
11556}
11557
11558MachineBasicBlock *
11559X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11560                                                 MachineInstr *MI,
11561                                                 MachineBasicBlock *MBB) const {
11562  // Emit code to save XMM registers to the stack. The ABI says that the
11563  // number of registers to save is given in %al, so it's theoretically
11564  // possible to do an indirect jump trick to avoid saving all of them,
11565  // however this code takes a simpler approach and just executes all
11566  // of the stores if %al is non-zero. It's less code, and it's probably
11567  // easier on the hardware branch predictor, and stores aren't all that
11568  // expensive anyway.
11569
11570  // Create the new basic blocks. One block contains all the XMM stores,
11571  // and one block is the final destination regardless of whether any
11572  // stores were performed.
11573  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11574  MachineFunction *F = MBB->getParent();
11575  MachineFunction::iterator MBBIter = MBB;
11576  ++MBBIter;
11577  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11578  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11579  F->insert(MBBIter, XMMSaveMBB);
11580  F->insert(MBBIter, EndMBB);
11581
11582  // Transfer the remainder of MBB and its successor edges to EndMBB.
11583  EndMBB->splice(EndMBB->begin(), MBB,
11584                 llvm::next(MachineBasicBlock::iterator(MI)),
11585                 MBB->end());
11586  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11587
11588  // The original block will now fall through to the XMM save block.
11589  MBB->addSuccessor(XMMSaveMBB);
11590  // The XMMSaveMBB will fall through to the end block.
11591  XMMSaveMBB->addSuccessor(EndMBB);
11592
11593  // Now add the instructions.
11594  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11595  DebugLoc DL = MI->getDebugLoc();
11596
11597  unsigned CountReg = MI->getOperand(0).getReg();
11598  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11599  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11600
11601  if (!Subtarget->isTargetWin64()) {
11602    // If %al is 0, branch around the XMM save block.
11603    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11604    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11605    MBB->addSuccessor(EndMBB);
11606  }
11607
11608  unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11609  // In the XMM save block, save all the XMM argument registers.
11610  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11611    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11612    MachineMemOperand *MMO =
11613      F->getMachineMemOperand(
11614          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11615        MachineMemOperand::MOStore,
11616        /*Size=*/16, /*Align=*/16);
11617    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11618      .addFrameIndex(RegSaveFrameIndex)
11619      .addImm(/*Scale=*/1)
11620      .addReg(/*IndexReg=*/0)
11621      .addImm(/*Disp=*/Offset)
11622      .addReg(/*Segment=*/0)
11623      .addReg(MI->getOperand(i).getReg())
11624      .addMemOperand(MMO);
11625  }
11626
11627  MI->eraseFromParent();   // The pseudo instruction is gone now.
11628
11629  return EndMBB;
11630}
11631
11632MachineBasicBlock *
11633X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11634                                     MachineBasicBlock *BB) const {
11635  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11636  DebugLoc DL = MI->getDebugLoc();
11637
11638  // To "insert" a SELECT_CC instruction, we actually have to insert the
11639  // diamond control-flow pattern.  The incoming instruction knows the
11640  // destination vreg to set, the condition code register to branch on, the
11641  // true/false values to select between, and a branch opcode to use.
11642  const BasicBlock *LLVM_BB = BB->getBasicBlock();
11643  MachineFunction::iterator It = BB;
11644  ++It;
11645
11646  //  thisMBB:
11647  //  ...
11648  //   TrueVal = ...
11649  //   cmpTY ccX, r1, r2
11650  //   bCC copy1MBB
11651  //   fallthrough --> copy0MBB
11652  MachineBasicBlock *thisMBB = BB;
11653  MachineFunction *F = BB->getParent();
11654  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11655  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11656  F->insert(It, copy0MBB);
11657  F->insert(It, sinkMBB);
11658
11659  // If the EFLAGS register isn't dead in the terminator, then claim that it's
11660  // live into the sink and copy blocks.
11661  if (!MI->killsRegister(X86::EFLAGS)) {
11662    copy0MBB->addLiveIn(X86::EFLAGS);
11663    sinkMBB->addLiveIn(X86::EFLAGS);
11664  }
11665
11666  // Transfer the remainder of BB and its successor edges to sinkMBB.
11667  sinkMBB->splice(sinkMBB->begin(), BB,
11668                  llvm::next(MachineBasicBlock::iterator(MI)),
11669                  BB->end());
11670  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11671
11672  // Add the true and fallthrough blocks as its successors.
11673  BB->addSuccessor(copy0MBB);
11674  BB->addSuccessor(sinkMBB);
11675
11676  // Create the conditional branch instruction.
11677  unsigned Opc =
11678    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11679  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11680
11681  //  copy0MBB:
11682  //   %FalseValue = ...
11683  //   # fallthrough to sinkMBB
11684  copy0MBB->addSuccessor(sinkMBB);
11685
11686  //  sinkMBB:
11687  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11688  //  ...
11689  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11690          TII->get(X86::PHI), MI->getOperand(0).getReg())
11691    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11692    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11693
11694  MI->eraseFromParent();   // The pseudo instruction is gone now.
11695  return sinkMBB;
11696}
11697
11698MachineBasicBlock *
11699X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11700                                        bool Is64Bit) const {
11701  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11702  DebugLoc DL = MI->getDebugLoc();
11703  MachineFunction *MF = BB->getParent();
11704  const BasicBlock *LLVM_BB = BB->getBasicBlock();
11705
11706  assert(EnableSegmentedStacks);
11707
11708  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11709  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11710
11711  // BB:
11712  //  ... [Till the alloca]
11713  // If stacklet is not large enough, jump to mallocMBB
11714  //
11715  // bumpMBB:
11716  //  Allocate by subtracting from RSP
11717  //  Jump to continueMBB
11718  //
11719  // mallocMBB:
11720  //  Allocate by call to runtime
11721  //
11722  // continueMBB:
11723  //  ...
11724  //  [rest of original BB]
11725  //
11726
11727  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11728  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11729  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11730
11731  MachineRegisterInfo &MRI = MF->getRegInfo();
11732  const TargetRegisterClass *AddrRegClass =
11733    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11734
11735  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11736    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11737    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11738    sizeVReg = MI->getOperand(1).getReg(),
11739    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11740
11741  MachineFunction::iterator MBBIter = BB;
11742  ++MBBIter;
11743
11744  MF->insert(MBBIter, bumpMBB);
11745  MF->insert(MBBIter, mallocMBB);
11746  MF->insert(MBBIter, continueMBB);
11747
11748  continueMBB->splice(continueMBB->begin(), BB, llvm::next
11749                      (MachineBasicBlock::iterator(MI)), BB->end());
11750  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11751
11752  // Add code to the main basic block to check if the stack limit has been hit,
11753  // and if so, jump to mallocMBB otherwise to bumpMBB.
11754  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11755  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11756    .addReg(tmpSPVReg).addReg(sizeVReg);
11757  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11758    .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11759    .addReg(tmpSPVReg);
11760  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11761
11762  // bumpMBB simply decreases the stack pointer, since we know the current
11763  // stacklet has enough space.
11764  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11765    .addReg(tmpSPVReg);
11766  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11767    .addReg(tmpSPVReg);
11768  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11769
11770  // Calls into a routine in libgcc to allocate more space from the heap.
11771  if (Is64Bit) {
11772    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11773      .addReg(sizeVReg);
11774    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11775    .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11776  } else {
11777    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11778      .addImm(12);
11779    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11780    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11781      .addExternalSymbol("__morestack_allocate_stack_space");
11782  }
11783
11784  if (!Is64Bit)
11785    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11786      .addImm(16);
11787
11788  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11789    .addReg(Is64Bit ? X86::RAX : X86::EAX);
11790  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11791
11792  // Set up the CFG correctly.
11793  BB->addSuccessor(bumpMBB);
11794  BB->addSuccessor(mallocMBB);
11795  mallocMBB->addSuccessor(continueMBB);
11796  bumpMBB->addSuccessor(continueMBB);
11797
11798  // Take care of the PHI nodes.
11799  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11800          MI->getOperand(0).getReg())
11801    .addReg(mallocPtrVReg).addMBB(mallocMBB)
11802    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11803
11804  // Delete the original pseudo instruction.
11805  MI->eraseFromParent();
11806
11807  // And we're done.
11808  return continueMBB;
11809}
11810
11811MachineBasicBlock *
11812X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11813                                          MachineBasicBlock *BB) const {
11814  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11815  DebugLoc DL = MI->getDebugLoc();
11816
11817  assert(!Subtarget->isTargetEnvMacho());
11818
11819  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11820  // non-trivial part is impdef of ESP.
11821
11822  if (Subtarget->isTargetWin64()) {
11823    if (Subtarget->isTargetCygMing()) {
11824      // ___chkstk(Mingw64):
11825      // Clobbers R10, R11, RAX and EFLAGS.
11826      // Updates RSP.
11827      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11828        .addExternalSymbol("___chkstk")
11829        .addReg(X86::RAX, RegState::Implicit)
11830        .addReg(X86::RSP, RegState::Implicit)
11831        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11832        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11833        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11834    } else {
11835      // __chkstk(MSVCRT): does not update stack pointer.
11836      // Clobbers R10, R11 and EFLAGS.
11837      // FIXME: RAX(allocated size) might be reused and not killed.
11838      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11839        .addExternalSymbol("__chkstk")
11840        .addReg(X86::RAX, RegState::Implicit)
11841        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11842      // RAX has the offset to subtracted from RSP.
11843      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11844        .addReg(X86::RSP)
11845        .addReg(X86::RAX);
11846    }
11847  } else {
11848    const char *StackProbeSymbol =
11849      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11850
11851    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11852      .addExternalSymbol(StackProbeSymbol)
11853      .addReg(X86::EAX, RegState::Implicit)
11854      .addReg(X86::ESP, RegState::Implicit)
11855      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11856      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11857      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11858  }
11859
11860  MI->eraseFromParent();   // The pseudo instruction is gone now.
11861  return BB;
11862}
11863
11864MachineBasicBlock *
11865X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11866                                      MachineBasicBlock *BB) const {
11867  // This is pretty easy.  We're taking the value that we received from
11868  // our load from the relocation, sticking it in either RDI (x86-64)
11869  // or EAX and doing an indirect call.  The return value will then
11870  // be in the normal return register.
11871  const X86InstrInfo *TII
11872    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11873  DebugLoc DL = MI->getDebugLoc();
11874  MachineFunction *F = BB->getParent();
11875
11876  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11877  assert(MI->getOperand(3).isGlobal() && "This should be a global");
11878
11879  if (Subtarget->is64Bit()) {
11880    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11881                                      TII->get(X86::MOV64rm), X86::RDI)
11882    .addReg(X86::RIP)
11883    .addImm(0).addReg(0)
11884    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11885                      MI->getOperand(3).getTargetFlags())
11886    .addReg(0);
11887    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11888    addDirectMem(MIB, X86::RDI);
11889  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11890    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11891                                      TII->get(X86::MOV32rm), X86::EAX)
11892    .addReg(0)
11893    .addImm(0).addReg(0)
11894    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11895                      MI->getOperand(3).getTargetFlags())
11896    .addReg(0);
11897    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11898    addDirectMem(MIB, X86::EAX);
11899  } else {
11900    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11901                                      TII->get(X86::MOV32rm), X86::EAX)
11902    .addReg(TII->getGlobalBaseReg(F))
11903    .addImm(0).addReg(0)
11904    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11905                      MI->getOperand(3).getTargetFlags())
11906    .addReg(0);
11907    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11908    addDirectMem(MIB, X86::EAX);
11909  }
11910
11911  MI->eraseFromParent(); // The pseudo instruction is gone now.
11912  return BB;
11913}
11914
11915MachineBasicBlock *
11916X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11917                                               MachineBasicBlock *BB) const {
11918  switch (MI->getOpcode()) {
11919  default: assert(false && "Unexpected instr type to insert");
11920  case X86::TAILJMPd64:
11921  case X86::TAILJMPr64:
11922  case X86::TAILJMPm64:
11923    assert(!"TAILJMP64 would not be touched here.");
11924  case X86::TCRETURNdi64:
11925  case X86::TCRETURNri64:
11926  case X86::TCRETURNmi64:
11927    // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11928    // On AMD64, additional defs should be added before register allocation.
11929    if (!Subtarget->isTargetWin64()) {
11930      MI->addRegisterDefined(X86::RSI);
11931      MI->addRegisterDefined(X86::RDI);
11932      MI->addRegisterDefined(X86::XMM6);
11933      MI->addRegisterDefined(X86::XMM7);
11934      MI->addRegisterDefined(X86::XMM8);
11935      MI->addRegisterDefined(X86::XMM9);
11936      MI->addRegisterDefined(X86::XMM10);
11937      MI->addRegisterDefined(X86::XMM11);
11938      MI->addRegisterDefined(X86::XMM12);
11939      MI->addRegisterDefined(X86::XMM13);
11940      MI->addRegisterDefined(X86::XMM14);
11941      MI->addRegisterDefined(X86::XMM15);
11942    }
11943    return BB;
11944  case X86::WIN_ALLOCA:
11945    return EmitLoweredWinAlloca(MI, BB);
11946  case X86::SEG_ALLOCA_32:
11947    return EmitLoweredSegAlloca(MI, BB, false);
11948  case X86::SEG_ALLOCA_64:
11949    return EmitLoweredSegAlloca(MI, BB, true);
11950  case X86::TLSCall_32:
11951  case X86::TLSCall_64:
11952    return EmitLoweredTLSCall(MI, BB);
11953  case X86::CMOV_GR8:
11954  case X86::CMOV_FR32:
11955  case X86::CMOV_FR64:
11956  case X86::CMOV_V4F32:
11957  case X86::CMOV_V2F64:
11958  case X86::CMOV_V2I64:
11959  case X86::CMOV_V8F32:
11960  case X86::CMOV_V4F64:
11961  case X86::CMOV_V4I64:
11962  case X86::CMOV_GR16:
11963  case X86::CMOV_GR32:
11964  case X86::CMOV_RFP32:
11965  case X86::CMOV_RFP64:
11966  case X86::CMOV_RFP80:
11967    return EmitLoweredSelect(MI, BB);
11968
11969  case X86::FP32_TO_INT16_IN_MEM:
11970  case X86::FP32_TO_INT32_IN_MEM:
11971  case X86::FP32_TO_INT64_IN_MEM:
11972  case X86::FP64_TO_INT16_IN_MEM:
11973  case X86::FP64_TO_INT32_IN_MEM:
11974  case X86::FP64_TO_INT64_IN_MEM:
11975  case X86::FP80_TO_INT16_IN_MEM:
11976  case X86::FP80_TO_INT32_IN_MEM:
11977  case X86::FP80_TO_INT64_IN_MEM: {
11978    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11979    DebugLoc DL = MI->getDebugLoc();
11980
11981    // Change the floating point control register to use "round towards zero"
11982    // mode when truncating to an integer value.
11983    MachineFunction *F = BB->getParent();
11984    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
11985    addFrameReference(BuildMI(*BB, MI, DL,
11986                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
11987
11988    // Load the old value of the high byte of the control word...
11989    unsigned OldCW =
11990      F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
11991    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
11992                      CWFrameIdx);
11993
11994    // Set the high part to be round to zero...
11995    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
11996      .addImm(0xC7F);
11997
11998    // Reload the modified control word now...
11999    addFrameReference(BuildMI(*BB, MI, DL,
12000                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12001
12002    // Restore the memory image of control word to original value
12003    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12004      .addReg(OldCW);
12005
12006    // Get the X86 opcode to use.
12007    unsigned Opc;
12008    switch (MI->getOpcode()) {
12009    default: llvm_unreachable("illegal opcode!");
12010    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12011    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12012    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12013    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12014    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12015    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12016    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12017    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12018    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12019    }
12020
12021    X86AddressMode AM;
12022    MachineOperand &Op = MI->getOperand(0);
12023    if (Op.isReg()) {
12024      AM.BaseType = X86AddressMode::RegBase;
12025      AM.Base.Reg = Op.getReg();
12026    } else {
12027      AM.BaseType = X86AddressMode::FrameIndexBase;
12028      AM.Base.FrameIndex = Op.getIndex();
12029    }
12030    Op = MI->getOperand(1);
12031    if (Op.isImm())
12032      AM.Scale = Op.getImm();
12033    Op = MI->getOperand(2);
12034    if (Op.isImm())
12035      AM.IndexReg = Op.getImm();
12036    Op = MI->getOperand(3);
12037    if (Op.isGlobal()) {
12038      AM.GV = Op.getGlobal();
12039    } else {
12040      AM.Disp = Op.getImm();
12041    }
12042    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12043                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12044
12045    // Reload the original control word now.
12046    addFrameReference(BuildMI(*BB, MI, DL,
12047                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12048
12049    MI->eraseFromParent();   // The pseudo instruction is gone now.
12050    return BB;
12051  }
12052    // String/text processing lowering.
12053  case X86::PCMPISTRM128REG:
12054  case X86::VPCMPISTRM128REG:
12055    return EmitPCMP(MI, BB, 3, false /* in-mem */);
12056  case X86::PCMPISTRM128MEM:
12057  case X86::VPCMPISTRM128MEM:
12058    return EmitPCMP(MI, BB, 3, true /* in-mem */);
12059  case X86::PCMPESTRM128REG:
12060  case X86::VPCMPESTRM128REG:
12061    return EmitPCMP(MI, BB, 5, false /* in mem */);
12062  case X86::PCMPESTRM128MEM:
12063  case X86::VPCMPESTRM128MEM:
12064    return EmitPCMP(MI, BB, 5, true /* in mem */);
12065
12066    // Thread synchronization.
12067  case X86::MONITOR:
12068    return EmitMonitor(MI, BB);
12069  case X86::MWAIT:
12070    return EmitMwait(MI, BB);
12071
12072    // Atomic Lowering.
12073  case X86::ATOMAND32:
12074    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12075                                               X86::AND32ri, X86::MOV32rm,
12076                                               X86::LCMPXCHG32,
12077                                               X86::NOT32r, X86::EAX,
12078                                               X86::GR32RegisterClass);
12079  case X86::ATOMOR32:
12080    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12081                                               X86::OR32ri, X86::MOV32rm,
12082                                               X86::LCMPXCHG32,
12083                                               X86::NOT32r, X86::EAX,
12084                                               X86::GR32RegisterClass);
12085  case X86::ATOMXOR32:
12086    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12087                                               X86::XOR32ri, X86::MOV32rm,
12088                                               X86::LCMPXCHG32,
12089                                               X86::NOT32r, X86::EAX,
12090                                               X86::GR32RegisterClass);
12091  case X86::ATOMNAND32:
12092    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12093                                               X86::AND32ri, X86::MOV32rm,
12094                                               X86::LCMPXCHG32,
12095                                               X86::NOT32r, X86::EAX,
12096                                               X86::GR32RegisterClass, true);
12097  case X86::ATOMMIN32:
12098    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12099  case X86::ATOMMAX32:
12100    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12101  case X86::ATOMUMIN32:
12102    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12103  case X86::ATOMUMAX32:
12104    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12105
12106  case X86::ATOMAND16:
12107    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12108                                               X86::AND16ri, X86::MOV16rm,
12109                                               X86::LCMPXCHG16,
12110                                               X86::NOT16r, X86::AX,
12111                                               X86::GR16RegisterClass);
12112  case X86::ATOMOR16:
12113    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12114                                               X86::OR16ri, X86::MOV16rm,
12115                                               X86::LCMPXCHG16,
12116                                               X86::NOT16r, X86::AX,
12117                                               X86::GR16RegisterClass);
12118  case X86::ATOMXOR16:
12119    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12120                                               X86::XOR16ri, X86::MOV16rm,
12121                                               X86::LCMPXCHG16,
12122                                               X86::NOT16r, X86::AX,
12123                                               X86::GR16RegisterClass);
12124  case X86::ATOMNAND16:
12125    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12126                                               X86::AND16ri, X86::MOV16rm,
12127                                               X86::LCMPXCHG16,
12128                                               X86::NOT16r, X86::AX,
12129                                               X86::GR16RegisterClass, true);
12130  case X86::ATOMMIN16:
12131    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12132  case X86::ATOMMAX16:
12133    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12134  case X86::ATOMUMIN16:
12135    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12136  case X86::ATOMUMAX16:
12137    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12138
12139  case X86::ATOMAND8:
12140    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12141                                               X86::AND8ri, X86::MOV8rm,
12142                                               X86::LCMPXCHG8,
12143                                               X86::NOT8r, X86::AL,
12144                                               X86::GR8RegisterClass);
12145  case X86::ATOMOR8:
12146    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12147                                               X86::OR8ri, X86::MOV8rm,
12148                                               X86::LCMPXCHG8,
12149                                               X86::NOT8r, X86::AL,
12150                                               X86::GR8RegisterClass);
12151  case X86::ATOMXOR8:
12152    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12153                                               X86::XOR8ri, X86::MOV8rm,
12154                                               X86::LCMPXCHG8,
12155                                               X86::NOT8r, X86::AL,
12156                                               X86::GR8RegisterClass);
12157  case X86::ATOMNAND8:
12158    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12159                                               X86::AND8ri, X86::MOV8rm,
12160                                               X86::LCMPXCHG8,
12161                                               X86::NOT8r, X86::AL,
12162                                               X86::GR8RegisterClass, true);
12163  // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12164  // This group is for 64-bit host.
12165  case X86::ATOMAND64:
12166    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12167                                               X86::AND64ri32, X86::MOV64rm,
12168                                               X86::LCMPXCHG64,
12169                                               X86::NOT64r, X86::RAX,
12170                                               X86::GR64RegisterClass);
12171  case X86::ATOMOR64:
12172    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12173                                               X86::OR64ri32, X86::MOV64rm,
12174                                               X86::LCMPXCHG64,
12175                                               X86::NOT64r, X86::RAX,
12176                                               X86::GR64RegisterClass);
12177  case X86::ATOMXOR64:
12178    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12179                                               X86::XOR64ri32, X86::MOV64rm,
12180                                               X86::LCMPXCHG64,
12181                                               X86::NOT64r, X86::RAX,
12182                                               X86::GR64RegisterClass);
12183  case X86::ATOMNAND64:
12184    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12185                                               X86::AND64ri32, X86::MOV64rm,
12186                                               X86::LCMPXCHG64,
12187                                               X86::NOT64r, X86::RAX,
12188                                               X86::GR64RegisterClass, true);
12189  case X86::ATOMMIN64:
12190    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12191  case X86::ATOMMAX64:
12192    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12193  case X86::ATOMUMIN64:
12194    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12195  case X86::ATOMUMAX64:
12196    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12197
12198  // This group does 64-bit operations on a 32-bit host.
12199  case X86::ATOMAND6432:
12200    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12201                                               X86::AND32rr, X86::AND32rr,
12202                                               X86::AND32ri, X86::AND32ri,
12203                                               false);
12204  case X86::ATOMOR6432:
12205    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12206                                               X86::OR32rr, X86::OR32rr,
12207                                               X86::OR32ri, X86::OR32ri,
12208                                               false);
12209  case X86::ATOMXOR6432:
12210    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12211                                               X86::XOR32rr, X86::XOR32rr,
12212                                               X86::XOR32ri, X86::XOR32ri,
12213                                               false);
12214  case X86::ATOMNAND6432:
12215    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12216                                               X86::AND32rr, X86::AND32rr,
12217                                               X86::AND32ri, X86::AND32ri,
12218                                               true);
12219  case X86::ATOMADD6432:
12220    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12221                                               X86::ADD32rr, X86::ADC32rr,
12222                                               X86::ADD32ri, X86::ADC32ri,
12223                                               false);
12224  case X86::ATOMSUB6432:
12225    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12226                                               X86::SUB32rr, X86::SBB32rr,
12227                                               X86::SUB32ri, X86::SBB32ri,
12228                                               false);
12229  case X86::ATOMSWAP6432:
12230    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12231                                               X86::MOV32rr, X86::MOV32rr,
12232                                               X86::MOV32ri, X86::MOV32ri,
12233                                               false);
12234  case X86::VASTART_SAVE_XMM_REGS:
12235    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12236
12237  case X86::VAARG_64:
12238    return EmitVAARG64WithCustomInserter(MI, BB);
12239  }
12240}
12241
12242//===----------------------------------------------------------------------===//
12243//                           X86 Optimization Hooks
12244//===----------------------------------------------------------------------===//
12245
12246void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12247                                                       const APInt &Mask,
12248                                                       APInt &KnownZero,
12249                                                       APInt &KnownOne,
12250                                                       const SelectionDAG &DAG,
12251                                                       unsigned Depth) const {
12252  unsigned Opc = Op.getOpcode();
12253  assert((Opc >= ISD::BUILTIN_OP_END ||
12254          Opc == ISD::INTRINSIC_WO_CHAIN ||
12255          Opc == ISD::INTRINSIC_W_CHAIN ||
12256          Opc == ISD::INTRINSIC_VOID) &&
12257         "Should use MaskedValueIsZero if you don't know whether Op"
12258         " is a target node!");
12259
12260  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12261  switch (Opc) {
12262  default: break;
12263  case X86ISD::ADD:
12264  case X86ISD::SUB:
12265  case X86ISD::ADC:
12266  case X86ISD::SBB:
12267  case X86ISD::SMUL:
12268  case X86ISD::UMUL:
12269  case X86ISD::INC:
12270  case X86ISD::DEC:
12271  case X86ISD::OR:
12272  case X86ISD::XOR:
12273  case X86ISD::AND:
12274    // These nodes' second result is a boolean.
12275    if (Op.getResNo() == 0)
12276      break;
12277    // Fallthrough
12278  case X86ISD::SETCC:
12279    KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12280                                       Mask.getBitWidth() - 1);
12281    break;
12282  }
12283}
12284
12285unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12286                                                         unsigned Depth) const {
12287  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12288  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12289    return Op.getValueType().getScalarType().getSizeInBits();
12290
12291  // Fallback case.
12292  return 1;
12293}
12294
12295/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12296/// node is a GlobalAddress + offset.
12297bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12298                                       const GlobalValue* &GA,
12299                                       int64_t &Offset) const {
12300  if (N->getOpcode() == X86ISD::Wrapper) {
12301    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12302      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12303      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12304      return true;
12305    }
12306  }
12307  return TargetLowering::isGAPlusOffset(N, GA, Offset);
12308}
12309
12310/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12311/// same as extracting the high 128-bit part of 256-bit vector and then
12312/// inserting the result into the low part of a new 256-bit vector
12313static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12314  EVT VT = SVOp->getValueType(0);
12315  int NumElems = VT.getVectorNumElements();
12316
12317  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12318  for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12319    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12320        SVOp->getMaskElt(j) >= 0)
12321      return false;
12322
12323  return true;
12324}
12325
12326/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12327/// same as extracting the low 128-bit part of 256-bit vector and then
12328/// inserting the result into the high part of a new 256-bit vector
12329static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12330  EVT VT = SVOp->getValueType(0);
12331  int NumElems = VT.getVectorNumElements();
12332
12333  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12334  for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12335    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12336        SVOp->getMaskElt(j) >= 0)
12337      return false;
12338
12339  return true;
12340}
12341
12342/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12343static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12344                                        TargetLowering::DAGCombinerInfo &DCI) {
12345  DebugLoc dl = N->getDebugLoc();
12346  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12347  SDValue V1 = SVOp->getOperand(0);
12348  SDValue V2 = SVOp->getOperand(1);
12349  EVT VT = SVOp->getValueType(0);
12350  int NumElems = VT.getVectorNumElements();
12351
12352  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12353      V2.getOpcode() == ISD::CONCAT_VECTORS) {
12354    //
12355    //                   0,0,0,...
12356    //                      |
12357    //    V      UNDEF    BUILD_VECTOR    UNDEF
12358    //     \      /           \           /
12359    //  CONCAT_VECTOR         CONCAT_VECTOR
12360    //         \                  /
12361    //          \                /
12362    //          RESULT: V + zero extended
12363    //
12364    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12365        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12366        V1.getOperand(1).getOpcode() != ISD::UNDEF)
12367      return SDValue();
12368
12369    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12370      return SDValue();
12371
12372    // To match the shuffle mask, the first half of the mask should
12373    // be exactly the first vector, and all the rest a splat with the
12374    // first element of the second one.
12375    for (int i = 0; i < NumElems/2; ++i)
12376      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12377          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12378        return SDValue();
12379
12380    // Emit a zeroed vector and insert the desired subvector on its
12381    // first half.
12382    SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
12383    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12384                         DAG.getConstant(0, MVT::i32), DAG, dl);
12385    return DCI.CombineTo(N, InsV);
12386  }
12387
12388  //===--------------------------------------------------------------------===//
12389  // Combine some shuffles into subvector extracts and inserts:
12390  //
12391
12392  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12393  if (isShuffleHigh128VectorInsertLow(SVOp)) {
12394    SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12395                                    DAG, dl);
12396    SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12397                                      V, DAG.getConstant(0, MVT::i32), DAG, dl);
12398    return DCI.CombineTo(N, InsV);
12399  }
12400
12401  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12402  if (isShuffleLow128VectorInsertHigh(SVOp)) {
12403    SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12404    SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12405                             V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12406    return DCI.CombineTo(N, InsV);
12407  }
12408
12409  return SDValue();
12410}
12411
12412/// PerformShuffleCombine - Performs several different shuffle combines.
12413static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12414                                     TargetLowering::DAGCombinerInfo &DCI,
12415                                     const X86Subtarget *Subtarget) {
12416  DebugLoc dl = N->getDebugLoc();
12417  EVT VT = N->getValueType(0);
12418
12419  // Don't create instructions with illegal types after legalize types has run.
12420  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12421  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12422    return SDValue();
12423
12424  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12425  if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12426      N->getOpcode() == ISD::VECTOR_SHUFFLE)
12427    return PerformShuffleCombine256(N, DAG, DCI);
12428
12429  // Only handle 128 wide vector from here on.
12430  if (VT.getSizeInBits() != 128)
12431    return SDValue();
12432
12433  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12434  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12435  // consecutive, non-overlapping, and in the right order.
12436  SmallVector<SDValue, 16> Elts;
12437  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12438    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12439
12440  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12441}
12442
12443/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12444/// generation and convert it from being a bunch of shuffles and extracts
12445/// to a simple store and scalar loads to extract the elements.
12446static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12447                                                const TargetLowering &TLI) {
12448  SDValue InputVector = N->getOperand(0);
12449
12450  // Only operate on vectors of 4 elements, where the alternative shuffling
12451  // gets to be more expensive.
12452  if (InputVector.getValueType() != MVT::v4i32)
12453    return SDValue();
12454
12455  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12456  // single use which is a sign-extend or zero-extend, and all elements are
12457  // used.
12458  SmallVector<SDNode *, 4> Uses;
12459  unsigned ExtractedElements = 0;
12460  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12461       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12462    if (UI.getUse().getResNo() != InputVector.getResNo())
12463      return SDValue();
12464
12465    SDNode *Extract = *UI;
12466    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12467      return SDValue();
12468
12469    if (Extract->getValueType(0) != MVT::i32)
12470      return SDValue();
12471    if (!Extract->hasOneUse())
12472      return SDValue();
12473    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12474        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12475      return SDValue();
12476    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12477      return SDValue();
12478
12479    // Record which element was extracted.
12480    ExtractedElements |=
12481      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12482
12483    Uses.push_back(Extract);
12484  }
12485
12486  // If not all the elements were used, this may not be worthwhile.
12487  if (ExtractedElements != 15)
12488    return SDValue();
12489
12490  // Ok, we've now decided to do the transformation.
12491  DebugLoc dl = InputVector.getDebugLoc();
12492
12493  // Store the value to a temporary stack slot.
12494  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12495  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12496                            MachinePointerInfo(), false, false, 0);
12497
12498  // Replace each use (extract) with a load of the appropriate element.
12499  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12500       UE = Uses.end(); UI != UE; ++UI) {
12501    SDNode *Extract = *UI;
12502
12503    // cOMpute the element's address.
12504    SDValue Idx = Extract->getOperand(1);
12505    unsigned EltSize =
12506        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12507    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12508    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12509
12510    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12511                                     StackPtr, OffsetVal);
12512
12513    // Load the scalar.
12514    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12515                                     ScalarAddr, MachinePointerInfo(),
12516                                     false, false, 0);
12517
12518    // Replace the exact with the load.
12519    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12520  }
12521
12522  // The replacement was made in place; don't return anything.
12523  return SDValue();
12524}
12525
12526/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
12527static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12528                                    const X86Subtarget *Subtarget) {
12529  DebugLoc DL = N->getDebugLoc();
12530  SDValue Cond = N->getOperand(0);
12531  // Get the LHS/RHS of the select.
12532  SDValue LHS = N->getOperand(1);
12533  SDValue RHS = N->getOperand(2);
12534
12535  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12536  // instructions match the semantics of the common C idiom x<y?x:y but not
12537  // x<=y?x:y, because of how they handle negative zero (which can be
12538  // ignored in unsafe-math mode).
12539  if (Subtarget->hasSSE2() &&
12540      (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
12541      Cond.getOpcode() == ISD::SETCC) {
12542    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12543
12544    unsigned Opcode = 0;
12545    // Check for x CC y ? x : y.
12546    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12547        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12548      switch (CC) {
12549      default: break;
12550      case ISD::SETULT:
12551        // Converting this to a min would handle NaNs incorrectly, and swapping
12552        // the operands would cause it to handle comparisons between positive
12553        // and negative zero incorrectly.
12554        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12555          if (!UnsafeFPMath &&
12556              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12557            break;
12558          std::swap(LHS, RHS);
12559        }
12560        Opcode = X86ISD::FMIN;
12561        break;
12562      case ISD::SETOLE:
12563        // Converting this to a min would handle comparisons between positive
12564        // and negative zero incorrectly.
12565        if (!UnsafeFPMath &&
12566            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12567          break;
12568        Opcode = X86ISD::FMIN;
12569        break;
12570      case ISD::SETULE:
12571        // Converting this to a min would handle both negative zeros and NaNs
12572        // incorrectly, but we can swap the operands to fix both.
12573        std::swap(LHS, RHS);
12574      case ISD::SETOLT:
12575      case ISD::SETLT:
12576      case ISD::SETLE:
12577        Opcode = X86ISD::FMIN;
12578        break;
12579
12580      case ISD::SETOGE:
12581        // Converting this to a max would handle comparisons between positive
12582        // and negative zero incorrectly.
12583        if (!UnsafeFPMath &&
12584            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12585          break;
12586        Opcode = X86ISD::FMAX;
12587        break;
12588      case ISD::SETUGT:
12589        // Converting this to a max would handle NaNs incorrectly, and swapping
12590        // the operands would cause it to handle comparisons between positive
12591        // and negative zero incorrectly.
12592        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12593          if (!UnsafeFPMath &&
12594              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12595            break;
12596          std::swap(LHS, RHS);
12597        }
12598        Opcode = X86ISD::FMAX;
12599        break;
12600      case ISD::SETUGE:
12601        // Converting this to a max would handle both negative zeros and NaNs
12602        // incorrectly, but we can swap the operands to fix both.
12603        std::swap(LHS, RHS);
12604      case ISD::SETOGT:
12605      case ISD::SETGT:
12606      case ISD::SETGE:
12607        Opcode = X86ISD::FMAX;
12608        break;
12609      }
12610    // Check for x CC y ? y : x -- a min/max with reversed arms.
12611    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12612               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12613      switch (CC) {
12614      default: break;
12615      case ISD::SETOGE:
12616        // Converting this to a min would handle comparisons between positive
12617        // and negative zero incorrectly, and swapping the operands would
12618        // cause it to handle NaNs incorrectly.
12619        if (!UnsafeFPMath &&
12620            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12621          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12622            break;
12623          std::swap(LHS, RHS);
12624        }
12625        Opcode = X86ISD::FMIN;
12626        break;
12627      case ISD::SETUGT:
12628        // Converting this to a min would handle NaNs incorrectly.
12629        if (!UnsafeFPMath &&
12630            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12631          break;
12632        Opcode = X86ISD::FMIN;
12633        break;
12634      case ISD::SETUGE:
12635        // Converting this to a min would handle both negative zeros and NaNs
12636        // incorrectly, but we can swap the operands to fix both.
12637        std::swap(LHS, RHS);
12638      case ISD::SETOGT:
12639      case ISD::SETGT:
12640      case ISD::SETGE:
12641        Opcode = X86ISD::FMIN;
12642        break;
12643
12644      case ISD::SETULT:
12645        // Converting this to a max would handle NaNs incorrectly.
12646        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12647          break;
12648        Opcode = X86ISD::FMAX;
12649        break;
12650      case ISD::SETOLE:
12651        // Converting this to a max would handle comparisons between positive
12652        // and negative zero incorrectly, and swapping the operands would
12653        // cause it to handle NaNs incorrectly.
12654        if (!UnsafeFPMath &&
12655            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12656          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12657            break;
12658          std::swap(LHS, RHS);
12659        }
12660        Opcode = X86ISD::FMAX;
12661        break;
12662      case ISD::SETULE:
12663        // Converting this to a max would handle both negative zeros and NaNs
12664        // incorrectly, but we can swap the operands to fix both.
12665        std::swap(LHS, RHS);
12666      case ISD::SETOLT:
12667      case ISD::SETLT:
12668      case ISD::SETLE:
12669        Opcode = X86ISD::FMAX;
12670        break;
12671      }
12672    }
12673
12674    if (Opcode)
12675      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12676  }
12677
12678  // If this is a select between two integer constants, try to do some
12679  // optimizations.
12680  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12681    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12682      // Don't do this for crazy integer types.
12683      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12684        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12685        // so that TrueC (the true value) is larger than FalseC.
12686        bool NeedsCondInvert = false;
12687
12688        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12689            // Efficiently invertible.
12690            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12691             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12692              isa<ConstantSDNode>(Cond.getOperand(1))))) {
12693          NeedsCondInvert = true;
12694          std::swap(TrueC, FalseC);
12695        }
12696
12697        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12698        if (FalseC->getAPIntValue() == 0 &&
12699            TrueC->getAPIntValue().isPowerOf2()) {
12700          if (NeedsCondInvert) // Invert the condition if needed.
12701            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12702                               DAG.getConstant(1, Cond.getValueType()));
12703
12704          // Zero extend the condition if needed.
12705          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12706
12707          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12708          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12709                             DAG.getConstant(ShAmt, MVT::i8));
12710        }
12711
12712        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12713        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12714          if (NeedsCondInvert) // Invert the condition if needed.
12715            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12716                               DAG.getConstant(1, Cond.getValueType()));
12717
12718          // Zero extend the condition if needed.
12719          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12720                             FalseC->getValueType(0), Cond);
12721          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12722                             SDValue(FalseC, 0));
12723        }
12724
12725        // Optimize cases that will turn into an LEA instruction.  This requires
12726        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12727        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12728          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12729          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12730
12731          bool isFastMultiplier = false;
12732          if (Diff < 10) {
12733            switch ((unsigned char)Diff) {
12734              default: break;
12735              case 1:  // result = add base, cond
12736              case 2:  // result = lea base(    , cond*2)
12737              case 3:  // result = lea base(cond, cond*2)
12738              case 4:  // result = lea base(    , cond*4)
12739              case 5:  // result = lea base(cond, cond*4)
12740              case 8:  // result = lea base(    , cond*8)
12741              case 9:  // result = lea base(cond, cond*8)
12742                isFastMultiplier = true;
12743                break;
12744            }
12745          }
12746
12747          if (isFastMultiplier) {
12748            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12749            if (NeedsCondInvert) // Invert the condition if needed.
12750              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12751                                 DAG.getConstant(1, Cond.getValueType()));
12752
12753            // Zero extend the condition if needed.
12754            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12755                               Cond);
12756            // Scale the condition by the difference.
12757            if (Diff != 1)
12758              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12759                                 DAG.getConstant(Diff, Cond.getValueType()));
12760
12761            // Add the base if non-zero.
12762            if (FalseC->getAPIntValue() != 0)
12763              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12764                                 SDValue(FalseC, 0));
12765            return Cond;
12766          }
12767        }
12768      }
12769  }
12770
12771  return SDValue();
12772}
12773
12774/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12775static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12776                                  TargetLowering::DAGCombinerInfo &DCI) {
12777  DebugLoc DL = N->getDebugLoc();
12778
12779  // If the flag operand isn't dead, don't touch this CMOV.
12780  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12781    return SDValue();
12782
12783  SDValue FalseOp = N->getOperand(0);
12784  SDValue TrueOp = N->getOperand(1);
12785  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12786  SDValue Cond = N->getOperand(3);
12787  if (CC == X86::COND_E || CC == X86::COND_NE) {
12788    switch (Cond.getOpcode()) {
12789    default: break;
12790    case X86ISD::BSR:
12791    case X86ISD::BSF:
12792      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12793      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12794        return (CC == X86::COND_E) ? FalseOp : TrueOp;
12795    }
12796  }
12797
12798  // If this is a select between two integer constants, try to do some
12799  // optimizations.  Note that the operands are ordered the opposite of SELECT
12800  // operands.
12801  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12802    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12803      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12804      // larger than FalseC (the false value).
12805      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12806        CC = X86::GetOppositeBranchCondition(CC);
12807        std::swap(TrueC, FalseC);
12808      }
12809
12810      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12811      // This is efficient for any integer data type (including i8/i16) and
12812      // shift amount.
12813      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12814        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12815                           DAG.getConstant(CC, MVT::i8), Cond);
12816
12817        // Zero extend the condition if needed.
12818        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12819
12820        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12821        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12822                           DAG.getConstant(ShAmt, MVT::i8));
12823        if (N->getNumValues() == 2)  // Dead flag value?
12824          return DCI.CombineTo(N, Cond, SDValue());
12825        return Cond;
12826      }
12827
12828      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12829      // for any integer data type, including i8/i16.
12830      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12831        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12832                           DAG.getConstant(CC, MVT::i8), Cond);
12833
12834        // Zero extend the condition if needed.
12835        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12836                           FalseC->getValueType(0), Cond);
12837        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12838                           SDValue(FalseC, 0));
12839
12840        if (N->getNumValues() == 2)  // Dead flag value?
12841          return DCI.CombineTo(N, Cond, SDValue());
12842        return Cond;
12843      }
12844
12845      // Optimize cases that will turn into an LEA instruction.  This requires
12846      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12847      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12848        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12849        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12850
12851        bool isFastMultiplier = false;
12852        if (Diff < 10) {
12853          switch ((unsigned char)Diff) {
12854          default: break;
12855          case 1:  // result = add base, cond
12856          case 2:  // result = lea base(    , cond*2)
12857          case 3:  // result = lea base(cond, cond*2)
12858          case 4:  // result = lea base(    , cond*4)
12859          case 5:  // result = lea base(cond, cond*4)
12860          case 8:  // result = lea base(    , cond*8)
12861          case 9:  // result = lea base(cond, cond*8)
12862            isFastMultiplier = true;
12863            break;
12864          }
12865        }
12866
12867        if (isFastMultiplier) {
12868          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12869          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12870                             DAG.getConstant(CC, MVT::i8), Cond);
12871          // Zero extend the condition if needed.
12872          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12873                             Cond);
12874          // Scale the condition by the difference.
12875          if (Diff != 1)
12876            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12877                               DAG.getConstant(Diff, Cond.getValueType()));
12878
12879          // Add the base if non-zero.
12880          if (FalseC->getAPIntValue() != 0)
12881            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12882                               SDValue(FalseC, 0));
12883          if (N->getNumValues() == 2)  // Dead flag value?
12884            return DCI.CombineTo(N, Cond, SDValue());
12885          return Cond;
12886        }
12887      }
12888    }
12889  }
12890  return SDValue();
12891}
12892
12893
12894/// PerformMulCombine - Optimize a single multiply with constant into two
12895/// in order to implement it with two cheaper instructions, e.g.
12896/// LEA + SHL, LEA + LEA.
12897static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12898                                 TargetLowering::DAGCombinerInfo &DCI) {
12899  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12900    return SDValue();
12901
12902  EVT VT = N->getValueType(0);
12903  if (VT != MVT::i64)
12904    return SDValue();
12905
12906  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12907  if (!C)
12908    return SDValue();
12909  uint64_t MulAmt = C->getZExtValue();
12910  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12911    return SDValue();
12912
12913  uint64_t MulAmt1 = 0;
12914  uint64_t MulAmt2 = 0;
12915  if ((MulAmt % 9) == 0) {
12916    MulAmt1 = 9;
12917    MulAmt2 = MulAmt / 9;
12918  } else if ((MulAmt % 5) == 0) {
12919    MulAmt1 = 5;
12920    MulAmt2 = MulAmt / 5;
12921  } else if ((MulAmt % 3) == 0) {
12922    MulAmt1 = 3;
12923    MulAmt2 = MulAmt / 3;
12924  }
12925  if (MulAmt2 &&
12926      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12927    DebugLoc DL = N->getDebugLoc();
12928
12929    if (isPowerOf2_64(MulAmt2) &&
12930        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12931      // If second multiplifer is pow2, issue it first. We want the multiply by
12932      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12933      // is an add.
12934      std::swap(MulAmt1, MulAmt2);
12935
12936    SDValue NewMul;
12937    if (isPowerOf2_64(MulAmt1))
12938      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12939                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12940    else
12941      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12942                           DAG.getConstant(MulAmt1, VT));
12943
12944    if (isPowerOf2_64(MulAmt2))
12945      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12946                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12947    else
12948      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12949                           DAG.getConstant(MulAmt2, VT));
12950
12951    // Do not add new nodes to DAG combiner worklist.
12952    DCI.CombineTo(N, NewMul, false);
12953  }
12954  return SDValue();
12955}
12956
12957static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12958  SDValue N0 = N->getOperand(0);
12959  SDValue N1 = N->getOperand(1);
12960  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12961  EVT VT = N0.getValueType();
12962
12963  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
12964  // since the result of setcc_c is all zero's or all ones.
12965  if (N1C && N0.getOpcode() == ISD::AND &&
12966      N0.getOperand(1).getOpcode() == ISD::Constant) {
12967    SDValue N00 = N0.getOperand(0);
12968    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
12969        ((N00.getOpcode() == ISD::ANY_EXTEND ||
12970          N00.getOpcode() == ISD::ZERO_EXTEND) &&
12971         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
12972      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
12973      APInt ShAmt = N1C->getAPIntValue();
12974      Mask = Mask.shl(ShAmt);
12975      if (Mask != 0)
12976        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
12977                           N00, DAG.getConstant(Mask, VT));
12978    }
12979  }
12980
12981  return SDValue();
12982}
12983
12984/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
12985///                       when possible.
12986static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
12987                                   const X86Subtarget *Subtarget) {
12988  EVT VT = N->getValueType(0);
12989  if (!VT.isVector() && VT.isInteger() &&
12990      N->getOpcode() == ISD::SHL)
12991    return PerformSHLCombine(N, DAG);
12992
12993  // On X86 with SSE2 support, we can transform this to a vector shift if
12994  // all elements are shifted by the same amount.  We can't do this in legalize
12995  // because the a constant vector is typically transformed to a constant pool
12996  // so we have no knowledge of the shift amount.
12997  if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
12998    return SDValue();
12999
13000  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13001    return SDValue();
13002
13003  SDValue ShAmtOp = N->getOperand(1);
13004  EVT EltVT = VT.getVectorElementType();
13005  DebugLoc DL = N->getDebugLoc();
13006  SDValue BaseShAmt = SDValue();
13007  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13008    unsigned NumElts = VT.getVectorNumElements();
13009    unsigned i = 0;
13010    for (; i != NumElts; ++i) {
13011      SDValue Arg = ShAmtOp.getOperand(i);
13012      if (Arg.getOpcode() == ISD::UNDEF) continue;
13013      BaseShAmt = Arg;
13014      break;
13015    }
13016    for (; i != NumElts; ++i) {
13017      SDValue Arg = ShAmtOp.getOperand(i);
13018      if (Arg.getOpcode() == ISD::UNDEF) continue;
13019      if (Arg != BaseShAmt) {
13020        return SDValue();
13021      }
13022    }
13023  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13024             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13025    SDValue InVec = ShAmtOp.getOperand(0);
13026    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13027      unsigned NumElts = InVec.getValueType().getVectorNumElements();
13028      unsigned i = 0;
13029      for (; i != NumElts; ++i) {
13030        SDValue Arg = InVec.getOperand(i);
13031        if (Arg.getOpcode() == ISD::UNDEF) continue;
13032        BaseShAmt = Arg;
13033        break;
13034      }
13035    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13036       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13037         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13038         if (C->getZExtValue() == SplatIdx)
13039           BaseShAmt = InVec.getOperand(1);
13040       }
13041    }
13042    if (BaseShAmt.getNode() == 0)
13043      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13044                              DAG.getIntPtrConstant(0));
13045  } else
13046    return SDValue();
13047
13048  // The shift amount is an i32.
13049  if (EltVT.bitsGT(MVT::i32))
13050    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13051  else if (EltVT.bitsLT(MVT::i32))
13052    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13053
13054  // The shift amount is identical so we can do a vector shift.
13055  SDValue  ValOp = N->getOperand(0);
13056  switch (N->getOpcode()) {
13057  default:
13058    llvm_unreachable("Unknown shift opcode!");
13059    break;
13060  case ISD::SHL:
13061    if (VT == MVT::v2i64)
13062      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13063                         DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13064                         ValOp, BaseShAmt);
13065    if (VT == MVT::v4i32)
13066      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13067                         DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13068                         ValOp, BaseShAmt);
13069    if (VT == MVT::v8i16)
13070      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13071                         DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13072                         ValOp, BaseShAmt);
13073    break;
13074  case ISD::SRA:
13075    if (VT == MVT::v4i32)
13076      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13077                         DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13078                         ValOp, BaseShAmt);
13079    if (VT == MVT::v8i16)
13080      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13081                         DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13082                         ValOp, BaseShAmt);
13083    break;
13084  case ISD::SRL:
13085    if (VT == MVT::v2i64)
13086      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13087                         DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13088                         ValOp, BaseShAmt);
13089    if (VT == MVT::v4i32)
13090      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13091                         DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13092                         ValOp, BaseShAmt);
13093    if (VT ==  MVT::v8i16)
13094      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13095                         DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13096                         ValOp, BaseShAmt);
13097    break;
13098  }
13099  return SDValue();
13100}
13101
13102
13103// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13104// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13105// and friends.  Likewise for OR -> CMPNEQSS.
13106static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13107                            TargetLowering::DAGCombinerInfo &DCI,
13108                            const X86Subtarget *Subtarget) {
13109  unsigned opcode;
13110
13111  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13112  // we're requiring SSE2 for both.
13113  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13114    SDValue N0 = N->getOperand(0);
13115    SDValue N1 = N->getOperand(1);
13116    SDValue CMP0 = N0->getOperand(1);
13117    SDValue CMP1 = N1->getOperand(1);
13118    DebugLoc DL = N->getDebugLoc();
13119
13120    // The SETCCs should both refer to the same CMP.
13121    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13122      return SDValue();
13123
13124    SDValue CMP00 = CMP0->getOperand(0);
13125    SDValue CMP01 = CMP0->getOperand(1);
13126    EVT     VT    = CMP00.getValueType();
13127
13128    if (VT == MVT::f32 || VT == MVT::f64) {
13129      bool ExpectingFlags = false;
13130      // Check for any users that want flags:
13131      for (SDNode::use_iterator UI = N->use_begin(),
13132             UE = N->use_end();
13133           !ExpectingFlags && UI != UE; ++UI)
13134        switch (UI->getOpcode()) {
13135        default:
13136        case ISD::BR_CC:
13137        case ISD::BRCOND:
13138        case ISD::SELECT:
13139          ExpectingFlags = true;
13140          break;
13141        case ISD::CopyToReg:
13142        case ISD::SIGN_EXTEND:
13143        case ISD::ZERO_EXTEND:
13144        case ISD::ANY_EXTEND:
13145          break;
13146        }
13147
13148      if (!ExpectingFlags) {
13149        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13150        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13151
13152        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13153          X86::CondCode tmp = cc0;
13154          cc0 = cc1;
13155          cc1 = tmp;
13156        }
13157
13158        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13159            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13160          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13161          X86ISD::NodeType NTOperator = is64BitFP ?
13162            X86ISD::FSETCCsd : X86ISD::FSETCCss;
13163          // FIXME: need symbolic constants for these magic numbers.
13164          // See X86ATTInstPrinter.cpp:printSSECC().
13165          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13166          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13167                                              DAG.getConstant(x86cc, MVT::i8));
13168          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13169                                              OnesOrZeroesF);
13170          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13171                                      DAG.getConstant(1, MVT::i32));
13172          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13173          return OneBitOfTruth;
13174        }
13175      }
13176    }
13177  }
13178  return SDValue();
13179}
13180
13181/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13182/// so it can be folded inside ANDNP.
13183static bool CanFoldXORWithAllOnes(const SDNode *N) {
13184  EVT VT = N->getValueType(0);
13185
13186  // Match direct AllOnes for 128 and 256-bit vectors
13187  if (ISD::isBuildVectorAllOnes(N))
13188    return true;
13189
13190  // Look through a bit convert.
13191  if (N->getOpcode() == ISD::BITCAST)
13192    N = N->getOperand(0).getNode();
13193
13194  // Sometimes the operand may come from a insert_subvector building a 256-bit
13195  // allones vector
13196  if (VT.getSizeInBits() == 256 &&
13197      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13198    SDValue V1 = N->getOperand(0);
13199    SDValue V2 = N->getOperand(1);
13200
13201    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13202        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13203        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13204        ISD::isBuildVectorAllOnes(V2.getNode()))
13205      return true;
13206  }
13207
13208  return false;
13209}
13210
13211static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13212                                 TargetLowering::DAGCombinerInfo &DCI,
13213                                 const X86Subtarget *Subtarget) {
13214  if (DCI.isBeforeLegalizeOps())
13215    return SDValue();
13216
13217  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13218  if (R.getNode())
13219    return R;
13220
13221  // Want to form ANDNP nodes:
13222  // 1) In the hopes of then easily combining them with OR and AND nodes
13223  //    to form PBLEND/PSIGN.
13224  // 2) To match ANDN packed intrinsics
13225  EVT VT = N->getValueType(0);
13226  if (VT != MVT::v2i64 && VT != MVT::v4i64)
13227    return SDValue();
13228
13229  SDValue N0 = N->getOperand(0);
13230  SDValue N1 = N->getOperand(1);
13231  DebugLoc DL = N->getDebugLoc();
13232
13233  // Check LHS for vnot
13234  if (N0.getOpcode() == ISD::XOR &&
13235      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13236      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13237    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13238
13239  // Check RHS for vnot
13240  if (N1.getOpcode() == ISD::XOR &&
13241      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13242      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13243    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13244
13245  return SDValue();
13246}
13247
13248static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13249                                TargetLowering::DAGCombinerInfo &DCI,
13250                                const X86Subtarget *Subtarget) {
13251  if (DCI.isBeforeLegalizeOps())
13252    return SDValue();
13253
13254  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13255  if (R.getNode())
13256    return R;
13257
13258  EVT VT = N->getValueType(0);
13259  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13260    return SDValue();
13261
13262  SDValue N0 = N->getOperand(0);
13263  SDValue N1 = N->getOperand(1);
13264
13265  // look for psign/blend
13266  if (Subtarget->hasSSSE3()) {
13267    if (VT == MVT::v2i64) {
13268      // Canonicalize pandn to RHS
13269      if (N0.getOpcode() == X86ISD::ANDNP)
13270        std::swap(N0, N1);
13271      // or (and (m, x), (pandn m, y))
13272      if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13273        SDValue Mask = N1.getOperand(0);
13274        SDValue X    = N1.getOperand(1);
13275        SDValue Y;
13276        if (N0.getOperand(0) == Mask)
13277          Y = N0.getOperand(1);
13278        if (N0.getOperand(1) == Mask)
13279          Y = N0.getOperand(0);
13280
13281        // Check to see if the mask appeared in both the AND and ANDNP and
13282        if (!Y.getNode())
13283          return SDValue();
13284
13285        // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13286        if (Mask.getOpcode() != ISD::BITCAST ||
13287            X.getOpcode() != ISD::BITCAST ||
13288            Y.getOpcode() != ISD::BITCAST)
13289          return SDValue();
13290
13291        // Look through mask bitcast.
13292        Mask = Mask.getOperand(0);
13293        EVT MaskVT = Mask.getValueType();
13294
13295        // Validate that the Mask operand is a vector sra node.  The sra node
13296        // will be an intrinsic.
13297        if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13298          return SDValue();
13299
13300        // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13301        // there is no psrai.b
13302        switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13303        case Intrinsic::x86_sse2_psrai_w:
13304        case Intrinsic::x86_sse2_psrai_d:
13305          break;
13306        default: return SDValue();
13307        }
13308
13309        // Check that the SRA is all signbits.
13310        SDValue SraC = Mask.getOperand(2);
13311        unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13312        unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13313        if ((SraAmt + 1) != EltBits)
13314          return SDValue();
13315
13316        DebugLoc DL = N->getDebugLoc();
13317
13318        // Now we know we at least have a plendvb with the mask val.  See if
13319        // we can form a psignb/w/d.
13320        // psign = x.type == y.type == mask.type && y = sub(0, x);
13321        X = X.getOperand(0);
13322        Y = Y.getOperand(0);
13323        if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13324            ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13325            X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13326          unsigned Opc = 0;
13327          switch (EltBits) {
13328          case 8: Opc = X86ISD::PSIGNB; break;
13329          case 16: Opc = X86ISD::PSIGNW; break;
13330          case 32: Opc = X86ISD::PSIGND; break;
13331          default: break;
13332          }
13333          if (Opc) {
13334            SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13335            return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13336          }
13337        }
13338        // PBLENDVB only available on SSE 4.1
13339        if (!Subtarget->hasSSE41())
13340          return SDValue();
13341
13342        X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13343        Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13344        Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13345        Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13346        return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13347      }
13348    }
13349  }
13350
13351  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13352  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13353    std::swap(N0, N1);
13354  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13355    return SDValue();
13356  if (!N0.hasOneUse() || !N1.hasOneUse())
13357    return SDValue();
13358
13359  SDValue ShAmt0 = N0.getOperand(1);
13360  if (ShAmt0.getValueType() != MVT::i8)
13361    return SDValue();
13362  SDValue ShAmt1 = N1.getOperand(1);
13363  if (ShAmt1.getValueType() != MVT::i8)
13364    return SDValue();
13365  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13366    ShAmt0 = ShAmt0.getOperand(0);
13367  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13368    ShAmt1 = ShAmt1.getOperand(0);
13369
13370  DebugLoc DL = N->getDebugLoc();
13371  unsigned Opc = X86ISD::SHLD;
13372  SDValue Op0 = N0.getOperand(0);
13373  SDValue Op1 = N1.getOperand(0);
13374  if (ShAmt0.getOpcode() == ISD::SUB) {
13375    Opc = X86ISD::SHRD;
13376    std::swap(Op0, Op1);
13377    std::swap(ShAmt0, ShAmt1);
13378  }
13379
13380  unsigned Bits = VT.getSizeInBits();
13381  if (ShAmt1.getOpcode() == ISD::SUB) {
13382    SDValue Sum = ShAmt1.getOperand(0);
13383    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13384      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13385      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13386        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13387      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13388        return DAG.getNode(Opc, DL, VT,
13389                           Op0, Op1,
13390                           DAG.getNode(ISD::TRUNCATE, DL,
13391                                       MVT::i8, ShAmt0));
13392    }
13393  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13394    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13395    if (ShAmt0C &&
13396        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13397      return DAG.getNode(Opc, DL, VT,
13398                         N0.getOperand(0), N1.getOperand(0),
13399                         DAG.getNode(ISD::TRUNCATE, DL,
13400                                       MVT::i8, ShAmt0));
13401  }
13402
13403  return SDValue();
13404}
13405
13406/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13407static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13408                                   const X86Subtarget *Subtarget) {
13409  StoreSDNode *St = cast<StoreSDNode>(N);
13410  EVT VT = St->getValue().getValueType();
13411  EVT StVT = St->getMemoryVT();
13412  DebugLoc dl = St->getDebugLoc();
13413  SDValue StoredVal = St->getOperand(1);
13414  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13415
13416  // If we are saving a concatination of two XMM registers, perform two stores.
13417  // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13418  // 128-bit ones. If in the future the cost becomes only one memory access the
13419  // first version would be better.
13420  if (VT.getSizeInBits() == 256 &&
13421    StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13422    StoredVal.getNumOperands() == 2) {
13423
13424    SDValue Value0 = StoredVal.getOperand(0);
13425    SDValue Value1 = StoredVal.getOperand(1);
13426
13427    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13428    SDValue Ptr0 = St->getBasePtr();
13429    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13430
13431    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13432                                St->getPointerInfo(), St->isVolatile(),
13433                                St->isNonTemporal(), St->getAlignment());
13434    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13435                                St->getPointerInfo(), St->isVolatile(),
13436                                St->isNonTemporal(), St->getAlignment());
13437    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13438  }
13439
13440  // Optimize trunc store (of multiple scalars) to shuffle and store.
13441  // First, pack all of the elements in one place. Next, store to memory
13442  // in fewer chunks.
13443  if (St->isTruncatingStore() && VT.isVector()) {
13444    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13445    unsigned NumElems = VT.getVectorNumElements();
13446    assert(StVT != VT && "Cannot truncate to the same type");
13447    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13448    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13449
13450    // From, To sizes and ElemCount must be pow of two
13451    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13452    // We are going to use the original vector elt for storing.
13453    // accumulated smaller vector elements must be a multiple of bigger size.
13454    if (0 != (NumElems * ToSz) % FromSz) return SDValue();
13455    unsigned SizeRatio  = FromSz / ToSz;
13456
13457    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13458
13459    // Create a type on which we perform the shuffle
13460    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13461            StVT.getScalarType(), NumElems*SizeRatio);
13462
13463    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13464
13465    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13466    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13467    for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13468
13469    // Can't shuffle using an illegal type
13470    if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13471
13472    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13473                                DAG.getUNDEF(WideVec.getValueType()),
13474                                ShuffleVec.data());
13475    // At this point all of the data is stored at the bottom of the
13476    // register. We now need to save it to mem.
13477
13478    // Find the largest store unit
13479    MVT StoreType = MVT::i8;
13480    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13481         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13482      MVT Tp = (MVT::SimpleValueType)tp;
13483      if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13484        StoreType = Tp;
13485    }
13486
13487    // Bitcast the original vector into a vector of store-size units
13488    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13489            StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13490    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13491    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13492    SmallVector<SDValue, 8> Chains;
13493    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13494                                        TLI.getPointerTy());
13495    SDValue Ptr = St->getBasePtr();
13496
13497    // Perform one or more big stores into memory.
13498    for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13499      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13500                                   StoreType, ShuffWide,
13501                                   DAG.getIntPtrConstant(i));
13502      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13503                                St->getPointerInfo(), St->isVolatile(),
13504                                St->isNonTemporal(), St->getAlignment());
13505      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13506      Chains.push_back(Ch);
13507    }
13508
13509    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13510                               Chains.size());
13511  }
13512
13513
13514  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13515  // the FP state in cases where an emms may be missing.
13516  // A preferable solution to the general problem is to figure out the right
13517  // places to insert EMMS.  This qualifies as a quick hack.
13518
13519  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13520  if (VT.getSizeInBits() != 64)
13521    return SDValue();
13522
13523  const Function *F = DAG.getMachineFunction().getFunction();
13524  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13525  bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13526    && Subtarget->hasSSE2();
13527  if ((VT.isVector() ||
13528       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13529      isa<LoadSDNode>(St->getValue()) &&
13530      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13531      St->getChain().hasOneUse() && !St->isVolatile()) {
13532    SDNode* LdVal = St->getValue().getNode();
13533    LoadSDNode *Ld = 0;
13534    int TokenFactorIndex = -1;
13535    SmallVector<SDValue, 8> Ops;
13536    SDNode* ChainVal = St->getChain().getNode();
13537    // Must be a store of a load.  We currently handle two cases:  the load
13538    // is a direct child, and it's under an intervening TokenFactor.  It is
13539    // possible to dig deeper under nested TokenFactors.
13540    if (ChainVal == LdVal)
13541      Ld = cast<LoadSDNode>(St->getChain());
13542    else if (St->getValue().hasOneUse() &&
13543             ChainVal->getOpcode() == ISD::TokenFactor) {
13544      for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13545        if (ChainVal->getOperand(i).getNode() == LdVal) {
13546          TokenFactorIndex = i;
13547          Ld = cast<LoadSDNode>(St->getValue());
13548        } else
13549          Ops.push_back(ChainVal->getOperand(i));
13550      }
13551    }
13552
13553    if (!Ld || !ISD::isNormalLoad(Ld))
13554      return SDValue();
13555
13556    // If this is not the MMX case, i.e. we are just turning i64 load/store
13557    // into f64 load/store, avoid the transformation if there are multiple
13558    // uses of the loaded value.
13559    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13560      return SDValue();
13561
13562    DebugLoc LdDL = Ld->getDebugLoc();
13563    DebugLoc StDL = N->getDebugLoc();
13564    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13565    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13566    // pair instead.
13567    if (Subtarget->is64Bit() || F64IsLegal) {
13568      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13569      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13570                                  Ld->getPointerInfo(), Ld->isVolatile(),
13571                                  Ld->isNonTemporal(), Ld->getAlignment());
13572      SDValue NewChain = NewLd.getValue(1);
13573      if (TokenFactorIndex != -1) {
13574        Ops.push_back(NewChain);
13575        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13576                               Ops.size());
13577      }
13578      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13579                          St->getPointerInfo(),
13580                          St->isVolatile(), St->isNonTemporal(),
13581                          St->getAlignment());
13582    }
13583
13584    // Otherwise, lower to two pairs of 32-bit loads / stores.
13585    SDValue LoAddr = Ld->getBasePtr();
13586    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13587                                 DAG.getConstant(4, MVT::i32));
13588
13589    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13590                               Ld->getPointerInfo(),
13591                               Ld->isVolatile(), Ld->isNonTemporal(),
13592                               Ld->getAlignment());
13593    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13594                               Ld->getPointerInfo().getWithOffset(4),
13595                               Ld->isVolatile(), Ld->isNonTemporal(),
13596                               MinAlign(Ld->getAlignment(), 4));
13597
13598    SDValue NewChain = LoLd.getValue(1);
13599    if (TokenFactorIndex != -1) {
13600      Ops.push_back(LoLd);
13601      Ops.push_back(HiLd);
13602      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13603                             Ops.size());
13604    }
13605
13606    LoAddr = St->getBasePtr();
13607    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13608                         DAG.getConstant(4, MVT::i32));
13609
13610    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13611                                St->getPointerInfo(),
13612                                St->isVolatile(), St->isNonTemporal(),
13613                                St->getAlignment());
13614    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13615                                St->getPointerInfo().getWithOffset(4),
13616                                St->isVolatile(),
13617                                St->isNonTemporal(),
13618                                MinAlign(St->getAlignment(), 4));
13619    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13620  }
13621  return SDValue();
13622}
13623
13624/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13625/// X86ISD::FXOR nodes.
13626static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13627  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13628  // F[X]OR(0.0, x) -> x
13629  // F[X]OR(x, 0.0) -> x
13630  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13631    if (C->getValueAPF().isPosZero())
13632      return N->getOperand(1);
13633  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13634    if (C->getValueAPF().isPosZero())
13635      return N->getOperand(0);
13636  return SDValue();
13637}
13638
13639/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13640static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13641  // FAND(0.0, x) -> 0.0
13642  // FAND(x, 0.0) -> 0.0
13643  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13644    if (C->getValueAPF().isPosZero())
13645      return N->getOperand(0);
13646  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13647    if (C->getValueAPF().isPosZero())
13648      return N->getOperand(1);
13649  return SDValue();
13650}
13651
13652static SDValue PerformBTCombine(SDNode *N,
13653                                SelectionDAG &DAG,
13654                                TargetLowering::DAGCombinerInfo &DCI) {
13655  // BT ignores high bits in the bit index operand.
13656  SDValue Op1 = N->getOperand(1);
13657  if (Op1.hasOneUse()) {
13658    unsigned BitWidth = Op1.getValueSizeInBits();
13659    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13660    APInt KnownZero, KnownOne;
13661    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13662                                          !DCI.isBeforeLegalizeOps());
13663    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13664    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13665        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13666      DCI.CommitTargetLoweringOpt(TLO);
13667  }
13668  return SDValue();
13669}
13670
13671static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13672  SDValue Op = N->getOperand(0);
13673  if (Op.getOpcode() == ISD::BITCAST)
13674    Op = Op.getOperand(0);
13675  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13676  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13677      VT.getVectorElementType().getSizeInBits() ==
13678      OpVT.getVectorElementType().getSizeInBits()) {
13679    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13680  }
13681  return SDValue();
13682}
13683
13684static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13685  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
13686  //           (and (i32 x86isd::setcc_carry), 1)
13687  // This eliminates the zext. This transformation is necessary because
13688  // ISD::SETCC is always legalized to i8.
13689  DebugLoc dl = N->getDebugLoc();
13690  SDValue N0 = N->getOperand(0);
13691  EVT VT = N->getValueType(0);
13692  if (N0.getOpcode() == ISD::AND &&
13693      N0.hasOneUse() &&
13694      N0.getOperand(0).hasOneUse()) {
13695    SDValue N00 = N0.getOperand(0);
13696    if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13697      return SDValue();
13698    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
13699    if (!C || C->getZExtValue() != 1)
13700      return SDValue();
13701    return DAG.getNode(ISD::AND, dl, VT,
13702                       DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
13703                                   N00.getOperand(0), N00.getOperand(1)),
13704                       DAG.getConstant(1, VT));
13705  }
13706
13707  return SDValue();
13708}
13709
13710// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
13711static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
13712  unsigned X86CC = N->getConstantOperandVal(0);
13713  SDValue EFLAG = N->getOperand(1);
13714  DebugLoc DL = N->getDebugLoc();
13715
13716  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
13717  // a zext and produces an all-ones bit which is more useful than 0/1 in some
13718  // cases.
13719  if (X86CC == X86::COND_B)
13720    return DAG.getNode(ISD::AND, DL, MVT::i8,
13721                       DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
13722                                   DAG.getConstant(X86CC, MVT::i8), EFLAG),
13723                       DAG.getConstant(1, MVT::i8));
13724
13725  return SDValue();
13726}
13727
13728static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
13729                                        const X86TargetLowering *XTLI) {
13730  SDValue Op0 = N->getOperand(0);
13731  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
13732  // a 32-bit target where SSE doesn't support i64->FP operations.
13733  if (Op0.getOpcode() == ISD::LOAD) {
13734    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
13735    EVT VT = Ld->getValueType(0);
13736    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
13737        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
13738        !XTLI->getSubtarget()->is64Bit() &&
13739        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13740      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
13741                                          Ld->getChain(), Op0, DAG);
13742      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
13743      return FILDChain;
13744    }
13745  }
13746  return SDValue();
13747}
13748
13749// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
13750static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
13751                                 X86TargetLowering::DAGCombinerInfo &DCI) {
13752  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
13753  // the result is either zero or one (depending on the input carry bit).
13754  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
13755  if (X86::isZeroNode(N->getOperand(0)) &&
13756      X86::isZeroNode(N->getOperand(1)) &&
13757      // We don't have a good way to replace an EFLAGS use, so only do this when
13758      // dead right now.
13759      SDValue(N, 1).use_empty()) {
13760    DebugLoc DL = N->getDebugLoc();
13761    EVT VT = N->getValueType(0);
13762    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
13763    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
13764                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
13765                                           DAG.getConstant(X86::COND_B,MVT::i8),
13766                                           N->getOperand(2)),
13767                               DAG.getConstant(1, VT));
13768    return DCI.CombineTo(N, Res1, CarryOut);
13769  }
13770
13771  return SDValue();
13772}
13773
13774// fold (add Y, (sete  X, 0)) -> adc  0, Y
13775//      (add Y, (setne X, 0)) -> sbb -1, Y
13776//      (sub (sete  X, 0), Y) -> sbb  0, Y
13777//      (sub (setne X, 0), Y) -> adc -1, Y
13778static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
13779  DebugLoc DL = N->getDebugLoc();
13780
13781  // Look through ZExts.
13782  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
13783  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
13784    return SDValue();
13785
13786  SDValue SetCC = Ext.getOperand(0);
13787  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
13788    return SDValue();
13789
13790  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
13791  if (CC != X86::COND_E && CC != X86::COND_NE)
13792    return SDValue();
13793
13794  SDValue Cmp = SetCC.getOperand(1);
13795  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
13796      !X86::isZeroNode(Cmp.getOperand(1)) ||
13797      !Cmp.getOperand(0).getValueType().isInteger())
13798    return SDValue();
13799
13800  SDValue CmpOp0 = Cmp.getOperand(0);
13801  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
13802                               DAG.getConstant(1, CmpOp0.getValueType()));
13803
13804  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
13805  if (CC == X86::COND_NE)
13806    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
13807                       DL, OtherVal.getValueType(), OtherVal,
13808                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
13809  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
13810                     DL, OtherVal.getValueType(), OtherVal,
13811                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
13812}
13813
13814static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
13815  SDValue Op0 = N->getOperand(0);
13816  SDValue Op1 = N->getOperand(1);
13817
13818  // X86 can't encode an immediate LHS of a sub. See if we can push the
13819  // negation into a preceding instruction.
13820  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
13821    // If the RHS of the sub is a XOR with one use and a constant, invert the
13822    // immediate. Then add one to the LHS of the sub so we can turn
13823    // X-Y -> X+~Y+1, saving one register.
13824    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
13825        isa<ConstantSDNode>(Op1.getOperand(1))) {
13826      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
13827      EVT VT = Op0.getValueType();
13828      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
13829                                   Op1.getOperand(0),
13830                                   DAG.getConstant(~XorC, VT));
13831      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
13832                         DAG.getConstant(C->getAPIntValue()+1, VT));
13833    }
13834  }
13835
13836  return OptimizeConditionalInDecrement(N, DAG);
13837}
13838
13839SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
13840                                             DAGCombinerInfo &DCI) const {
13841  SelectionDAG &DAG = DCI.DAG;
13842  switch (N->getOpcode()) {
13843  default: break;
13844  case ISD::EXTRACT_VECTOR_ELT:
13845    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
13846  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
13847  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
13848  case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
13849  case ISD::SUB:            return PerformSubCombine(N, DAG);
13850  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
13851  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
13852  case ISD::SHL:
13853  case ISD::SRA:
13854  case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
13855  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
13856  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
13857  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
13858  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
13859  case X86ISD::FXOR:
13860  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
13861  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
13862  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
13863  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
13864  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
13865  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
13866  case X86ISD::SHUFPS:      // Handle all target specific shuffles
13867  case X86ISD::SHUFPD:
13868  case X86ISD::PALIGN:
13869  case X86ISD::PUNPCKHBW:
13870  case X86ISD::PUNPCKHWD:
13871  case X86ISD::PUNPCKHDQ:
13872  case X86ISD::PUNPCKHQDQ:
13873  case X86ISD::UNPCKHPS:
13874  case X86ISD::UNPCKHPD:
13875  case X86ISD::VUNPCKHPSY:
13876  case X86ISD::VUNPCKHPDY:
13877  case X86ISD::PUNPCKLBW:
13878  case X86ISD::PUNPCKLWD:
13879  case X86ISD::PUNPCKLDQ:
13880  case X86ISD::PUNPCKLQDQ:
13881  case X86ISD::UNPCKLPS:
13882  case X86ISD::UNPCKLPD:
13883  case X86ISD::VUNPCKLPSY:
13884  case X86ISD::VUNPCKLPDY:
13885  case X86ISD::MOVHLPS:
13886  case X86ISD::MOVLHPS:
13887  case X86ISD::PSHUFD:
13888  case X86ISD::PSHUFHW:
13889  case X86ISD::PSHUFLW:
13890  case X86ISD::MOVSS:
13891  case X86ISD::MOVSD:
13892  case X86ISD::VPERMILPS:
13893  case X86ISD::VPERMILPSY:
13894  case X86ISD::VPERMILPD:
13895  case X86ISD::VPERMILPDY:
13896  case X86ISD::VPERM2F128:
13897  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
13898  }
13899
13900  return SDValue();
13901}
13902
13903/// isTypeDesirableForOp - Return true if the target has native support for
13904/// the specified value type and it is 'desirable' to use the type for the
13905/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
13906/// instruction encodings are longer and some i16 instructions are slow.
13907bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
13908  if (!isTypeLegal(VT))
13909    return false;
13910  if (VT != MVT::i16)
13911    return true;
13912
13913  switch (Opc) {
13914  default:
13915    return true;
13916  case ISD::LOAD:
13917  case ISD::SIGN_EXTEND:
13918  case ISD::ZERO_EXTEND:
13919  case ISD::ANY_EXTEND:
13920  case ISD::SHL:
13921  case ISD::SRL:
13922  case ISD::SUB:
13923  case ISD::ADD:
13924  case ISD::MUL:
13925  case ISD::AND:
13926  case ISD::OR:
13927  case ISD::XOR:
13928    return false;
13929  }
13930}
13931
13932/// IsDesirableToPromoteOp - This method query the target whether it is
13933/// beneficial for dag combiner to promote the specified node. If true, it
13934/// should return the desired promotion type by reference.
13935bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
13936  EVT VT = Op.getValueType();
13937  if (VT != MVT::i16)
13938    return false;
13939
13940  bool Promote = false;
13941  bool Commute = false;
13942  switch (Op.getOpcode()) {
13943  default: break;
13944  case ISD::LOAD: {
13945    LoadSDNode *LD = cast<LoadSDNode>(Op);
13946    // If the non-extending load has a single use and it's not live out, then it
13947    // might be folded.
13948    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
13949                                                     Op.hasOneUse()*/) {
13950      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13951             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
13952        // The only case where we'd want to promote LOAD (rather then it being
13953        // promoted as an operand is when it's only use is liveout.
13954        if (UI->getOpcode() != ISD::CopyToReg)
13955          return false;
13956      }
13957    }
13958    Promote = true;
13959    break;
13960  }
13961  case ISD::SIGN_EXTEND:
13962  case ISD::ZERO_EXTEND:
13963  case ISD::ANY_EXTEND:
13964    Promote = true;
13965    break;
13966  case ISD::SHL:
13967  case ISD::SRL: {
13968    SDValue N0 = Op.getOperand(0);
13969    // Look out for (store (shl (load), x)).
13970    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
13971      return false;
13972    Promote = true;
13973    break;
13974  }
13975  case ISD::ADD:
13976  case ISD::MUL:
13977  case ISD::AND:
13978  case ISD::OR:
13979  case ISD::XOR:
13980    Commute = true;
13981    // fallthrough
13982  case ISD::SUB: {
13983    SDValue N0 = Op.getOperand(0);
13984    SDValue N1 = Op.getOperand(1);
13985    if (!Commute && MayFoldLoad(N1))
13986      return false;
13987    // Avoid disabling potential load folding opportunities.
13988    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
13989      return false;
13990    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
13991      return false;
13992    Promote = true;
13993  }
13994  }
13995
13996  PVT = MVT::i32;
13997  return Promote;
13998}
13999
14000//===----------------------------------------------------------------------===//
14001//                           X86 Inline Assembly Support
14002//===----------------------------------------------------------------------===//
14003
14004bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14005  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14006
14007  std::string AsmStr = IA->getAsmString();
14008
14009  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14010  SmallVector<StringRef, 4> AsmPieces;
14011  SplitString(AsmStr, AsmPieces, ";\n");
14012
14013  switch (AsmPieces.size()) {
14014  default: return false;
14015  case 1:
14016    AsmStr = AsmPieces[0];
14017    AsmPieces.clear();
14018    SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14019
14020    // FIXME: this should verify that we are targeting a 486 or better.  If not,
14021    // we will turn this bswap into something that will be lowered to logical ops
14022    // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14023    // so don't worry about this.
14024    // bswap $0
14025    if (AsmPieces.size() == 2 &&
14026        (AsmPieces[0] == "bswap" ||
14027         AsmPieces[0] == "bswapq" ||
14028         AsmPieces[0] == "bswapl") &&
14029        (AsmPieces[1] == "$0" ||
14030         AsmPieces[1] == "${0:q}")) {
14031      // No need to check constraints, nothing other than the equivalent of
14032      // "=r,0" would be valid here.
14033      IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14034      if (!Ty || Ty->getBitWidth() % 16 != 0)
14035        return false;
14036      return IntrinsicLowering::LowerToByteSwap(CI);
14037    }
14038    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14039    if (CI->getType()->isIntegerTy(16) &&
14040        AsmPieces.size() == 3 &&
14041        (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14042        AsmPieces[1] == "$$8," &&
14043        AsmPieces[2] == "${0:w}" &&
14044        IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14045      AsmPieces.clear();
14046      const std::string &ConstraintsStr = IA->getConstraintString();
14047      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14048      std::sort(AsmPieces.begin(), AsmPieces.end());
14049      if (AsmPieces.size() == 4 &&
14050          AsmPieces[0] == "~{cc}" &&
14051          AsmPieces[1] == "~{dirflag}" &&
14052          AsmPieces[2] == "~{flags}" &&
14053          AsmPieces[3] == "~{fpsr}") {
14054        IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14055        if (!Ty || Ty->getBitWidth() % 16 != 0)
14056          return false;
14057        return IntrinsicLowering::LowerToByteSwap(CI);
14058      }
14059    }
14060    break;
14061  case 3:
14062    if (CI->getType()->isIntegerTy(32) &&
14063        IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14064      SmallVector<StringRef, 4> Words;
14065      SplitString(AsmPieces[0], Words, " \t,");
14066      if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14067          Words[2] == "${0:w}") {
14068        Words.clear();
14069        SplitString(AsmPieces[1], Words, " \t,");
14070        if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14071            Words[2] == "$0") {
14072          Words.clear();
14073          SplitString(AsmPieces[2], Words, " \t,");
14074          if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14075              Words[2] == "${0:w}") {
14076            AsmPieces.clear();
14077            const std::string &ConstraintsStr = IA->getConstraintString();
14078            SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14079            std::sort(AsmPieces.begin(), AsmPieces.end());
14080            if (AsmPieces.size() == 4 &&
14081                AsmPieces[0] == "~{cc}" &&
14082                AsmPieces[1] == "~{dirflag}" &&
14083                AsmPieces[2] == "~{flags}" &&
14084                AsmPieces[3] == "~{fpsr}") {
14085              IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14086              if (!Ty || Ty->getBitWidth() % 16 != 0)
14087                return false;
14088              return IntrinsicLowering::LowerToByteSwap(CI);
14089            }
14090          }
14091        }
14092      }
14093    }
14094
14095    if (CI->getType()->isIntegerTy(64)) {
14096      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14097      if (Constraints.size() >= 2 &&
14098          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14099          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14100        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14101        SmallVector<StringRef, 4> Words;
14102        SplitString(AsmPieces[0], Words, " \t");
14103        if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14104          Words.clear();
14105          SplitString(AsmPieces[1], Words, " \t");
14106          if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14107            Words.clear();
14108            SplitString(AsmPieces[2], Words, " \t,");
14109            if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14110                Words[2] == "%edx") {
14111              IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14112              if (!Ty || Ty->getBitWidth() % 16 != 0)
14113                return false;
14114              return IntrinsicLowering::LowerToByteSwap(CI);
14115            }
14116          }
14117        }
14118      }
14119    }
14120    break;
14121  }
14122  return false;
14123}
14124
14125
14126
14127/// getConstraintType - Given a constraint letter, return the type of
14128/// constraint it is for this target.
14129X86TargetLowering::ConstraintType
14130X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14131  if (Constraint.size() == 1) {
14132    switch (Constraint[0]) {
14133    case 'R':
14134    case 'q':
14135    case 'Q':
14136    case 'f':
14137    case 't':
14138    case 'u':
14139    case 'y':
14140    case 'x':
14141    case 'Y':
14142    case 'l':
14143      return C_RegisterClass;
14144    case 'a':
14145    case 'b':
14146    case 'c':
14147    case 'd':
14148    case 'S':
14149    case 'D':
14150    case 'A':
14151      return C_Register;
14152    case 'I':
14153    case 'J':
14154    case 'K':
14155    case 'L':
14156    case 'M':
14157    case 'N':
14158    case 'G':
14159    case 'C':
14160    case 'e':
14161    case 'Z':
14162      return C_Other;
14163    default:
14164      break;
14165    }
14166  }
14167  return TargetLowering::getConstraintType(Constraint);
14168}
14169
14170/// Examine constraint type and operand type and determine a weight value.
14171/// This object must already have been set up with the operand type
14172/// and the current alternative constraint selected.
14173TargetLowering::ConstraintWeight
14174  X86TargetLowering::getSingleConstraintMatchWeight(
14175    AsmOperandInfo &info, const char *constraint) const {
14176  ConstraintWeight weight = CW_Invalid;
14177  Value *CallOperandVal = info.CallOperandVal;
14178    // If we don't have a value, we can't do a match,
14179    // but allow it at the lowest weight.
14180  if (CallOperandVal == NULL)
14181    return CW_Default;
14182  Type *type = CallOperandVal->getType();
14183  // Look at the constraint type.
14184  switch (*constraint) {
14185  default:
14186    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14187  case 'R':
14188  case 'q':
14189  case 'Q':
14190  case 'a':
14191  case 'b':
14192  case 'c':
14193  case 'd':
14194  case 'S':
14195  case 'D':
14196  case 'A':
14197    if (CallOperandVal->getType()->isIntegerTy())
14198      weight = CW_SpecificReg;
14199    break;
14200  case 'f':
14201  case 't':
14202  case 'u':
14203      if (type->isFloatingPointTy())
14204        weight = CW_SpecificReg;
14205      break;
14206  case 'y':
14207      if (type->isX86_MMXTy() && Subtarget->hasMMX())
14208        weight = CW_SpecificReg;
14209      break;
14210  case 'x':
14211  case 'Y':
14212    if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14213      weight = CW_Register;
14214    break;
14215  case 'I':
14216    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14217      if (C->getZExtValue() <= 31)
14218        weight = CW_Constant;
14219    }
14220    break;
14221  case 'J':
14222    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14223      if (C->getZExtValue() <= 63)
14224        weight = CW_Constant;
14225    }
14226    break;
14227  case 'K':
14228    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14229      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14230        weight = CW_Constant;
14231    }
14232    break;
14233  case 'L':
14234    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14235      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14236        weight = CW_Constant;
14237    }
14238    break;
14239  case 'M':
14240    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14241      if (C->getZExtValue() <= 3)
14242        weight = CW_Constant;
14243    }
14244    break;
14245  case 'N':
14246    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14247      if (C->getZExtValue() <= 0xff)
14248        weight = CW_Constant;
14249    }
14250    break;
14251  case 'G':
14252  case 'C':
14253    if (dyn_cast<ConstantFP>(CallOperandVal)) {
14254      weight = CW_Constant;
14255    }
14256    break;
14257  case 'e':
14258    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14259      if ((C->getSExtValue() >= -0x80000000LL) &&
14260          (C->getSExtValue() <= 0x7fffffffLL))
14261        weight = CW_Constant;
14262    }
14263    break;
14264  case 'Z':
14265    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14266      if (C->getZExtValue() <= 0xffffffff)
14267        weight = CW_Constant;
14268    }
14269    break;
14270  }
14271  return weight;
14272}
14273
14274/// LowerXConstraint - try to replace an X constraint, which matches anything,
14275/// with another that has more specific requirements based on the type of the
14276/// corresponding operand.
14277const char *X86TargetLowering::
14278LowerXConstraint(EVT ConstraintVT) const {
14279  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14280  // 'f' like normal targets.
14281  if (ConstraintVT.isFloatingPoint()) {
14282    if (Subtarget->hasXMMInt())
14283      return "Y";
14284    if (Subtarget->hasXMM())
14285      return "x";
14286  }
14287
14288  return TargetLowering::LowerXConstraint(ConstraintVT);
14289}
14290
14291/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14292/// vector.  If it is invalid, don't add anything to Ops.
14293void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14294                                                     std::string &Constraint,
14295                                                     std::vector<SDValue>&Ops,
14296                                                     SelectionDAG &DAG) const {
14297  SDValue Result(0, 0);
14298
14299  // Only support length 1 constraints for now.
14300  if (Constraint.length() > 1) return;
14301
14302  char ConstraintLetter = Constraint[0];
14303  switch (ConstraintLetter) {
14304  default: break;
14305  case 'I':
14306    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14307      if (C->getZExtValue() <= 31) {
14308        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14309        break;
14310      }
14311    }
14312    return;
14313  case 'J':
14314    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14315      if (C->getZExtValue() <= 63) {
14316        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14317        break;
14318      }
14319    }
14320    return;
14321  case 'K':
14322    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14323      if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14324        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14325        break;
14326      }
14327    }
14328    return;
14329  case 'N':
14330    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14331      if (C->getZExtValue() <= 255) {
14332        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14333        break;
14334      }
14335    }
14336    return;
14337  case 'e': {
14338    // 32-bit signed value
14339    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14340      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14341                                           C->getSExtValue())) {
14342        // Widen to 64 bits here to get it sign extended.
14343        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14344        break;
14345      }
14346    // FIXME gcc accepts some relocatable values here too, but only in certain
14347    // memory models; it's complicated.
14348    }
14349    return;
14350  }
14351  case 'Z': {
14352    // 32-bit unsigned value
14353    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14354      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14355                                           C->getZExtValue())) {
14356        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14357        break;
14358      }
14359    }
14360    // FIXME gcc accepts some relocatable values here too, but only in certain
14361    // memory models; it's complicated.
14362    return;
14363  }
14364  case 'i': {
14365    // Literal immediates are always ok.
14366    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14367      // Widen to 64 bits here to get it sign extended.
14368      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14369      break;
14370    }
14371
14372    // In any sort of PIC mode addresses need to be computed at runtime by
14373    // adding in a register or some sort of table lookup.  These can't
14374    // be used as immediates.
14375    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14376      return;
14377
14378    // If we are in non-pic codegen mode, we allow the address of a global (with
14379    // an optional displacement) to be used with 'i'.
14380    GlobalAddressSDNode *GA = 0;
14381    int64_t Offset = 0;
14382
14383    // Match either (GA), (GA+C), (GA+C1+C2), etc.
14384    while (1) {
14385      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14386        Offset += GA->getOffset();
14387        break;
14388      } else if (Op.getOpcode() == ISD::ADD) {
14389        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14390          Offset += C->getZExtValue();
14391          Op = Op.getOperand(0);
14392          continue;
14393        }
14394      } else if (Op.getOpcode() == ISD::SUB) {
14395        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14396          Offset += -C->getZExtValue();
14397          Op = Op.getOperand(0);
14398          continue;
14399        }
14400      }
14401
14402      // Otherwise, this isn't something we can handle, reject it.
14403      return;
14404    }
14405
14406    const GlobalValue *GV = GA->getGlobal();
14407    // If we require an extra load to get this address, as in PIC mode, we
14408    // can't accept it.
14409    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14410                                                        getTargetMachine())))
14411      return;
14412
14413    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14414                                        GA->getValueType(0), Offset);
14415    break;
14416  }
14417  }
14418
14419  if (Result.getNode()) {
14420    Ops.push_back(Result);
14421    return;
14422  }
14423  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14424}
14425
14426std::pair<unsigned, const TargetRegisterClass*>
14427X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14428                                                EVT VT) const {
14429  // First, see if this is a constraint that directly corresponds to an LLVM
14430  // register class.
14431  if (Constraint.size() == 1) {
14432    // GCC Constraint Letters
14433    switch (Constraint[0]) {
14434    default: break;
14435      // TODO: Slight differences here in allocation order and leaving
14436      // RIP in the class. Do they matter any more here than they do
14437      // in the normal allocation?
14438    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14439      if (Subtarget->is64Bit()) {
14440	if (VT == MVT::i32 || VT == MVT::f32)
14441	  return std::make_pair(0U, X86::GR32RegisterClass);
14442	else if (VT == MVT::i16)
14443	  return std::make_pair(0U, X86::GR16RegisterClass);
14444	else if (VT == MVT::i8 || VT == MVT::i1)
14445	  return std::make_pair(0U, X86::GR8RegisterClass);
14446	else if (VT == MVT::i64 || VT == MVT::f64)
14447	  return std::make_pair(0U, X86::GR64RegisterClass);
14448	break;
14449      }
14450      // 32-bit fallthrough
14451    case 'Q':   // Q_REGS
14452      if (VT == MVT::i32 || VT == MVT::f32)
14453	return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14454      else if (VT == MVT::i16)
14455	return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14456      else if (VT == MVT::i8 || VT == MVT::i1)
14457	return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14458      else if (VT == MVT::i64)
14459	return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14460      break;
14461    case 'r':   // GENERAL_REGS
14462    case 'l':   // INDEX_REGS
14463      if (VT == MVT::i8 || VT == MVT::i1)
14464        return std::make_pair(0U, X86::GR8RegisterClass);
14465      if (VT == MVT::i16)
14466        return std::make_pair(0U, X86::GR16RegisterClass);
14467      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14468        return std::make_pair(0U, X86::GR32RegisterClass);
14469      return std::make_pair(0U, X86::GR64RegisterClass);
14470    case 'R':   // LEGACY_REGS
14471      if (VT == MVT::i8 || VT == MVT::i1)
14472        return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14473      if (VT == MVT::i16)
14474        return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14475      if (VT == MVT::i32 || !Subtarget->is64Bit())
14476        return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14477      return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14478    case 'f':  // FP Stack registers.
14479      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14480      // value to the correct fpstack register class.
14481      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14482        return std::make_pair(0U, X86::RFP32RegisterClass);
14483      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14484        return std::make_pair(0U, X86::RFP64RegisterClass);
14485      return std::make_pair(0U, X86::RFP80RegisterClass);
14486    case 'y':   // MMX_REGS if MMX allowed.
14487      if (!Subtarget->hasMMX()) break;
14488      return std::make_pair(0U, X86::VR64RegisterClass);
14489    case 'Y':   // SSE_REGS if SSE2 allowed
14490      if (!Subtarget->hasXMMInt()) break;
14491      // FALL THROUGH.
14492    case 'x':   // SSE_REGS if SSE1 allowed
14493      if (!Subtarget->hasXMM()) break;
14494
14495      switch (VT.getSimpleVT().SimpleTy) {
14496      default: break;
14497      // Scalar SSE types.
14498      case MVT::f32:
14499      case MVT::i32:
14500        return std::make_pair(0U, X86::FR32RegisterClass);
14501      case MVT::f64:
14502      case MVT::i64:
14503        return std::make_pair(0U, X86::FR64RegisterClass);
14504      // Vector types.
14505      case MVT::v16i8:
14506      case MVT::v8i16:
14507      case MVT::v4i32:
14508      case MVT::v2i64:
14509      case MVT::v4f32:
14510      case MVT::v2f64:
14511        return std::make_pair(0U, X86::VR128RegisterClass);
14512      }
14513      break;
14514    }
14515  }
14516
14517  // Use the default implementation in TargetLowering to convert the register
14518  // constraint into a member of a register class.
14519  std::pair<unsigned, const TargetRegisterClass*> Res;
14520  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14521
14522  // Not found as a standard register?
14523  if (Res.second == 0) {
14524    // Map st(0) -> st(7) -> ST0
14525    if (Constraint.size() == 7 && Constraint[0] == '{' &&
14526        tolower(Constraint[1]) == 's' &&
14527        tolower(Constraint[2]) == 't' &&
14528        Constraint[3] == '(' &&
14529        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14530        Constraint[5] == ')' &&
14531        Constraint[6] == '}') {
14532
14533      Res.first = X86::ST0+Constraint[4]-'0';
14534      Res.second = X86::RFP80RegisterClass;
14535      return Res;
14536    }
14537
14538    // GCC allows "st(0)" to be called just plain "st".
14539    if (StringRef("{st}").equals_lower(Constraint)) {
14540      Res.first = X86::ST0;
14541      Res.second = X86::RFP80RegisterClass;
14542      return Res;
14543    }
14544
14545    // flags -> EFLAGS
14546    if (StringRef("{flags}").equals_lower(Constraint)) {
14547      Res.first = X86::EFLAGS;
14548      Res.second = X86::CCRRegisterClass;
14549      return Res;
14550    }
14551
14552    // 'A' means EAX + EDX.
14553    if (Constraint == "A") {
14554      Res.first = X86::EAX;
14555      Res.second = X86::GR32_ADRegisterClass;
14556      return Res;
14557    }
14558    return Res;
14559  }
14560
14561  // Otherwise, check to see if this is a register class of the wrong value
14562  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14563  // turn into {ax},{dx}.
14564  if (Res.second->hasType(VT))
14565    return Res;   // Correct type already, nothing to do.
14566
14567  // All of the single-register GCC register classes map their values onto
14568  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14569  // really want an 8-bit or 32-bit register, map to the appropriate register
14570  // class and return the appropriate register.
14571  if (Res.second == X86::GR16RegisterClass) {
14572    if (VT == MVT::i8) {
14573      unsigned DestReg = 0;
14574      switch (Res.first) {
14575      default: break;
14576      case X86::AX: DestReg = X86::AL; break;
14577      case X86::DX: DestReg = X86::DL; break;
14578      case X86::CX: DestReg = X86::CL; break;
14579      case X86::BX: DestReg = X86::BL; break;
14580      }
14581      if (DestReg) {
14582        Res.first = DestReg;
14583        Res.second = X86::GR8RegisterClass;
14584      }
14585    } else if (VT == MVT::i32) {
14586      unsigned DestReg = 0;
14587      switch (Res.first) {
14588      default: break;
14589      case X86::AX: DestReg = X86::EAX; break;
14590      case X86::DX: DestReg = X86::EDX; break;
14591      case X86::CX: DestReg = X86::ECX; break;
14592      case X86::BX: DestReg = X86::EBX; break;
14593      case X86::SI: DestReg = X86::ESI; break;
14594      case X86::DI: DestReg = X86::EDI; break;
14595      case X86::BP: DestReg = X86::EBP; break;
14596      case X86::SP: DestReg = X86::ESP; break;
14597      }
14598      if (DestReg) {
14599        Res.first = DestReg;
14600        Res.second = X86::GR32RegisterClass;
14601      }
14602    } else if (VT == MVT::i64) {
14603      unsigned DestReg = 0;
14604      switch (Res.first) {
14605      default: break;
14606      case X86::AX: DestReg = X86::RAX; break;
14607      case X86::DX: DestReg = X86::RDX; break;
14608      case X86::CX: DestReg = X86::RCX; break;
14609      case X86::BX: DestReg = X86::RBX; break;
14610      case X86::SI: DestReg = X86::RSI; break;
14611      case X86::DI: DestReg = X86::RDI; break;
14612      case X86::BP: DestReg = X86::RBP; break;
14613      case X86::SP: DestReg = X86::RSP; break;
14614      }
14615      if (DestReg) {
14616        Res.first = DestReg;
14617        Res.second = X86::GR64RegisterClass;
14618      }
14619    }
14620  } else if (Res.second == X86::FR32RegisterClass ||
14621             Res.second == X86::FR64RegisterClass ||
14622             Res.second == X86::VR128RegisterClass) {
14623    // Handle references to XMM physical registers that got mapped into the
14624    // wrong class.  This can happen with constraints like {xmm0} where the
14625    // target independent register mapper will just pick the first match it can
14626    // find, ignoring the required type.
14627    if (VT == MVT::f32)
14628      Res.second = X86::FR32RegisterClass;
14629    else if (VT == MVT::f64)
14630      Res.second = X86::FR64RegisterClass;
14631    else if (X86::VR128RegisterClass->hasType(VT))
14632      Res.second = X86::VR128RegisterClass;
14633  }
14634
14635  return Res;
14636}
14637