X86ISelLowering.cpp revision 705f2431a086bbe662bca0035938e774378de3ec
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/MC/MCAsmInfo.h"
39#include "llvm/MC/MCContext.h"
40#include "llvm/MC/MCExpr.h"
41#include "llvm/MC/MCSymbol.h"
42#include "llvm/ADT/BitVector.h"
43#include "llvm/ADT/SmallSet.h"
44#include "llvm/ADT/Statistic.h"
45#include "llvm/ADT/StringExtras.h"
46#include "llvm/ADT/VectorExtras.h"
47#include "llvm/Support/CallSite.h"
48#include "llvm/Support/Debug.h"
49#include "llvm/Support/Dwarf.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/raw_ostream.h"
53#include "llvm/Target/TargetOptions.h"
54using namespace llvm;
55using namespace dwarf;
56
57STATISTIC(NumTailCalls, "Number of tail calls");
58
59// Forward declarations.
60static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                       SDValue V2);
62
63static SDValue Insert128BitVector(SDValue Result,
64                                  SDValue Vec,
65                                  SDValue Idx,
66                                  SelectionDAG &DAG,
67                                  DebugLoc dl);
68
69static SDValue Extract128BitVector(SDValue Vec,
70                                   SDValue Idx,
71                                   SelectionDAG &DAG,
72                                   DebugLoc dl);
73
74/// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
75/// sets things up to match to an AVX VEXTRACTF128 instruction or a
76/// simple subregister reference.  Idx is an index in the 128 bits we
77/// want.  It need not be aligned to a 128-bit bounday.  That makes
78/// lowering EXTRACT_VECTOR_ELT operations easier.
79static SDValue Extract128BitVector(SDValue Vec,
80                                   SDValue Idx,
81                                   SelectionDAG &DAG,
82                                   DebugLoc dl) {
83  EVT VT = Vec.getValueType();
84  assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85  EVT ElVT = VT.getVectorElementType();
86  int Factor = VT.getSizeInBits()/128;
87  EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88                                  VT.getVectorNumElements()/Factor);
89
90  // Extract from UNDEF is UNDEF.
91  if (Vec.getOpcode() == ISD::UNDEF)
92    return DAG.getNode(ISD::UNDEF, dl, ResultVT);
93
94  if (isa<ConstantSDNode>(Idx)) {
95    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
96
97    // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
98    // we can match to VEXTRACTF128.
99    unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
100
101    // This is the index of the first element of the 128-bit chunk
102    // we want.
103    unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
104                                 * ElemsPerChunk);
105
106    SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107    SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                 VecIdx);
109
110    return Result;
111  }
112
113  return SDValue();
114}
115
116/// Generate a DAG to put 128-bits into a vector > 128 bits.  This
117/// sets things up to match to an AVX VINSERTF128 instruction or a
118/// simple superregister reference.  Idx is an index in the 128 bits
119/// we want.  It need not be aligned to a 128-bit bounday.  That makes
120/// lowering INSERT_VECTOR_ELT operations easier.
121static SDValue Insert128BitVector(SDValue Result,
122                                  SDValue Vec,
123                                  SDValue Idx,
124                                  SelectionDAG &DAG,
125                                  DebugLoc dl) {
126  if (isa<ConstantSDNode>(Idx)) {
127    EVT VT = Vec.getValueType();
128    assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
129
130    EVT ElVT = VT.getVectorElementType();
131    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132    EVT ResultVT = Result.getValueType();
133
134    // Insert the relevant 128 bits.
135    unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
136
137    // This is the index of the first element of the 128-bit chunk
138    // we want.
139    unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
140                                 * ElemsPerChunk);
141
142    SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143    Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
144                         VecIdx);
145    return Result;
146  }
147
148  return SDValue();
149}
150
151static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153  bool is64Bit = Subtarget->is64Bit();
154
155  if (Subtarget->isTargetEnvMacho()) {
156    if (is64Bit)
157      return new X8664_MachoTargetObjectFile();
158    return new TargetLoweringObjectFileMachO();
159  }
160
161  if (Subtarget->isTargetELF())
162    return new TargetLoweringObjectFileELF();
163  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164    return new TargetLoweringObjectFileCOFF();
165  llvm_unreachable("unknown subtarget type");
166}
167
168X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169  : TargetLowering(TM, createTLOF(TM)) {
170  Subtarget = &TM.getSubtarget<X86Subtarget>();
171  X86ScalarSSEf64 = Subtarget->hasXMMInt();
172  X86ScalarSSEf32 = Subtarget->hasXMM();
173  X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
174
175  RegInfo = TM.getRegisterInfo();
176  TD = getTargetData();
177
178  // Set up the TargetLowering object.
179  static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
180
181  // X86 is weird, it always uses i8 for shift amounts and setcc results.
182  setBooleanContents(ZeroOrOneBooleanContent);
183  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
184  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
185
186  // For 64-bit since we have so many registers use the ILP scheduler, for
187  // 32-bit code use the register pressure specific scheduling.
188  if (Subtarget->is64Bit())
189    setSchedulingPreference(Sched::ILP);
190  else
191    setSchedulingPreference(Sched::RegPressure);
192  setStackPointerRegisterToSaveRestore(X86StackPtr);
193
194  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
195    // Setup Windows compiler runtime calls.
196    setLibcallName(RTLIB::SDIV_I64, "_alldiv");
197    setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
198    setLibcallName(RTLIB::SREM_I64, "_allrem");
199    setLibcallName(RTLIB::UREM_I64, "_aullrem");
200    setLibcallName(RTLIB::MUL_I64, "_allmul");
201    setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
202    setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
203    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205    setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206    setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207    setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
209    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
210  }
211
212  if (Subtarget->isTargetDarwin()) {
213    // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
214    setUseUnderscoreSetJmp(false);
215    setUseUnderscoreLongJmp(false);
216  } else if (Subtarget->isTargetMingw()) {
217    // MS runtime is weird: it exports _setjmp, but longjmp!
218    setUseUnderscoreSetJmp(true);
219    setUseUnderscoreLongJmp(false);
220  } else {
221    setUseUnderscoreSetJmp(true);
222    setUseUnderscoreLongJmp(true);
223  }
224
225  // Set up the register classes.
226  addRegisterClass(MVT::i8, X86::GR8RegisterClass);
227  addRegisterClass(MVT::i16, X86::GR16RegisterClass);
228  addRegisterClass(MVT::i32, X86::GR32RegisterClass);
229  if (Subtarget->is64Bit())
230    addRegisterClass(MVT::i64, X86::GR64RegisterClass);
231
232  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
233
234  // We don't accept any truncstore of integer registers.
235  setTruncStoreAction(MVT::i64, MVT::i32, Expand);
236  setTruncStoreAction(MVT::i64, MVT::i16, Expand);
237  setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
238  setTruncStoreAction(MVT::i32, MVT::i16, Expand);
239  setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
240  setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
241
242  // SETOEQ and SETUNE require checking two conditions.
243  setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
244  setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
245  setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
246  setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
247  setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
248  setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
249
250  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
251  // operation.
252  setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
253  setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
254  setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
255
256  if (Subtarget->is64Bit()) {
257    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
258    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
259  } else if (!UseSoftFloat) {
260    // We have an algorithm for SSE2->double, and we turn this into a
261    // 64-bit FILD followed by conditional FADD for other targets.
262    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
263    // We have an algorithm for SSE2, and we turn this into a 64-bit
264    // FILD for other targets.
265    setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
266  }
267
268  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
269  // this operation.
270  setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
271  setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
272
273  if (!UseSoftFloat) {
274    // SSE has no i16 to fp conversion, only i32
275    if (X86ScalarSSEf32) {
276      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
277      // f32 and f64 cases are Legal, f80 case is not
278      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279    } else {
280      setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
281      setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
282    }
283  } else {
284    setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
285    setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
286  }
287
288  // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
289  // are Legal, f80 is custom lowered.
290  setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
291  setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
292
293  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
294  // this operation.
295  setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
296  setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
297
298  if (X86ScalarSSEf32) {
299    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
300    // f32 and f64 cases are Legal, f80 case is not
301    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302  } else {
303    setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
304    setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
305  }
306
307  // Handle FP_TO_UINT by promoting the destination to a larger signed
308  // conversion.
309  setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
310  setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
311  setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
312
313  if (Subtarget->is64Bit()) {
314    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
315    setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
316  } else if (!UseSoftFloat) {
317    // Since AVX is a superset of SSE3, only check for SSE here.
318    if (Subtarget->hasSSE1() && !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  if (Subtarget->hasBMI()) {
382    setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
383  } else {
384    setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
385    setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
386    setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
387    if (Subtarget->is64Bit())
388      setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
389  }
390
391  if (Subtarget->hasLZCNT()) {
392    setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
393  } else {
394    setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
395    setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
396    setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
397    if (Subtarget->is64Bit())
398      setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
399  }
400
401  if (Subtarget->hasPOPCNT()) {
402    setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
403  } else {
404    setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
405    setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
406    setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
407    if (Subtarget->is64Bit())
408      setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
409  }
410
411  setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
412  setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
413
414  // These should be promoted to a larger select which is supported.
415  setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
416  // X86 wants to expand cmov itself.
417  setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
418  setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
419  setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
420  setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
421  setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
422  setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
423  setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
424  setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
425  setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
426  setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
427  setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
428  setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
429  if (Subtarget->is64Bit()) {
430    setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
431    setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
432  }
433  setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
434
435  // Darwin ABI issue.
436  setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
437  setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
438  setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
439  setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
440  if (Subtarget->is64Bit())
441    setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
442  setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
443  setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
444  if (Subtarget->is64Bit()) {
445    setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
446    setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
447    setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
448    setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
449    setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
450  }
451  // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
452  setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
453  setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
454  setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
455  if (Subtarget->is64Bit()) {
456    setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
457    setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
458    setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
459  }
460
461  if (Subtarget->hasXMM())
462    setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
463
464  setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
465  setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
466
467  // On X86 and X86-64, atomic operations are lowered to locked instructions.
468  // Locked instructions, in turn, have implicit fence semantics (all memory
469  // operations are flushed before issuing the locked instruction, and they
470  // are not buffered), so we can fold away the common pattern of
471  // fence-atomic-fence.
472  setShouldFoldAtomicFences(true);
473
474  // Expand certain atomics
475  for (unsigned i = 0, e = 4; i != e; ++i) {
476    MVT VT = IntVTs[i];
477    setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
478    setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
479    setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
480  }
481
482  if (!Subtarget->is64Bit()) {
483    setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
484    setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
485    setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
486    setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
487    setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
488    setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
489    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
490    setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
491  }
492
493  if (Subtarget->hasCmpxchg16b()) {
494    setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
495  }
496
497  // FIXME - use subtarget debug flags
498  if (!Subtarget->isTargetDarwin() &&
499      !Subtarget->isTargetELF() &&
500      !Subtarget->isTargetCygMing()) {
501    setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
502  }
503
504  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
505  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
506  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
507  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
508  if (Subtarget->is64Bit()) {
509    setExceptionPointerRegister(X86::RAX);
510    setExceptionSelectorRegister(X86::RDX);
511  } else {
512    setExceptionPointerRegister(X86::EAX);
513    setExceptionSelectorRegister(X86::EDX);
514  }
515  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
516  setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
517
518  setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
519  setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
520
521  setOperationAction(ISD::TRAP, MVT::Other, Legal);
522
523  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
524  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
525  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
526  if (Subtarget->is64Bit()) {
527    setOperationAction(ISD::VAARG           , MVT::Other, Custom);
528    setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
529  } else {
530    setOperationAction(ISD::VAARG           , MVT::Other, Expand);
531    setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
532  }
533
534  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
535  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
536
537  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
538    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
539                       MVT::i64 : MVT::i32, Custom);
540  else if (EnableSegmentedStacks)
541    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542                       MVT::i64 : MVT::i32, Custom);
543  else
544    setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
545                       MVT::i64 : MVT::i32, Expand);
546
547  if (!UseSoftFloat && X86ScalarSSEf64) {
548    // f32 and f64 use SSE.
549    // Set up the FP register classes.
550    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
551    addRegisterClass(MVT::f64, X86::FR64RegisterClass);
552
553    // Use ANDPD to simulate FABS.
554    setOperationAction(ISD::FABS , MVT::f64, Custom);
555    setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557    // Use XORP to simulate FNEG.
558    setOperationAction(ISD::FNEG , MVT::f64, Custom);
559    setOperationAction(ISD::FNEG , MVT::f32, Custom);
560
561    // Use ANDPD and ORPD to simulate FCOPYSIGN.
562    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
563    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
564
565    // Lower this to FGETSIGNx86 plus an AND.
566    setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
567    setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
568
569    // We don't support sin/cos/fmod
570    setOperationAction(ISD::FSIN , MVT::f64, Expand);
571    setOperationAction(ISD::FCOS , MVT::f64, Expand);
572    setOperationAction(ISD::FSIN , MVT::f32, Expand);
573    setOperationAction(ISD::FCOS , MVT::f32, Expand);
574
575    // Expand FP immediates into loads from the stack, except for the special
576    // cases we handle.
577    addLegalFPImmediate(APFloat(+0.0)); // xorpd
578    addLegalFPImmediate(APFloat(+0.0f)); // xorps
579  } else if (!UseSoftFloat && X86ScalarSSEf32) {
580    // Use SSE for f32, x87 for f64.
581    // Set up the FP register classes.
582    addRegisterClass(MVT::f32, X86::FR32RegisterClass);
583    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
584
585    // Use ANDPS to simulate FABS.
586    setOperationAction(ISD::FABS , MVT::f32, Custom);
587
588    // Use XORP to simulate FNEG.
589    setOperationAction(ISD::FNEG , MVT::f32, Custom);
590
591    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592
593    // Use ANDPS and ORPS to simulate FCOPYSIGN.
594    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
596
597    // We don't support sin/cos/fmod
598    setOperationAction(ISD::FSIN , MVT::f32, Expand);
599    setOperationAction(ISD::FCOS , MVT::f32, Expand);
600
601    // Special cases we handle for FP constants.
602    addLegalFPImmediate(APFloat(+0.0f)); // xorps
603    addLegalFPImmediate(APFloat(+0.0)); // FLD0
604    addLegalFPImmediate(APFloat(+1.0)); // FLD1
605    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
607
608    if (!UnsafeFPMath) {
609      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
610      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
611    }
612  } else if (!UseSoftFloat) {
613    // f32 and f64 in x87.
614    // Set up the FP register classes.
615    addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
616    addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
617
618    setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
619    setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
620    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
622
623    if (!UnsafeFPMath) {
624      setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
625      setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
626    }
627    addLegalFPImmediate(APFloat(+0.0)); // FLD0
628    addLegalFPImmediate(APFloat(+1.0)); // FLD1
629    addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
630    addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
631    addLegalFPImmediate(APFloat(+0.0f)); // FLD0
632    addLegalFPImmediate(APFloat(+1.0f)); // FLD1
633    addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
634    addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
635  }
636
637  // We don't support FMA.
638  setOperationAction(ISD::FMA, MVT::f64, Expand);
639  setOperationAction(ISD::FMA, MVT::f32, Expand);
640
641  // Long double always uses X87.
642  if (!UseSoftFloat) {
643    addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
644    setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
645    setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
646    {
647      APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
648      addLegalFPImmediate(TmpFlt);  // FLD0
649      TmpFlt.changeSign();
650      addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
651
652      bool ignored;
653      APFloat TmpFlt2(+1.0);
654      TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
655                      &ignored);
656      addLegalFPImmediate(TmpFlt2);  // FLD1
657      TmpFlt2.changeSign();
658      addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
659    }
660
661    if (!UnsafeFPMath) {
662      setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
663      setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
664    }
665
666    setOperationAction(ISD::FMA, MVT::f80, Expand);
667  }
668
669  // Always use a library call for pow.
670  setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
671  setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
672  setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
673
674  setOperationAction(ISD::FLOG, MVT::f80, Expand);
675  setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676  setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677  setOperationAction(ISD::FEXP, MVT::f80, Expand);
678  setOperationAction(ISD::FEXP2, MVT::f80, Expand);
679
680  // First set operation action for all vector types to either promote
681  // (for widening) or expand (for scalarization). Then we will selectively
682  // turn on ones that can be effectively codegen'd.
683  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
684       VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
685    setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
686    setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
687    setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
688    setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
689    setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
690    setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
691    setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
692    setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
693    setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
694    setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
695    setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
696    setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
697    setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
698    setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
699    setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
700    setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
701    setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
702    setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703    setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
704    setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
705    setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
706    setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
707    setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
708    setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
709    setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
710    setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
711    setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712    setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
713    setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
714    setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
715    setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
716    setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
717    setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
718    setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
719    setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
720    setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
721    setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
722    setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
723    setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
724    setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
725    setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
726    setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
727    setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
728    setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
729    setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
730    setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
731    setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
732    setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
733    setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
735    setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
736    setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
737    setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
738    setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739    setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
740    for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
741         InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
742      setTruncStoreAction((MVT::SimpleValueType)VT,
743                          (MVT::SimpleValueType)InnerVT, Expand);
744    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
745    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
747  }
748
749  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
750  // with -msoft-float, disable use of MMX as well.
751  if (!UseSoftFloat && Subtarget->hasMMX()) {
752    addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
753    // No operations on x86mmx supported, everything uses intrinsics.
754  }
755
756  // MMX-sized vectors (other than x86mmx) are expected to be expanded
757  // into smaller operations.
758  setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
759  setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
760  setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
761  setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
762  setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
763  setOperationAction(ISD::AND,                MVT::v4i16, Expand);
764  setOperationAction(ISD::AND,                MVT::v2i32, Expand);
765  setOperationAction(ISD::AND,                MVT::v1i64, Expand);
766  setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
767  setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
768  setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
769  setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
770  setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
771  setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
772  setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
773  setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
774  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
775  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
776  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
777  setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
778  setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
779  setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
780  setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
781  setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
782  setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
783  setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
784  setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
785  setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
786  setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
787
788  if (!UseSoftFloat && Subtarget->hasXMM()) {
789    addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
790
791    setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
792    setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
793    setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
794    setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
795    setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
796    setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
797    setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
798    setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
799    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
800    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
801    setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
802    setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
803  }
804
805  if (!UseSoftFloat && Subtarget->hasXMMInt()) {
806    addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
807
808    // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
809    // registers cannot be used even for integer operations.
810    addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
811    addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
812    addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
813    addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
814
815    setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
816    setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
817    setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
818    setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
819    setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
820    setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
821    setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
822    setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
823    setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
824    setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
825    setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
826    setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
827    setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
828    setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
829    setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
830    setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
831
832    setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
833    setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
834    setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
835    setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
836
837    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
838    setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
839    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
840    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
841    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
842
843    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
844    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
845    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
846    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
847    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
848
849    // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
851      EVT VT = (MVT::SimpleValueType)i;
852      // Do not attempt to custom lower non-power-of-2 vectors
853      if (!isPowerOf2_32(VT.getVectorNumElements()))
854        continue;
855      // Do not attempt to custom lower non-128-bit vectors
856      if (!VT.is128BitVector())
857        continue;
858      setOperationAction(ISD::BUILD_VECTOR,
859                         VT.getSimpleVT().SimpleTy, Custom);
860      setOperationAction(ISD::VECTOR_SHUFFLE,
861                         VT.getSimpleVT().SimpleTy, Custom);
862      setOperationAction(ISD::EXTRACT_VECTOR_ELT,
863                         VT.getSimpleVT().SimpleTy, Custom);
864    }
865
866    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
867    setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
868    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
869    setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
870    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
871    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
872
873    if (Subtarget->is64Bit()) {
874      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
875      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
876    }
877
878    // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
879    for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
880      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
881      EVT VT = SVT;
882
883      // Do not attempt to promote non-128-bit vectors
884      if (!VT.is128BitVector())
885        continue;
886
887      setOperationAction(ISD::AND,    SVT, Promote);
888      AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
889      setOperationAction(ISD::OR,     SVT, Promote);
890      AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
891      setOperationAction(ISD::XOR,    SVT, Promote);
892      AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
893      setOperationAction(ISD::LOAD,   SVT, Promote);
894      AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
895      setOperationAction(ISD::SELECT, SVT, Promote);
896      AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
897    }
898
899    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
900
901    // Custom lower v2i64 and v2f64 selects.
902    setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
903    setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
904    setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
905    setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
906
907    setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
908    setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
909  }
910
911  if (Subtarget->hasSSE41orAVX()) {
912    setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
913    setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
914    setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
915    setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
916    setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
917    setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
918    setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
919    setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
920    setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
921    setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
922
923    // FIXME: Do we need to handle scalar-to-vector here?
924    setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
925
926    setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
927    setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
928    setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
929    setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
930    setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
931
932    // i8 and i16 vectors are custom , because the source register and source
933    // source memory operand types are not the same width.  f32 vectors are
934    // custom since the immediate controlling the insert encodes additional
935    // information.
936    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
937    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
938    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
939    setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
940
941    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
942    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
943    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
944    setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
945
946    // FIXME: these should be Legal but thats only for the case where
947    // the index is constant.  For now custom expand to deal with that
948    if (Subtarget->is64Bit()) {
949      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
950      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
951    }
952  }
953
954  if (Subtarget->hasXMMInt()) {
955    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
956    setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
957
958    setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
959    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
960
961    setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
962    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
963
964    if (Subtarget->hasAVX2()) {
965      setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
966      setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
967
968      setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
969      setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
970
971      setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
972    } else {
973      setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
974      setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
975
976      setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
977      setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
978
979      setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
980    }
981  }
982
983  if (Subtarget->hasSSE42orAVX())
984    setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
985
986  if (!UseSoftFloat && Subtarget->hasAVX()) {
987    addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
988    addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
989    addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
990    addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
991    addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
992    addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
993
994    setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
995    setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
996    setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
997
998    setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
999    setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1000    setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1001    setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1002    setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1003    setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1004
1005    setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1006    setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1007    setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1008    setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1009    setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1010    setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1011
1012    setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1013    setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1014    setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1015
1016    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1017    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1018    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1019    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1020    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1021    setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1022
1023    setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1024    setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1025
1026    setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1027    setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1028
1029    setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1030    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1031
1032    setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1033    setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1034    setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1035    setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1036
1037    setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1038    setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1039    setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1040
1041    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1042    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1043    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1044    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1045
1046    if (Subtarget->hasAVX2()) {
1047      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1048      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1049      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1050      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1051
1052      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1053      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1054      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1055      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1056
1057      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1058      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1059      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1060      // Don't lower v32i8 because there is no 128-bit byte mul
1061
1062      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1063
1064      setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1065      setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1066
1067      setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1068      setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1069
1070      setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1071    } else {
1072      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1073      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1074      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1075      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1076
1077      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1078      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1079      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1080      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1081
1082      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1083      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1084      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1085      // Don't lower v32i8 because there is no 128-bit byte mul
1086
1087      setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1088      setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1089
1090      setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1091      setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1092
1093      setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1094    }
1095
1096    // Custom lower several nodes for 256-bit types.
1097    for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1098                  i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1099      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1100      EVT VT = SVT;
1101
1102      // Extract subvector is special because the value type
1103      // (result) is 128-bit but the source is 256-bit wide.
1104      if (VT.is128BitVector())
1105        setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1106
1107      // Do not attempt to custom lower other non-256-bit vectors
1108      if (!VT.is256BitVector())
1109        continue;
1110
1111      setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1112      setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1113      setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1114      setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1115      setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1116      setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1117    }
1118
1119    // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1120    for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1121      MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1122      EVT VT = SVT;
1123
1124      // Do not attempt to promote non-256-bit vectors
1125      if (!VT.is256BitVector())
1126        continue;
1127
1128      setOperationAction(ISD::AND,    SVT, Promote);
1129      AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1130      setOperationAction(ISD::OR,     SVT, Promote);
1131      AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1132      setOperationAction(ISD::XOR,    SVT, Promote);
1133      AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1134      setOperationAction(ISD::LOAD,   SVT, Promote);
1135      AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1136      setOperationAction(ISD::SELECT, SVT, Promote);
1137      AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1138    }
1139  }
1140
1141  // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1142  // of this type with custom code.
1143  for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1144         VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1145    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1146  }
1147
1148  // We want to custom lower some of our intrinsics.
1149  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1150
1151
1152  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1153  // handle type legalization for these operations here.
1154  //
1155  // FIXME: We really should do custom legalization for addition and
1156  // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1157  // than generic legalization for 64-bit multiplication-with-overflow, though.
1158  for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1159    // Add/Sub/Mul with overflow operations are custom lowered.
1160    MVT VT = IntVTs[i];
1161    setOperationAction(ISD::SADDO, VT, Custom);
1162    setOperationAction(ISD::UADDO, VT, Custom);
1163    setOperationAction(ISD::SSUBO, VT, Custom);
1164    setOperationAction(ISD::USUBO, VT, Custom);
1165    setOperationAction(ISD::SMULO, VT, Custom);
1166    setOperationAction(ISD::UMULO, VT, Custom);
1167  }
1168
1169  // There are no 8-bit 3-address imul/mul instructions
1170  setOperationAction(ISD::SMULO, MVT::i8, Expand);
1171  setOperationAction(ISD::UMULO, MVT::i8, Expand);
1172
1173  if (!Subtarget->is64Bit()) {
1174    // These libcalls are not available in 32-bit.
1175    setLibcallName(RTLIB::SHL_I128, 0);
1176    setLibcallName(RTLIB::SRL_I128, 0);
1177    setLibcallName(RTLIB::SRA_I128, 0);
1178  }
1179
1180  // We have target-specific dag combine patterns for the following nodes:
1181  setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1182  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1183  setTargetDAGCombine(ISD::BUILD_VECTOR);
1184  setTargetDAGCombine(ISD::VSELECT);
1185  setTargetDAGCombine(ISD::SELECT);
1186  setTargetDAGCombine(ISD::SHL);
1187  setTargetDAGCombine(ISD::SRA);
1188  setTargetDAGCombine(ISD::SRL);
1189  setTargetDAGCombine(ISD::OR);
1190  setTargetDAGCombine(ISD::AND);
1191  setTargetDAGCombine(ISD::ADD);
1192  setTargetDAGCombine(ISD::FADD);
1193  setTargetDAGCombine(ISD::FSUB);
1194  setTargetDAGCombine(ISD::SUB);
1195  setTargetDAGCombine(ISD::LOAD);
1196  setTargetDAGCombine(ISD::STORE);
1197  setTargetDAGCombine(ISD::ZERO_EXTEND);
1198  setTargetDAGCombine(ISD::SINT_TO_FP);
1199  if (Subtarget->is64Bit())
1200    setTargetDAGCombine(ISD::MUL);
1201  if (Subtarget->hasBMI())
1202    setTargetDAGCombine(ISD::XOR);
1203
1204  computeRegisterProperties();
1205
1206  // On Darwin, -Os means optimize for size without hurting performance,
1207  // do not reduce the limit.
1208  maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1209  maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1210  maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1211  maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1212  maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1213  maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1214  setPrefLoopAlignment(16);
1215  benefitFromCodePlacementOpt = true;
1216
1217  setPrefFunctionAlignment(4);
1218}
1219
1220
1221EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1222  if (!VT.isVector()) return MVT::i8;
1223  return VT.changeVectorElementTypeToInteger();
1224}
1225
1226
1227/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1228/// the desired ByVal argument alignment.
1229static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1230  if (MaxAlign == 16)
1231    return;
1232  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1233    if (VTy->getBitWidth() == 128)
1234      MaxAlign = 16;
1235  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1236    unsigned EltAlign = 0;
1237    getMaxByValAlign(ATy->getElementType(), EltAlign);
1238    if (EltAlign > MaxAlign)
1239      MaxAlign = EltAlign;
1240  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1241    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1242      unsigned EltAlign = 0;
1243      getMaxByValAlign(STy->getElementType(i), EltAlign);
1244      if (EltAlign > MaxAlign)
1245        MaxAlign = EltAlign;
1246      if (MaxAlign == 16)
1247        break;
1248    }
1249  }
1250  return;
1251}
1252
1253/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1254/// function arguments in the caller parameter area. For X86, aggregates
1255/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1256/// are at 4-byte boundaries.
1257unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1258  if (Subtarget->is64Bit()) {
1259    // Max of 8 and alignment of type.
1260    unsigned TyAlign = TD->getABITypeAlignment(Ty);
1261    if (TyAlign > 8)
1262      return TyAlign;
1263    return 8;
1264  }
1265
1266  unsigned Align = 4;
1267  if (Subtarget->hasXMM())
1268    getMaxByValAlign(Ty, Align);
1269  return Align;
1270}
1271
1272/// getOptimalMemOpType - Returns the target specific optimal type for load
1273/// and store operations as a result of memset, memcpy, and memmove
1274/// lowering. If DstAlign is zero that means it's safe to destination
1275/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1276/// means there isn't a need to check it against alignment requirement,
1277/// probably because the source does not need to be loaded. If
1278/// 'IsZeroVal' is true, that means it's safe to return a
1279/// non-scalar-integer type, e.g. empty string source, constant, or loaded
1280/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1281/// constant so it does not need to be loaded.
1282/// It returns EVT::Other if the type should be determined using generic
1283/// target-independent logic.
1284EVT
1285X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1286                                       unsigned DstAlign, unsigned SrcAlign,
1287                                       bool IsZeroVal,
1288                                       bool MemcpyStrSrc,
1289                                       MachineFunction &MF) const {
1290  // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1291  // linux.  This is because the stack realignment code can't handle certain
1292  // cases like PR2962.  This should be removed when PR2962 is fixed.
1293  const Function *F = MF.getFunction();
1294  if (IsZeroVal &&
1295      !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1296    if (Size >= 16 &&
1297        (Subtarget->isUnalignedMemAccessFast() ||
1298         ((DstAlign == 0 || DstAlign >= 16) &&
1299          (SrcAlign == 0 || SrcAlign >= 16))) &&
1300        Subtarget->getStackAlignment() >= 16) {
1301      if (Subtarget->hasAVX() &&
1302          Subtarget->getStackAlignment() >= 32)
1303        return MVT::v8f32;
1304      if (Subtarget->hasXMMInt())
1305        return MVT::v4i32;
1306      if (Subtarget->hasXMM())
1307        return MVT::v4f32;
1308    } else if (!MemcpyStrSrc && Size >= 8 &&
1309               !Subtarget->is64Bit() &&
1310               Subtarget->getStackAlignment() >= 8 &&
1311               Subtarget->hasXMMInt()) {
1312      // Do not use f64 to lower memcpy if source is string constant. It's
1313      // better to use i32 to avoid the loads.
1314      return MVT::f64;
1315    }
1316  }
1317  if (Subtarget->is64Bit() && Size >= 8)
1318    return MVT::i64;
1319  return MVT::i32;
1320}
1321
1322/// getJumpTableEncoding - Return the entry encoding for a jump table in the
1323/// current function.  The returned value is a member of the
1324/// MachineJumpTableInfo::JTEntryKind enum.
1325unsigned X86TargetLowering::getJumpTableEncoding() const {
1326  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1327  // symbol.
1328  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1329      Subtarget->isPICStyleGOT())
1330    return MachineJumpTableInfo::EK_Custom32;
1331
1332  // Otherwise, use the normal jump table encoding heuristics.
1333  return TargetLowering::getJumpTableEncoding();
1334}
1335
1336const MCExpr *
1337X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1338                                             const MachineBasicBlock *MBB,
1339                                             unsigned uid,MCContext &Ctx) const{
1340  assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1341         Subtarget->isPICStyleGOT());
1342  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1343  // entries.
1344  return MCSymbolRefExpr::Create(MBB->getSymbol(),
1345                                 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1346}
1347
1348/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1349/// jumptable.
1350SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1351                                                    SelectionDAG &DAG) const {
1352  if (!Subtarget->is64Bit())
1353    // This doesn't have DebugLoc associated with it, but is not really the
1354    // same as a Register.
1355    return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1356  return Table;
1357}
1358
1359/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1360/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1361/// MCExpr.
1362const MCExpr *X86TargetLowering::
1363getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1364                             MCContext &Ctx) const {
1365  // X86-64 uses RIP relative addressing based on the jump table label.
1366  if (Subtarget->isPICStyleRIPRel())
1367    return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1368
1369  // Otherwise, the reference is relative to the PIC base.
1370  return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1371}
1372
1373// FIXME: Why this routine is here? Move to RegInfo!
1374std::pair<const TargetRegisterClass*, uint8_t>
1375X86TargetLowering::findRepresentativeClass(EVT VT) const{
1376  const TargetRegisterClass *RRC = 0;
1377  uint8_t Cost = 1;
1378  switch (VT.getSimpleVT().SimpleTy) {
1379  default:
1380    return TargetLowering::findRepresentativeClass(VT);
1381  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1382    RRC = (Subtarget->is64Bit()
1383           ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1384    break;
1385  case MVT::x86mmx:
1386    RRC = X86::VR64RegisterClass;
1387    break;
1388  case MVT::f32: case MVT::f64:
1389  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1390  case MVT::v4f32: case MVT::v2f64:
1391  case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1392  case MVT::v4f64:
1393    RRC = X86::VR128RegisterClass;
1394    break;
1395  }
1396  return std::make_pair(RRC, Cost);
1397}
1398
1399bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1400                                               unsigned &Offset) const {
1401  if (!Subtarget->isTargetLinux())
1402    return false;
1403
1404  if (Subtarget->is64Bit()) {
1405    // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1406    Offset = 0x28;
1407    if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1408      AddressSpace = 256;
1409    else
1410      AddressSpace = 257;
1411  } else {
1412    // %gs:0x14 on i386
1413    Offset = 0x14;
1414    AddressSpace = 256;
1415  }
1416  return true;
1417}
1418
1419
1420//===----------------------------------------------------------------------===//
1421//               Return Value Calling Convention Implementation
1422//===----------------------------------------------------------------------===//
1423
1424#include "X86GenCallingConv.inc"
1425
1426bool
1427X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1428				  MachineFunction &MF, bool isVarArg,
1429                        const SmallVectorImpl<ISD::OutputArg> &Outs,
1430                        LLVMContext &Context) const {
1431  SmallVector<CCValAssign, 16> RVLocs;
1432  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1433                 RVLocs, Context);
1434  return CCInfo.CheckReturn(Outs, RetCC_X86);
1435}
1436
1437SDValue
1438X86TargetLowering::LowerReturn(SDValue Chain,
1439                               CallingConv::ID CallConv, bool isVarArg,
1440                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1441                               const SmallVectorImpl<SDValue> &OutVals,
1442                               DebugLoc dl, SelectionDAG &DAG) const {
1443  MachineFunction &MF = DAG.getMachineFunction();
1444  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1445
1446  SmallVector<CCValAssign, 16> RVLocs;
1447  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1448                 RVLocs, *DAG.getContext());
1449  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1450
1451  // Add the regs to the liveout set for the function.
1452  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1453  for (unsigned i = 0; i != RVLocs.size(); ++i)
1454    if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1455      MRI.addLiveOut(RVLocs[i].getLocReg());
1456
1457  SDValue Flag;
1458
1459  SmallVector<SDValue, 6> RetOps;
1460  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1461  // Operand #1 = Bytes To Pop
1462  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1463                   MVT::i16));
1464
1465  // Copy the result values into the output registers.
1466  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1467    CCValAssign &VA = RVLocs[i];
1468    assert(VA.isRegLoc() && "Can only return in registers!");
1469    SDValue ValToCopy = OutVals[i];
1470    EVT ValVT = ValToCopy.getValueType();
1471
1472    // If this is x86-64, and we disabled SSE, we can't return FP values,
1473    // or SSE or MMX vectors.
1474    if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1475         VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1476          (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1477      report_fatal_error("SSE register return with SSE disabled");
1478    }
1479    // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1480    // llvm-gcc has never done it right and no one has noticed, so this
1481    // should be OK for now.
1482    if (ValVT == MVT::f64 &&
1483        (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1484      report_fatal_error("SSE2 register return with SSE2 disabled");
1485
1486    // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1487    // the RET instruction and handled by the FP Stackifier.
1488    if (VA.getLocReg() == X86::ST0 ||
1489        VA.getLocReg() == X86::ST1) {
1490      // If this is a copy from an xmm register to ST(0), use an FPExtend to
1491      // change the value to the FP stack register class.
1492      if (isScalarFPTypeInSSEReg(VA.getValVT()))
1493        ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1494      RetOps.push_back(ValToCopy);
1495      // Don't emit a copytoreg.
1496      continue;
1497    }
1498
1499    // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1500    // which is returned in RAX / RDX.
1501    if (Subtarget->is64Bit()) {
1502      if (ValVT == MVT::x86mmx) {
1503        if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1504          ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1505          ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1506                                  ValToCopy);
1507          // If we don't have SSE2 available, convert to v4f32 so the generated
1508          // register is legal.
1509          if (!Subtarget->hasXMMInt())
1510            ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1511        }
1512      }
1513    }
1514
1515    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1516    Flag = Chain.getValue(1);
1517  }
1518
1519  // The x86-64 ABI for returning structs by value requires that we copy
1520  // the sret argument into %rax for the return. We saved the argument into
1521  // a virtual register in the entry block, so now we copy the value out
1522  // and into %rax.
1523  if (Subtarget->is64Bit() &&
1524      DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1525    MachineFunction &MF = DAG.getMachineFunction();
1526    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1527    unsigned Reg = FuncInfo->getSRetReturnReg();
1528    assert(Reg &&
1529           "SRetReturnReg should have been set in LowerFormalArguments().");
1530    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1531
1532    Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1533    Flag = Chain.getValue(1);
1534
1535    // RAX now acts like a return value.
1536    MRI.addLiveOut(X86::RAX);
1537  }
1538
1539  RetOps[0] = Chain;  // Update chain.
1540
1541  // Add the flag if we have it.
1542  if (Flag.getNode())
1543    RetOps.push_back(Flag);
1544
1545  return DAG.getNode(X86ISD::RET_FLAG, dl,
1546                     MVT::Other, &RetOps[0], RetOps.size());
1547}
1548
1549bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1550  if (N->getNumValues() != 1)
1551    return false;
1552  if (!N->hasNUsesOfValue(1, 0))
1553    return false;
1554
1555  SDNode *Copy = *N->use_begin();
1556  if (Copy->getOpcode() != ISD::CopyToReg &&
1557      Copy->getOpcode() != ISD::FP_EXTEND)
1558    return false;
1559
1560  bool HasRet = false;
1561  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1562       UI != UE; ++UI) {
1563    if (UI->getOpcode() != X86ISD::RET_FLAG)
1564      return false;
1565    HasRet = true;
1566  }
1567
1568  return HasRet;
1569}
1570
1571EVT
1572X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1573                                            ISD::NodeType ExtendKind) const {
1574  MVT ReturnMVT;
1575  // TODO: Is this also valid on 32-bit?
1576  if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1577    ReturnMVT = MVT::i8;
1578  else
1579    ReturnMVT = MVT::i32;
1580
1581  EVT MinVT = getRegisterType(Context, ReturnMVT);
1582  return VT.bitsLT(MinVT) ? MinVT : VT;
1583}
1584
1585/// LowerCallResult - Lower the result values of a call into the
1586/// appropriate copies out of appropriate physical registers.
1587///
1588SDValue
1589X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1590                                   CallingConv::ID CallConv, bool isVarArg,
1591                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1592                                   DebugLoc dl, SelectionDAG &DAG,
1593                                   SmallVectorImpl<SDValue> &InVals) const {
1594
1595  // Assign locations to each value returned by this call.
1596  SmallVector<CCValAssign, 16> RVLocs;
1597  bool Is64Bit = Subtarget->is64Bit();
1598  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1599		 getTargetMachine(), RVLocs, *DAG.getContext());
1600  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1601
1602  // Copy all of the result registers out of their specified physreg.
1603  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604    CCValAssign &VA = RVLocs[i];
1605    EVT CopyVT = VA.getValVT();
1606
1607    // If this is x86-64, and we disabled SSE, we can't return FP values
1608    if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1609        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1610      report_fatal_error("SSE register return with SSE disabled");
1611    }
1612
1613    SDValue Val;
1614
1615    // If this is a call to a function that returns an fp value on the floating
1616    // point stack, we must guarantee the the value is popped from the stack, so
1617    // a CopyFromReg is not good enough - the copy instruction may be eliminated
1618    // if the return value is not used. We use the FpPOP_RETVAL instruction
1619    // instead.
1620    if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1621      // If we prefer to use the value in xmm registers, copy it out as f80 and
1622      // use a truncate to move it from fp stack reg to xmm reg.
1623      if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1624      SDValue Ops[] = { Chain, InFlag };
1625      Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1626                                         MVT::Other, MVT::Glue, Ops, 2), 1);
1627      Val = Chain.getValue(0);
1628
1629      // Round the f80 to the right size, which also moves it to the appropriate
1630      // xmm register.
1631      if (CopyVT != VA.getValVT())
1632        Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1633                          // This truncation won't change the value.
1634                          DAG.getIntPtrConstant(1));
1635    } else {
1636      Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1637                                 CopyVT, InFlag).getValue(1);
1638      Val = Chain.getValue(0);
1639    }
1640    InFlag = Chain.getValue(2);
1641    InVals.push_back(Val);
1642  }
1643
1644  return Chain;
1645}
1646
1647
1648//===----------------------------------------------------------------------===//
1649//                C & StdCall & Fast Calling Convention implementation
1650//===----------------------------------------------------------------------===//
1651//  StdCall calling convention seems to be standard for many Windows' API
1652//  routines and around. It differs from C calling convention just a little:
1653//  callee should clean up the stack, not caller. Symbols should be also
1654//  decorated in some fancy way :) It doesn't support any vector arguments.
1655//  For info on fast calling convention see Fast Calling Convention (tail call)
1656//  implementation LowerX86_32FastCCCallTo.
1657
1658/// CallIsStructReturn - Determines whether a call uses struct return
1659/// semantics.
1660static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1661  if (Outs.empty())
1662    return false;
1663
1664  return Outs[0].Flags.isSRet();
1665}
1666
1667/// ArgsAreStructReturn - Determines whether a function uses struct
1668/// return semantics.
1669static bool
1670ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1671  if (Ins.empty())
1672    return false;
1673
1674  return Ins[0].Flags.isSRet();
1675}
1676
1677/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1678/// by "Src" to address "Dst" with size and alignment information specified by
1679/// the specific parameter attribute. The copy will be passed as a byval
1680/// function parameter.
1681static SDValue
1682CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1683                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1684                          DebugLoc dl) {
1685  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1686
1687  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1688                       /*isVolatile*/false, /*AlwaysInline=*/true,
1689                       MachinePointerInfo(), MachinePointerInfo());
1690}
1691
1692/// IsTailCallConvention - Return true if the calling convention is one that
1693/// supports tail call optimization.
1694static bool IsTailCallConvention(CallingConv::ID CC) {
1695  return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1696}
1697
1698bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1699  if (!CI->isTailCall())
1700    return false;
1701
1702  CallSite CS(CI);
1703  CallingConv::ID CalleeCC = CS.getCallingConv();
1704  if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1705    return false;
1706
1707  return true;
1708}
1709
1710/// FuncIsMadeTailCallSafe - Return true if the function is being made into
1711/// a tailcall target by changing its ABI.
1712static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1713  return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1714}
1715
1716SDValue
1717X86TargetLowering::LowerMemArgument(SDValue Chain,
1718                                    CallingConv::ID CallConv,
1719                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1720                                    DebugLoc dl, SelectionDAG &DAG,
1721                                    const CCValAssign &VA,
1722                                    MachineFrameInfo *MFI,
1723                                    unsigned i) const {
1724  // Create the nodes corresponding to a load from this parameter slot.
1725  ISD::ArgFlagsTy Flags = Ins[i].Flags;
1726  bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1727  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1728  EVT ValVT;
1729
1730  // If value is passed by pointer we have address passed instead of the value
1731  // itself.
1732  if (VA.getLocInfo() == CCValAssign::Indirect)
1733    ValVT = VA.getLocVT();
1734  else
1735    ValVT = VA.getValVT();
1736
1737  // FIXME: For now, all byval parameter objects are marked mutable. This can be
1738  // changed with more analysis.
1739  // In case of tail call optimization mark all arguments mutable. Since they
1740  // could be overwritten by lowering of arguments in case of a tail call.
1741  if (Flags.isByVal()) {
1742    unsigned Bytes = Flags.getByValSize();
1743    if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1744    int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1745    return DAG.getFrameIndex(FI, getPointerTy());
1746  } else {
1747    int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1748                                    VA.getLocMemOffset(), isImmutable);
1749    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1750    return DAG.getLoad(ValVT, dl, Chain, FIN,
1751                       MachinePointerInfo::getFixedStack(FI),
1752                       false, false, false, 0);
1753  }
1754}
1755
1756SDValue
1757X86TargetLowering::LowerFormalArguments(SDValue Chain,
1758                                        CallingConv::ID CallConv,
1759                                        bool isVarArg,
1760                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1761                                        DebugLoc dl,
1762                                        SelectionDAG &DAG,
1763                                        SmallVectorImpl<SDValue> &InVals)
1764                                          const {
1765  MachineFunction &MF = DAG.getMachineFunction();
1766  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1767
1768  const Function* Fn = MF.getFunction();
1769  if (Fn->hasExternalLinkage() &&
1770      Subtarget->isTargetCygMing() &&
1771      Fn->getName() == "main")
1772    FuncInfo->setForceFramePointer(true);
1773
1774  MachineFrameInfo *MFI = MF.getFrameInfo();
1775  bool Is64Bit = Subtarget->is64Bit();
1776  bool IsWin64 = Subtarget->isTargetWin64();
1777
1778  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1779         "Var args not supported with calling convention fastcc or ghc");
1780
1781  // Assign locations to all of the incoming arguments.
1782  SmallVector<CCValAssign, 16> ArgLocs;
1783  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1784                 ArgLocs, *DAG.getContext());
1785
1786  // Allocate shadow area for Win64
1787  if (IsWin64) {
1788    CCInfo.AllocateStack(32, 8);
1789  }
1790
1791  CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1792
1793  unsigned LastVal = ~0U;
1794  SDValue ArgValue;
1795  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1796    CCValAssign &VA = ArgLocs[i];
1797    // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1798    // places.
1799    assert(VA.getValNo() != LastVal &&
1800           "Don't support value assigned to multiple locs yet");
1801    (void)LastVal;
1802    LastVal = VA.getValNo();
1803
1804    if (VA.isRegLoc()) {
1805      EVT RegVT = VA.getLocVT();
1806      TargetRegisterClass *RC = NULL;
1807      if (RegVT == MVT::i32)
1808        RC = X86::GR32RegisterClass;
1809      else if (Is64Bit && RegVT == MVT::i64)
1810        RC = X86::GR64RegisterClass;
1811      else if (RegVT == MVT::f32)
1812        RC = X86::FR32RegisterClass;
1813      else if (RegVT == MVT::f64)
1814        RC = X86::FR64RegisterClass;
1815      else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1816        RC = X86::VR256RegisterClass;
1817      else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1818        RC = X86::VR128RegisterClass;
1819      else if (RegVT == MVT::x86mmx)
1820        RC = X86::VR64RegisterClass;
1821      else
1822        llvm_unreachable("Unknown argument type!");
1823
1824      unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1825      ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1826
1827      // If this is an 8 or 16-bit value, it is really passed promoted to 32
1828      // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1829      // right size.
1830      if (VA.getLocInfo() == CCValAssign::SExt)
1831        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1832                               DAG.getValueType(VA.getValVT()));
1833      else if (VA.getLocInfo() == CCValAssign::ZExt)
1834        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1835                               DAG.getValueType(VA.getValVT()));
1836      else if (VA.getLocInfo() == CCValAssign::BCvt)
1837        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1838
1839      if (VA.isExtInLoc()) {
1840        // Handle MMX values passed in XMM regs.
1841        if (RegVT.isVector()) {
1842          ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1843                                 ArgValue);
1844        } else
1845          ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1846      }
1847    } else {
1848      assert(VA.isMemLoc());
1849      ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1850    }
1851
1852    // If value is passed via pointer - do a load.
1853    if (VA.getLocInfo() == CCValAssign::Indirect)
1854      ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1855                             MachinePointerInfo(), false, false, false, 0);
1856
1857    InVals.push_back(ArgValue);
1858  }
1859
1860  // The x86-64 ABI for returning structs by value requires that we copy
1861  // the sret argument into %rax for the return. Save the argument into
1862  // a virtual register so that we can access it from the return points.
1863  if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1864    X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865    unsigned Reg = FuncInfo->getSRetReturnReg();
1866    if (!Reg) {
1867      Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1868      FuncInfo->setSRetReturnReg(Reg);
1869    }
1870    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1871    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1872  }
1873
1874  unsigned StackSize = CCInfo.getNextStackOffset();
1875  // Align stack specially for tail calls.
1876  if (FuncIsMadeTailCallSafe(CallConv))
1877    StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1878
1879  // If the function takes variable number of arguments, make a frame index for
1880  // the start of the first vararg value... for expansion of llvm.va_start.
1881  if (isVarArg) {
1882    if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1883                    CallConv != CallingConv::X86_ThisCall)) {
1884      FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1885    }
1886    if (Is64Bit) {
1887      unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1888
1889      // FIXME: We should really autogenerate these arrays
1890      static const unsigned GPR64ArgRegsWin64[] = {
1891        X86::RCX, X86::RDX, X86::R8,  X86::R9
1892      };
1893      static const unsigned GPR64ArgRegs64Bit[] = {
1894        X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1895      };
1896      static const unsigned XMMArgRegs64Bit[] = {
1897        X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1898        X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1899      };
1900      const unsigned *GPR64ArgRegs;
1901      unsigned NumXMMRegs = 0;
1902
1903      if (IsWin64) {
1904        // The XMM registers which might contain var arg parameters are shadowed
1905        // in their paired GPR.  So we only need to save the GPR to their home
1906        // slots.
1907        TotalNumIntRegs = 4;
1908        GPR64ArgRegs = GPR64ArgRegsWin64;
1909      } else {
1910        TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1911        GPR64ArgRegs = GPR64ArgRegs64Bit;
1912
1913        NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1914      }
1915      unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1916                                                       TotalNumIntRegs);
1917
1918      bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1919      assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1920             "SSE register cannot be used when SSE is disabled!");
1921      assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1922             "SSE register cannot be used when SSE is disabled!");
1923      if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1924        // Kernel mode asks for SSE to be disabled, so don't push them
1925        // on the stack.
1926        TotalNumXMMRegs = 0;
1927
1928      if (IsWin64) {
1929        const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1930        // Get to the caller-allocated home save location.  Add 8 to account
1931        // for the return address.
1932        int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1933        FuncInfo->setRegSaveFrameIndex(
1934          MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1935        // Fixup to set vararg frame on shadow area (4 x i64).
1936        if (NumIntRegs < 4)
1937          FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1938      } else {
1939        // For X86-64, if there are vararg parameters that are passed via
1940        // registers, then we must store them to their spots on the stack so they
1941        // may be loaded by deferencing the result of va_next.
1942        FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1943        FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1944        FuncInfo->setRegSaveFrameIndex(
1945          MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1946                               false));
1947      }
1948
1949      // Store the integer parameter registers.
1950      SmallVector<SDValue, 8> MemOps;
1951      SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1952                                        getPointerTy());
1953      unsigned Offset = FuncInfo->getVarArgsGPOffset();
1954      for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1955        SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1956                                  DAG.getIntPtrConstant(Offset));
1957        unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1958                                     X86::GR64RegisterClass);
1959        SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1960        SDValue Store =
1961          DAG.getStore(Val.getValue(1), dl, Val, FIN,
1962                       MachinePointerInfo::getFixedStack(
1963                         FuncInfo->getRegSaveFrameIndex(), Offset),
1964                       false, false, 0);
1965        MemOps.push_back(Store);
1966        Offset += 8;
1967      }
1968
1969      if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1970        // Now store the XMM (fp + vector) parameter registers.
1971        SmallVector<SDValue, 11> SaveXMMOps;
1972        SaveXMMOps.push_back(Chain);
1973
1974        unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1975        SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1976        SaveXMMOps.push_back(ALVal);
1977
1978        SaveXMMOps.push_back(DAG.getIntPtrConstant(
1979                               FuncInfo->getRegSaveFrameIndex()));
1980        SaveXMMOps.push_back(DAG.getIntPtrConstant(
1981                               FuncInfo->getVarArgsFPOffset()));
1982
1983        for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1984          unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1985                                       X86::VR128RegisterClass);
1986          SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1987          SaveXMMOps.push_back(Val);
1988        }
1989        MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1990                                     MVT::Other,
1991                                     &SaveXMMOps[0], SaveXMMOps.size()));
1992      }
1993
1994      if (!MemOps.empty())
1995        Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1996                            &MemOps[0], MemOps.size());
1997    }
1998  }
1999
2000  // Some CCs need callee pop.
2001  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
2002    FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2003  } else {
2004    FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2005    // If this is an sret function, the return should pop the hidden pointer.
2006    if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2007      FuncInfo->setBytesToPopOnReturn(4);
2008  }
2009
2010  if (!Is64Bit) {
2011    // RegSaveFrameIndex is X86-64 only.
2012    FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2013    if (CallConv == CallingConv::X86_FastCall ||
2014        CallConv == CallingConv::X86_ThisCall)
2015      // fastcc functions can't have varargs.
2016      FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2017  }
2018
2019  FuncInfo->setArgumentStackSize(StackSize);
2020
2021  return Chain;
2022}
2023
2024SDValue
2025X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2026                                    SDValue StackPtr, SDValue Arg,
2027                                    DebugLoc dl, SelectionDAG &DAG,
2028                                    const CCValAssign &VA,
2029                                    ISD::ArgFlagsTy Flags) const {
2030  unsigned LocMemOffset = VA.getLocMemOffset();
2031  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2032  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2033  if (Flags.isByVal())
2034    return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2035
2036  return DAG.getStore(Chain, dl, Arg, PtrOff,
2037                      MachinePointerInfo::getStack(LocMemOffset),
2038                      false, false, 0);
2039}
2040
2041/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2042/// optimization is performed and it is required.
2043SDValue
2044X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2045                                           SDValue &OutRetAddr, SDValue Chain,
2046                                           bool IsTailCall, bool Is64Bit,
2047                                           int FPDiff, DebugLoc dl) const {
2048  // Adjust the Return address stack slot.
2049  EVT VT = getPointerTy();
2050  OutRetAddr = getReturnAddressFrameIndex(DAG);
2051
2052  // Load the "old" Return address.
2053  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2054                           false, false, false, 0);
2055  return SDValue(OutRetAddr.getNode(), 1);
2056}
2057
2058/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2059/// optimization is performed and it is required (FPDiff!=0).
2060static SDValue
2061EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2062                         SDValue Chain, SDValue RetAddrFrIdx,
2063                         bool Is64Bit, int FPDiff, DebugLoc dl) {
2064  // Store the return address to the appropriate stack slot.
2065  if (!FPDiff) return Chain;
2066  // Calculate the new stack slot for the return address.
2067  int SlotSize = Is64Bit ? 8 : 4;
2068  int NewReturnAddrFI =
2069    MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2070  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2071  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2072  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2073                       MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2074                       false, false, 0);
2075  return Chain;
2076}
2077
2078SDValue
2079X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2080                             CallingConv::ID CallConv, bool isVarArg,
2081                             bool &isTailCall,
2082                             const SmallVectorImpl<ISD::OutputArg> &Outs,
2083                             const SmallVectorImpl<SDValue> &OutVals,
2084                             const SmallVectorImpl<ISD::InputArg> &Ins,
2085                             DebugLoc dl, SelectionDAG &DAG,
2086                             SmallVectorImpl<SDValue> &InVals) const {
2087  MachineFunction &MF = DAG.getMachineFunction();
2088  bool Is64Bit        = Subtarget->is64Bit();
2089  bool IsWin64        = Subtarget->isTargetWin64();
2090  bool IsStructRet    = CallIsStructReturn(Outs);
2091  bool IsSibcall      = false;
2092
2093  if (isTailCall) {
2094    // Check if it's really possible to do a tail call.
2095    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2096                    isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2097                                                   Outs, OutVals, Ins, DAG);
2098
2099    // Sibcalls are automatically detected tailcalls which do not require
2100    // ABI changes.
2101    if (!GuaranteedTailCallOpt && isTailCall)
2102      IsSibcall = true;
2103
2104    if (isTailCall)
2105      ++NumTailCalls;
2106  }
2107
2108  assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2109         "Var args not supported with calling convention fastcc or ghc");
2110
2111  // Analyze operands of the call, assigning locations to each operand.
2112  SmallVector<CCValAssign, 16> ArgLocs;
2113  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2114                 ArgLocs, *DAG.getContext());
2115
2116  // Allocate shadow area for Win64
2117  if (IsWin64) {
2118    CCInfo.AllocateStack(32, 8);
2119  }
2120
2121  CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2122
2123  // Get a count of how many bytes are to be pushed on the stack.
2124  unsigned NumBytes = CCInfo.getNextStackOffset();
2125  if (IsSibcall)
2126    // This is a sibcall. The memory operands are available in caller's
2127    // own caller's stack.
2128    NumBytes = 0;
2129  else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2130    NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2131
2132  int FPDiff = 0;
2133  if (isTailCall && !IsSibcall) {
2134    // Lower arguments at fp - stackoffset + fpdiff.
2135    unsigned NumBytesCallerPushed =
2136      MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2137    FPDiff = NumBytesCallerPushed - NumBytes;
2138
2139    // Set the delta of movement of the returnaddr stackslot.
2140    // But only set if delta is greater than previous delta.
2141    if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2142      MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2143  }
2144
2145  if (!IsSibcall)
2146    Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2147
2148  SDValue RetAddrFrIdx;
2149  // Load return address for tail calls.
2150  if (isTailCall && FPDiff)
2151    Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2152                                    Is64Bit, FPDiff, dl);
2153
2154  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2155  SmallVector<SDValue, 8> MemOpChains;
2156  SDValue StackPtr;
2157
2158  // Walk the register/memloc assignments, inserting copies/loads.  In the case
2159  // of tail call optimization arguments are handle later.
2160  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2161    CCValAssign &VA = ArgLocs[i];
2162    EVT RegVT = VA.getLocVT();
2163    SDValue Arg = OutVals[i];
2164    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2165    bool isByVal = Flags.isByVal();
2166
2167    // Promote the value if needed.
2168    switch (VA.getLocInfo()) {
2169    default: llvm_unreachable("Unknown loc info!");
2170    case CCValAssign::Full: break;
2171    case CCValAssign::SExt:
2172      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2173      break;
2174    case CCValAssign::ZExt:
2175      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2176      break;
2177    case CCValAssign::AExt:
2178      if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2179        // Special case: passing MMX values in XMM registers.
2180        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2181        Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2182        Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2183      } else
2184        Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2185      break;
2186    case CCValAssign::BCvt:
2187      Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2188      break;
2189    case CCValAssign::Indirect: {
2190      // Store the argument.
2191      SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2192      int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2193      Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2194                           MachinePointerInfo::getFixedStack(FI),
2195                           false, false, 0);
2196      Arg = SpillSlot;
2197      break;
2198    }
2199    }
2200
2201    if (VA.isRegLoc()) {
2202      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2203      if (isVarArg && IsWin64) {
2204        // Win64 ABI requires argument XMM reg to be copied to the corresponding
2205        // shadow reg if callee is a varargs function.
2206        unsigned ShadowReg = 0;
2207        switch (VA.getLocReg()) {
2208        case X86::XMM0: ShadowReg = X86::RCX; break;
2209        case X86::XMM1: ShadowReg = X86::RDX; break;
2210        case X86::XMM2: ShadowReg = X86::R8; break;
2211        case X86::XMM3: ShadowReg = X86::R9; break;
2212        }
2213        if (ShadowReg)
2214          RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2215      }
2216    } else if (!IsSibcall && (!isTailCall || isByVal)) {
2217      assert(VA.isMemLoc());
2218      if (StackPtr.getNode() == 0)
2219        StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2220      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2221                                             dl, DAG, VA, Flags));
2222    }
2223  }
2224
2225  if (!MemOpChains.empty())
2226    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2227                        &MemOpChains[0], MemOpChains.size());
2228
2229  // Build a sequence of copy-to-reg nodes chained together with token chain
2230  // and flag operands which copy the outgoing args into registers.
2231  SDValue InFlag;
2232  // Tail call byval lowering might overwrite argument registers so in case of
2233  // tail call optimization the copies to registers are lowered later.
2234  if (!isTailCall)
2235    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2236      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2237                               RegsToPass[i].second, InFlag);
2238      InFlag = Chain.getValue(1);
2239    }
2240
2241  if (Subtarget->isPICStyleGOT()) {
2242    // ELF / PIC requires GOT in the EBX register before function calls via PLT
2243    // GOT pointer.
2244    if (!isTailCall) {
2245      Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2246                               DAG.getNode(X86ISD::GlobalBaseReg,
2247                                           DebugLoc(), getPointerTy()),
2248                               InFlag);
2249      InFlag = Chain.getValue(1);
2250    } else {
2251      // If we are tail calling and generating PIC/GOT style code load the
2252      // address of the callee into ECX. The value in ecx is used as target of
2253      // the tail jump. This is done to circumvent the ebx/callee-saved problem
2254      // for tail calls on PIC/GOT architectures. Normally we would just put the
2255      // address of GOT into ebx and then call target@PLT. But for tail calls
2256      // ebx would be restored (since ebx is callee saved) before jumping to the
2257      // target@PLT.
2258
2259      // Note: The actual moving to ECX is done further down.
2260      GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2261      if (G && !G->getGlobal()->hasHiddenVisibility() &&
2262          !G->getGlobal()->hasProtectedVisibility())
2263        Callee = LowerGlobalAddress(Callee, DAG);
2264      else if (isa<ExternalSymbolSDNode>(Callee))
2265        Callee = LowerExternalSymbol(Callee, DAG);
2266    }
2267  }
2268
2269  if (Is64Bit && isVarArg && !IsWin64) {
2270    // From AMD64 ABI document:
2271    // For calls that may call functions that use varargs or stdargs
2272    // (prototype-less calls or calls to functions containing ellipsis (...) in
2273    // the declaration) %al is used as hidden argument to specify the number
2274    // of SSE registers used. The contents of %al do not need to match exactly
2275    // the number of registers, but must be an ubound on the number of SSE
2276    // registers used and is in the range 0 - 8 inclusive.
2277
2278    // Count the number of XMM registers allocated.
2279    static const unsigned XMMArgRegs[] = {
2280      X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2281      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2282    };
2283    unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2284    assert((Subtarget->hasXMM() || !NumXMMRegs)
2285           && "SSE registers cannot be used when SSE is disabled");
2286
2287    Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2288                             DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2289    InFlag = Chain.getValue(1);
2290  }
2291
2292
2293  // For tail calls lower the arguments to the 'real' stack slot.
2294  if (isTailCall) {
2295    // Force all the incoming stack arguments to be loaded from the stack
2296    // before any new outgoing arguments are stored to the stack, because the
2297    // outgoing stack slots may alias the incoming argument stack slots, and
2298    // the alias isn't otherwise explicit. This is slightly more conservative
2299    // than necessary, because it means that each store effectively depends
2300    // on every argument instead of just those arguments it would clobber.
2301    SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2302
2303    SmallVector<SDValue, 8> MemOpChains2;
2304    SDValue FIN;
2305    int FI = 0;
2306    // Do not flag preceding copytoreg stuff together with the following stuff.
2307    InFlag = SDValue();
2308    if (GuaranteedTailCallOpt) {
2309      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310        CCValAssign &VA = ArgLocs[i];
2311        if (VA.isRegLoc())
2312          continue;
2313        assert(VA.isMemLoc());
2314        SDValue Arg = OutVals[i];
2315        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2316        // Create frame index.
2317        int32_t Offset = VA.getLocMemOffset()+FPDiff;
2318        uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2319        FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2320        FIN = DAG.getFrameIndex(FI, getPointerTy());
2321
2322        if (Flags.isByVal()) {
2323          // Copy relative to framepointer.
2324          SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2325          if (StackPtr.getNode() == 0)
2326            StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2327                                          getPointerTy());
2328          Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2329
2330          MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2331                                                           ArgChain,
2332                                                           Flags, DAG, dl));
2333        } else {
2334          // Store relative to framepointer.
2335          MemOpChains2.push_back(
2336            DAG.getStore(ArgChain, dl, Arg, FIN,
2337                         MachinePointerInfo::getFixedStack(FI),
2338                         false, false, 0));
2339        }
2340      }
2341    }
2342
2343    if (!MemOpChains2.empty())
2344      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2345                          &MemOpChains2[0], MemOpChains2.size());
2346
2347    // Copy arguments to their registers.
2348    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2349      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2350                               RegsToPass[i].second, InFlag);
2351      InFlag = Chain.getValue(1);
2352    }
2353    InFlag =SDValue();
2354
2355    // Store the return address to the appropriate stack slot.
2356    Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2357                                     FPDiff, dl);
2358  }
2359
2360  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2361    assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2362    // In the 64-bit large code model, we have to make all calls
2363    // through a register, since the call instruction's 32-bit
2364    // pc-relative offset may not be large enough to hold the whole
2365    // address.
2366  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2367    // If the callee is a GlobalAddress node (quite common, every direct call
2368    // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2369    // it.
2370
2371    // We should use extra load for direct calls to dllimported functions in
2372    // non-JIT mode.
2373    const GlobalValue *GV = G->getGlobal();
2374    if (!GV->hasDLLImportLinkage()) {
2375      unsigned char OpFlags = 0;
2376      bool ExtraLoad = false;
2377      unsigned WrapperKind = ISD::DELETED_NODE;
2378
2379      // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2380      // external symbols most go through the PLT in PIC mode.  If the symbol
2381      // has hidden or protected visibility, or if it is static or local, then
2382      // we don't need to use the PLT - we can directly call it.
2383      if (Subtarget->isTargetELF() &&
2384          getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2385          GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2386        OpFlags = X86II::MO_PLT;
2387      } else if (Subtarget->isPICStyleStubAny() &&
2388                 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2389                 (!Subtarget->getTargetTriple().isMacOSX() ||
2390                  Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2391        // PC-relative references to external symbols should go through $stub,
2392        // unless we're building with the leopard linker or later, which
2393        // automatically synthesizes these stubs.
2394        OpFlags = X86II::MO_DARWIN_STUB;
2395      } else if (Subtarget->isPICStyleRIPRel() &&
2396                 isa<Function>(GV) &&
2397                 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2398        // If the function is marked as non-lazy, generate an indirect call
2399        // which loads from the GOT directly. This avoids runtime overhead
2400        // at the cost of eager binding (and one extra byte of encoding).
2401        OpFlags = X86II::MO_GOTPCREL;
2402        WrapperKind = X86ISD::WrapperRIP;
2403        ExtraLoad = true;
2404      }
2405
2406      Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2407                                          G->getOffset(), OpFlags);
2408
2409      // Add a wrapper if needed.
2410      if (WrapperKind != ISD::DELETED_NODE)
2411        Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2412      // Add extra indirection if needed.
2413      if (ExtraLoad)
2414        Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2415                             MachinePointerInfo::getGOT(),
2416                             false, false, false, 0);
2417    }
2418  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2419    unsigned char OpFlags = 0;
2420
2421    // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2422    // external symbols should go through the PLT.
2423    if (Subtarget->isTargetELF() &&
2424        getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2425      OpFlags = X86II::MO_PLT;
2426    } else if (Subtarget->isPICStyleStubAny() &&
2427               (!Subtarget->getTargetTriple().isMacOSX() ||
2428                Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2429      // PC-relative references to external symbols should go through $stub,
2430      // unless we're building with the leopard linker or later, which
2431      // automatically synthesizes these stubs.
2432      OpFlags = X86II::MO_DARWIN_STUB;
2433    }
2434
2435    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2436                                         OpFlags);
2437  }
2438
2439  // Returns a chain & a flag for retval copy to use.
2440  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2441  SmallVector<SDValue, 8> Ops;
2442
2443  if (!IsSibcall && isTailCall) {
2444    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2445                           DAG.getIntPtrConstant(0, true), InFlag);
2446    InFlag = Chain.getValue(1);
2447  }
2448
2449  Ops.push_back(Chain);
2450  Ops.push_back(Callee);
2451
2452  if (isTailCall)
2453    Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2454
2455  // Add argument registers to the end of the list so that they are known live
2456  // into the call.
2457  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2458    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2459                                  RegsToPass[i].second.getValueType()));
2460
2461  // Add an implicit use GOT pointer in EBX.
2462  if (!isTailCall && Subtarget->isPICStyleGOT())
2463    Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2464
2465  // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2466  if (Is64Bit && isVarArg && !IsWin64)
2467    Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2468
2469  if (InFlag.getNode())
2470    Ops.push_back(InFlag);
2471
2472  if (isTailCall) {
2473    // We used to do:
2474    //// If this is the first return lowered for this function, add the regs
2475    //// to the liveout set for the function.
2476    // This isn't right, although it's probably harmless on x86; liveouts
2477    // should be computed from returns not tail calls.  Consider a void
2478    // function making a tail call to a function returning int.
2479    return DAG.getNode(X86ISD::TC_RETURN, dl,
2480                       NodeTys, &Ops[0], Ops.size());
2481  }
2482
2483  Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2484  InFlag = Chain.getValue(1);
2485
2486  // Create the CALLSEQ_END node.
2487  unsigned NumBytesForCalleeToPush;
2488  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2489    NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2490  else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2491    // If this is a call to a struct-return function, the callee
2492    // pops the hidden struct pointer, so we have to push it back.
2493    // This is common for Darwin/X86, Linux & Mingw32 targets.
2494    NumBytesForCalleeToPush = 4;
2495  else
2496    NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2497
2498  // Returns a flag for retval copy to use.
2499  if (!IsSibcall) {
2500    Chain = DAG.getCALLSEQ_END(Chain,
2501                               DAG.getIntPtrConstant(NumBytes, true),
2502                               DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2503                                                     true),
2504                               InFlag);
2505    InFlag = Chain.getValue(1);
2506  }
2507
2508  // Handle result values, copying them out of physregs into vregs that we
2509  // return.
2510  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2511                         Ins, dl, DAG, InVals);
2512}
2513
2514
2515//===----------------------------------------------------------------------===//
2516//                Fast Calling Convention (tail call) implementation
2517//===----------------------------------------------------------------------===//
2518
2519//  Like std call, callee cleans arguments, convention except that ECX is
2520//  reserved for storing the tail called function address. Only 2 registers are
2521//  free for argument passing (inreg). Tail call optimization is performed
2522//  provided:
2523//                * tailcallopt is enabled
2524//                * caller/callee are fastcc
2525//  On X86_64 architecture with GOT-style position independent code only local
2526//  (within module) calls are supported at the moment.
2527//  To keep the stack aligned according to platform abi the function
2528//  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2529//  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2530//  If a tail called function callee has more arguments than the caller the
2531//  caller needs to make sure that there is room to move the RETADDR to. This is
2532//  achieved by reserving an area the size of the argument delta right after the
2533//  original REtADDR, but before the saved framepointer or the spilled registers
2534//  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2535//  stack layout:
2536//    arg1
2537//    arg2
2538//    RETADDR
2539//    [ new RETADDR
2540//      move area ]
2541//    (possible EBP)
2542//    ESI
2543//    EDI
2544//    local1 ..
2545
2546/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2547/// for a 16 byte align requirement.
2548unsigned
2549X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2550                                               SelectionDAG& DAG) const {
2551  MachineFunction &MF = DAG.getMachineFunction();
2552  const TargetMachine &TM = MF.getTarget();
2553  const TargetFrameLowering &TFI = *TM.getFrameLowering();
2554  unsigned StackAlignment = TFI.getStackAlignment();
2555  uint64_t AlignMask = StackAlignment - 1;
2556  int64_t Offset = StackSize;
2557  uint64_t SlotSize = TD->getPointerSize();
2558  if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2559    // Number smaller than 12 so just add the difference.
2560    Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2561  } else {
2562    // Mask out lower bits, add stackalignment once plus the 12 bytes.
2563    Offset = ((~AlignMask) & Offset) + StackAlignment +
2564      (StackAlignment-SlotSize);
2565  }
2566  return Offset;
2567}
2568
2569/// MatchingStackOffset - Return true if the given stack call argument is
2570/// already available in the same position (relatively) of the caller's
2571/// incoming argument stack.
2572static
2573bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2574                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2575                         const X86InstrInfo *TII) {
2576  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2577  int FI = INT_MAX;
2578  if (Arg.getOpcode() == ISD::CopyFromReg) {
2579    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2580    if (!TargetRegisterInfo::isVirtualRegister(VR))
2581      return false;
2582    MachineInstr *Def = MRI->getVRegDef(VR);
2583    if (!Def)
2584      return false;
2585    if (!Flags.isByVal()) {
2586      if (!TII->isLoadFromStackSlot(Def, FI))
2587        return false;
2588    } else {
2589      unsigned Opcode = Def->getOpcode();
2590      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2591          Def->getOperand(1).isFI()) {
2592        FI = Def->getOperand(1).getIndex();
2593        Bytes = Flags.getByValSize();
2594      } else
2595        return false;
2596    }
2597  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2598    if (Flags.isByVal())
2599      // ByVal argument is passed in as a pointer but it's now being
2600      // dereferenced. e.g.
2601      // define @foo(%struct.X* %A) {
2602      //   tail call @bar(%struct.X* byval %A)
2603      // }
2604      return false;
2605    SDValue Ptr = Ld->getBasePtr();
2606    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2607    if (!FINode)
2608      return false;
2609    FI = FINode->getIndex();
2610  } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2611    FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2612    FI = FINode->getIndex();
2613    Bytes = Flags.getByValSize();
2614  } else
2615    return false;
2616
2617  assert(FI != INT_MAX);
2618  if (!MFI->isFixedObjectIndex(FI))
2619    return false;
2620  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2621}
2622
2623/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2624/// for tail call optimization. Targets which want to do tail call
2625/// optimization should implement this function.
2626bool
2627X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2628                                                     CallingConv::ID CalleeCC,
2629                                                     bool isVarArg,
2630                                                     bool isCalleeStructRet,
2631                                                     bool isCallerStructRet,
2632                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2633                                    const SmallVectorImpl<SDValue> &OutVals,
2634                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2635                                                     SelectionDAG& DAG) const {
2636  if (!IsTailCallConvention(CalleeCC) &&
2637      CalleeCC != CallingConv::C)
2638    return false;
2639
2640  // If -tailcallopt is specified, make fastcc functions tail-callable.
2641  const MachineFunction &MF = DAG.getMachineFunction();
2642  const Function *CallerF = DAG.getMachineFunction().getFunction();
2643  CallingConv::ID CallerCC = CallerF->getCallingConv();
2644  bool CCMatch = CallerCC == CalleeCC;
2645
2646  if (GuaranteedTailCallOpt) {
2647    if (IsTailCallConvention(CalleeCC) && CCMatch)
2648      return true;
2649    return false;
2650  }
2651
2652  // Look for obvious safe cases to perform tail call optimization that do not
2653  // require ABI changes. This is what gcc calls sibcall.
2654
2655  // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2656  // emit a special epilogue.
2657  if (RegInfo->needsStackRealignment(MF))
2658    return false;
2659
2660  // Also avoid sibcall optimization if either caller or callee uses struct
2661  // return semantics.
2662  if (isCalleeStructRet || isCallerStructRet)
2663    return false;
2664
2665  // An stdcall caller is expected to clean up its arguments; the callee
2666  // isn't going to do that.
2667  if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2668    return false;
2669
2670  // Do not sibcall optimize vararg calls unless all arguments are passed via
2671  // registers.
2672  if (isVarArg && !Outs.empty()) {
2673
2674    // Optimizing for varargs on Win64 is unlikely to be safe without
2675    // additional testing.
2676    if (Subtarget->isTargetWin64())
2677      return false;
2678
2679    SmallVector<CCValAssign, 16> ArgLocs;
2680    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2681		   getTargetMachine(), ArgLocs, *DAG.getContext());
2682
2683    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2684    for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2685      if (!ArgLocs[i].isRegLoc())
2686        return false;
2687  }
2688
2689  // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2690  // Therefore if it's not used by the call it is not safe to optimize this into
2691  // a sibcall.
2692  bool Unused = false;
2693  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2694    if (!Ins[i].Used) {
2695      Unused = true;
2696      break;
2697    }
2698  }
2699  if (Unused) {
2700    SmallVector<CCValAssign, 16> RVLocs;
2701    CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2702		   getTargetMachine(), RVLocs, *DAG.getContext());
2703    CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2704    for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2705      CCValAssign &VA = RVLocs[i];
2706      if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2707        return false;
2708    }
2709  }
2710
2711  // If the calling conventions do not match, then we'd better make sure the
2712  // results are returned in the same way as what the caller expects.
2713  if (!CCMatch) {
2714    SmallVector<CCValAssign, 16> RVLocs1;
2715    CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2716		    getTargetMachine(), RVLocs1, *DAG.getContext());
2717    CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2718
2719    SmallVector<CCValAssign, 16> RVLocs2;
2720    CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2721		    getTargetMachine(), RVLocs2, *DAG.getContext());
2722    CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2723
2724    if (RVLocs1.size() != RVLocs2.size())
2725      return false;
2726    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2727      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2728        return false;
2729      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2730        return false;
2731      if (RVLocs1[i].isRegLoc()) {
2732        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2733          return false;
2734      } else {
2735        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2736          return false;
2737      }
2738    }
2739  }
2740
2741  // If the callee takes no arguments then go on to check the results of the
2742  // call.
2743  if (!Outs.empty()) {
2744    // Check if stack adjustment is needed. For now, do not do this if any
2745    // argument is passed on the stack.
2746    SmallVector<CCValAssign, 16> ArgLocs;
2747    CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2748		   getTargetMachine(), ArgLocs, *DAG.getContext());
2749
2750    // Allocate shadow area for Win64
2751    if (Subtarget->isTargetWin64()) {
2752      CCInfo.AllocateStack(32, 8);
2753    }
2754
2755    CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2756    if (CCInfo.getNextStackOffset()) {
2757      MachineFunction &MF = DAG.getMachineFunction();
2758      if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2759        return false;
2760
2761      // Check if the arguments are already laid out in the right way as
2762      // the caller's fixed stack objects.
2763      MachineFrameInfo *MFI = MF.getFrameInfo();
2764      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2765      const X86InstrInfo *TII =
2766        ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2767      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2768        CCValAssign &VA = ArgLocs[i];
2769        SDValue Arg = OutVals[i];
2770        ISD::ArgFlagsTy Flags = Outs[i].Flags;
2771        if (VA.getLocInfo() == CCValAssign::Indirect)
2772          return false;
2773        if (!VA.isRegLoc()) {
2774          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2775                                   MFI, MRI, TII))
2776            return false;
2777        }
2778      }
2779    }
2780
2781    // If the tailcall address may be in a register, then make sure it's
2782    // possible to register allocate for it. In 32-bit, the call address can
2783    // only target EAX, EDX, or ECX since the tail call must be scheduled after
2784    // callee-saved registers are restored. These happen to be the same
2785    // registers used to pass 'inreg' arguments so watch out for those.
2786    if (!Subtarget->is64Bit() &&
2787        !isa<GlobalAddressSDNode>(Callee) &&
2788        !isa<ExternalSymbolSDNode>(Callee)) {
2789      unsigned NumInRegs = 0;
2790      for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2791        CCValAssign &VA = ArgLocs[i];
2792        if (!VA.isRegLoc())
2793          continue;
2794        unsigned Reg = VA.getLocReg();
2795        switch (Reg) {
2796        default: break;
2797        case X86::EAX: case X86::EDX: case X86::ECX:
2798          if (++NumInRegs == 3)
2799            return false;
2800          break;
2801        }
2802      }
2803    }
2804  }
2805
2806  return true;
2807}
2808
2809FastISel *
2810X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2811  return X86::createFastISel(funcInfo);
2812}
2813
2814
2815//===----------------------------------------------------------------------===//
2816//                           Other Lowering Hooks
2817//===----------------------------------------------------------------------===//
2818
2819static bool MayFoldLoad(SDValue Op) {
2820  return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2821}
2822
2823static bool MayFoldIntoStore(SDValue Op) {
2824  return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2825}
2826
2827static bool isTargetShuffle(unsigned Opcode) {
2828  switch(Opcode) {
2829  default: return false;
2830  case X86ISD::PSHUFD:
2831  case X86ISD::PSHUFHW:
2832  case X86ISD::PSHUFLW:
2833  case X86ISD::SHUFPD:
2834  case X86ISD::PALIGN:
2835  case X86ISD::SHUFPS:
2836  case X86ISD::MOVLHPS:
2837  case X86ISD::MOVLHPD:
2838  case X86ISD::MOVHLPS:
2839  case X86ISD::MOVLPS:
2840  case X86ISD::MOVLPD:
2841  case X86ISD::MOVSHDUP:
2842  case X86ISD::MOVSLDUP:
2843  case X86ISD::MOVDDUP:
2844  case X86ISD::MOVSS:
2845  case X86ISD::MOVSD:
2846  case X86ISD::UNPCKLPS:
2847  case X86ISD::UNPCKLPD:
2848  case X86ISD::PUNPCKLWD:
2849  case X86ISD::PUNPCKLBW:
2850  case X86ISD::PUNPCKLDQ:
2851  case X86ISD::PUNPCKLQDQ:
2852  case X86ISD::UNPCKHPS:
2853  case X86ISD::UNPCKHPD:
2854  case X86ISD::PUNPCKHWD:
2855  case X86ISD::PUNPCKHBW:
2856  case X86ISD::PUNPCKHDQ:
2857  case X86ISD::PUNPCKHQDQ:
2858  case X86ISD::VPERMILPS:
2859  case X86ISD::VPERMILPSY:
2860  case X86ISD::VPERMILPD:
2861  case X86ISD::VPERMILPDY:
2862  case X86ISD::VPERM2F128:
2863    return true;
2864  }
2865  return false;
2866}
2867
2868static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2869                                               SDValue V1, SelectionDAG &DAG) {
2870  switch(Opc) {
2871  default: llvm_unreachable("Unknown x86 shuffle node");
2872  case X86ISD::MOVSHDUP:
2873  case X86ISD::MOVSLDUP:
2874  case X86ISD::MOVDDUP:
2875    return DAG.getNode(Opc, dl, VT, V1);
2876  }
2877
2878  return SDValue();
2879}
2880
2881static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2882                          SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2883  switch(Opc) {
2884  default: llvm_unreachable("Unknown x86 shuffle node");
2885  case X86ISD::PSHUFD:
2886  case X86ISD::PSHUFHW:
2887  case X86ISD::PSHUFLW:
2888  case X86ISD::VPERMILPS:
2889  case X86ISD::VPERMILPSY:
2890  case X86ISD::VPERMILPD:
2891  case X86ISD::VPERMILPDY:
2892    return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2893  }
2894
2895  return SDValue();
2896}
2897
2898static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2899               SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2900  switch(Opc) {
2901  default: llvm_unreachable("Unknown x86 shuffle node");
2902  case X86ISD::PALIGN:
2903  case X86ISD::SHUFPD:
2904  case X86ISD::SHUFPS:
2905  case X86ISD::VPERM2F128:
2906    return DAG.getNode(Opc, dl, VT, V1, V2,
2907                       DAG.getConstant(TargetMask, MVT::i8));
2908  }
2909  return SDValue();
2910}
2911
2912static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2913                                    SDValue V1, SDValue V2, SelectionDAG &DAG) {
2914  switch(Opc) {
2915  default: llvm_unreachable("Unknown x86 shuffle node");
2916  case X86ISD::MOVLHPS:
2917  case X86ISD::MOVLHPD:
2918  case X86ISD::MOVHLPS:
2919  case X86ISD::MOVLPS:
2920  case X86ISD::MOVLPD:
2921  case X86ISD::MOVSS:
2922  case X86ISD::MOVSD:
2923  case X86ISD::UNPCKLPS:
2924  case X86ISD::UNPCKLPD:
2925  case X86ISD::PUNPCKLWD:
2926  case X86ISD::PUNPCKLBW:
2927  case X86ISD::PUNPCKLDQ:
2928  case X86ISD::PUNPCKLQDQ:
2929  case X86ISD::UNPCKHPS:
2930  case X86ISD::UNPCKHPD:
2931  case X86ISD::PUNPCKHWD:
2932  case X86ISD::PUNPCKHBW:
2933  case X86ISD::PUNPCKHDQ:
2934  case X86ISD::PUNPCKHQDQ:
2935    return DAG.getNode(Opc, dl, VT, V1, V2);
2936  }
2937  return SDValue();
2938}
2939
2940SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2941  MachineFunction &MF = DAG.getMachineFunction();
2942  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2943  int ReturnAddrIndex = FuncInfo->getRAIndex();
2944
2945  if (ReturnAddrIndex == 0) {
2946    // Set up a frame object for the return address.
2947    uint64_t SlotSize = TD->getPointerSize();
2948    ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2949                                                           false);
2950    FuncInfo->setRAIndex(ReturnAddrIndex);
2951  }
2952
2953  return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2954}
2955
2956
2957bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2958                                       bool hasSymbolicDisplacement) {
2959  // Offset should fit into 32 bit immediate field.
2960  if (!isInt<32>(Offset))
2961    return false;
2962
2963  // If we don't have a symbolic displacement - we don't have any extra
2964  // restrictions.
2965  if (!hasSymbolicDisplacement)
2966    return true;
2967
2968  // FIXME: Some tweaks might be needed for medium code model.
2969  if (M != CodeModel::Small && M != CodeModel::Kernel)
2970    return false;
2971
2972  // For small code model we assume that latest object is 16MB before end of 31
2973  // bits boundary. We may also accept pretty large negative constants knowing
2974  // that all objects are in the positive half of address space.
2975  if (M == CodeModel::Small && Offset < 16*1024*1024)
2976    return true;
2977
2978  // For kernel code model we know that all object resist in the negative half
2979  // of 32bits address space. We may not accept negative offsets, since they may
2980  // be just off and we may accept pretty large positive ones.
2981  if (M == CodeModel::Kernel && Offset > 0)
2982    return true;
2983
2984  return false;
2985}
2986
2987/// isCalleePop - Determines whether the callee is required to pop its
2988/// own arguments. Callee pop is necessary to support tail calls.
2989bool X86::isCalleePop(CallingConv::ID CallingConv,
2990                      bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2991  if (IsVarArg)
2992    return false;
2993
2994  switch (CallingConv) {
2995  default:
2996    return false;
2997  case CallingConv::X86_StdCall:
2998    return !is64Bit;
2999  case CallingConv::X86_FastCall:
3000    return !is64Bit;
3001  case CallingConv::X86_ThisCall:
3002    return !is64Bit;
3003  case CallingConv::Fast:
3004    return TailCallOpt;
3005  case CallingConv::GHC:
3006    return TailCallOpt;
3007  }
3008}
3009
3010/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3011/// specific condition code, returning the condition code and the LHS/RHS of the
3012/// comparison to make.
3013static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3014                               SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3015  if (!isFP) {
3016    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3017      if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3018        // X > -1   -> X == 0, jump !sign.
3019        RHS = DAG.getConstant(0, RHS.getValueType());
3020        return X86::COND_NS;
3021      } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3022        // X < 0   -> X == 0, jump on sign.
3023        return X86::COND_S;
3024      } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3025        // X < 1   -> X <= 0
3026        RHS = DAG.getConstant(0, RHS.getValueType());
3027        return X86::COND_LE;
3028      }
3029    }
3030
3031    switch (SetCCOpcode) {
3032    default: llvm_unreachable("Invalid integer condition!");
3033    case ISD::SETEQ:  return X86::COND_E;
3034    case ISD::SETGT:  return X86::COND_G;
3035    case ISD::SETGE:  return X86::COND_GE;
3036    case ISD::SETLT:  return X86::COND_L;
3037    case ISD::SETLE:  return X86::COND_LE;
3038    case ISD::SETNE:  return X86::COND_NE;
3039    case ISD::SETULT: return X86::COND_B;
3040    case ISD::SETUGT: return X86::COND_A;
3041    case ISD::SETULE: return X86::COND_BE;
3042    case ISD::SETUGE: return X86::COND_AE;
3043    }
3044  }
3045
3046  // First determine if it is required or is profitable to flip the operands.
3047
3048  // If LHS is a foldable load, but RHS is not, flip the condition.
3049  if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3050      !ISD::isNON_EXTLoad(RHS.getNode())) {
3051    SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3052    std::swap(LHS, RHS);
3053  }
3054
3055  switch (SetCCOpcode) {
3056  default: break;
3057  case ISD::SETOLT:
3058  case ISD::SETOLE:
3059  case ISD::SETUGT:
3060  case ISD::SETUGE:
3061    std::swap(LHS, RHS);
3062    break;
3063  }
3064
3065  // On a floating point condition, the flags are set as follows:
3066  // ZF  PF  CF   op
3067  //  0 | 0 | 0 | X > Y
3068  //  0 | 0 | 1 | X < Y
3069  //  1 | 0 | 0 | X == Y
3070  //  1 | 1 | 1 | unordered
3071  switch (SetCCOpcode) {
3072  default: llvm_unreachable("Condcode should be pre-legalized away");
3073  case ISD::SETUEQ:
3074  case ISD::SETEQ:   return X86::COND_E;
3075  case ISD::SETOLT:              // flipped
3076  case ISD::SETOGT:
3077  case ISD::SETGT:   return X86::COND_A;
3078  case ISD::SETOLE:              // flipped
3079  case ISD::SETOGE:
3080  case ISD::SETGE:   return X86::COND_AE;
3081  case ISD::SETUGT:              // flipped
3082  case ISD::SETULT:
3083  case ISD::SETLT:   return X86::COND_B;
3084  case ISD::SETUGE:              // flipped
3085  case ISD::SETULE:
3086  case ISD::SETLE:   return X86::COND_BE;
3087  case ISD::SETONE:
3088  case ISD::SETNE:   return X86::COND_NE;
3089  case ISD::SETUO:   return X86::COND_P;
3090  case ISD::SETO:    return X86::COND_NP;
3091  case ISD::SETOEQ:
3092  case ISD::SETUNE:  return X86::COND_INVALID;
3093  }
3094}
3095
3096/// hasFPCMov - is there a floating point cmov for the specific X86 condition
3097/// code. Current x86 isa includes the following FP cmov instructions:
3098/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3099static bool hasFPCMov(unsigned X86CC) {
3100  switch (X86CC) {
3101  default:
3102    return false;
3103  case X86::COND_B:
3104  case X86::COND_BE:
3105  case X86::COND_E:
3106  case X86::COND_P:
3107  case X86::COND_A:
3108  case X86::COND_AE:
3109  case X86::COND_NE:
3110  case X86::COND_NP:
3111    return true;
3112  }
3113}
3114
3115/// isFPImmLegal - Returns true if the target can instruction select the
3116/// specified FP immediate natively. If false, the legalizer will
3117/// materialize the FP immediate as a load from a constant pool.
3118bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3119  for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3120    if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3121      return true;
3122  }
3123  return false;
3124}
3125
3126/// isUndefOrInRange - Return true if Val is undef or if its value falls within
3127/// the specified range (L, H].
3128static bool isUndefOrInRange(int Val, int Low, int Hi) {
3129  return (Val < 0) || (Val >= Low && Val < Hi);
3130}
3131
3132/// isUndefOrInRange - Return true if every element in Mask, begining
3133/// from position Pos and ending in Pos+Size, falls within the specified
3134/// range (L, L+Pos]. or is undef.
3135static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3136                             int Pos, int Size, int Low, int Hi) {
3137  for (int i = Pos, e = Pos+Size; i != e; ++i)
3138    if (!isUndefOrInRange(Mask[i], Low, Hi))
3139      return false;
3140  return true;
3141}
3142
3143/// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3144/// specified value.
3145static bool isUndefOrEqual(int Val, int CmpVal) {
3146  if (Val < 0 || Val == CmpVal)
3147    return true;
3148  return false;
3149}
3150
3151/// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3152/// from position Pos and ending in Pos+Size, falls within the specified
3153/// sequential range (L, L+Pos]. or is undef.
3154static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3155                                       int Pos, int Size, int Low) {
3156  for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3157    if (!isUndefOrEqual(Mask[i], Low))
3158      return false;
3159  return true;
3160}
3161
3162/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3163/// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3164/// the second operand.
3165static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3166  if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3167    return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3168  if (VT == MVT::v2f64 || VT == MVT::v2i64)
3169    return (Mask[0] < 2 && Mask[1] < 2);
3170  return false;
3171}
3172
3173bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3174  SmallVector<int, 8> M;
3175  N->getMask(M);
3176  return ::isPSHUFDMask(M, N->getValueType(0));
3177}
3178
3179/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3180/// is suitable for input to PSHUFHW.
3181static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3182  if (VT != MVT::v8i16)
3183    return false;
3184
3185  // Lower quadword copied in order or undef.
3186  for (int i = 0; i != 4; ++i)
3187    if (Mask[i] >= 0 && Mask[i] != i)
3188      return false;
3189
3190  // Upper quadword shuffled.
3191  for (int i = 4; i != 8; ++i)
3192    if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3193      return false;
3194
3195  return true;
3196}
3197
3198bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3199  SmallVector<int, 8> M;
3200  N->getMask(M);
3201  return ::isPSHUFHWMask(M, N->getValueType(0));
3202}
3203
3204/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3205/// is suitable for input to PSHUFLW.
3206static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3207  if (VT != MVT::v8i16)
3208    return false;
3209
3210  // Upper quadword copied in order.
3211  for (int i = 4; i != 8; ++i)
3212    if (Mask[i] >= 0 && Mask[i] != i)
3213      return false;
3214
3215  // Lower quadword shuffled.
3216  for (int i = 0; i != 4; ++i)
3217    if (Mask[i] >= 4)
3218      return false;
3219
3220  return true;
3221}
3222
3223bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3224  SmallVector<int, 8> M;
3225  N->getMask(M);
3226  return ::isPSHUFLWMask(M, N->getValueType(0));
3227}
3228
3229/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3230/// is suitable for input to PALIGNR.
3231static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3232                          bool hasSSSE3OrAVX) {
3233  int i, e = VT.getVectorNumElements();
3234  if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3235    return false;
3236
3237  // Do not handle v2i64 / v2f64 shuffles with palignr.
3238  if (e < 4 || !hasSSSE3OrAVX)
3239    return false;
3240
3241  for (i = 0; i != e; ++i)
3242    if (Mask[i] >= 0)
3243      break;
3244
3245  // All undef, not a palignr.
3246  if (i == e)
3247    return false;
3248
3249  // Make sure we're shifting in the right direction.
3250  if (Mask[i] <= i)
3251    return false;
3252
3253  int s = Mask[i] - i;
3254
3255  // Check the rest of the elements to see if they are consecutive.
3256  for (++i; i != e; ++i) {
3257    int m = Mask[i];
3258    if (m >= 0 && m != s+i)
3259      return false;
3260  }
3261  return true;
3262}
3263
3264/// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3265/// specifies a shuffle of elements that is suitable for input to 256-bit
3266/// VSHUFPSY.
3267static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3268                          const X86Subtarget *Subtarget) {
3269  int NumElems = VT.getVectorNumElements();
3270
3271  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3272    return false;
3273
3274  if (NumElems != 8)
3275    return false;
3276
3277  // VSHUFPSY divides the resulting vector into 4 chunks.
3278  // The sources are also splitted into 4 chunks, and each destination
3279  // chunk must come from a different source chunk.
3280  //
3281  //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3282  //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3283  //
3284  //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3285  //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3286  //
3287  int QuarterSize = NumElems/4;
3288  int HalfSize = QuarterSize*2;
3289  for (int i = 0; i < QuarterSize; ++i)
3290    if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3291      return false;
3292  for (int i = QuarterSize; i < QuarterSize*2; ++i)
3293    if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3294      return false;
3295
3296  // The mask of the second half must be the same as the first but with
3297  // the appropriate offsets. This works in the same way as VPERMILPS
3298  // works with masks.
3299  for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3300    if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3301      return false;
3302    int FstHalfIdx = i-HalfSize;
3303    if (Mask[FstHalfIdx] < 0)
3304      continue;
3305    if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3306      return false;
3307  }
3308  for (int i = QuarterSize*3; i < NumElems; ++i) {
3309    if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3310      return false;
3311    int FstHalfIdx = i-HalfSize;
3312    if (Mask[FstHalfIdx] < 0)
3313      continue;
3314    if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3315      return false;
3316
3317  }
3318
3319  return true;
3320}
3321
3322/// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3323/// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3324static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3325  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3326  EVT VT = SVOp->getValueType(0);
3327  int NumElems = VT.getVectorNumElements();
3328
3329  assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3330         "Only supports v8i32 and v8f32 types");
3331
3332  int HalfSize = NumElems/2;
3333  unsigned Mask = 0;
3334  for (int i = 0; i != NumElems ; ++i) {
3335    if (SVOp->getMaskElt(i) < 0)
3336      continue;
3337    // The mask of the first half must be equal to the second one.
3338    unsigned Shamt = (i%HalfSize)*2;
3339    unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3340    Mask |= Elt << Shamt;
3341  }
3342
3343  return Mask;
3344}
3345
3346/// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3347/// specifies a shuffle of elements that is suitable for input to 256-bit
3348/// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3349/// version and the mask of the second half isn't binded with the first
3350/// one.
3351static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3352                           const X86Subtarget *Subtarget) {
3353  int NumElems = VT.getVectorNumElements();
3354
3355  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3356    return false;
3357
3358  if (NumElems != 4)
3359    return false;
3360
3361  // VSHUFPSY divides the resulting vector into 4 chunks.
3362  // The sources are also splitted into 4 chunks, and each destination
3363  // chunk must come from a different source chunk.
3364  //
3365  //  SRC1 =>      X3       X2       X1       X0
3366  //  SRC2 =>      Y3       Y2       Y1       Y0
3367  //
3368  //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3369  //
3370  int QuarterSize = NumElems/4;
3371  int HalfSize = QuarterSize*2;
3372  for (int i = 0; i < QuarterSize; ++i)
3373    if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3374      return false;
3375  for (int i = QuarterSize; i < QuarterSize*2; ++i)
3376    if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3377      return false;
3378  for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3379    if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3380      return false;
3381  for (int i = QuarterSize*3; i < NumElems; ++i)
3382    if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3383      return false;
3384
3385  return true;
3386}
3387
3388/// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3389/// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3390static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3391  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3392  EVT VT = SVOp->getValueType(0);
3393  int NumElems = VT.getVectorNumElements();
3394
3395  assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3396         "Only supports v4i64 and v4f64 types");
3397
3398  int HalfSize = NumElems/2;
3399  unsigned Mask = 0;
3400  for (int i = 0; i != NumElems ; ++i) {
3401    if (SVOp->getMaskElt(i) < 0)
3402      continue;
3403    int Elt = SVOp->getMaskElt(i) % HalfSize;
3404    Mask |= Elt << i;
3405  }
3406
3407  return Mask;
3408}
3409
3410/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3411/// the two vector operands have swapped position.
3412static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3413  unsigned NumElems = VT.getVectorNumElements();
3414  for (unsigned i = 0; i != NumElems; ++i) {
3415    int idx = Mask[i];
3416    if (idx < 0)
3417      continue;
3418    else if (idx < (int)NumElems)
3419      Mask[i] = idx + NumElems;
3420    else
3421      Mask[i] = idx - NumElems;
3422  }
3423}
3424
3425/// isCommutedVSHUFP() - Return true if swapping operands will
3426///  allow to use the "vshufpd" or "vshufps" instruction
3427///  for 256-bit vectors
3428static bool isCommutedVSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3429                               const X86Subtarget *Subtarget) {
3430
3431  unsigned NumElems = VT.getVectorNumElements();
3432  if ((VT.getSizeInBits() != 256) || ((NumElems != 4) && (NumElems != 8)))
3433    return false;
3434
3435  SmallVector<int, 8> CommutedMask;
3436  for (unsigned i = 0; i < NumElems; ++i)
3437    CommutedMask.push_back(Mask[i]);
3438
3439  CommuteVectorShuffleMask(CommutedMask, VT);
3440  return (NumElems == 4) ? isVSHUFPDYMask(CommutedMask, VT, Subtarget):
3441      isVSHUFPSYMask(CommutedMask, VT, Subtarget);
3442}
3443
3444
3445/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3446/// specifies a shuffle of elements that is suitable for input to 128-bit
3447/// SHUFPS and SHUFPD.
3448static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3449  int NumElems = VT.getVectorNumElements();
3450
3451  if (VT.getSizeInBits() != 128)
3452    return false;
3453
3454  if (NumElems != 2 && NumElems != 4)
3455    return false;
3456
3457  int Half = NumElems / 2;
3458  for (int i = 0; i < Half; ++i)
3459    if (!isUndefOrInRange(Mask[i], 0, NumElems))
3460      return false;
3461  for (int i = Half; i < NumElems; ++i)
3462    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3463      return false;
3464
3465  return true;
3466}
3467
3468bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3469  SmallVector<int, 8> M;
3470  N->getMask(M);
3471  return ::isSHUFPMask(M, N->getValueType(0));
3472}
3473
3474/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3475/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3476/// half elements to come from vector 1 (which would equal the dest.) and
3477/// the upper half to come from vector 2.
3478static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3479  int NumElems = VT.getVectorNumElements();
3480
3481  if (NumElems != 2 && NumElems != 4)
3482    return false;
3483
3484  int Half = NumElems / 2;
3485  for (int i = 0; i < Half; ++i)
3486    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3487      return false;
3488  for (int i = Half; i < NumElems; ++i)
3489    if (!isUndefOrInRange(Mask[i], 0, NumElems))
3490      return false;
3491  return true;
3492}
3493
3494static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3495  SmallVector<int, 8> M;
3496  N->getMask(M);
3497  return isCommutedSHUFPMask(M, N->getValueType(0));
3498}
3499
3500/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3501/// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3502bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3503  EVT VT = N->getValueType(0);
3504  unsigned NumElems = VT.getVectorNumElements();
3505
3506  if (VT.getSizeInBits() != 128)
3507    return false;
3508
3509  if (NumElems != 4)
3510    return false;
3511
3512  // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3513  return isUndefOrEqual(N->getMaskElt(0), 6) &&
3514         isUndefOrEqual(N->getMaskElt(1), 7) &&
3515         isUndefOrEqual(N->getMaskElt(2), 2) &&
3516         isUndefOrEqual(N->getMaskElt(3), 3);
3517}
3518
3519/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3520/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3521/// <2, 3, 2, 3>
3522bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3523  EVT VT = N->getValueType(0);
3524  unsigned NumElems = VT.getVectorNumElements();
3525
3526  if (VT.getSizeInBits() != 128)
3527    return false;
3528
3529  if (NumElems != 4)
3530    return false;
3531
3532  return isUndefOrEqual(N->getMaskElt(0), 2) &&
3533         isUndefOrEqual(N->getMaskElt(1), 3) &&
3534         isUndefOrEqual(N->getMaskElt(2), 2) &&
3535         isUndefOrEqual(N->getMaskElt(3), 3);
3536}
3537
3538/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3539/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3540bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3541  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3542
3543  if (NumElems != 2 && NumElems != 4)
3544    return false;
3545
3546  for (unsigned i = 0; i < NumElems/2; ++i)
3547    if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3548      return false;
3549
3550  for (unsigned i = NumElems/2; i < NumElems; ++i)
3551    if (!isUndefOrEqual(N->getMaskElt(i), i))
3552      return false;
3553
3554  return true;
3555}
3556
3557/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3558/// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3559bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3560  unsigned NumElems = N->getValueType(0).getVectorNumElements();
3561
3562  if ((NumElems != 2 && NumElems != 4)
3563      || N->getValueType(0).getSizeInBits() > 128)
3564    return false;
3565
3566  for (unsigned i = 0; i < NumElems/2; ++i)
3567    if (!isUndefOrEqual(N->getMaskElt(i), i))
3568      return false;
3569
3570  for (unsigned i = 0; i < NumElems/2; ++i)
3571    if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3572      return false;
3573
3574  return true;
3575}
3576
3577/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3578/// specifies a shuffle of elements that is suitable for input to UNPCKL.
3579static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3580                         bool HasAVX2, bool V2IsSplat = false) {
3581  int NumElts = VT.getVectorNumElements();
3582
3583  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3584         "Unsupported vector type for unpckh");
3585
3586  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3587      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3588    return false;
3589
3590  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3591  // independently on 128-bit lanes.
3592  unsigned NumLanes = VT.getSizeInBits()/128;
3593  unsigned NumLaneElts = NumElts/NumLanes;
3594
3595  unsigned Start = 0;
3596  unsigned End = NumLaneElts;
3597  for (unsigned s = 0; s < NumLanes; ++s) {
3598    for (unsigned i = Start, j = s * NumLaneElts;
3599         i != End;
3600         i += 2, ++j) {
3601      int BitI  = Mask[i];
3602      int BitI1 = Mask[i+1];
3603      if (!isUndefOrEqual(BitI, j))
3604        return false;
3605      if (V2IsSplat) {
3606        if (!isUndefOrEqual(BitI1, NumElts))
3607          return false;
3608      } else {
3609        if (!isUndefOrEqual(BitI1, j + NumElts))
3610          return false;
3611      }
3612    }
3613    // Process the next 128 bits.
3614    Start += NumLaneElts;
3615    End += NumLaneElts;
3616  }
3617
3618  return true;
3619}
3620
3621bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3622  SmallVector<int, 8> M;
3623  N->getMask(M);
3624  return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3625}
3626
3627/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3628/// specifies a shuffle of elements that is suitable for input to UNPCKH.
3629static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3630                         bool HasAVX2, bool V2IsSplat = false) {
3631  int NumElts = VT.getVectorNumElements();
3632
3633  assert((VT.is128BitVector() || VT.is256BitVector()) &&
3634         "Unsupported vector type for unpckh");
3635
3636  if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3637      (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3638    return false;
3639
3640  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3641  // independently on 128-bit lanes.
3642  unsigned NumLanes = VT.getSizeInBits()/128;
3643  unsigned NumLaneElts = NumElts/NumLanes;
3644
3645  unsigned Start = 0;
3646  unsigned End = NumLaneElts;
3647  for (unsigned l = 0; l != NumLanes; ++l) {
3648    for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3649                             i != End; i += 2, ++j) {
3650      int BitI  = Mask[i];
3651      int BitI1 = Mask[i+1];
3652      if (!isUndefOrEqual(BitI, j))
3653        return false;
3654      if (V2IsSplat) {
3655        if (isUndefOrEqual(BitI1, NumElts))
3656          return false;
3657      } else {
3658        if (!isUndefOrEqual(BitI1, j+NumElts))
3659          return false;
3660      }
3661    }
3662    // Process the next 128 bits.
3663    Start += NumLaneElts;
3664    End += NumLaneElts;
3665  }
3666  return true;
3667}
3668
3669bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3670  SmallVector<int, 8> M;
3671  N->getMask(M);
3672  return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3673}
3674
3675/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3676/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3677/// <0, 0, 1, 1>
3678static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3679  int NumElems = VT.getVectorNumElements();
3680  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3681    return false;
3682
3683  // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3684  // FIXME: Need a better way to get rid of this, there's no latency difference
3685  // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3686  // the former later. We should also remove the "_undef" special mask.
3687  if (NumElems == 4 && VT.getSizeInBits() == 256)
3688    return false;
3689
3690  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3691  // independently on 128-bit lanes.
3692  unsigned NumLanes = VT.getSizeInBits() / 128;
3693  unsigned NumLaneElts = NumElems / NumLanes;
3694
3695  for (unsigned s = 0; s < NumLanes; ++s) {
3696    for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3697         i != NumLaneElts * (s + 1);
3698         i += 2, ++j) {
3699      int BitI  = Mask[i];
3700      int BitI1 = Mask[i+1];
3701
3702      if (!isUndefOrEqual(BitI, j))
3703        return false;
3704      if (!isUndefOrEqual(BitI1, j))
3705        return false;
3706    }
3707  }
3708
3709  return true;
3710}
3711
3712bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3713  SmallVector<int, 8> M;
3714  N->getMask(M);
3715  return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3716}
3717
3718/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3719/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3720/// <2, 2, 3, 3>
3721static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3722  int NumElems = VT.getVectorNumElements();
3723  if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3724    return false;
3725
3726  for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3727    int BitI  = Mask[i];
3728    int BitI1 = Mask[i+1];
3729    if (!isUndefOrEqual(BitI, j))
3730      return false;
3731    if (!isUndefOrEqual(BitI1, j))
3732      return false;
3733  }
3734  return true;
3735}
3736
3737bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3738  SmallVector<int, 8> M;
3739  N->getMask(M);
3740  return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3741}
3742
3743/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3744/// specifies a shuffle of elements that is suitable for input to MOVSS,
3745/// MOVSD, and MOVD, i.e. setting the lowest element.
3746static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3747  if (VT.getVectorElementType().getSizeInBits() < 32)
3748    return false;
3749
3750  int NumElts = VT.getVectorNumElements();
3751
3752  if (!isUndefOrEqual(Mask[0], NumElts))
3753    return false;
3754
3755  for (int i = 1; i < NumElts; ++i)
3756    if (!isUndefOrEqual(Mask[i], i))
3757      return false;
3758
3759  return true;
3760}
3761
3762bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3763  SmallVector<int, 8> M;
3764  N->getMask(M);
3765  return ::isMOVLMask(M, N->getValueType(0));
3766}
3767
3768/// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3769/// as permutations between 128-bit chunks or halves. As an example: this
3770/// shuffle bellow:
3771///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3772/// The first half comes from the second half of V1 and the second half from the
3773/// the second half of V2.
3774static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3775                             const X86Subtarget *Subtarget) {
3776  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3777    return false;
3778
3779  // The shuffle result is divided into half A and half B. In total the two
3780  // sources have 4 halves, namely: C, D, E, F. The final values of A and
3781  // B must come from C, D, E or F.
3782  int HalfSize = VT.getVectorNumElements()/2;
3783  bool MatchA = false, MatchB = false;
3784
3785  // Check if A comes from one of C, D, E, F.
3786  for (int Half = 0; Half < 4; ++Half) {
3787    if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3788      MatchA = true;
3789      break;
3790    }
3791  }
3792
3793  // Check if B comes from one of C, D, E, F.
3794  for (int Half = 0; Half < 4; ++Half) {
3795    if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3796      MatchB = true;
3797      break;
3798    }
3799  }
3800
3801  return MatchA && MatchB;
3802}
3803
3804/// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3805/// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3806static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3807  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3808  EVT VT = SVOp->getValueType(0);
3809
3810  int HalfSize = VT.getVectorNumElements()/2;
3811
3812  int FstHalf = 0, SndHalf = 0;
3813  for (int i = 0; i < HalfSize; ++i) {
3814    if (SVOp->getMaskElt(i) > 0) {
3815      FstHalf = SVOp->getMaskElt(i)/HalfSize;
3816      break;
3817    }
3818  }
3819  for (int i = HalfSize; i < HalfSize*2; ++i) {
3820    if (SVOp->getMaskElt(i) > 0) {
3821      SndHalf = SVOp->getMaskElt(i)/HalfSize;
3822      break;
3823    }
3824  }
3825
3826  return (FstHalf | (SndHalf << 4));
3827}
3828
3829/// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3830/// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3831/// Note that VPERMIL mask matching is different depending whether theunderlying
3832/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3833/// to the same elements of the low, but to the higher half of the source.
3834/// In VPERMILPD the two lanes could be shuffled independently of each other
3835/// with the same restriction that lanes can't be crossed.
3836static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3837                            const X86Subtarget *Subtarget) {
3838  int NumElts = VT.getVectorNumElements();
3839  int NumLanes = VT.getSizeInBits()/128;
3840
3841  if (!Subtarget->hasAVX())
3842    return false;
3843
3844  // Only match 256-bit with 64-bit types
3845  if (VT.getSizeInBits() != 256 || NumElts != 4)
3846    return false;
3847
3848  // The mask on the high lane is independent of the low. Both can match
3849  // any element in inside its own lane, but can't cross.
3850  int LaneSize = NumElts/NumLanes;
3851  for (int l = 0; l < NumLanes; ++l)
3852    for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3853      int LaneStart = l*LaneSize;
3854      if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3855        return false;
3856    }
3857
3858  return true;
3859}
3860
3861/// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3862/// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3863/// Note that VPERMIL mask matching is different depending whether theunderlying
3864/// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3865/// to the same elements of the low, but to the higher half of the source.
3866/// In VPERMILPD the two lanes could be shuffled independently of each other
3867/// with the same restriction that lanes can't be crossed.
3868static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3869                            const X86Subtarget *Subtarget) {
3870  unsigned NumElts = VT.getVectorNumElements();
3871  unsigned NumLanes = VT.getSizeInBits()/128;
3872
3873  if (!Subtarget->hasAVX())
3874    return false;
3875
3876  // Only match 256-bit with 32-bit types
3877  if (VT.getSizeInBits() != 256 || NumElts != 8)
3878    return false;
3879
3880  // The mask on the high lane should be the same as the low. Actually,
3881  // they can differ if any of the corresponding index in a lane is undef
3882  // and the other stays in range.
3883  int LaneSize = NumElts/NumLanes;
3884  for (int i = 0; i < LaneSize; ++i) {
3885    int HighElt = i+LaneSize;
3886    bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3887    bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3888
3889    if (!HighValid || !LowValid)
3890      return false;
3891    if (Mask[i] < 0 || Mask[HighElt] < 0)
3892      continue;
3893    if (Mask[HighElt]-Mask[i] != LaneSize)
3894      return false;
3895  }
3896
3897  return true;
3898}
3899
3900/// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3901/// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3902static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3903  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3904  EVT VT = SVOp->getValueType(0);
3905
3906  int NumElts = VT.getVectorNumElements();
3907  int NumLanes = VT.getSizeInBits()/128;
3908  int LaneSize = NumElts/NumLanes;
3909
3910  // Although the mask is equal for both lanes do it twice to get the cases
3911  // where a mask will match because the same mask element is undef on the
3912  // first half but valid on the second. This would get pathological cases
3913  // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3914  unsigned Mask = 0;
3915  for (int l = 0; l < NumLanes; ++l) {
3916    for (int i = 0; i < LaneSize; ++i) {
3917      int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3918      if (MaskElt < 0)
3919        continue;
3920      if (MaskElt >= LaneSize)
3921        MaskElt -= LaneSize;
3922      Mask |= MaskElt << (i*2);
3923    }
3924  }
3925
3926  return Mask;
3927}
3928
3929/// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3930/// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3931static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3932  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3933  EVT VT = SVOp->getValueType(0);
3934
3935  int NumElts = VT.getVectorNumElements();
3936  int NumLanes = VT.getSizeInBits()/128;
3937
3938  unsigned Mask = 0;
3939  int LaneSize = NumElts/NumLanes;
3940  for (int l = 0; l < NumLanes; ++l)
3941    for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3942      int MaskElt = SVOp->getMaskElt(i);
3943      if (MaskElt < 0)
3944        continue;
3945      Mask |= (MaskElt-l*LaneSize) << i;
3946    }
3947
3948  return Mask;
3949}
3950
3951/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3952/// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3953/// element of vector 2 and the other elements to come from vector 1 in order.
3954static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3955                               bool V2IsSplat = false, bool V2IsUndef = false) {
3956  int NumOps = VT.getVectorNumElements();
3957  if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3958    return false;
3959
3960  if (!isUndefOrEqual(Mask[0], 0))
3961    return false;
3962
3963  for (int i = 1; i < NumOps; ++i)
3964    if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3965          (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3966          (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3967      return false;
3968
3969  return true;
3970}
3971
3972static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3973                           bool V2IsUndef = false) {
3974  SmallVector<int, 8> M;
3975  N->getMask(M);
3976  return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3977}
3978
3979/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3980/// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3981/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3982bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3983                         const X86Subtarget *Subtarget) {
3984  if (!Subtarget->hasSSE3orAVX())
3985    return false;
3986
3987  // The second vector must be undef
3988  if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3989    return false;
3990
3991  EVT VT = N->getValueType(0);
3992  unsigned NumElems = VT.getVectorNumElements();
3993
3994  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3995      (VT.getSizeInBits() == 256 && NumElems != 8))
3996    return false;
3997
3998  // "i+1" is the value the indexed mask element must have
3999  for (unsigned i = 0; i < NumElems; i += 2)
4000    if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
4001        !isUndefOrEqual(N->getMaskElt(i+1), i+1))
4002      return false;
4003
4004  return true;
4005}
4006
4007/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4008/// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4009/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4010bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
4011                         const X86Subtarget *Subtarget) {
4012  if (!Subtarget->hasSSE3orAVX())
4013    return false;
4014
4015  // The second vector must be undef
4016  if (N->getOperand(1).getOpcode() != ISD::UNDEF)
4017    return false;
4018
4019  EVT VT = N->getValueType(0);
4020  unsigned NumElems = VT.getVectorNumElements();
4021
4022  if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
4023      (VT.getSizeInBits() == 256 && NumElems != 8))
4024    return false;
4025
4026  // "i" is the value the indexed mask element must have
4027  for (unsigned i = 0; i < NumElems; i += 2)
4028    if (!isUndefOrEqual(N->getMaskElt(i), i) ||
4029        !isUndefOrEqual(N->getMaskElt(i+1), i))
4030      return false;
4031
4032  return true;
4033}
4034
4035/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4036/// specifies a shuffle of elements that is suitable for input to 256-bit
4037/// version of MOVDDUP.
4038static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
4039                           const X86Subtarget *Subtarget) {
4040  EVT VT = N->getValueType(0);
4041  int NumElts = VT.getVectorNumElements();
4042  bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4043
4044  if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4045      !V2IsUndef || NumElts != 4)
4046    return false;
4047
4048  for (int i = 0; i != NumElts/2; ++i)
4049    if (!isUndefOrEqual(N->getMaskElt(i), 0))
4050      return false;
4051  for (int i = NumElts/2; i != NumElts; ++i)
4052    if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4053      return false;
4054  return true;
4055}
4056
4057/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4058/// specifies a shuffle of elements that is suitable for input to 128-bit
4059/// version of MOVDDUP.
4060bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4061  EVT VT = N->getValueType(0);
4062
4063  if (VT.getSizeInBits() != 128)
4064    return false;
4065
4066  int e = VT.getVectorNumElements() / 2;
4067  for (int i = 0; i < e; ++i)
4068    if (!isUndefOrEqual(N->getMaskElt(i), i))
4069      return false;
4070  for (int i = 0; i < e; ++i)
4071    if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4072      return false;
4073  return true;
4074}
4075
4076/// isVEXTRACTF128Index - Return true if the specified
4077/// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4078/// suitable for input to VEXTRACTF128.
4079bool X86::isVEXTRACTF128Index(SDNode *N) {
4080  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4081    return false;
4082
4083  // The index should be aligned on a 128-bit boundary.
4084  uint64_t Index =
4085    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4086
4087  unsigned VL = N->getValueType(0).getVectorNumElements();
4088  unsigned VBits = N->getValueType(0).getSizeInBits();
4089  unsigned ElSize = VBits / VL;
4090  bool Result = (Index * ElSize) % 128 == 0;
4091
4092  return Result;
4093}
4094
4095/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4096/// operand specifies a subvector insert that is suitable for input to
4097/// VINSERTF128.
4098bool X86::isVINSERTF128Index(SDNode *N) {
4099  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4100    return false;
4101
4102  // The index should be aligned on a 128-bit boundary.
4103  uint64_t Index =
4104    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4105
4106  unsigned VL = N->getValueType(0).getVectorNumElements();
4107  unsigned VBits = N->getValueType(0).getSizeInBits();
4108  unsigned ElSize = VBits / VL;
4109  bool Result = (Index * ElSize) % 128 == 0;
4110
4111  return Result;
4112}
4113
4114/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4115/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4116unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4117  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4118  int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4119
4120  unsigned Shift = (NumOperands == 4) ? 2 : 1;
4121  unsigned Mask = 0;
4122  for (int i = 0; i < NumOperands; ++i) {
4123    int Val = SVOp->getMaskElt(NumOperands-i-1);
4124    if (Val < 0) Val = 0;
4125    if (Val >= NumOperands) Val -= NumOperands;
4126    Mask |= Val;
4127    if (i != NumOperands - 1)
4128      Mask <<= Shift;
4129  }
4130  return Mask;
4131}
4132
4133/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4134/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4135unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4136  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4137  unsigned Mask = 0;
4138  // 8 nodes, but we only care about the last 4.
4139  for (unsigned i = 7; i >= 4; --i) {
4140    int Val = SVOp->getMaskElt(i);
4141    if (Val >= 0)
4142      Mask |= (Val - 4);
4143    if (i != 4)
4144      Mask <<= 2;
4145  }
4146  return Mask;
4147}
4148
4149/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4150/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4151unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4152  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4153  unsigned Mask = 0;
4154  // 8 nodes, but we only care about the first 4.
4155  for (int i = 3; i >= 0; --i) {
4156    int Val = SVOp->getMaskElt(i);
4157    if (Val >= 0)
4158      Mask |= Val;
4159    if (i != 0)
4160      Mask <<= 2;
4161  }
4162  return Mask;
4163}
4164
4165/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4166/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4167unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4168  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4169  EVT VVT = N->getValueType(0);
4170  unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4171  int Val = 0;
4172
4173  unsigned i, e;
4174  for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4175    Val = SVOp->getMaskElt(i);
4176    if (Val >= 0)
4177      break;
4178  }
4179  assert(Val - i > 0 && "PALIGNR imm should be positive");
4180  return (Val - i) * EltSize;
4181}
4182
4183/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4184/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4185/// instructions.
4186unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4187  if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4188    llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4189
4190  uint64_t Index =
4191    cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4192
4193  EVT VecVT = N->getOperand(0).getValueType();
4194  EVT ElVT = VecVT.getVectorElementType();
4195
4196  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4197  return Index / NumElemsPerChunk;
4198}
4199
4200/// getInsertVINSERTF128Immediate - Return the appropriate immediate
4201/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4202/// instructions.
4203unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4204  if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4205    llvm_unreachable("Illegal insert subvector for VINSERTF128");
4206
4207  uint64_t Index =
4208    cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4209
4210  EVT VecVT = N->getValueType(0);
4211  EVT ElVT = VecVT.getVectorElementType();
4212
4213  unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4214  return Index / NumElemsPerChunk;
4215}
4216
4217/// isZeroNode - Returns true if Elt is a constant zero or a floating point
4218/// constant +0.0.
4219bool X86::isZeroNode(SDValue Elt) {
4220  return ((isa<ConstantSDNode>(Elt) &&
4221           cast<ConstantSDNode>(Elt)->isNullValue()) ||
4222          (isa<ConstantFPSDNode>(Elt) &&
4223           cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4224}
4225
4226/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4227/// their permute mask.
4228static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4229                                    SelectionDAG &DAG) {
4230  EVT VT = SVOp->getValueType(0);
4231  unsigned NumElems = VT.getVectorNumElements();
4232  SmallVector<int, 8> MaskVec;
4233
4234  for (unsigned i = 0; i != NumElems; ++i) {
4235    int idx = SVOp->getMaskElt(i);
4236    if (idx < 0)
4237      MaskVec.push_back(idx);
4238    else if (idx < (int)NumElems)
4239      MaskVec.push_back(idx + NumElems);
4240    else
4241      MaskVec.push_back(idx - NumElems);
4242  }
4243  return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4244                              SVOp->getOperand(0), &MaskVec[0]);
4245}
4246
4247/// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4248/// match movhlps. The lower half elements should come from upper half of
4249/// V1 (and in order), and the upper half elements should come from the upper
4250/// half of V2 (and in order).
4251static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4252  EVT VT = Op->getValueType(0);
4253  if (VT.getSizeInBits() != 128)
4254    return false;
4255  if (VT.getVectorNumElements() != 4)
4256    return false;
4257  for (unsigned i = 0, e = 2; i != e; ++i)
4258    if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4259      return false;
4260  for (unsigned i = 2; i != 4; ++i)
4261    if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4262      return false;
4263  return true;
4264}
4265
4266/// isScalarLoadToVector - Returns true if the node is a scalar load that
4267/// is promoted to a vector. It also returns the LoadSDNode by reference if
4268/// required.
4269static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4270  if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4271    return false;
4272  N = N->getOperand(0).getNode();
4273  if (!ISD::isNON_EXTLoad(N))
4274    return false;
4275  if (LD)
4276    *LD = cast<LoadSDNode>(N);
4277  return true;
4278}
4279
4280// Test whether the given value is a vector value which will be legalized
4281// into a load.
4282static bool WillBeConstantPoolLoad(SDNode *N) {
4283  if (N->getOpcode() != ISD::BUILD_VECTOR)
4284    return false;
4285
4286  // Check for any non-constant elements.
4287  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4288    switch (N->getOperand(i).getNode()->getOpcode()) {
4289    case ISD::UNDEF:
4290    case ISD::ConstantFP:
4291    case ISD::Constant:
4292      break;
4293    default:
4294      return false;
4295    }
4296
4297  // Vectors of all-zeros and all-ones are materialized with special
4298  // instructions rather than being loaded.
4299  return !ISD::isBuildVectorAllZeros(N) &&
4300         !ISD::isBuildVectorAllOnes(N);
4301}
4302
4303/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4304/// match movlp{s|d}. The lower half elements should come from lower half of
4305/// V1 (and in order), and the upper half elements should come from the upper
4306/// half of V2 (and in order). And since V1 will become the source of the
4307/// MOVLP, it must be either a vector load or a scalar load to vector.
4308static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4309                               ShuffleVectorSDNode *Op) {
4310  EVT VT = Op->getValueType(0);
4311  if (VT.getSizeInBits() != 128)
4312    return false;
4313
4314  if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4315    return false;
4316  // Is V2 is a vector load, don't do this transformation. We will try to use
4317  // load folding shufps op.
4318  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4319    return false;
4320
4321  unsigned NumElems = VT.getVectorNumElements();
4322
4323  if (NumElems != 2 && NumElems != 4)
4324    return false;
4325  for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4326    if (!isUndefOrEqual(Op->getMaskElt(i), i))
4327      return false;
4328  for (unsigned i = NumElems/2; i != NumElems; ++i)
4329    if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4330      return false;
4331  return true;
4332}
4333
4334/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4335/// all the same.
4336static bool isSplatVector(SDNode *N) {
4337  if (N->getOpcode() != ISD::BUILD_VECTOR)
4338    return false;
4339
4340  SDValue SplatValue = N->getOperand(0);
4341  for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4342    if (N->getOperand(i) != SplatValue)
4343      return false;
4344  return true;
4345}
4346
4347/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4348/// to an zero vector.
4349/// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4350static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4351  SDValue V1 = N->getOperand(0);
4352  SDValue V2 = N->getOperand(1);
4353  unsigned NumElems = N->getValueType(0).getVectorNumElements();
4354  for (unsigned i = 0; i != NumElems; ++i) {
4355    int Idx = N->getMaskElt(i);
4356    if (Idx >= (int)NumElems) {
4357      unsigned Opc = V2.getOpcode();
4358      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4359        continue;
4360      if (Opc != ISD::BUILD_VECTOR ||
4361          !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4362        return false;
4363    } else if (Idx >= 0) {
4364      unsigned Opc = V1.getOpcode();
4365      if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4366        continue;
4367      if (Opc != ISD::BUILD_VECTOR ||
4368          !X86::isZeroNode(V1.getOperand(Idx)))
4369        return false;
4370    }
4371  }
4372  return true;
4373}
4374
4375/// getZeroVector - Returns a vector of specified type with all zero elements.
4376///
4377static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4378                             DebugLoc dl) {
4379  assert(VT.isVector() && "Expected a vector type");
4380
4381  // Always build SSE zero vectors as <4 x i32> bitcasted
4382  // to their dest type. This ensures they get CSE'd.
4383  SDValue Vec;
4384  if (VT.getSizeInBits() == 128) {  // SSE
4385    if (HasXMMInt) {  // SSE2
4386      SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4387      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4388    } else { // SSE1
4389      SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4390      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4391    }
4392  } else if (VT.getSizeInBits() == 256) { // AVX
4393    // 256-bit logic and arithmetic instructions in AVX are
4394    // all floating-point, no support for integer ops. Default
4395    // to emitting fp zeroed vectors then.
4396    SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4397    SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4398    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4399  }
4400  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4401}
4402
4403/// getOnesVector - Returns a vector of specified type with all bits set.
4404/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4405/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4406/// Then bitcast to their original type, ensuring they get CSE'd.
4407static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4408                             DebugLoc dl) {
4409  assert(VT.isVector() && "Expected a vector type");
4410  assert((VT.is128BitVector() || VT.is256BitVector())
4411         && "Expected a 128-bit or 256-bit vector type");
4412
4413  SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4414  SDValue Vec;
4415  if (VT.getSizeInBits() == 256) {
4416    if (HasAVX2) { // AVX2
4417      SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4418      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4419    } else { // AVX
4420      Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4421      SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4422                                Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4423      Vec = Insert128BitVector(InsV, Vec,
4424                    DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4425    }
4426  } else {
4427    Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4428  }
4429
4430  return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4431}
4432
4433/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4434/// that point to V2 points to its first element.
4435static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4436  EVT VT = SVOp->getValueType(0);
4437  unsigned NumElems = VT.getVectorNumElements();
4438
4439  bool Changed = false;
4440  SmallVector<int, 8> MaskVec;
4441  SVOp->getMask(MaskVec);
4442
4443  for (unsigned i = 0; i != NumElems; ++i) {
4444    if (MaskVec[i] > (int)NumElems) {
4445      MaskVec[i] = NumElems;
4446      Changed = true;
4447    }
4448  }
4449  if (Changed)
4450    return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4451                                SVOp->getOperand(1), &MaskVec[0]);
4452  return SDValue(SVOp, 0);
4453}
4454
4455/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4456/// operation of specified width.
4457static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4458                       SDValue V2) {
4459  unsigned NumElems = VT.getVectorNumElements();
4460  SmallVector<int, 8> Mask;
4461  Mask.push_back(NumElems);
4462  for (unsigned i = 1; i != NumElems; ++i)
4463    Mask.push_back(i);
4464  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4465}
4466
4467/// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4468static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4469                          SDValue V2) {
4470  unsigned NumElems = VT.getVectorNumElements();
4471  SmallVector<int, 8> Mask;
4472  for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4473    Mask.push_back(i);
4474    Mask.push_back(i + NumElems);
4475  }
4476  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4477}
4478
4479/// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4480static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4481                          SDValue V2) {
4482  unsigned NumElems = VT.getVectorNumElements();
4483  unsigned Half = NumElems/2;
4484  SmallVector<int, 8> Mask;
4485  for (unsigned i = 0; i != Half; ++i) {
4486    Mask.push_back(i + Half);
4487    Mask.push_back(i + NumElems + Half);
4488  }
4489  return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4490}
4491
4492// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4493// a generic shuffle instruction because the target has no such instructions.
4494// Generate shuffles which repeat i16 and i8 several times until they can be
4495// represented by v4f32 and then be manipulated by target suported shuffles.
4496static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4497  EVT VT = V.getValueType();
4498  int NumElems = VT.getVectorNumElements();
4499  DebugLoc dl = V.getDebugLoc();
4500
4501  while (NumElems > 4) {
4502    if (EltNo < NumElems/2) {
4503      V = getUnpackl(DAG, dl, VT, V, V);
4504    } else {
4505      V = getUnpackh(DAG, dl, VT, V, V);
4506      EltNo -= NumElems/2;
4507    }
4508    NumElems >>= 1;
4509  }
4510  return V;
4511}
4512
4513/// getLegalSplat - Generate a legal splat with supported x86 shuffles
4514static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4515  EVT VT = V.getValueType();
4516  DebugLoc dl = V.getDebugLoc();
4517  assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4518         && "Vector size not supported");
4519
4520  if (VT.getSizeInBits() == 128) {
4521    V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4522    int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4523    V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4524                             &SplatMask[0]);
4525  } else {
4526    // To use VPERMILPS to splat scalars, the second half of indicies must
4527    // refer to the higher part, which is a duplication of the lower one,
4528    // because VPERMILPS can only handle in-lane permutations.
4529    int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4530                         EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4531
4532    V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4533    V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4534                             &SplatMask[0]);
4535  }
4536
4537  return DAG.getNode(ISD::BITCAST, dl, VT, V);
4538}
4539
4540/// PromoteSplat - Splat is promoted to target supported vector shuffles.
4541static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4542  EVT SrcVT = SV->getValueType(0);
4543  SDValue V1 = SV->getOperand(0);
4544  DebugLoc dl = SV->getDebugLoc();
4545
4546  int EltNo = SV->getSplatIndex();
4547  int NumElems = SrcVT.getVectorNumElements();
4548  unsigned Size = SrcVT.getSizeInBits();
4549
4550  assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4551          "Unknown how to promote splat for type");
4552
4553  // Extract the 128-bit part containing the splat element and update
4554  // the splat element index when it refers to the higher register.
4555  if (Size == 256) {
4556    unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4557    V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4558    if (Idx > 0)
4559      EltNo -= NumElems/2;
4560  }
4561
4562  // All i16 and i8 vector types can't be used directly by a generic shuffle
4563  // instruction because the target has no such instruction. Generate shuffles
4564  // which repeat i16 and i8 several times until they fit in i32, and then can
4565  // be manipulated by target suported shuffles.
4566  EVT EltVT = SrcVT.getVectorElementType();
4567  if (EltVT == MVT::i8 || EltVT == MVT::i16)
4568    V1 = PromoteSplati8i16(V1, DAG, EltNo);
4569
4570  // Recreate the 256-bit vector and place the same 128-bit vector
4571  // into the low and high part. This is necessary because we want
4572  // to use VPERM* to shuffle the vectors
4573  if (Size == 256) {
4574    SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4575                         DAG.getConstant(0, MVT::i32), DAG, dl);
4576    V1 = Insert128BitVector(InsV, V1,
4577               DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4578  }
4579
4580  return getLegalSplat(DAG, V1, EltNo);
4581}
4582
4583/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4584/// vector of zero or undef vector.  This produces a shuffle where the low
4585/// element of V2 is swizzled into the zero/undef vector, landing at element
4586/// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4587static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4588                                           bool isZero, bool HasXMMInt,
4589                                           SelectionDAG &DAG) {
4590  EVT VT = V2.getValueType();
4591  SDValue V1 = isZero
4592    ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4593  unsigned NumElems = VT.getVectorNumElements();
4594  SmallVector<int, 16> MaskVec;
4595  for (unsigned i = 0; i != NumElems; ++i)
4596    // If this is the insertion idx, put the low elt of V2 here.
4597    MaskVec.push_back(i == Idx ? NumElems : i);
4598  return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4599}
4600
4601/// getShuffleScalarElt - Returns the scalar element that will make up the ith
4602/// element of the result of the vector shuffle.
4603static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4604                                   unsigned Depth) {
4605  if (Depth == 6)
4606    return SDValue();  // Limit search depth.
4607
4608  SDValue V = SDValue(N, 0);
4609  EVT VT = V.getValueType();
4610  unsigned Opcode = V.getOpcode();
4611
4612  // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4613  if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4614    Index = SV->getMaskElt(Index);
4615
4616    if (Index < 0)
4617      return DAG.getUNDEF(VT.getVectorElementType());
4618
4619    int NumElems = VT.getVectorNumElements();
4620    SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4621    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4622  }
4623
4624  // Recurse into target specific vector shuffles to find scalars.
4625  if (isTargetShuffle(Opcode)) {
4626    int NumElems = VT.getVectorNumElements();
4627    SmallVector<unsigned, 16> ShuffleMask;
4628    SDValue ImmN;
4629
4630    switch(Opcode) {
4631    case X86ISD::SHUFPS:
4632    case X86ISD::SHUFPD:
4633      ImmN = N->getOperand(N->getNumOperands()-1);
4634      DecodeSHUFPSMask(NumElems,
4635                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4636                       ShuffleMask);
4637      break;
4638    case X86ISD::PUNPCKHBW:
4639    case X86ISD::PUNPCKHWD:
4640    case X86ISD::PUNPCKHDQ:
4641    case X86ISD::PUNPCKHQDQ:
4642      DecodePUNPCKHMask(NumElems, ShuffleMask);
4643      break;
4644    case X86ISD::UNPCKHPS:
4645    case X86ISD::UNPCKHPD:
4646      DecodeUNPCKHPMask(VT, ShuffleMask);
4647      break;
4648    case X86ISD::PUNPCKLBW:
4649    case X86ISD::PUNPCKLWD:
4650    case X86ISD::PUNPCKLDQ:
4651    case X86ISD::PUNPCKLQDQ:
4652      DecodePUNPCKLMask(VT, ShuffleMask);
4653      break;
4654    case X86ISD::UNPCKLPS:
4655    case X86ISD::UNPCKLPD:
4656      DecodeUNPCKLPMask(VT, ShuffleMask);
4657      break;
4658    case X86ISD::MOVHLPS:
4659      DecodeMOVHLPSMask(NumElems, ShuffleMask);
4660      break;
4661    case X86ISD::MOVLHPS:
4662      DecodeMOVLHPSMask(NumElems, ShuffleMask);
4663      break;
4664    case X86ISD::PSHUFD:
4665      ImmN = N->getOperand(N->getNumOperands()-1);
4666      DecodePSHUFMask(NumElems,
4667                      cast<ConstantSDNode>(ImmN)->getZExtValue(),
4668                      ShuffleMask);
4669      break;
4670    case X86ISD::PSHUFHW:
4671      ImmN = N->getOperand(N->getNumOperands()-1);
4672      DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4673                        ShuffleMask);
4674      break;
4675    case X86ISD::PSHUFLW:
4676      ImmN = N->getOperand(N->getNumOperands()-1);
4677      DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4678                        ShuffleMask);
4679      break;
4680    case X86ISD::MOVSS:
4681    case X86ISD::MOVSD: {
4682      // The index 0 always comes from the first element of the second source,
4683      // this is why MOVSS and MOVSD are used in the first place. The other
4684      // elements come from the other positions of the first source vector.
4685      unsigned OpNum = (Index == 0) ? 1 : 0;
4686      return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4687                                 Depth+1);
4688    }
4689    case X86ISD::VPERMILPS:
4690      ImmN = N->getOperand(N->getNumOperands()-1);
4691      DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4692                        ShuffleMask);
4693      break;
4694    case X86ISD::VPERMILPSY:
4695      ImmN = N->getOperand(N->getNumOperands()-1);
4696      DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4697                        ShuffleMask);
4698      break;
4699    case X86ISD::VPERMILPD:
4700      ImmN = N->getOperand(N->getNumOperands()-1);
4701      DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4702                        ShuffleMask);
4703      break;
4704    case X86ISD::VPERMILPDY:
4705      ImmN = N->getOperand(N->getNumOperands()-1);
4706      DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4707                        ShuffleMask);
4708      break;
4709    case X86ISD::VPERM2F128:
4710      ImmN = N->getOperand(N->getNumOperands()-1);
4711      DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4712                           ShuffleMask);
4713      break;
4714    case X86ISD::MOVDDUP:
4715    case X86ISD::MOVLHPD:
4716    case X86ISD::MOVLPD:
4717    case X86ISD::MOVLPS:
4718    case X86ISD::MOVSHDUP:
4719    case X86ISD::MOVSLDUP:
4720    case X86ISD::PALIGN:
4721      return SDValue(); // Not yet implemented.
4722    default:
4723      assert(0 && "unknown target shuffle node");
4724      return SDValue();
4725    }
4726
4727    Index = ShuffleMask[Index];
4728    if (Index < 0)
4729      return DAG.getUNDEF(VT.getVectorElementType());
4730
4731    SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4732    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4733                               Depth+1);
4734  }
4735
4736  // Actual nodes that may contain scalar elements
4737  if (Opcode == ISD::BITCAST) {
4738    V = V.getOperand(0);
4739    EVT SrcVT = V.getValueType();
4740    unsigned NumElems = VT.getVectorNumElements();
4741
4742    if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4743      return SDValue();
4744  }
4745
4746  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4747    return (Index == 0) ? V.getOperand(0)
4748                          : DAG.getUNDEF(VT.getVectorElementType());
4749
4750  if (V.getOpcode() == ISD::BUILD_VECTOR)
4751    return V.getOperand(Index);
4752
4753  return SDValue();
4754}
4755
4756/// getNumOfConsecutiveZeros - Return the number of elements of a vector
4757/// shuffle operation which come from a consecutively from a zero. The
4758/// search can start in two different directions, from left or right.
4759static
4760unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4761                                  bool ZerosFromLeft, SelectionDAG &DAG) {
4762  int i = 0;
4763
4764  while (i < NumElems) {
4765    unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4766    SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4767    if (!(Elt.getNode() &&
4768         (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4769      break;
4770    ++i;
4771  }
4772
4773  return i;
4774}
4775
4776/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4777/// MaskE correspond consecutively to elements from one of the vector operands,
4778/// starting from its index OpIdx. Also tell OpNum which source vector operand.
4779static
4780bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4781                              int OpIdx, int NumElems, unsigned &OpNum) {
4782  bool SeenV1 = false;
4783  bool SeenV2 = false;
4784
4785  for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4786    int Idx = SVOp->getMaskElt(i);
4787    // Ignore undef indicies
4788    if (Idx < 0)
4789      continue;
4790
4791    if (Idx < NumElems)
4792      SeenV1 = true;
4793    else
4794      SeenV2 = true;
4795
4796    // Only accept consecutive elements from the same vector
4797    if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4798      return false;
4799  }
4800
4801  OpNum = SeenV1 ? 0 : 1;
4802  return true;
4803}
4804
4805/// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4806/// logical left shift of a vector.
4807static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4808                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4809  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4810  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4811              false /* check zeros from right */, DAG);
4812  unsigned OpSrc;
4813
4814  if (!NumZeros)
4815    return false;
4816
4817  // Considering the elements in the mask that are not consecutive zeros,
4818  // check if they consecutively come from only one of the source vectors.
4819  //
4820  //               V1 = {X, A, B, C}     0
4821  //                         \  \  \    /
4822  //   vector_shuffle V1, V2 <1, 2, 3, X>
4823  //
4824  if (!isShuffleMaskConsecutive(SVOp,
4825            0,                   // Mask Start Index
4826            NumElems-NumZeros-1, // Mask End Index
4827            NumZeros,            // Where to start looking in the src vector
4828            NumElems,            // Number of elements in vector
4829            OpSrc))              // Which source operand ?
4830    return false;
4831
4832  isLeft = false;
4833  ShAmt = NumZeros;
4834  ShVal = SVOp->getOperand(OpSrc);
4835  return true;
4836}
4837
4838/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4839/// logical left shift of a vector.
4840static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4841                              bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4842  unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4843  unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4844              true /* check zeros from left */, DAG);
4845  unsigned OpSrc;
4846
4847  if (!NumZeros)
4848    return false;
4849
4850  // Considering the elements in the mask that are not consecutive zeros,
4851  // check if they consecutively come from only one of the source vectors.
4852  //
4853  //                           0    { A, B, X, X } = V2
4854  //                          / \    /  /
4855  //   vector_shuffle V1, V2 <X, X, 4, 5>
4856  //
4857  if (!isShuffleMaskConsecutive(SVOp,
4858            NumZeros,     // Mask Start Index
4859            NumElems-1,   // Mask End Index
4860            0,            // Where to start looking in the src vector
4861            NumElems,     // Number of elements in vector
4862            OpSrc))       // Which source operand ?
4863    return false;
4864
4865  isLeft = true;
4866  ShAmt = NumZeros;
4867  ShVal = SVOp->getOperand(OpSrc);
4868  return true;
4869}
4870
4871/// isVectorShift - Returns true if the shuffle can be implemented as a
4872/// logical left or right shift of a vector.
4873static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4874                          bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4875  // Although the logic below support any bitwidth size, there are no
4876  // shift instructions which handle more than 128-bit vectors.
4877  if (SVOp->getValueType(0).getSizeInBits() > 128)
4878    return false;
4879
4880  if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4881      isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4882    return true;
4883
4884  return false;
4885}
4886
4887/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4888///
4889static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4890                                       unsigned NumNonZero, unsigned NumZero,
4891                                       SelectionDAG &DAG,
4892                                       const TargetLowering &TLI) {
4893  if (NumNonZero > 8)
4894    return SDValue();
4895
4896  DebugLoc dl = Op.getDebugLoc();
4897  SDValue V(0, 0);
4898  bool First = true;
4899  for (unsigned i = 0; i < 16; ++i) {
4900    bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4901    if (ThisIsNonZero && First) {
4902      if (NumZero)
4903        V = getZeroVector(MVT::v8i16, true, DAG, dl);
4904      else
4905        V = DAG.getUNDEF(MVT::v8i16);
4906      First = false;
4907    }
4908
4909    if ((i & 1) != 0) {
4910      SDValue ThisElt(0, 0), LastElt(0, 0);
4911      bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4912      if (LastIsNonZero) {
4913        LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4914                              MVT::i16, Op.getOperand(i-1));
4915      }
4916      if (ThisIsNonZero) {
4917        ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4918        ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4919                              ThisElt, DAG.getConstant(8, MVT::i8));
4920        if (LastIsNonZero)
4921          ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4922      } else
4923        ThisElt = LastElt;
4924
4925      if (ThisElt.getNode())
4926        V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4927                        DAG.getIntPtrConstant(i/2));
4928    }
4929  }
4930
4931  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4932}
4933
4934/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4935///
4936static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4937                                     unsigned NumNonZero, unsigned NumZero,
4938                                     SelectionDAG &DAG,
4939                                     const TargetLowering &TLI) {
4940  if (NumNonZero > 4)
4941    return SDValue();
4942
4943  DebugLoc dl = Op.getDebugLoc();
4944  SDValue V(0, 0);
4945  bool First = true;
4946  for (unsigned i = 0; i < 8; ++i) {
4947    bool isNonZero = (NonZeros & (1 << i)) != 0;
4948    if (isNonZero) {
4949      if (First) {
4950        if (NumZero)
4951          V = getZeroVector(MVT::v8i16, true, DAG, dl);
4952        else
4953          V = DAG.getUNDEF(MVT::v8i16);
4954        First = false;
4955      }
4956      V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4957                      MVT::v8i16, V, Op.getOperand(i),
4958                      DAG.getIntPtrConstant(i));
4959    }
4960  }
4961
4962  return V;
4963}
4964
4965/// getVShift - Return a vector logical shift node.
4966///
4967static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4968                         unsigned NumBits, SelectionDAG &DAG,
4969                         const TargetLowering &TLI, DebugLoc dl) {
4970  assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4971  EVT ShVT = MVT::v2i64;
4972  unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4973  SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4974  return DAG.getNode(ISD::BITCAST, dl, VT,
4975                     DAG.getNode(Opc, dl, ShVT, SrcOp,
4976                             DAG.getConstant(NumBits,
4977                                  TLI.getShiftAmountTy(SrcOp.getValueType()))));
4978}
4979
4980SDValue
4981X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4982                                          SelectionDAG &DAG) const {
4983
4984  // Check if the scalar load can be widened into a vector load. And if
4985  // the address is "base + cst" see if the cst can be "absorbed" into
4986  // the shuffle mask.
4987  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4988    SDValue Ptr = LD->getBasePtr();
4989    if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4990      return SDValue();
4991    EVT PVT = LD->getValueType(0);
4992    if (PVT != MVT::i32 && PVT != MVT::f32)
4993      return SDValue();
4994
4995    int FI = -1;
4996    int64_t Offset = 0;
4997    if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4998      FI = FINode->getIndex();
4999      Offset = 0;
5000    } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5001               isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5002      FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5003      Offset = Ptr.getConstantOperandVal(1);
5004      Ptr = Ptr.getOperand(0);
5005    } else {
5006      return SDValue();
5007    }
5008
5009    // FIXME: 256-bit vector instructions don't require a strict alignment,
5010    // improve this code to support it better.
5011    unsigned RequiredAlign = VT.getSizeInBits()/8;
5012    SDValue Chain = LD->getChain();
5013    // Make sure the stack object alignment is at least 16 or 32.
5014    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5015    if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5016      if (MFI->isFixedObjectIndex(FI)) {
5017        // Can't change the alignment. FIXME: It's possible to compute
5018        // the exact stack offset and reference FI + adjust offset instead.
5019        // If someone *really* cares about this. That's the way to implement it.
5020        return SDValue();
5021      } else {
5022        MFI->setObjectAlignment(FI, RequiredAlign);
5023      }
5024    }
5025
5026    // (Offset % 16 or 32) must be multiple of 4. Then address is then
5027    // Ptr + (Offset & ~15).
5028    if (Offset < 0)
5029      return SDValue();
5030    if ((Offset % RequiredAlign) & 3)
5031      return SDValue();
5032    int64_t StartOffset = Offset & ~(RequiredAlign-1);
5033    if (StartOffset)
5034      Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5035                        Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5036
5037    int EltNo = (Offset - StartOffset) >> 2;
5038    int NumElems = VT.getVectorNumElements();
5039
5040    EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5041    EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5042    SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5043                             LD->getPointerInfo().getWithOffset(StartOffset),
5044                             false, false, false, 0);
5045
5046    // Canonicalize it to a v4i32 or v8i32 shuffle.
5047    SmallVector<int, 8> Mask;
5048    for (int i = 0; i < NumElems; ++i)
5049      Mask.push_back(EltNo);
5050
5051    V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5052    return DAG.getNode(ISD::BITCAST, dl, NVT,
5053                       DAG.getVectorShuffle(CanonVT, dl, V1,
5054                                            DAG.getUNDEF(CanonVT),&Mask[0]));
5055  }
5056
5057  return SDValue();
5058}
5059
5060/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5061/// vector of type 'VT', see if the elements can be replaced by a single large
5062/// load which has the same value as a build_vector whose operands are 'elts'.
5063///
5064/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5065///
5066/// FIXME: we'd also like to handle the case where the last elements are zero
5067/// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5068/// There's even a handy isZeroNode for that purpose.
5069static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5070                                        DebugLoc &DL, SelectionDAG &DAG) {
5071  EVT EltVT = VT.getVectorElementType();
5072  unsigned NumElems = Elts.size();
5073
5074  LoadSDNode *LDBase = NULL;
5075  unsigned LastLoadedElt = -1U;
5076
5077  // For each element in the initializer, see if we've found a load or an undef.
5078  // If we don't find an initial load element, or later load elements are
5079  // non-consecutive, bail out.
5080  for (unsigned i = 0; i < NumElems; ++i) {
5081    SDValue Elt = Elts[i];
5082
5083    if (!Elt.getNode() ||
5084        (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5085      return SDValue();
5086    if (!LDBase) {
5087      if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5088        return SDValue();
5089      LDBase = cast<LoadSDNode>(Elt.getNode());
5090      LastLoadedElt = i;
5091      continue;
5092    }
5093    if (Elt.getOpcode() == ISD::UNDEF)
5094      continue;
5095
5096    LoadSDNode *LD = cast<LoadSDNode>(Elt);
5097    if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5098      return SDValue();
5099    LastLoadedElt = i;
5100  }
5101
5102  // If we have found an entire vector of loads and undefs, then return a large
5103  // load of the entire vector width starting at the base pointer.  If we found
5104  // consecutive loads for the low half, generate a vzext_load node.
5105  if (LastLoadedElt == NumElems - 1) {
5106    if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5107      return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5108                         LDBase->getPointerInfo(),
5109                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5110                         LDBase->isInvariant(), 0);
5111    return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5112                       LDBase->getPointerInfo(),
5113                       LDBase->isVolatile(), LDBase->isNonTemporal(),
5114                       LDBase->isInvariant(), LDBase->getAlignment());
5115  } else if (NumElems == 4 && LastLoadedElt == 1 &&
5116             DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5117    SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5118    SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5119    SDValue ResNode =
5120        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5121                                LDBase->getPointerInfo(),
5122                                LDBase->getAlignment(),
5123                                false/*isVolatile*/, true/*ReadMem*/,
5124                                false/*WriteMem*/);
5125    return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5126  }
5127  return SDValue();
5128}
5129
5130/// isVectorBroadcast - Check if the node chain is suitable to be xformed to
5131/// a vbroadcast node. We support two patterns:
5132/// 1. A splat BUILD_VECTOR which uses a single scalar load.
5133/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5134/// a scalar load.
5135/// The scalar load node is returned when a pattern is found,
5136/// or SDValue() otherwise.
5137static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
5138  EVT VT = Op.getValueType();
5139  SDValue V = Op;
5140
5141  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5142    V = V.getOperand(0);
5143
5144  //A suspected load to be broadcasted.
5145  SDValue Ld;
5146
5147  switch (V.getOpcode()) {
5148    default:
5149      // Unknown pattern found.
5150      return SDValue();
5151
5152    case ISD::BUILD_VECTOR: {
5153      // The BUILD_VECTOR node must be a splat.
5154      if (!isSplatVector(V.getNode()))
5155        return SDValue();
5156
5157      Ld = V.getOperand(0);
5158
5159      // The suspected load node has several users. Make sure that all
5160      // of its users are from the BUILD_VECTOR node.
5161      if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5162        return SDValue();
5163      break;
5164    }
5165
5166    case ISD::VECTOR_SHUFFLE: {
5167      ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5168
5169      // Shuffles must have a splat mask where the first element is
5170      // broadcasted.
5171      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5172        return SDValue();
5173
5174      SDValue Sc = Op.getOperand(0);
5175      if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5176        return SDValue();
5177
5178      Ld = Sc.getOperand(0);
5179
5180      // The scalar_to_vector node and the suspected
5181      // load node must have exactly one user.
5182      if (!Sc.hasOneUse() || !Ld.hasOneUse())
5183        return SDValue();
5184      break;
5185    }
5186  }
5187
5188  // The scalar source must be a normal load.
5189  if (!ISD::isNormalLoad(Ld.getNode()))
5190    return SDValue();
5191
5192  bool Is256 = VT.getSizeInBits() == 256;
5193  bool Is128 = VT.getSizeInBits() == 128;
5194  unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5195
5196  if (hasAVX2) {
5197    // VBroadcast to YMM
5198    if (Is256 && (ScalarSize == 8  || ScalarSize == 16 ||
5199                  ScalarSize == 32 || ScalarSize == 64 ))
5200      return Ld;
5201
5202    // VBroadcast to XMM
5203    if (Is128 && (ScalarSize ==  8 || ScalarSize == 32 ||
5204                  ScalarSize == 16 || ScalarSize == 64 ))
5205      return Ld;
5206  }
5207
5208  // VBroadcast to YMM
5209  if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5210    return Ld;
5211
5212  // VBroadcast to XMM
5213  if (Is128 && (ScalarSize == 32))
5214    return Ld;
5215
5216
5217  // Unsupported broadcast.
5218  return SDValue();
5219}
5220
5221SDValue
5222X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5223  DebugLoc dl = Op.getDebugLoc();
5224
5225  EVT VT = Op.getValueType();
5226  EVT ExtVT = VT.getVectorElementType();
5227  unsigned NumElems = Op.getNumOperands();
5228
5229  // Vectors containing all zeros can be matched by pxor and xorps later
5230  if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5231    // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5232    // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5233    if (Op.getValueType() == MVT::v4i32 ||
5234        Op.getValueType() == MVT::v8i32)
5235      return Op;
5236
5237    return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5238  }
5239
5240  // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5241  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5242  // vpcmpeqd on 256-bit vectors.
5243  if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5244    if (Op.getValueType() == MVT::v4i32 ||
5245        (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5246      return Op;
5247
5248    return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5249  }
5250
5251  SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5252  if (Subtarget->hasAVX() && LD.getNode())
5253      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5254
5255  unsigned EVTBits = ExtVT.getSizeInBits();
5256
5257  unsigned NumZero  = 0;
5258  unsigned NumNonZero = 0;
5259  unsigned NonZeros = 0;
5260  bool IsAllConstants = true;
5261  SmallSet<SDValue, 8> Values;
5262  for (unsigned i = 0; i < NumElems; ++i) {
5263    SDValue Elt = Op.getOperand(i);
5264    if (Elt.getOpcode() == ISD::UNDEF)
5265      continue;
5266    Values.insert(Elt);
5267    if (Elt.getOpcode() != ISD::Constant &&
5268        Elt.getOpcode() != ISD::ConstantFP)
5269      IsAllConstants = false;
5270    if (X86::isZeroNode(Elt))
5271      NumZero++;
5272    else {
5273      NonZeros |= (1 << i);
5274      NumNonZero++;
5275    }
5276  }
5277
5278  // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5279  if (NumNonZero == 0)
5280    return DAG.getUNDEF(VT);
5281
5282  // Special case for single non-zero, non-undef, element.
5283  if (NumNonZero == 1) {
5284    unsigned Idx = CountTrailingZeros_32(NonZeros);
5285    SDValue Item = Op.getOperand(Idx);
5286
5287    // If this is an insertion of an i64 value on x86-32, and if the top bits of
5288    // the value are obviously zero, truncate the value to i32 and do the
5289    // insertion that way.  Only do this if the value is non-constant or if the
5290    // value is a constant being inserted into element 0.  It is cheaper to do
5291    // a constant pool load than it is to do a movd + shuffle.
5292    if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5293        (!IsAllConstants || Idx == 0)) {
5294      if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5295        // Handle SSE only.
5296        assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5297        EVT VecVT = MVT::v4i32;
5298        unsigned VecElts = 4;
5299
5300        // Truncate the value (which may itself be a constant) to i32, and
5301        // convert it to a vector with movd (S2V+shuffle to zero extend).
5302        Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5303        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5304        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5305                                           Subtarget->hasXMMInt(), DAG);
5306
5307        // Now we have our 32-bit value zero extended in the low element of
5308        // a vector.  If Idx != 0, swizzle it into place.
5309        if (Idx != 0) {
5310          SmallVector<int, 4> Mask;
5311          Mask.push_back(Idx);
5312          for (unsigned i = 1; i != VecElts; ++i)
5313            Mask.push_back(i);
5314          Item = DAG.getVectorShuffle(VecVT, dl, Item,
5315                                      DAG.getUNDEF(Item.getValueType()),
5316                                      &Mask[0]);
5317        }
5318        return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5319      }
5320    }
5321
5322    // If we have a constant or non-constant insertion into the low element of
5323    // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5324    // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5325    // depending on what the source datatype is.
5326    if (Idx == 0) {
5327      if (NumZero == 0) {
5328        return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5329      } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5330          (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5331        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5332        // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5333        return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5334                                           DAG);
5335      } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5336        Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5337        assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5338        EVT MiddleVT = MVT::v4i32;
5339        Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5340        Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5341                                           Subtarget->hasXMMInt(), DAG);
5342        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5343      }
5344    }
5345
5346    // Is it a vector logical left shift?
5347    if (NumElems == 2 && Idx == 1 &&
5348        X86::isZeroNode(Op.getOperand(0)) &&
5349        !X86::isZeroNode(Op.getOperand(1))) {
5350      unsigned NumBits = VT.getSizeInBits();
5351      return getVShift(true, VT,
5352                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5353                                   VT, Op.getOperand(1)),
5354                       NumBits/2, DAG, *this, dl);
5355    }
5356
5357    if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5358      return SDValue();
5359
5360    // Otherwise, if this is a vector with i32 or f32 elements, and the element
5361    // is a non-constant being inserted into an element other than the low one,
5362    // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5363    // movd/movss) to move this into the low element, then shuffle it into
5364    // place.
5365    if (EVTBits == 32) {
5366      Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5367
5368      // Turn it into a shuffle of zero and zero-extended scalar to vector.
5369      Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5370                                         Subtarget->hasXMMInt(), DAG);
5371      SmallVector<int, 8> MaskVec;
5372      for (unsigned i = 0; i < NumElems; i++)
5373        MaskVec.push_back(i == Idx ? 0 : 1);
5374      return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5375    }
5376  }
5377
5378  // Splat is obviously ok. Let legalizer expand it to a shuffle.
5379  if (Values.size() == 1) {
5380    if (EVTBits == 32) {
5381      // Instead of a shuffle like this:
5382      // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5383      // Check if it's possible to issue this instead.
5384      // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5385      unsigned Idx = CountTrailingZeros_32(NonZeros);
5386      SDValue Item = Op.getOperand(Idx);
5387      if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5388        return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5389    }
5390    return SDValue();
5391  }
5392
5393  // A vector full of immediates; various special cases are already
5394  // handled, so this is best done with a single constant-pool load.
5395  if (IsAllConstants)
5396    return SDValue();
5397
5398  // For AVX-length vectors, build the individual 128-bit pieces and use
5399  // shuffles to put them in place.
5400  if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5401    SmallVector<SDValue, 32> V;
5402    for (unsigned i = 0; i < NumElems; ++i)
5403      V.push_back(Op.getOperand(i));
5404
5405    EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5406
5407    // Build both the lower and upper subvector.
5408    SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5409    SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5410                                NumElems/2);
5411
5412    // Recreate the wider vector with the lower and upper part.
5413    SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5414                                DAG.getConstant(0, MVT::i32), DAG, dl);
5415    return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5416                              DAG, dl);
5417  }
5418
5419  // Let legalizer expand 2-wide build_vectors.
5420  if (EVTBits == 64) {
5421    if (NumNonZero == 1) {
5422      // One half is zero or undef.
5423      unsigned Idx = CountTrailingZeros_32(NonZeros);
5424      SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5425                                 Op.getOperand(Idx));
5426      return getShuffleVectorZeroOrUndef(V2, Idx, true,
5427                                         Subtarget->hasXMMInt(), DAG);
5428    }
5429    return SDValue();
5430  }
5431
5432  // If element VT is < 32 bits, convert it to inserts into a zero vector.
5433  if (EVTBits == 8 && NumElems == 16) {
5434    SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5435                                        *this);
5436    if (V.getNode()) return V;
5437  }
5438
5439  if (EVTBits == 16 && NumElems == 8) {
5440    SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5441                                      *this);
5442    if (V.getNode()) return V;
5443  }
5444
5445  // If element VT is == 32 bits, turn it into a number of shuffles.
5446  SmallVector<SDValue, 8> V;
5447  V.resize(NumElems);
5448  if (NumElems == 4 && NumZero > 0) {
5449    for (unsigned i = 0; i < 4; ++i) {
5450      bool isZero = !(NonZeros & (1 << i));
5451      if (isZero)
5452        V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5453      else
5454        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5455    }
5456
5457    for (unsigned i = 0; i < 2; ++i) {
5458      switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5459        default: break;
5460        case 0:
5461          V[i] = V[i*2];  // Must be a zero vector.
5462          break;
5463        case 1:
5464          V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5465          break;
5466        case 2:
5467          V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5468          break;
5469        case 3:
5470          V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5471          break;
5472      }
5473    }
5474
5475    SmallVector<int, 8> MaskVec;
5476    bool Reverse = (NonZeros & 0x3) == 2;
5477    for (unsigned i = 0; i < 2; ++i)
5478      MaskVec.push_back(Reverse ? 1-i : i);
5479    Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5480    for (unsigned i = 0; i < 2; ++i)
5481      MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5482    return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5483  }
5484
5485  if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5486    // Check for a build vector of consecutive loads.
5487    for (unsigned i = 0; i < NumElems; ++i)
5488      V[i] = Op.getOperand(i);
5489
5490    // Check for elements which are consecutive loads.
5491    SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5492    if (LD.getNode())
5493      return LD;
5494
5495    // For SSE 4.1, use insertps to put the high elements into the low element.
5496    if (getSubtarget()->hasSSE41orAVX()) {
5497      SDValue Result;
5498      if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5499        Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5500      else
5501        Result = DAG.getUNDEF(VT);
5502
5503      for (unsigned i = 1; i < NumElems; ++i) {
5504        if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5505        Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5506                             Op.getOperand(i), DAG.getIntPtrConstant(i));
5507      }
5508      return Result;
5509    }
5510
5511    // Otherwise, expand into a number of unpckl*, start by extending each of
5512    // our (non-undef) elements to the full vector width with the element in the
5513    // bottom slot of the vector (which generates no code for SSE).
5514    for (unsigned i = 0; i < NumElems; ++i) {
5515      if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5516        V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5517      else
5518        V[i] = DAG.getUNDEF(VT);
5519    }
5520
5521    // Next, we iteratively mix elements, e.g. for v4f32:
5522    //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5523    //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5524    //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5525    unsigned EltStride = NumElems >> 1;
5526    while (EltStride != 0) {
5527      for (unsigned i = 0; i < EltStride; ++i) {
5528        // If V[i+EltStride] is undef and this is the first round of mixing,
5529        // then it is safe to just drop this shuffle: V[i] is already in the
5530        // right place, the one element (since it's the first round) being
5531        // inserted as undef can be dropped.  This isn't safe for successive
5532        // rounds because they will permute elements within both vectors.
5533        if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5534            EltStride == NumElems/2)
5535          continue;
5536
5537        V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5538      }
5539      EltStride >>= 1;
5540    }
5541    return V[0];
5542  }
5543  return SDValue();
5544}
5545
5546// LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5547// them in a MMX register.  This is better than doing a stack convert.
5548static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5549  DebugLoc dl = Op.getDebugLoc();
5550  EVT ResVT = Op.getValueType();
5551
5552  assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5553         ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5554  int Mask[2];
5555  SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5556  SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5557  InVec = Op.getOperand(1);
5558  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5559    unsigned NumElts = ResVT.getVectorNumElements();
5560    VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5561    VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5562                       InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5563  } else {
5564    InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5565    SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5566    Mask[0] = 0; Mask[1] = 2;
5567    VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5568  }
5569  return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5570}
5571
5572// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5573// to create 256-bit vectors from two other 128-bit ones.
5574static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5575  DebugLoc dl = Op.getDebugLoc();
5576  EVT ResVT = Op.getValueType();
5577
5578  assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5579
5580  SDValue V1 = Op.getOperand(0);
5581  SDValue V2 = Op.getOperand(1);
5582  unsigned NumElems = ResVT.getVectorNumElements();
5583
5584  SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5585                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5586  return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5587                            DAG, dl);
5588}
5589
5590SDValue
5591X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5592  EVT ResVT = Op.getValueType();
5593
5594  assert(Op.getNumOperands() == 2);
5595  assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5596         "Unsupported CONCAT_VECTORS for value type");
5597
5598  // We support concatenate two MMX registers and place them in a MMX register.
5599  // This is better than doing a stack convert.
5600  if (ResVT.is128BitVector())
5601    return LowerMMXCONCAT_VECTORS(Op, DAG);
5602
5603  // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5604  // from two other 128-bit ones.
5605  return LowerAVXCONCAT_VECTORS(Op, DAG);
5606}
5607
5608// v8i16 shuffles - Prefer shuffles in the following order:
5609// 1. [all]   pshuflw, pshufhw, optional move
5610// 2. [ssse3] 1 x pshufb
5611// 3. [ssse3] 2 x pshufb + 1 x por
5612// 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5613SDValue
5614X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5615                                            SelectionDAG &DAG) const {
5616  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5617  SDValue V1 = SVOp->getOperand(0);
5618  SDValue V2 = SVOp->getOperand(1);
5619  DebugLoc dl = SVOp->getDebugLoc();
5620  SmallVector<int, 8> MaskVals;
5621
5622  // Determine if more than 1 of the words in each of the low and high quadwords
5623  // of the result come from the same quadword of one of the two inputs.  Undef
5624  // mask values count as coming from any quadword, for better codegen.
5625  unsigned LoQuad[] = { 0, 0, 0, 0 };
5626  unsigned HiQuad[] = { 0, 0, 0, 0 };
5627  BitVector InputQuads(4);
5628  for (unsigned i = 0; i < 8; ++i) {
5629    unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5630    int EltIdx = SVOp->getMaskElt(i);
5631    MaskVals.push_back(EltIdx);
5632    if (EltIdx < 0) {
5633      ++Quad[0];
5634      ++Quad[1];
5635      ++Quad[2];
5636      ++Quad[3];
5637      continue;
5638    }
5639    ++Quad[EltIdx / 4];
5640    InputQuads.set(EltIdx / 4);
5641  }
5642
5643  int BestLoQuad = -1;
5644  unsigned MaxQuad = 1;
5645  for (unsigned i = 0; i < 4; ++i) {
5646    if (LoQuad[i] > MaxQuad) {
5647      BestLoQuad = i;
5648      MaxQuad = LoQuad[i];
5649    }
5650  }
5651
5652  int BestHiQuad = -1;
5653  MaxQuad = 1;
5654  for (unsigned i = 0; i < 4; ++i) {
5655    if (HiQuad[i] > MaxQuad) {
5656      BestHiQuad = i;
5657      MaxQuad = HiQuad[i];
5658    }
5659  }
5660
5661  // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5662  // of the two input vectors, shuffle them into one input vector so only a
5663  // single pshufb instruction is necessary. If There are more than 2 input
5664  // quads, disable the next transformation since it does not help SSSE3.
5665  bool V1Used = InputQuads[0] || InputQuads[1];
5666  bool V2Used = InputQuads[2] || InputQuads[3];
5667  if (Subtarget->hasSSSE3orAVX()) {
5668    if (InputQuads.count() == 2 && V1Used && V2Used) {
5669      BestLoQuad = InputQuads.find_first();
5670      BestHiQuad = InputQuads.find_next(BestLoQuad);
5671    }
5672    if (InputQuads.count() > 2) {
5673      BestLoQuad = -1;
5674      BestHiQuad = -1;
5675    }
5676  }
5677
5678  // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5679  // the shuffle mask.  If a quad is scored as -1, that means that it contains
5680  // words from all 4 input quadwords.
5681  SDValue NewV;
5682  if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5683    SmallVector<int, 8> MaskV;
5684    MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5685    MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5686    NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5687                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5688                  DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5689    NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5690
5691    // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5692    // source words for the shuffle, to aid later transformations.
5693    bool AllWordsInNewV = true;
5694    bool InOrder[2] = { true, true };
5695    for (unsigned i = 0; i != 8; ++i) {
5696      int idx = MaskVals[i];
5697      if (idx != (int)i)
5698        InOrder[i/4] = false;
5699      if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5700        continue;
5701      AllWordsInNewV = false;
5702      break;
5703    }
5704
5705    bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5706    if (AllWordsInNewV) {
5707      for (int i = 0; i != 8; ++i) {
5708        int idx = MaskVals[i];
5709        if (idx < 0)
5710          continue;
5711        idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5712        if ((idx != i) && idx < 4)
5713          pshufhw = false;
5714        if ((idx != i) && idx > 3)
5715          pshuflw = false;
5716      }
5717      V1 = NewV;
5718      V2Used = false;
5719      BestLoQuad = 0;
5720      BestHiQuad = 1;
5721    }
5722
5723    // If we've eliminated the use of V2, and the new mask is a pshuflw or
5724    // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5725    if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5726      unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5727      unsigned TargetMask = 0;
5728      NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5729                                  DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5730      TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5731                             X86::getShufflePSHUFLWImmediate(NewV.getNode());
5732      V1 = NewV.getOperand(0);
5733      return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5734    }
5735  }
5736
5737  // If we have SSSE3, and all words of the result are from 1 input vector,
5738  // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5739  // is present, fall back to case 4.
5740  if (Subtarget->hasSSSE3orAVX()) {
5741    SmallVector<SDValue,16> pshufbMask;
5742
5743    // If we have elements from both input vectors, set the high bit of the
5744    // shuffle mask element to zero out elements that come from V2 in the V1
5745    // mask, and elements that come from V1 in the V2 mask, so that the two
5746    // results can be OR'd together.
5747    bool TwoInputs = V1Used && V2Used;
5748    for (unsigned i = 0; i != 8; ++i) {
5749      int EltIdx = MaskVals[i] * 2;
5750      if (TwoInputs && (EltIdx >= 16)) {
5751        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5752        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5753        continue;
5754      }
5755      pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5756      pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5757    }
5758    V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5759    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5760                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5761                                 MVT::v16i8, &pshufbMask[0], 16));
5762    if (!TwoInputs)
5763      return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5764
5765    // Calculate the shuffle mask for the second input, shuffle it, and
5766    // OR it with the first shuffled input.
5767    pshufbMask.clear();
5768    for (unsigned i = 0; i != 8; ++i) {
5769      int EltIdx = MaskVals[i] * 2;
5770      if (EltIdx < 16) {
5771        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5772        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5773        continue;
5774      }
5775      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5776      pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5777    }
5778    V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5779    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5780                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5781                                 MVT::v16i8, &pshufbMask[0], 16));
5782    V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5783    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5784  }
5785
5786  // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5787  // and update MaskVals with new element order.
5788  BitVector InOrder(8);
5789  if (BestLoQuad >= 0) {
5790    SmallVector<int, 8> MaskV;
5791    for (int i = 0; i != 4; ++i) {
5792      int idx = MaskVals[i];
5793      if (idx < 0) {
5794        MaskV.push_back(-1);
5795        InOrder.set(i);
5796      } else if ((idx / 4) == BestLoQuad) {
5797        MaskV.push_back(idx & 3);
5798        InOrder.set(i);
5799      } else {
5800        MaskV.push_back(-1);
5801      }
5802    }
5803    for (unsigned i = 4; i != 8; ++i)
5804      MaskV.push_back(i);
5805    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5806                                &MaskV[0]);
5807
5808    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5809      NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5810                               NewV.getOperand(0),
5811                               X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5812                               DAG);
5813  }
5814
5815  // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5816  // and update MaskVals with the new element order.
5817  if (BestHiQuad >= 0) {
5818    SmallVector<int, 8> MaskV;
5819    for (unsigned i = 0; i != 4; ++i)
5820      MaskV.push_back(i);
5821    for (unsigned i = 4; i != 8; ++i) {
5822      int idx = MaskVals[i];
5823      if (idx < 0) {
5824        MaskV.push_back(-1);
5825        InOrder.set(i);
5826      } else if ((idx / 4) == BestHiQuad) {
5827        MaskV.push_back((idx & 3) + 4);
5828        InOrder.set(i);
5829      } else {
5830        MaskV.push_back(-1);
5831      }
5832    }
5833    NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5834                                &MaskV[0]);
5835
5836    if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5837      NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5838                              NewV.getOperand(0),
5839                              X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5840                              DAG);
5841  }
5842
5843  // In case BestHi & BestLo were both -1, which means each quadword has a word
5844  // from each of the four input quadwords, calculate the InOrder bitvector now
5845  // before falling through to the insert/extract cleanup.
5846  if (BestLoQuad == -1 && BestHiQuad == -1) {
5847    NewV = V1;
5848    for (int i = 0; i != 8; ++i)
5849      if (MaskVals[i] < 0 || MaskVals[i] == i)
5850        InOrder.set(i);
5851  }
5852
5853  // The other elements are put in the right place using pextrw and pinsrw.
5854  for (unsigned i = 0; i != 8; ++i) {
5855    if (InOrder[i])
5856      continue;
5857    int EltIdx = MaskVals[i];
5858    if (EltIdx < 0)
5859      continue;
5860    SDValue ExtOp = (EltIdx < 8)
5861    ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5862                  DAG.getIntPtrConstant(EltIdx))
5863    : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5864                  DAG.getIntPtrConstant(EltIdx - 8));
5865    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5866                       DAG.getIntPtrConstant(i));
5867  }
5868  return NewV;
5869}
5870
5871// v16i8 shuffles - Prefer shuffles in the following order:
5872// 1. [ssse3] 1 x pshufb
5873// 2. [ssse3] 2 x pshufb + 1 x por
5874// 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5875static
5876SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5877                                 SelectionDAG &DAG,
5878                                 const X86TargetLowering &TLI) {
5879  SDValue V1 = SVOp->getOperand(0);
5880  SDValue V2 = SVOp->getOperand(1);
5881  DebugLoc dl = SVOp->getDebugLoc();
5882  SmallVector<int, 16> MaskVals;
5883  SVOp->getMask(MaskVals);
5884
5885  // If we have SSSE3, case 1 is generated when all result bytes come from
5886  // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5887  // present, fall back to case 3.
5888  // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5889  bool V1Only = true;
5890  bool V2Only = true;
5891  for (unsigned i = 0; i < 16; ++i) {
5892    int EltIdx = MaskVals[i];
5893    if (EltIdx < 0)
5894      continue;
5895    if (EltIdx < 16)
5896      V2Only = false;
5897    else
5898      V1Only = false;
5899  }
5900
5901  // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5902  if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5903    SmallVector<SDValue,16> pshufbMask;
5904
5905    // If all result elements are from one input vector, then only translate
5906    // undef mask values to 0x80 (zero out result) in the pshufb mask.
5907    //
5908    // Otherwise, we have elements from both input vectors, and must zero out
5909    // elements that come from V2 in the first mask, and V1 in the second mask
5910    // so that we can OR them together.
5911    bool TwoInputs = !(V1Only || V2Only);
5912    for (unsigned i = 0; i != 16; ++i) {
5913      int EltIdx = MaskVals[i];
5914      if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5915        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5916        continue;
5917      }
5918      pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5919    }
5920    // If all the elements are from V2, assign it to V1 and return after
5921    // building the first pshufb.
5922    if (V2Only)
5923      V1 = V2;
5924    V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5925                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5926                                 MVT::v16i8, &pshufbMask[0], 16));
5927    if (!TwoInputs)
5928      return V1;
5929
5930    // Calculate the shuffle mask for the second input, shuffle it, and
5931    // OR it with the first shuffled input.
5932    pshufbMask.clear();
5933    for (unsigned i = 0; i != 16; ++i) {
5934      int EltIdx = MaskVals[i];
5935      if (EltIdx < 16) {
5936        pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5937        continue;
5938      }
5939      pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5940    }
5941    V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5942                     DAG.getNode(ISD::BUILD_VECTOR, dl,
5943                                 MVT::v16i8, &pshufbMask[0], 16));
5944    return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5945  }
5946
5947  // No SSSE3 - Calculate in place words and then fix all out of place words
5948  // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5949  // the 16 different words that comprise the two doublequadword input vectors.
5950  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5951  V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5952  SDValue NewV = V2Only ? V2 : V1;
5953  for (int i = 0; i != 8; ++i) {
5954    int Elt0 = MaskVals[i*2];
5955    int Elt1 = MaskVals[i*2+1];
5956
5957    // This word of the result is all undef, skip it.
5958    if (Elt0 < 0 && Elt1 < 0)
5959      continue;
5960
5961    // This word of the result is already in the correct place, skip it.
5962    if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5963      continue;
5964    if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5965      continue;
5966
5967    SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5968    SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5969    SDValue InsElt;
5970
5971    // If Elt0 and Elt1 are defined, are consecutive, and can be load
5972    // using a single extract together, load it and store it.
5973    if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5974      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5975                           DAG.getIntPtrConstant(Elt1 / 2));
5976      NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5977                        DAG.getIntPtrConstant(i));
5978      continue;
5979    }
5980
5981    // If Elt1 is defined, extract it from the appropriate source.  If the
5982    // source byte is not also odd, shift the extracted word left 8 bits
5983    // otherwise clear the bottom 8 bits if we need to do an or.
5984    if (Elt1 >= 0) {
5985      InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5986                           DAG.getIntPtrConstant(Elt1 / 2));
5987      if ((Elt1 & 1) == 0)
5988        InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5989                             DAG.getConstant(8,
5990                                  TLI.getShiftAmountTy(InsElt.getValueType())));
5991      else if (Elt0 >= 0)
5992        InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5993                             DAG.getConstant(0xFF00, MVT::i16));
5994    }
5995    // If Elt0 is defined, extract it from the appropriate source.  If the
5996    // source byte is not also even, shift the extracted word right 8 bits. If
5997    // Elt1 was also defined, OR the extracted values together before
5998    // inserting them in the result.
5999    if (Elt0 >= 0) {
6000      SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6001                                    Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6002      if ((Elt0 & 1) != 0)
6003        InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6004                              DAG.getConstant(8,
6005                                 TLI.getShiftAmountTy(InsElt0.getValueType())));
6006      else if (Elt1 >= 0)
6007        InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6008                             DAG.getConstant(0x00FF, MVT::i16));
6009      InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6010                         : InsElt0;
6011    }
6012    NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6013                       DAG.getIntPtrConstant(i));
6014  }
6015  return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6016}
6017
6018/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6019/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6020/// done when every pair / quad of shuffle mask elements point to elements in
6021/// the right sequence. e.g.
6022/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6023static
6024SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6025                                 SelectionDAG &DAG, DebugLoc dl) {
6026  EVT VT = SVOp->getValueType(0);
6027  SDValue V1 = SVOp->getOperand(0);
6028  SDValue V2 = SVOp->getOperand(1);
6029  unsigned NumElems = VT.getVectorNumElements();
6030  unsigned NewWidth = (NumElems == 4) ? 2 : 4;
6031  EVT NewVT;
6032  switch (VT.getSimpleVT().SimpleTy) {
6033  default: assert(false && "Unexpected!");
6034  case MVT::v4f32: NewVT = MVT::v2f64; break;
6035  case MVT::v4i32: NewVT = MVT::v2i64; break;
6036  case MVT::v8i16: NewVT = MVT::v4i32; break;
6037  case MVT::v16i8: NewVT = MVT::v4i32; break;
6038  }
6039
6040  int Scale = NumElems / NewWidth;
6041  SmallVector<int, 8> MaskVec;
6042  for (unsigned i = 0; i < NumElems; i += Scale) {
6043    int StartIdx = -1;
6044    for (int j = 0; j < Scale; ++j) {
6045      int EltIdx = SVOp->getMaskElt(i+j);
6046      if (EltIdx < 0)
6047        continue;
6048      if (StartIdx == -1)
6049        StartIdx = EltIdx - (EltIdx % Scale);
6050      if (EltIdx != StartIdx + j)
6051        return SDValue();
6052    }
6053    if (StartIdx == -1)
6054      MaskVec.push_back(-1);
6055    else
6056      MaskVec.push_back(StartIdx / Scale);
6057  }
6058
6059  V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
6060  V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
6061  return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6062}
6063
6064/// getVZextMovL - Return a zero-extending vector move low node.
6065///
6066static SDValue getVZextMovL(EVT VT, EVT OpVT,
6067                            SDValue SrcOp, SelectionDAG &DAG,
6068                            const X86Subtarget *Subtarget, DebugLoc dl) {
6069  if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6070    LoadSDNode *LD = NULL;
6071    if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6072      LD = dyn_cast<LoadSDNode>(SrcOp);
6073    if (!LD) {
6074      // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6075      // instead.
6076      MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6077      if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6078          SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6079          SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6080          SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6081        // PR2108
6082        OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6083        return DAG.getNode(ISD::BITCAST, dl, VT,
6084                           DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6085                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6086                                                   OpVT,
6087                                                   SrcOp.getOperand(0)
6088                                                          .getOperand(0))));
6089      }
6090    }
6091  }
6092
6093  return DAG.getNode(ISD::BITCAST, dl, VT,
6094                     DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6095                                 DAG.getNode(ISD::BITCAST, dl,
6096                                             OpVT, SrcOp)));
6097}
6098
6099/// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
6100/// shuffle node referes to only one lane in the sources.
6101static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
6102  EVT VT = SVOp->getValueType(0);
6103  int NumElems = VT.getVectorNumElements();
6104  int HalfSize = NumElems/2;
6105  SmallVector<int, 16> M;
6106  SVOp->getMask(M);
6107  bool MatchA = false, MatchB = false;
6108
6109  for (int l = 0; l < NumElems*2; l += HalfSize) {
6110    if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
6111      MatchA = true;
6112      break;
6113    }
6114  }
6115
6116  for (int l = 0; l < NumElems*2; l += HalfSize) {
6117    if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6118      MatchB = true;
6119      break;
6120    }
6121  }
6122
6123  return MatchA && MatchB;
6124}
6125
6126/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6127/// which could not be matched by any known target speficic shuffle
6128static SDValue
6129LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6130  if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6131    // If each half of a vector shuffle node referes to only one lane in the
6132    // source vectors, extract each used 128-bit lane and shuffle them using
6133    // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6134    // the work to the legalizer.
6135    DebugLoc dl = SVOp->getDebugLoc();
6136    EVT VT = SVOp->getValueType(0);
6137    int NumElems = VT.getVectorNumElements();
6138    int HalfSize = NumElems/2;
6139
6140    // Extract the reference for each half
6141    int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6142    int FstVecOpNum = 0, SndVecOpNum = 0;
6143    for (int i = 0; i < HalfSize; ++i) {
6144      int Elt = SVOp->getMaskElt(i);
6145      if (SVOp->getMaskElt(i) < 0)
6146        continue;
6147      FstVecOpNum = Elt/NumElems;
6148      FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6149      break;
6150    }
6151    for (int i = HalfSize; i < NumElems; ++i) {
6152      int Elt = SVOp->getMaskElt(i);
6153      if (SVOp->getMaskElt(i) < 0)
6154        continue;
6155      SndVecOpNum = Elt/NumElems;
6156      SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6157      break;
6158    }
6159
6160    // Extract the subvectors
6161    SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6162                      DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6163    SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6164                      DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6165
6166    // Generate 128-bit shuffles
6167    SmallVector<int, 16> MaskV1, MaskV2;
6168    for (int i = 0; i < HalfSize; ++i) {
6169      int Elt = SVOp->getMaskElt(i);
6170      MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6171    }
6172    for (int i = HalfSize; i < NumElems; ++i) {
6173      int Elt = SVOp->getMaskElt(i);
6174      MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6175    }
6176
6177    EVT NVT = V1.getValueType();
6178    V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6179    V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6180
6181    // Concatenate the result back
6182    SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6183                                   DAG.getConstant(0, MVT::i32), DAG, dl);
6184    return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6185                              DAG, dl);
6186  }
6187
6188  return SDValue();
6189}
6190
6191/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6192/// 4 elements, and match them with several different shuffle types.
6193static SDValue
6194LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6195  SDValue V1 = SVOp->getOperand(0);
6196  SDValue V2 = SVOp->getOperand(1);
6197  DebugLoc dl = SVOp->getDebugLoc();
6198  EVT VT = SVOp->getValueType(0);
6199
6200  assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6201
6202  SmallVector<std::pair<int, int>, 8> Locs;
6203  Locs.resize(4);
6204  SmallVector<int, 8> Mask1(4U, -1);
6205  SmallVector<int, 8> PermMask;
6206  SVOp->getMask(PermMask);
6207
6208  unsigned NumHi = 0;
6209  unsigned NumLo = 0;
6210  for (unsigned i = 0; i != 4; ++i) {
6211    int Idx = PermMask[i];
6212    if (Idx < 0) {
6213      Locs[i] = std::make_pair(-1, -1);
6214    } else {
6215      assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6216      if (Idx < 4) {
6217        Locs[i] = std::make_pair(0, NumLo);
6218        Mask1[NumLo] = Idx;
6219        NumLo++;
6220      } else {
6221        Locs[i] = std::make_pair(1, NumHi);
6222        if (2+NumHi < 4)
6223          Mask1[2+NumHi] = Idx;
6224        NumHi++;
6225      }
6226    }
6227  }
6228
6229  if (NumLo <= 2 && NumHi <= 2) {
6230    // If no more than two elements come from either vector. This can be
6231    // implemented with two shuffles. First shuffle gather the elements.
6232    // The second shuffle, which takes the first shuffle as both of its
6233    // vector operands, put the elements into the right order.
6234    V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6235
6236    SmallVector<int, 8> Mask2(4U, -1);
6237
6238    for (unsigned i = 0; i != 4; ++i) {
6239      if (Locs[i].first == -1)
6240        continue;
6241      else {
6242        unsigned Idx = (i < 2) ? 0 : 4;
6243        Idx += Locs[i].first * 2 + Locs[i].second;
6244        Mask2[i] = Idx;
6245      }
6246    }
6247
6248    return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6249  } else if (NumLo == 3 || NumHi == 3) {
6250    // Otherwise, we must have three elements from one vector, call it X, and
6251    // one element from the other, call it Y.  First, use a shufps to build an
6252    // intermediate vector with the one element from Y and the element from X
6253    // that will be in the same half in the final destination (the indexes don't
6254    // matter). Then, use a shufps to build the final vector, taking the half
6255    // containing the element from Y from the intermediate, and the other half
6256    // from X.
6257    if (NumHi == 3) {
6258      // Normalize it so the 3 elements come from V1.
6259      CommuteVectorShuffleMask(PermMask, VT);
6260      std::swap(V1, V2);
6261    }
6262
6263    // Find the element from V2.
6264    unsigned HiIndex;
6265    for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6266      int Val = PermMask[HiIndex];
6267      if (Val < 0)
6268        continue;
6269      if (Val >= 4)
6270        break;
6271    }
6272
6273    Mask1[0] = PermMask[HiIndex];
6274    Mask1[1] = -1;
6275    Mask1[2] = PermMask[HiIndex^1];
6276    Mask1[3] = -1;
6277    V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6278
6279    if (HiIndex >= 2) {
6280      Mask1[0] = PermMask[0];
6281      Mask1[1] = PermMask[1];
6282      Mask1[2] = HiIndex & 1 ? 6 : 4;
6283      Mask1[3] = HiIndex & 1 ? 4 : 6;
6284      return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6285    } else {
6286      Mask1[0] = HiIndex & 1 ? 2 : 0;
6287      Mask1[1] = HiIndex & 1 ? 0 : 2;
6288      Mask1[2] = PermMask[2];
6289      Mask1[3] = PermMask[3];
6290      if (Mask1[2] >= 0)
6291        Mask1[2] += 4;
6292      if (Mask1[3] >= 0)
6293        Mask1[3] += 4;
6294      return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6295    }
6296  }
6297
6298  // Break it into (shuffle shuffle_hi, shuffle_lo).
6299  Locs.clear();
6300  Locs.resize(4);
6301  SmallVector<int,8> LoMask(4U, -1);
6302  SmallVector<int,8> HiMask(4U, -1);
6303
6304  SmallVector<int,8> *MaskPtr = &LoMask;
6305  unsigned MaskIdx = 0;
6306  unsigned LoIdx = 0;
6307  unsigned HiIdx = 2;
6308  for (unsigned i = 0; i != 4; ++i) {
6309    if (i == 2) {
6310      MaskPtr = &HiMask;
6311      MaskIdx = 1;
6312      LoIdx = 0;
6313      HiIdx = 2;
6314    }
6315    int Idx = PermMask[i];
6316    if (Idx < 0) {
6317      Locs[i] = std::make_pair(-1, -1);
6318    } else if (Idx < 4) {
6319      Locs[i] = std::make_pair(MaskIdx, LoIdx);
6320      (*MaskPtr)[LoIdx] = Idx;
6321      LoIdx++;
6322    } else {
6323      Locs[i] = std::make_pair(MaskIdx, HiIdx);
6324      (*MaskPtr)[HiIdx] = Idx;
6325      HiIdx++;
6326    }
6327  }
6328
6329  SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6330  SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6331  SmallVector<int, 8> MaskOps;
6332  for (unsigned i = 0; i != 4; ++i) {
6333    if (Locs[i].first == -1) {
6334      MaskOps.push_back(-1);
6335    } else {
6336      unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6337      MaskOps.push_back(Idx);
6338    }
6339  }
6340  return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6341}
6342
6343static bool MayFoldVectorLoad(SDValue V) {
6344  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6345    V = V.getOperand(0);
6346  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6347    V = V.getOperand(0);
6348  if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6349      V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6350    // BUILD_VECTOR (load), undef
6351    V = V.getOperand(0);
6352  if (MayFoldLoad(V))
6353    return true;
6354  return false;
6355}
6356
6357// FIXME: the version above should always be used. Since there's
6358// a bug where several vector shuffles can't be folded because the
6359// DAG is not updated during lowering and a node claims to have two
6360// uses while it only has one, use this version, and let isel match
6361// another instruction if the load really happens to have more than
6362// one use. Remove this version after this bug get fixed.
6363// rdar://8434668, PR8156
6364static bool RelaxedMayFoldVectorLoad(SDValue V) {
6365  if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6366    V = V.getOperand(0);
6367  if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6368    V = V.getOperand(0);
6369  if (ISD::isNormalLoad(V.getNode()))
6370    return true;
6371  return false;
6372}
6373
6374/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6375/// a vector extract, and if both can be later optimized into a single load.
6376/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6377/// here because otherwise a target specific shuffle node is going to be
6378/// emitted for this shuffle, and the optimization not done.
6379/// FIXME: This is probably not the best approach, but fix the problem
6380/// until the right path is decided.
6381static
6382bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6383                                         const TargetLowering &TLI) {
6384  EVT VT = V.getValueType();
6385  ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6386
6387  // Be sure that the vector shuffle is present in a pattern like this:
6388  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6389  if (!V.hasOneUse())
6390    return false;
6391
6392  SDNode *N = *V.getNode()->use_begin();
6393  if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6394    return false;
6395
6396  SDValue EltNo = N->getOperand(1);
6397  if (!isa<ConstantSDNode>(EltNo))
6398    return false;
6399
6400  // If the bit convert changed the number of elements, it is unsafe
6401  // to examine the mask.
6402  bool HasShuffleIntoBitcast = false;
6403  if (V.getOpcode() == ISD::BITCAST) {
6404    EVT SrcVT = V.getOperand(0).getValueType();
6405    if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6406      return false;
6407    V = V.getOperand(0);
6408    HasShuffleIntoBitcast = true;
6409  }
6410
6411  // Select the input vector, guarding against out of range extract vector.
6412  unsigned NumElems = VT.getVectorNumElements();
6413  unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6414  int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6415  V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6416
6417  // Skip one more bit_convert if necessary
6418  if (V.getOpcode() == ISD::BITCAST)
6419    V = V.getOperand(0);
6420
6421  if (ISD::isNormalLoad(V.getNode())) {
6422    // Is the original load suitable?
6423    LoadSDNode *LN0 = cast<LoadSDNode>(V);
6424
6425    // FIXME: avoid the multi-use bug that is preventing lots of
6426    // of foldings to be detected, this is still wrong of course, but
6427    // give the temporary desired behavior, and if it happens that
6428    // the load has real more uses, during isel it will not fold, and
6429    // will generate poor code.
6430    if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6431      return false;
6432
6433    if (!HasShuffleIntoBitcast)
6434      return true;
6435
6436    // If there's a bitcast before the shuffle, check if the load type and
6437    // alignment is valid.
6438    unsigned Align = LN0->getAlignment();
6439    unsigned NewAlign =
6440      TLI.getTargetData()->getABITypeAlignment(
6441                                    VT.getTypeForEVT(*DAG.getContext()));
6442
6443    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6444      return false;
6445  }
6446
6447  return true;
6448}
6449
6450static
6451SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6452  EVT VT = Op.getValueType();
6453
6454  // Canonizalize to v2f64.
6455  V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6456  return DAG.getNode(ISD::BITCAST, dl, VT,
6457                     getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6458                                          V1, DAG));
6459}
6460
6461static
6462SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6463                        bool HasXMMInt) {
6464  SDValue V1 = Op.getOperand(0);
6465  SDValue V2 = Op.getOperand(1);
6466  EVT VT = Op.getValueType();
6467
6468  assert(VT != MVT::v2i64 && "unsupported shuffle type");
6469
6470  if (HasXMMInt && VT == MVT::v2f64)
6471    return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6472
6473  // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6474  return DAG.getNode(ISD::BITCAST, dl, VT,
6475                     getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6476                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6477                           DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6478}
6479
6480static
6481SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6482  SDValue V1 = Op.getOperand(0);
6483  SDValue V2 = Op.getOperand(1);
6484  EVT VT = Op.getValueType();
6485
6486  assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6487         "unsupported shuffle type");
6488
6489  if (V2.getOpcode() == ISD::UNDEF)
6490    V2 = V1;
6491
6492  // v4i32 or v4f32
6493  return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6494}
6495
6496static inline unsigned getSHUFPOpcode(EVT VT) {
6497  switch(VT.getSimpleVT().SimpleTy) {
6498  case MVT::v8i32: // Use fp unit for int unpack.
6499  case MVT::v8f32:
6500  case MVT::v4i32: // Use fp unit for int unpack.
6501  case MVT::v4f32: return X86ISD::SHUFPS;
6502  case MVT::v4i64: // Use fp unit for int unpack.
6503  case MVT::v4f64:
6504  case MVT::v2i64: // Use fp unit for int unpack.
6505  case MVT::v2f64: return X86ISD::SHUFPD;
6506  default:
6507    llvm_unreachable("Unknown type for shufp*");
6508  }
6509  return 0;
6510}
6511
6512static
6513SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6514  SDValue V1 = Op.getOperand(0);
6515  SDValue V2 = Op.getOperand(1);
6516  EVT VT = Op.getValueType();
6517  unsigned NumElems = VT.getVectorNumElements();
6518
6519  // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6520  // operand of these instructions is only memory, so check if there's a
6521  // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6522  // same masks.
6523  bool CanFoldLoad = false;
6524
6525  // Trivial case, when V2 comes from a load.
6526  if (MayFoldVectorLoad(V2))
6527    CanFoldLoad = true;
6528
6529  // When V1 is a load, it can be folded later into a store in isel, example:
6530  //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6531  //    turns into:
6532  //  (MOVLPSmr addr:$src1, VR128:$src2)
6533  // So, recognize this potential and also use MOVLPS or MOVLPD
6534  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6535    CanFoldLoad = true;
6536
6537  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6538  if (CanFoldLoad) {
6539    if (HasXMMInt && NumElems == 2)
6540      return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6541
6542    if (NumElems == 4)
6543      // If we don't care about the second element, procede to use movss.
6544      if (SVOp->getMaskElt(1) != -1)
6545        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6546  }
6547
6548  // movl and movlp will both match v2i64, but v2i64 is never matched by
6549  // movl earlier because we make it strict to avoid messing with the movlp load
6550  // folding logic (see the code above getMOVLP call). Match it here then,
6551  // this is horrible, but will stay like this until we move all shuffle
6552  // matching to x86 specific nodes. Note that for the 1st condition all
6553  // types are matched with movsd.
6554  if (HasXMMInt) {
6555    // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6556    // as to remove this logic from here, as much as possible
6557    if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6558      return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6559    return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6560  }
6561
6562  assert(VT != MVT::v4i32 && "unsupported shuffle type");
6563
6564  // Invert the operand order and use SHUFPS to match it.
6565  return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6566                              X86::getShuffleSHUFImmediate(SVOp), DAG);
6567}
6568
6569static inline unsigned getUNPCKLOpcode(EVT VT, bool HasAVX2) {
6570  switch(VT.getSimpleVT().SimpleTy) {
6571  case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6572  case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6573  case MVT::v8i32:
6574    if (HasAVX2)   return X86ISD::PUNPCKLDQ;
6575    // else use fp unit for int unpack.
6576  case MVT::v8f32:
6577  case MVT::v4f32: return X86ISD::UNPCKLPS;
6578  case MVT::v4i64:
6579    if (HasAVX2)   return X86ISD::PUNPCKLQDQ;
6580    // else use fp unit for int unpack.
6581  case MVT::v4f64:
6582  case MVT::v2f64: return X86ISD::UNPCKLPD;
6583  case MVT::v32i8:
6584  case MVT::v16i8: return X86ISD::PUNPCKLBW;
6585  case MVT::v16i16:
6586  case MVT::v8i16: return X86ISD::PUNPCKLWD;
6587  default:
6588    llvm_unreachable("Unknown type for unpckl");
6589  }
6590  return 0;
6591}
6592
6593static inline unsigned getUNPCKHOpcode(EVT VT, bool HasAVX2) {
6594  switch(VT.getSimpleVT().SimpleTy) {
6595  case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6596  case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6597  case MVT::v8i32:
6598    if (HasAVX2)   return X86ISD::PUNPCKHDQ;
6599    // else use fp unit for int unpack.
6600  case MVT::v8f32:
6601  case MVT::v4f32: return X86ISD::UNPCKHPS;
6602  case MVT::v4i64:
6603    if (HasAVX2)   return X86ISD::PUNPCKHQDQ;
6604    // else use fp unit for int unpack.
6605  case MVT::v4f64:
6606  case MVT::v2f64: return X86ISD::UNPCKHPD;
6607  case MVT::v32i8:
6608  case MVT::v16i8: return X86ISD::PUNPCKHBW;
6609  case MVT::v16i16:
6610  case MVT::v8i16: return X86ISD::PUNPCKHWD;
6611  default:
6612    llvm_unreachable("Unknown type for unpckh");
6613  }
6614  return 0;
6615}
6616
6617static inline unsigned getVPERMILOpcode(EVT VT) {
6618  switch(VT.getSimpleVT().SimpleTy) {
6619  case MVT::v4i32:
6620  case MVT::v4f32: return X86ISD::VPERMILPS;
6621  case MVT::v2i64:
6622  case MVT::v2f64: return X86ISD::VPERMILPD;
6623  case MVT::v8i32:
6624  case MVT::v8f32: return X86ISD::VPERMILPSY;
6625  case MVT::v4i64:
6626  case MVT::v4f64: return X86ISD::VPERMILPDY;
6627  default:
6628    llvm_unreachable("Unknown type for vpermil");
6629  }
6630  return 0;
6631}
6632
6633static
6634SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6635                               const TargetLowering &TLI,
6636                               const X86Subtarget *Subtarget) {
6637  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6638  EVT VT = Op.getValueType();
6639  DebugLoc dl = Op.getDebugLoc();
6640  SDValue V1 = Op.getOperand(0);
6641  SDValue V2 = Op.getOperand(1);
6642
6643  if (isZeroShuffle(SVOp))
6644    return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6645
6646  // Handle splat operations
6647  if (SVOp->isSplat()) {
6648    unsigned NumElem = VT.getVectorNumElements();
6649    int Size = VT.getSizeInBits();
6650    // Special case, this is the only place now where it's allowed to return
6651    // a vector_shuffle operation without using a target specific node, because
6652    // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6653    // this be moved to DAGCombine instead?
6654    if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6655      return Op;
6656
6657    // Use vbroadcast whenever the splat comes from a foldable load
6658    SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6659    if (Subtarget->hasAVX() && LD.getNode())
6660      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6661
6662    // Handle splats by matching through known shuffle masks
6663    if ((Size == 128 && NumElem <= 4) ||
6664        (Size == 256 && NumElem < 8))
6665      return SDValue();
6666
6667    // All remaning splats are promoted to target supported vector shuffles.
6668    return PromoteSplat(SVOp, DAG);
6669  }
6670
6671  // If the shuffle can be profitably rewritten as a narrower shuffle, then
6672  // do it!
6673  if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6674    SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6675    if (NewOp.getNode())
6676      return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6677  } else if ((VT == MVT::v4i32 ||
6678             (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6679    // FIXME: Figure out a cleaner way to do this.
6680    // Try to make use of movq to zero out the top part.
6681    if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6682      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6683      if (NewOp.getNode()) {
6684        if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6685          return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6686                              DAG, Subtarget, dl);
6687      }
6688    } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6689      SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6690      if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6691        return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6692                            DAG, Subtarget, dl);
6693    }
6694  }
6695  return SDValue();
6696}
6697
6698SDValue
6699X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6700  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6701  SDValue V1 = Op.getOperand(0);
6702  SDValue V2 = Op.getOperand(1);
6703  EVT VT = Op.getValueType();
6704  DebugLoc dl = Op.getDebugLoc();
6705  unsigned NumElems = VT.getVectorNumElements();
6706  bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6707  bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6708  bool V1IsSplat = false;
6709  bool V2IsSplat = false;
6710  bool HasXMMInt = Subtarget->hasXMMInt();
6711  bool HasAVX2   = Subtarget->hasAVX2();
6712  MachineFunction &MF = DAG.getMachineFunction();
6713  bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6714
6715  assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6716
6717  // Vector shuffle lowering takes 3 steps:
6718  //
6719  // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6720  //    narrowing and commutation of operands should be handled.
6721  // 2) Matching of shuffles with known shuffle masks to x86 target specific
6722  //    shuffle nodes.
6723  // 3) Rewriting of unmatched masks into new generic shuffle operations,
6724  //    so the shuffle can be broken into other shuffles and the legalizer can
6725  //    try the lowering again.
6726  //
6727  // The general idea is that no vector_shuffle operation should be left to
6728  // be matched during isel, all of them must be converted to a target specific
6729  // node here.
6730
6731  // Normalize the input vectors. Here splats, zeroed vectors, profitable
6732  // narrowing and commutation of operands should be handled. The actual code
6733  // doesn't include all of those, work in progress...
6734  SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6735  if (NewOp.getNode())
6736    return NewOp;
6737
6738  // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6739  // unpckh_undef). Only use pshufd if speed is more important than size.
6740  if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6741    return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6742                                DAG);
6743  if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6744    return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6745                                DAG);
6746
6747  if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6748      V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6749    return getMOVDDup(Op, dl, V1, DAG);
6750
6751  if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6752    return getMOVHighToLow(Op, dl, DAG);
6753
6754  // Use to match splats
6755  if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6756      (VT == MVT::v2f64 || VT == MVT::v2i64))
6757    return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6758                                DAG);
6759
6760  if (X86::isPSHUFDMask(SVOp)) {
6761    // The actual implementation will match the mask in the if above and then
6762    // during isel it can match several different instructions, not only pshufd
6763    // as its name says, sad but true, emulate the behavior for now...
6764    if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6765        return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6766
6767    unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6768
6769    if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6770      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6771
6772    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6773                                TargetMask, DAG);
6774  }
6775
6776  // Check if this can be converted into a logical shift.
6777  bool isLeft = false;
6778  unsigned ShAmt = 0;
6779  SDValue ShVal;
6780  bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6781  if (isShift && ShVal.hasOneUse()) {
6782    // If the shifted value has multiple uses, it may be cheaper to use
6783    // v_set0 + movlhps or movhlps, etc.
6784    EVT EltVT = VT.getVectorElementType();
6785    ShAmt *= EltVT.getSizeInBits();
6786    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6787  }
6788
6789  if (X86::isMOVLMask(SVOp)) {
6790    if (V1IsUndef)
6791      return V2;
6792    if (ISD::isBuildVectorAllZeros(V1.getNode()))
6793      return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6794    if (!X86::isMOVLPMask(SVOp)) {
6795      if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6796        return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6797
6798      if (VT == MVT::v4i32 || VT == MVT::v4f32)
6799        return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6800    }
6801  }
6802
6803  // FIXME: fold these into legal mask.
6804  if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6805    return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6806
6807  if (X86::isMOVHLPSMask(SVOp))
6808    return getMOVHighToLow(Op, dl, DAG);
6809
6810  if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6811    return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6812
6813  if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6814    return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6815
6816  if (X86::isMOVLPMask(SVOp))
6817    return getMOVLP(Op, dl, DAG, HasXMMInt);
6818
6819  if (ShouldXformToMOVHLPS(SVOp) ||
6820      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6821    return CommuteVectorShuffle(SVOp, DAG);
6822
6823  if (isShift) {
6824    // No better options. Use a vshl / vsrl.
6825    EVT EltVT = VT.getVectorElementType();
6826    ShAmt *= EltVT.getSizeInBits();
6827    return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6828  }
6829
6830  bool Commuted = false;
6831  // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6832  // 1,1,1,1 -> v8i16 though.
6833  V1IsSplat = isSplatVector(V1.getNode());
6834  V2IsSplat = isSplatVector(V2.getNode());
6835
6836  // Canonicalize the splat or undef, if present, to be on the RHS.
6837  if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6838    Op = CommuteVectorShuffle(SVOp, DAG);
6839    SVOp = cast<ShuffleVectorSDNode>(Op);
6840    V1 = SVOp->getOperand(0);
6841    V2 = SVOp->getOperand(1);
6842    std::swap(V1IsSplat, V2IsSplat);
6843    std::swap(V1IsUndef, V2IsUndef);
6844    Commuted = true;
6845  }
6846
6847  if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6848    // Shuffling low element of v1 into undef, just return v1.
6849    if (V2IsUndef)
6850      return V1;
6851    // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6852    // the instruction selector will not match, so get a canonical MOVL with
6853    // swapped operands to undo the commute.
6854    return getMOVL(DAG, dl, VT, V2, V1);
6855  }
6856
6857  if (X86::isUNPCKLMask(SVOp, HasAVX2))
6858    return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V2,
6859                                DAG);
6860
6861  if (X86::isUNPCKHMask(SVOp, HasAVX2))
6862    return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V2,
6863                                DAG);
6864
6865  if (V2IsSplat) {
6866    // Normalize mask so all entries that point to V2 points to its first
6867    // element then try to match unpck{h|l} again. If match, return a
6868    // new vector_shuffle with the corrected mask.
6869    SDValue NewMask = NormalizeMask(SVOp, DAG);
6870    ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6871    if (NSVOp != SVOp) {
6872      if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6873        return NewMask;
6874      } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6875        return NewMask;
6876      }
6877    }
6878  }
6879
6880  if (Commuted) {
6881    // Commute is back and try unpck* again.
6882    // FIXME: this seems wrong.
6883    SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6884    ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6885
6886    if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6887      return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V2, V1,
6888                                  DAG);
6889
6890    if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6891      return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V2, V1,
6892                                  DAG);
6893  }
6894
6895  // Normalize the node to match x86 shuffle ops if needed
6896  if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6897    return CommuteVectorShuffle(SVOp, DAG);
6898
6899  // The checks below are all present in isShuffleMaskLegal, but they are
6900  // inlined here right now to enable us to directly emit target specific
6901  // nodes, and remove one by one until they don't return Op anymore.
6902  SmallVector<int, 16> M;
6903  SVOp->getMask(M);
6904
6905  if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6906    return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6907                                X86::getShufflePALIGNRImmediate(SVOp),
6908                                DAG);
6909
6910  if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6911      SVOp->getSplatIndex() == 0 && V2IsUndef) {
6912    if (VT == MVT::v2f64)
6913      return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6914    if (VT == MVT::v2i64)
6915      return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6916  }
6917
6918  if (isPSHUFHWMask(M, VT))
6919    return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6920                                X86::getShufflePSHUFHWImmediate(SVOp),
6921                                DAG);
6922
6923  if (isPSHUFLWMask(M, VT))
6924    return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6925                                X86::getShufflePSHUFLWImmediate(SVOp),
6926                                DAG);
6927
6928  if (isSHUFPMask(M, VT))
6929    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6930                                X86::getShuffleSHUFImmediate(SVOp), DAG);
6931
6932  if (X86::isUNPCKL_v_undef_Mask(SVOp))
6933    return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6934                                DAG);
6935  if (X86::isUNPCKH_v_undef_Mask(SVOp))
6936    return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6937                                DAG);
6938
6939  //===--------------------------------------------------------------------===//
6940  // Generate target specific nodes for 128 or 256-bit shuffles only
6941  // supported in the AVX instruction set.
6942  //
6943
6944  // Handle VMOVDDUPY permutations
6945  if (isMOVDDUPYMask(SVOp, Subtarget))
6946    return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6947
6948  // Handle VPERMILPS* permutations
6949  if (isVPERMILPSMask(M, VT, Subtarget))
6950    return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6951                                getShuffleVPERMILPSImmediate(SVOp), DAG);
6952
6953  // Handle VPERMILPD* permutations
6954  if (isVPERMILPDMask(M, VT, Subtarget))
6955    return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6956                                getShuffleVPERMILPDImmediate(SVOp), DAG);
6957
6958  // Handle VPERM2F128 permutations
6959  if (isVPERM2F128Mask(M, VT, Subtarget))
6960    return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6961                                getShuffleVPERM2F128Immediate(SVOp), DAG);
6962
6963  // Handle VSHUFPSY permutations
6964  if (isVSHUFPSYMask(M, VT, Subtarget))
6965    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6966                                getShuffleVSHUFPSYImmediate(SVOp), DAG);
6967
6968  // Handle VSHUFPDY permutations
6969  if (isVSHUFPDYMask(M, VT, Subtarget))
6970    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6971                                getShuffleVSHUFPDYImmediate(SVOp), DAG);
6972
6973  // Try to swap operands in the node to match x86 shuffle ops
6974  if (isCommutedVSHUFPMask(M, VT, Subtarget)) {
6975    // Now we need to commute operands.
6976    SVOp = cast<ShuffleVectorSDNode>(CommuteVectorShuffle(SVOp, DAG));
6977    V1 = SVOp->getOperand(0);
6978    V2 = SVOp->getOperand(1);
6979    unsigned Immediate = (NumElems == 4) ? getShuffleVSHUFPDYImmediate(SVOp):
6980        getShuffleVSHUFPSYImmediate(SVOp);
6981    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, Immediate, DAG);
6982  }
6983
6984  //===--------------------------------------------------------------------===//
6985  // Since no target specific shuffle was selected for this generic one,
6986  // lower it into other known shuffles. FIXME: this isn't true yet, but
6987  // this is the plan.
6988  //
6989
6990  // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6991  if (VT == MVT::v8i16) {
6992    SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6993    if (NewOp.getNode())
6994      return NewOp;
6995  }
6996
6997  if (VT == MVT::v16i8) {
6998    SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6999    if (NewOp.getNode())
7000      return NewOp;
7001  }
7002
7003  // Handle all 128-bit wide vectors with 4 elements, and match them with
7004  // several different shuffle types.
7005  if (NumElems == 4 && VT.getSizeInBits() == 128)
7006    return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7007
7008  // Handle general 256-bit shuffles
7009  if (VT.is256BitVector())
7010    return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7011
7012  return SDValue();
7013}
7014
7015SDValue
7016X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7017                                                SelectionDAG &DAG) const {
7018  EVT VT = Op.getValueType();
7019  DebugLoc dl = Op.getDebugLoc();
7020
7021  if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
7022    return SDValue();
7023
7024  if (VT.getSizeInBits() == 8) {
7025    SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7026                                    Op.getOperand(0), Op.getOperand(1));
7027    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7028                                    DAG.getValueType(VT));
7029    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7030  } else if (VT.getSizeInBits() == 16) {
7031    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7032    // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7033    if (Idx == 0)
7034      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7035                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7036                                     DAG.getNode(ISD::BITCAST, dl,
7037                                                 MVT::v4i32,
7038                                                 Op.getOperand(0)),
7039                                     Op.getOperand(1)));
7040    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7041                                    Op.getOperand(0), Op.getOperand(1));
7042    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7043                                    DAG.getValueType(VT));
7044    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7045  } else if (VT == MVT::f32) {
7046    // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7047    // the result back to FR32 register. It's only worth matching if the
7048    // result has a single use which is a store or a bitcast to i32.  And in
7049    // the case of a store, it's not worth it if the index is a constant 0,
7050    // because a MOVSSmr can be used instead, which is smaller and faster.
7051    if (!Op.hasOneUse())
7052      return SDValue();
7053    SDNode *User = *Op.getNode()->use_begin();
7054    if ((User->getOpcode() != ISD::STORE ||
7055         (isa<ConstantSDNode>(Op.getOperand(1)) &&
7056          cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7057        (User->getOpcode() != ISD::BITCAST ||
7058         User->getValueType(0) != MVT::i32))
7059      return SDValue();
7060    SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7061                                  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7062                                              Op.getOperand(0)),
7063                                              Op.getOperand(1));
7064    return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7065  } else if (VT == MVT::i32 || VT == MVT::i64) {
7066    // ExtractPS/pextrq works with constant index.
7067    if (isa<ConstantSDNode>(Op.getOperand(1)))
7068      return Op;
7069  }
7070  return SDValue();
7071}
7072
7073
7074SDValue
7075X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7076                                           SelectionDAG &DAG) const {
7077  if (!isa<ConstantSDNode>(Op.getOperand(1)))
7078    return SDValue();
7079
7080  SDValue Vec = Op.getOperand(0);
7081  EVT VecVT = Vec.getValueType();
7082
7083  // If this is a 256-bit vector result, first extract the 128-bit vector and
7084  // then extract the element from the 128-bit vector.
7085  if (VecVT.getSizeInBits() == 256) {
7086    DebugLoc dl = Op.getNode()->getDebugLoc();
7087    unsigned NumElems = VecVT.getVectorNumElements();
7088    SDValue Idx = Op.getOperand(1);
7089    unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7090
7091    // Get the 128-bit vector.
7092    bool Upper = IdxVal >= NumElems/2;
7093    Vec = Extract128BitVector(Vec,
7094                    DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
7095
7096    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7097                    Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7098  }
7099
7100  assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7101
7102  if (Subtarget->hasSSE41orAVX()) {
7103    SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7104    if (Res.getNode())
7105      return Res;
7106  }
7107
7108  EVT VT = Op.getValueType();
7109  DebugLoc dl = Op.getDebugLoc();
7110  // TODO: handle v16i8.
7111  if (VT.getSizeInBits() == 16) {
7112    SDValue Vec = Op.getOperand(0);
7113    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7114    if (Idx == 0)
7115      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7116                         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7117                                     DAG.getNode(ISD::BITCAST, dl,
7118                                                 MVT::v4i32, Vec),
7119                                     Op.getOperand(1)));
7120    // Transform it so it match pextrw which produces a 32-bit result.
7121    EVT EltVT = MVT::i32;
7122    SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7123                                    Op.getOperand(0), Op.getOperand(1));
7124    SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7125                                    DAG.getValueType(VT));
7126    return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7127  } else if (VT.getSizeInBits() == 32) {
7128    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7129    if (Idx == 0)
7130      return Op;
7131
7132    // SHUFPS the element to the lowest double word, then movss.
7133    int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7134    EVT VVT = Op.getOperand(0).getValueType();
7135    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7136                                       DAG.getUNDEF(VVT), Mask);
7137    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7138                       DAG.getIntPtrConstant(0));
7139  } else if (VT.getSizeInBits() == 64) {
7140    // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7141    // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7142    //        to match extract_elt for f64.
7143    unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7144    if (Idx == 0)
7145      return Op;
7146
7147    // UNPCKHPD the element to the lowest double word, then movsd.
7148    // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7149    // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7150    int Mask[2] = { 1, -1 };
7151    EVT VVT = Op.getOperand(0).getValueType();
7152    SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7153                                       DAG.getUNDEF(VVT), Mask);
7154    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7155                       DAG.getIntPtrConstant(0));
7156  }
7157
7158  return SDValue();
7159}
7160
7161SDValue
7162X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7163                                               SelectionDAG &DAG) const {
7164  EVT VT = Op.getValueType();
7165  EVT EltVT = VT.getVectorElementType();
7166  DebugLoc dl = Op.getDebugLoc();
7167
7168  SDValue N0 = Op.getOperand(0);
7169  SDValue N1 = Op.getOperand(1);
7170  SDValue N2 = Op.getOperand(2);
7171
7172  if (VT.getSizeInBits() == 256)
7173    return SDValue();
7174
7175  if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7176      isa<ConstantSDNode>(N2)) {
7177    unsigned Opc;
7178    if (VT == MVT::v8i16)
7179      Opc = X86ISD::PINSRW;
7180    else if (VT == MVT::v16i8)
7181      Opc = X86ISD::PINSRB;
7182    else
7183      Opc = X86ISD::PINSRB;
7184
7185    // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7186    // argument.
7187    if (N1.getValueType() != MVT::i32)
7188      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7189    if (N2.getValueType() != MVT::i32)
7190      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7191    return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7192  } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7193    // Bits [7:6] of the constant are the source select.  This will always be
7194    //  zero here.  The DAG Combiner may combine an extract_elt index into these
7195    //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7196    //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7197    // Bits [5:4] of the constant are the destination select.  This is the
7198    //  value of the incoming immediate.
7199    // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7200    //   combine either bitwise AND or insert of float 0.0 to set these bits.
7201    N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7202    // Create this as a scalar to vector..
7203    N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7204    return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7205  } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
7206             isa<ConstantSDNode>(N2)) {
7207    // PINSR* works with constant index.
7208    return Op;
7209  }
7210  return SDValue();
7211}
7212
7213SDValue
7214X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7215  EVT VT = Op.getValueType();
7216  EVT EltVT = VT.getVectorElementType();
7217
7218  DebugLoc dl = Op.getDebugLoc();
7219  SDValue N0 = Op.getOperand(0);
7220  SDValue N1 = Op.getOperand(1);
7221  SDValue N2 = Op.getOperand(2);
7222
7223  // If this is a 256-bit vector result, first extract the 128-bit vector,
7224  // insert the element into the extracted half and then place it back.
7225  if (VT.getSizeInBits() == 256) {
7226    if (!isa<ConstantSDNode>(N2))
7227      return SDValue();
7228
7229    // Get the desired 128-bit vector half.
7230    unsigned NumElems = VT.getVectorNumElements();
7231    unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7232    bool Upper = IdxVal >= NumElems/2;
7233    SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7234    SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7235
7236    // Insert the element into the desired half.
7237    V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7238                 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7239
7240    // Insert the changed part back to the 256-bit vector
7241    return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7242  }
7243
7244  if (Subtarget->hasSSE41orAVX())
7245    return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7246
7247  if (EltVT == MVT::i8)
7248    return SDValue();
7249
7250  if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7251    // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7252    // as its second argument.
7253    if (N1.getValueType() != MVT::i32)
7254      N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7255    if (N2.getValueType() != MVT::i32)
7256      N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7257    return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7258  }
7259  return SDValue();
7260}
7261
7262SDValue
7263X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7264  LLVMContext *Context = DAG.getContext();
7265  DebugLoc dl = Op.getDebugLoc();
7266  EVT OpVT = Op.getValueType();
7267
7268  // If this is a 256-bit vector result, first insert into a 128-bit
7269  // vector and then insert into the 256-bit vector.
7270  if (OpVT.getSizeInBits() > 128) {
7271    // Insert into a 128-bit vector.
7272    EVT VT128 = EVT::getVectorVT(*Context,
7273                                 OpVT.getVectorElementType(),
7274                                 OpVT.getVectorNumElements() / 2);
7275
7276    Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7277
7278    // Insert the 128-bit vector.
7279    return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7280                              DAG.getConstant(0, MVT::i32),
7281                              DAG, dl);
7282  }
7283
7284  if (Op.getValueType() == MVT::v1i64 &&
7285      Op.getOperand(0).getValueType() == MVT::i64)
7286    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7287
7288  SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7289  assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7290         "Expected an SSE type!");
7291  return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7292                     DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7293}
7294
7295// Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7296// a simple subregister reference or explicit instructions to grab
7297// upper bits of a vector.
7298SDValue
7299X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7300  if (Subtarget->hasAVX()) {
7301    DebugLoc dl = Op.getNode()->getDebugLoc();
7302    SDValue Vec = Op.getNode()->getOperand(0);
7303    SDValue Idx = Op.getNode()->getOperand(1);
7304
7305    if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7306        && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7307        return Extract128BitVector(Vec, Idx, DAG, dl);
7308    }
7309  }
7310  return SDValue();
7311}
7312
7313// Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7314// simple superregister reference or explicit instructions to insert
7315// the upper bits of a vector.
7316SDValue
7317X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7318  if (Subtarget->hasAVX()) {
7319    DebugLoc dl = Op.getNode()->getDebugLoc();
7320    SDValue Vec = Op.getNode()->getOperand(0);
7321    SDValue SubVec = Op.getNode()->getOperand(1);
7322    SDValue Idx = Op.getNode()->getOperand(2);
7323
7324    if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7325        && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7326      return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7327    }
7328  }
7329  return SDValue();
7330}
7331
7332// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7333// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7334// one of the above mentioned nodes. It has to be wrapped because otherwise
7335// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7336// be used to form addressing mode. These wrapped nodes will be selected
7337// into MOV32ri.
7338SDValue
7339X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7340  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7341
7342  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7343  // global base reg.
7344  unsigned char OpFlag = 0;
7345  unsigned WrapperKind = X86ISD::Wrapper;
7346  CodeModel::Model M = getTargetMachine().getCodeModel();
7347
7348  if (Subtarget->isPICStyleRIPRel() &&
7349      (M == CodeModel::Small || M == CodeModel::Kernel))
7350    WrapperKind = X86ISD::WrapperRIP;
7351  else if (Subtarget->isPICStyleGOT())
7352    OpFlag = X86II::MO_GOTOFF;
7353  else if (Subtarget->isPICStyleStubPIC())
7354    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7355
7356  SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7357                                             CP->getAlignment(),
7358                                             CP->getOffset(), OpFlag);
7359  DebugLoc DL = CP->getDebugLoc();
7360  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7361  // With PIC, the address is actually $g + Offset.
7362  if (OpFlag) {
7363    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7364                         DAG.getNode(X86ISD::GlobalBaseReg,
7365                                     DebugLoc(), getPointerTy()),
7366                         Result);
7367  }
7368
7369  return Result;
7370}
7371
7372SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7373  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7374
7375  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7376  // global base reg.
7377  unsigned char OpFlag = 0;
7378  unsigned WrapperKind = X86ISD::Wrapper;
7379  CodeModel::Model M = getTargetMachine().getCodeModel();
7380
7381  if (Subtarget->isPICStyleRIPRel() &&
7382      (M == CodeModel::Small || M == CodeModel::Kernel))
7383    WrapperKind = X86ISD::WrapperRIP;
7384  else if (Subtarget->isPICStyleGOT())
7385    OpFlag = X86II::MO_GOTOFF;
7386  else if (Subtarget->isPICStyleStubPIC())
7387    OpFlag = X86II::MO_PIC_BASE_OFFSET;
7388
7389  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7390                                          OpFlag);
7391  DebugLoc DL = JT->getDebugLoc();
7392  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7393
7394  // With PIC, the address is actually $g + Offset.
7395  if (OpFlag)
7396    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7397                         DAG.getNode(X86ISD::GlobalBaseReg,
7398                                     DebugLoc(), getPointerTy()),
7399                         Result);
7400
7401  return Result;
7402}
7403
7404SDValue
7405X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7406  const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7407
7408  // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7409  // global base reg.
7410  unsigned char OpFlag = 0;
7411  unsigned WrapperKind = X86ISD::Wrapper;
7412  CodeModel::Model M = getTargetMachine().getCodeModel();
7413
7414  if (Subtarget->isPICStyleRIPRel() &&
7415      (M == CodeModel::Small || M == CodeModel::Kernel)) {
7416    if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7417      OpFlag = X86II::MO_GOTPCREL;
7418    WrapperKind = X86ISD::WrapperRIP;
7419  } else if (Subtarget->isPICStyleGOT()) {
7420    OpFlag = X86II::MO_GOT;
7421  } else if (Subtarget->isPICStyleStubPIC()) {
7422    OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7423  } else if (Subtarget->isPICStyleStubNoDynamic()) {
7424    OpFlag = X86II::MO_DARWIN_NONLAZY;
7425  }
7426
7427  SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7428
7429  DebugLoc DL = Op.getDebugLoc();
7430  Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7431
7432
7433  // With PIC, the address is actually $g + Offset.
7434  if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7435      !Subtarget->is64Bit()) {
7436    Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7437                         DAG.getNode(X86ISD::GlobalBaseReg,
7438                                     DebugLoc(), getPointerTy()),
7439                         Result);
7440  }
7441
7442  // For symbols that require a load from a stub to get the address, emit the
7443  // load.
7444  if (isGlobalStubReference(OpFlag))
7445    Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7446                         MachinePointerInfo::getGOT(), false, false, false, 0);
7447
7448  return Result;
7449}
7450
7451SDValue
7452X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7453  // Create the TargetBlockAddressAddress node.
7454  unsigned char OpFlags =
7455    Subtarget->ClassifyBlockAddressReference();
7456  CodeModel::Model M = getTargetMachine().getCodeModel();
7457  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7458  DebugLoc dl = Op.getDebugLoc();
7459  SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7460                                       /*isTarget=*/true, OpFlags);
7461
7462  if (Subtarget->isPICStyleRIPRel() &&
7463      (M == CodeModel::Small || M == CodeModel::Kernel))
7464    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7465  else
7466    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7467
7468  // With PIC, the address is actually $g + Offset.
7469  if (isGlobalRelativeToPICBase(OpFlags)) {
7470    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7471                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7472                         Result);
7473  }
7474
7475  return Result;
7476}
7477
7478SDValue
7479X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7480                                      int64_t Offset,
7481                                      SelectionDAG &DAG) const {
7482  // Create the TargetGlobalAddress node, folding in the constant
7483  // offset if it is legal.
7484  unsigned char OpFlags =
7485    Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7486  CodeModel::Model M = getTargetMachine().getCodeModel();
7487  SDValue Result;
7488  if (OpFlags == X86II::MO_NO_FLAG &&
7489      X86::isOffsetSuitableForCodeModel(Offset, M)) {
7490    // A direct static reference to a global.
7491    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7492    Offset = 0;
7493  } else {
7494    Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7495  }
7496
7497  if (Subtarget->isPICStyleRIPRel() &&
7498      (M == CodeModel::Small || M == CodeModel::Kernel))
7499    Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7500  else
7501    Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7502
7503  // With PIC, the address is actually $g + Offset.
7504  if (isGlobalRelativeToPICBase(OpFlags)) {
7505    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7506                         DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7507                         Result);
7508  }
7509
7510  // For globals that require a load from a stub to get the address, emit the
7511  // load.
7512  if (isGlobalStubReference(OpFlags))
7513    Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7514                         MachinePointerInfo::getGOT(), false, false, false, 0);
7515
7516  // If there was a non-zero offset that we didn't fold, create an explicit
7517  // addition for it.
7518  if (Offset != 0)
7519    Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7520                         DAG.getConstant(Offset, getPointerTy()));
7521
7522  return Result;
7523}
7524
7525SDValue
7526X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7527  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7528  int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7529  return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7530}
7531
7532static SDValue
7533GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7534           SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7535           unsigned char OperandFlags) {
7536  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7537  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7538  DebugLoc dl = GA->getDebugLoc();
7539  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7540                                           GA->getValueType(0),
7541                                           GA->getOffset(),
7542                                           OperandFlags);
7543  if (InFlag) {
7544    SDValue Ops[] = { Chain,  TGA, *InFlag };
7545    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7546  } else {
7547    SDValue Ops[]  = { Chain, TGA };
7548    Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7549  }
7550
7551  // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7552  MFI->setAdjustsStack(true);
7553
7554  SDValue Flag = Chain.getValue(1);
7555  return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7556}
7557
7558// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7559static SDValue
7560LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7561                                const EVT PtrVT) {
7562  SDValue InFlag;
7563  DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7564  SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7565                                     DAG.getNode(X86ISD::GlobalBaseReg,
7566                                                 DebugLoc(), PtrVT), InFlag);
7567  InFlag = Chain.getValue(1);
7568
7569  return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7570}
7571
7572// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7573static SDValue
7574LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7575                                const EVT PtrVT) {
7576  return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7577                    X86::RAX, X86II::MO_TLSGD);
7578}
7579
7580// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7581// "local exec" model.
7582static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7583                                   const EVT PtrVT, TLSModel::Model model,
7584                                   bool is64Bit) {
7585  DebugLoc dl = GA->getDebugLoc();
7586
7587  // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7588  Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7589                                                         is64Bit ? 257 : 256));
7590
7591  SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7592                                      DAG.getIntPtrConstant(0),
7593                                      MachinePointerInfo(Ptr),
7594                                      false, false, false, 0);
7595
7596  unsigned char OperandFlags = 0;
7597  // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7598  // initialexec.
7599  unsigned WrapperKind = X86ISD::Wrapper;
7600  if (model == TLSModel::LocalExec) {
7601    OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7602  } else if (is64Bit) {
7603    assert(model == TLSModel::InitialExec);
7604    OperandFlags = X86II::MO_GOTTPOFF;
7605    WrapperKind = X86ISD::WrapperRIP;
7606  } else {
7607    assert(model == TLSModel::InitialExec);
7608    OperandFlags = X86II::MO_INDNTPOFF;
7609  }
7610
7611  // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7612  // exec)
7613  SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7614                                           GA->getValueType(0),
7615                                           GA->getOffset(), OperandFlags);
7616  SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7617
7618  if (model == TLSModel::InitialExec)
7619    Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7620                         MachinePointerInfo::getGOT(), false, false, false, 0);
7621
7622  // The address of the thread local variable is the add of the thread
7623  // pointer with the offset of the variable.
7624  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7625}
7626
7627SDValue
7628X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7629
7630  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7631  const GlobalValue *GV = GA->getGlobal();
7632
7633  if (Subtarget->isTargetELF()) {
7634    // TODO: implement the "local dynamic" model
7635    // TODO: implement the "initial exec"model for pic executables
7636
7637    // If GV is an alias then use the aliasee for determining
7638    // thread-localness.
7639    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7640      GV = GA->resolveAliasedGlobal(false);
7641
7642    TLSModel::Model model
7643      = getTLSModel(GV, getTargetMachine().getRelocationModel());
7644
7645    switch (model) {
7646      case TLSModel::GeneralDynamic:
7647      case TLSModel::LocalDynamic: // not implemented
7648        if (Subtarget->is64Bit())
7649          return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7650        return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7651
7652      case TLSModel::InitialExec:
7653      case TLSModel::LocalExec:
7654        return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7655                                   Subtarget->is64Bit());
7656    }
7657  } else if (Subtarget->isTargetDarwin()) {
7658    // Darwin only has one model of TLS.  Lower to that.
7659    unsigned char OpFlag = 0;
7660    unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7661                           X86ISD::WrapperRIP : X86ISD::Wrapper;
7662
7663    // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7664    // global base reg.
7665    bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7666                  !Subtarget->is64Bit();
7667    if (PIC32)
7668      OpFlag = X86II::MO_TLVP_PIC_BASE;
7669    else
7670      OpFlag = X86II::MO_TLVP;
7671    DebugLoc DL = Op.getDebugLoc();
7672    SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7673                                                GA->getValueType(0),
7674                                                GA->getOffset(), OpFlag);
7675    SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7676
7677    // With PIC32, the address is actually $g + Offset.
7678    if (PIC32)
7679      Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7680                           DAG.getNode(X86ISD::GlobalBaseReg,
7681                                       DebugLoc(), getPointerTy()),
7682                           Offset);
7683
7684    // Lowering the machine isd will make sure everything is in the right
7685    // location.
7686    SDValue Chain = DAG.getEntryNode();
7687    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7688    SDValue Args[] = { Chain, Offset };
7689    Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7690
7691    // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7692    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7693    MFI->setAdjustsStack(true);
7694
7695    // And our return value (tls address) is in the standard call return value
7696    // location.
7697    unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7698    return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7699                              Chain.getValue(1));
7700  }
7701
7702  assert(false &&
7703         "TLS not implemented for this target.");
7704
7705  llvm_unreachable("Unreachable");
7706  return SDValue();
7707}
7708
7709
7710/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7711/// take a 2 x i32 value to shift plus a shift amount.
7712SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7713  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7714  EVT VT = Op.getValueType();
7715  unsigned VTBits = VT.getSizeInBits();
7716  DebugLoc dl = Op.getDebugLoc();
7717  bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7718  SDValue ShOpLo = Op.getOperand(0);
7719  SDValue ShOpHi = Op.getOperand(1);
7720  SDValue ShAmt  = Op.getOperand(2);
7721  SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7722                                     DAG.getConstant(VTBits - 1, MVT::i8))
7723                       : DAG.getConstant(0, VT);
7724
7725  SDValue Tmp2, Tmp3;
7726  if (Op.getOpcode() == ISD::SHL_PARTS) {
7727    Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7728    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7729  } else {
7730    Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7731    Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7732  }
7733
7734  SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7735                                DAG.getConstant(VTBits, MVT::i8));
7736  SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7737                             AndNode, DAG.getConstant(0, MVT::i8));
7738
7739  SDValue Hi, Lo;
7740  SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7741  SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7742  SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7743
7744  if (Op.getOpcode() == ISD::SHL_PARTS) {
7745    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7746    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7747  } else {
7748    Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7749    Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7750  }
7751
7752  SDValue Ops[2] = { Lo, Hi };
7753  return DAG.getMergeValues(Ops, 2, dl);
7754}
7755
7756SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7757                                           SelectionDAG &DAG) const {
7758  EVT SrcVT = Op.getOperand(0).getValueType();
7759
7760  if (SrcVT.isVector())
7761    return SDValue();
7762
7763  assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7764         "Unknown SINT_TO_FP to lower!");
7765
7766  // These are really Legal; return the operand so the caller accepts it as
7767  // Legal.
7768  if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7769    return Op;
7770  if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7771      Subtarget->is64Bit()) {
7772    return Op;
7773  }
7774
7775  DebugLoc dl = Op.getDebugLoc();
7776  unsigned Size = SrcVT.getSizeInBits()/8;
7777  MachineFunction &MF = DAG.getMachineFunction();
7778  int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7779  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7780  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7781                               StackSlot,
7782                               MachinePointerInfo::getFixedStack(SSFI),
7783                               false, false, 0);
7784  return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7785}
7786
7787SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7788                                     SDValue StackSlot,
7789                                     SelectionDAG &DAG) const {
7790  // Build the FILD
7791  DebugLoc DL = Op.getDebugLoc();
7792  SDVTList Tys;
7793  bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7794  if (useSSE)
7795    Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7796  else
7797    Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7798
7799  unsigned ByteSize = SrcVT.getSizeInBits()/8;
7800
7801  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7802  MachineMemOperand *MMO;
7803  if (FI) {
7804    int SSFI = FI->getIndex();
7805    MMO =
7806      DAG.getMachineFunction()
7807      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7808                            MachineMemOperand::MOLoad, ByteSize, ByteSize);
7809  } else {
7810    MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7811    StackSlot = StackSlot.getOperand(1);
7812  }
7813  SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7814  SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7815                                           X86ISD::FILD, DL,
7816                                           Tys, Ops, array_lengthof(Ops),
7817                                           SrcVT, MMO);
7818
7819  if (useSSE) {
7820    Chain = Result.getValue(1);
7821    SDValue InFlag = Result.getValue(2);
7822
7823    // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7824    // shouldn't be necessary except that RFP cannot be live across
7825    // multiple blocks. When stackifier is fixed, they can be uncoupled.
7826    MachineFunction &MF = DAG.getMachineFunction();
7827    unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7828    int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7829    SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7830    Tys = DAG.getVTList(MVT::Other);
7831    SDValue Ops[] = {
7832      Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7833    };
7834    MachineMemOperand *MMO =
7835      DAG.getMachineFunction()
7836      .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7837                            MachineMemOperand::MOStore, SSFISize, SSFISize);
7838
7839    Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7840                                    Ops, array_lengthof(Ops),
7841                                    Op.getValueType(), MMO);
7842    Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7843                         MachinePointerInfo::getFixedStack(SSFI),
7844                         false, false, false, 0);
7845  }
7846
7847  return Result;
7848}
7849
7850// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7851SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7852                                               SelectionDAG &DAG) const {
7853  // This algorithm is not obvious. Here it is in C code, more or less:
7854  /*
7855    double uint64_to_double( uint32_t hi, uint32_t lo ) {
7856      static const __m128i exp = { 0x4330000045300000ULL, 0 };
7857      static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7858
7859      // Copy ints to xmm registers.
7860      __m128i xh = _mm_cvtsi32_si128( hi );
7861      __m128i xl = _mm_cvtsi32_si128( lo );
7862
7863      // Combine into low half of a single xmm register.
7864      __m128i x = _mm_unpacklo_epi32( xh, xl );
7865      __m128d d;
7866      double sd;
7867
7868      // Merge in appropriate exponents to give the integer bits the right
7869      // magnitude.
7870      x = _mm_unpacklo_epi32( x, exp );
7871
7872      // Subtract away the biases to deal with the IEEE-754 double precision
7873      // implicit 1.
7874      d = _mm_sub_pd( (__m128d) x, bias );
7875
7876      // All conversions up to here are exact. The correctly rounded result is
7877      // calculated using the current rounding mode using the following
7878      // horizontal add.
7879      d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7880      _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7881                                // store doesn't really need to be here (except
7882                                // maybe to zero the other double)
7883      return sd;
7884    }
7885  */
7886
7887  DebugLoc dl = Op.getDebugLoc();
7888  LLVMContext *Context = DAG.getContext();
7889
7890  // Build some magic constants.
7891  std::vector<Constant*> CV0;
7892  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7893  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7894  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7895  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7896  Constant *C0 = ConstantVector::get(CV0);
7897  SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7898
7899  std::vector<Constant*> CV1;
7900  CV1.push_back(
7901    ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7902  CV1.push_back(
7903    ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7904  Constant *C1 = ConstantVector::get(CV1);
7905  SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7906
7907  SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7908                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7909                                        Op.getOperand(0),
7910                                        DAG.getIntPtrConstant(1)));
7911  SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7912                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7913                                        Op.getOperand(0),
7914                                        DAG.getIntPtrConstant(0)));
7915  SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7916  SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7917                              MachinePointerInfo::getConstantPool(),
7918                              false, false, false, 16);
7919  SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7920  SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7921  SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7922                              MachinePointerInfo::getConstantPool(),
7923                              false, false, false, 16);
7924  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7925
7926  // Add the halves; easiest way is to swap them into another reg first.
7927  int ShufMask[2] = { 1, -1 };
7928  SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7929                                      DAG.getUNDEF(MVT::v2f64), ShufMask);
7930  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7931  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7932                     DAG.getIntPtrConstant(0));
7933}
7934
7935// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7936SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7937                                               SelectionDAG &DAG) const {
7938  DebugLoc dl = Op.getDebugLoc();
7939  // FP constant to bias correct the final result.
7940  SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7941                                   MVT::f64);
7942
7943  // Load the 32-bit value into an XMM register.
7944  SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7945                             Op.getOperand(0));
7946
7947  // Zero out the upper parts of the register.
7948  Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7949                                     DAG);
7950
7951  Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7952                     DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7953                     DAG.getIntPtrConstant(0));
7954
7955  // Or the load with the bias.
7956  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7957                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7958                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7959                                                   MVT::v2f64, Load)),
7960                           DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7961                                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7962                                                   MVT::v2f64, Bias)));
7963  Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7964                   DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7965                   DAG.getIntPtrConstant(0));
7966
7967  // Subtract the bias.
7968  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7969
7970  // Handle final rounding.
7971  EVT DestVT = Op.getValueType();
7972
7973  if (DestVT.bitsLT(MVT::f64)) {
7974    return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7975                       DAG.getIntPtrConstant(0));
7976  } else if (DestVT.bitsGT(MVT::f64)) {
7977    return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7978  }
7979
7980  // Handle final rounding.
7981  return Sub;
7982}
7983
7984SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7985                                           SelectionDAG &DAG) const {
7986  SDValue N0 = Op.getOperand(0);
7987  DebugLoc dl = Op.getDebugLoc();
7988
7989  // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7990  // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7991  // the optimization here.
7992  if (DAG.SignBitIsZero(N0))
7993    return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7994
7995  EVT SrcVT = N0.getValueType();
7996  EVT DstVT = Op.getValueType();
7997  if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7998    return LowerUINT_TO_FP_i64(Op, DAG);
7999  else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8000    return LowerUINT_TO_FP_i32(Op, DAG);
8001
8002  // Make a 64-bit buffer, and use it to build an FILD.
8003  SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8004  if (SrcVT == MVT::i32) {
8005    SDValue WordOff = DAG.getConstant(4, getPointerTy());
8006    SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8007                                     getPointerTy(), StackSlot, WordOff);
8008    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8009                                  StackSlot, MachinePointerInfo(),
8010                                  false, false, 0);
8011    SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8012                                  OffsetSlot, MachinePointerInfo(),
8013                                  false, false, 0);
8014    SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8015    return Fild;
8016  }
8017
8018  assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8019  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8020                                StackSlot, MachinePointerInfo(),
8021                               false, false, 0);
8022  // For i64 source, we need to add the appropriate power of 2 if the input
8023  // was negative.  This is the same as the optimization in
8024  // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8025  // we must be careful to do the computation in x87 extended precision, not
8026  // in SSE. (The generic code can't know it's OK to do this, or how to.)
8027  int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8028  MachineMemOperand *MMO =
8029    DAG.getMachineFunction()
8030    .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8031                          MachineMemOperand::MOLoad, 8, 8);
8032
8033  SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8034  SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8035  SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8036                                         MVT::i64, MMO);
8037
8038  APInt FF(32, 0x5F800000ULL);
8039
8040  // Check whether the sign bit is set.
8041  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8042                                 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8043                                 ISD::SETLT);
8044
8045  // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8046  SDValue FudgePtr = DAG.getConstantPool(
8047                             ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8048                                         getPointerTy());
8049
8050  // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8051  SDValue Zero = DAG.getIntPtrConstant(0);
8052  SDValue Four = DAG.getIntPtrConstant(4);
8053  SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8054                               Zero, Four);
8055  FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8056
8057  // Load the value out, extending it from f32 to f80.
8058  // FIXME: Avoid the extend by constructing the right constant pool?
8059  SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8060                                 FudgePtr, MachinePointerInfo::getConstantPool(),
8061                                 MVT::f32, false, false, 4);
8062  // Extend everything to 80 bits to force it to be done on x87.
8063  SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8064  return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8065}
8066
8067std::pair<SDValue,SDValue> X86TargetLowering::
8068FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
8069  DebugLoc DL = Op.getDebugLoc();
8070
8071  EVT DstTy = Op.getValueType();
8072
8073  if (!IsSigned) {
8074    assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8075    DstTy = MVT::i64;
8076  }
8077
8078  assert(DstTy.getSimpleVT() <= MVT::i64 &&
8079         DstTy.getSimpleVT() >= MVT::i16 &&
8080         "Unknown FP_TO_SINT to lower!");
8081
8082  // These are really Legal.
8083  if (DstTy == MVT::i32 &&
8084      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8085    return std::make_pair(SDValue(), SDValue());
8086  if (Subtarget->is64Bit() &&
8087      DstTy == MVT::i64 &&
8088      isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8089    return std::make_pair(SDValue(), SDValue());
8090
8091  // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
8092  // stack slot.
8093  MachineFunction &MF = DAG.getMachineFunction();
8094  unsigned MemSize = DstTy.getSizeInBits()/8;
8095  int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8096  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8097
8098
8099
8100  unsigned Opc;
8101  switch (DstTy.getSimpleVT().SimpleTy) {
8102  default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8103  case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8104  case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8105  case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8106  }
8107
8108  SDValue Chain = DAG.getEntryNode();
8109  SDValue Value = Op.getOperand(0);
8110  EVT TheVT = Op.getOperand(0).getValueType();
8111  if (isScalarFPTypeInSSEReg(TheVT)) {
8112    assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8113    Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8114                         MachinePointerInfo::getFixedStack(SSFI),
8115                         false, false, 0);
8116    SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8117    SDValue Ops[] = {
8118      Chain, StackSlot, DAG.getValueType(TheVT)
8119    };
8120
8121    MachineMemOperand *MMO =
8122      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8123                              MachineMemOperand::MOLoad, MemSize, MemSize);
8124    Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8125                                    DstTy, MMO);
8126    Chain = Value.getValue(1);
8127    SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8128    StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8129  }
8130
8131  MachineMemOperand *MMO =
8132    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8133                            MachineMemOperand::MOStore, MemSize, MemSize);
8134
8135  // Build the FP_TO_INT*_IN_MEM
8136  SDValue Ops[] = { Chain, Value, StackSlot };
8137  SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8138                                         Ops, 3, DstTy, MMO);
8139
8140  return std::make_pair(FIST, StackSlot);
8141}
8142
8143SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8144                                           SelectionDAG &DAG) const {
8145  if (Op.getValueType().isVector())
8146    return SDValue();
8147
8148  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8149  SDValue FIST = Vals.first, StackSlot = Vals.second;
8150  // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8151  if (FIST.getNode() == 0) return Op;
8152
8153  // Load the result.
8154  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8155                     FIST, StackSlot, MachinePointerInfo(),
8156                     false, false, false, 0);
8157}
8158
8159SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8160                                           SelectionDAG &DAG) const {
8161  std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8162  SDValue FIST = Vals.first, StackSlot = Vals.second;
8163  assert(FIST.getNode() && "Unexpected failure");
8164
8165  // Load the result.
8166  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8167                     FIST, StackSlot, MachinePointerInfo(),
8168                     false, false, false, 0);
8169}
8170
8171SDValue X86TargetLowering::LowerFABS(SDValue Op,
8172                                     SelectionDAG &DAG) const {
8173  LLVMContext *Context = DAG.getContext();
8174  DebugLoc dl = Op.getDebugLoc();
8175  EVT VT = Op.getValueType();
8176  EVT EltVT = VT;
8177  if (VT.isVector())
8178    EltVT = VT.getVectorElementType();
8179  std::vector<Constant*> CV;
8180  if (EltVT == MVT::f64) {
8181    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8182    CV.push_back(C);
8183    CV.push_back(C);
8184  } else {
8185    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8186    CV.push_back(C);
8187    CV.push_back(C);
8188    CV.push_back(C);
8189    CV.push_back(C);
8190  }
8191  Constant *C = ConstantVector::get(CV);
8192  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8193  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8194                             MachinePointerInfo::getConstantPool(),
8195                             false, false, false, 16);
8196  return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8197}
8198
8199SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8200  LLVMContext *Context = DAG.getContext();
8201  DebugLoc dl = Op.getDebugLoc();
8202  EVT VT = Op.getValueType();
8203  EVT EltVT = VT;
8204  if (VT.isVector())
8205    EltVT = VT.getVectorElementType();
8206  std::vector<Constant*> CV;
8207  if (EltVT == MVT::f64) {
8208    Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8209    CV.push_back(C);
8210    CV.push_back(C);
8211  } else {
8212    Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8213    CV.push_back(C);
8214    CV.push_back(C);
8215    CV.push_back(C);
8216    CV.push_back(C);
8217  }
8218  Constant *C = ConstantVector::get(CV);
8219  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8220  SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8221                             MachinePointerInfo::getConstantPool(),
8222                             false, false, false, 16);
8223  if (VT.isVector()) {
8224    return DAG.getNode(ISD::BITCAST, dl, VT,
8225                       DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8226                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8227                                Op.getOperand(0)),
8228                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8229  } else {
8230    return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8231  }
8232}
8233
8234SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8235  LLVMContext *Context = DAG.getContext();
8236  SDValue Op0 = Op.getOperand(0);
8237  SDValue Op1 = Op.getOperand(1);
8238  DebugLoc dl = Op.getDebugLoc();
8239  EVT VT = Op.getValueType();
8240  EVT SrcVT = Op1.getValueType();
8241
8242  // If second operand is smaller, extend it first.
8243  if (SrcVT.bitsLT(VT)) {
8244    Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8245    SrcVT = VT;
8246  }
8247  // And if it is bigger, shrink it first.
8248  if (SrcVT.bitsGT(VT)) {
8249    Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8250    SrcVT = VT;
8251  }
8252
8253  // At this point the operands and the result should have the same
8254  // type, and that won't be f80 since that is not custom lowered.
8255
8256  // First get the sign bit of second operand.
8257  std::vector<Constant*> CV;
8258  if (SrcVT == MVT::f64) {
8259    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8260    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8261  } else {
8262    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8263    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8264    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8265    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8266  }
8267  Constant *C = ConstantVector::get(CV);
8268  SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8269  SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8270                              MachinePointerInfo::getConstantPool(),
8271                              false, false, false, 16);
8272  SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8273
8274  // Shift sign bit right or left if the two operands have different types.
8275  if (SrcVT.bitsGT(VT)) {
8276    // Op0 is MVT::f32, Op1 is MVT::f64.
8277    SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8278    SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8279                          DAG.getConstant(32, MVT::i32));
8280    SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8281    SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8282                          DAG.getIntPtrConstant(0));
8283  }
8284
8285  // Clear first operand sign bit.
8286  CV.clear();
8287  if (VT == MVT::f64) {
8288    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8289    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8290  } else {
8291    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8292    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8293    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8294    CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8295  }
8296  C = ConstantVector::get(CV);
8297  CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8298  SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8299                              MachinePointerInfo::getConstantPool(),
8300                              false, false, false, 16);
8301  SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8302
8303  // Or the value with the sign bit.
8304  return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8305}
8306
8307SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8308  SDValue N0 = Op.getOperand(0);
8309  DebugLoc dl = Op.getDebugLoc();
8310  EVT VT = Op.getValueType();
8311
8312  // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8313  SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8314                                  DAG.getConstant(1, VT));
8315  return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8316}
8317
8318/// Emit nodes that will be selected as "test Op0,Op0", or something
8319/// equivalent.
8320SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8321                                    SelectionDAG &DAG) const {
8322  DebugLoc dl = Op.getDebugLoc();
8323
8324  // CF and OF aren't always set the way we want. Determine which
8325  // of these we need.
8326  bool NeedCF = false;
8327  bool NeedOF = false;
8328  switch (X86CC) {
8329  default: break;
8330  case X86::COND_A: case X86::COND_AE:
8331  case X86::COND_B: case X86::COND_BE:
8332    NeedCF = true;
8333    break;
8334  case X86::COND_G: case X86::COND_GE:
8335  case X86::COND_L: case X86::COND_LE:
8336  case X86::COND_O: case X86::COND_NO:
8337    NeedOF = true;
8338    break;
8339  }
8340
8341  // See if we can use the EFLAGS value from the operand instead of
8342  // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8343  // we prove that the arithmetic won't overflow, we can't use OF or CF.
8344  if (Op.getResNo() != 0 || NeedOF || NeedCF)
8345    // Emit a CMP with 0, which is the TEST pattern.
8346    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8347                       DAG.getConstant(0, Op.getValueType()));
8348
8349  unsigned Opcode = 0;
8350  unsigned NumOperands = 0;
8351  switch (Op.getNode()->getOpcode()) {
8352  case ISD::ADD:
8353    // Due to an isel shortcoming, be conservative if this add is likely to be
8354    // selected as part of a load-modify-store instruction. When the root node
8355    // in a match is a store, isel doesn't know how to remap non-chain non-flag
8356    // uses of other nodes in the match, such as the ADD in this case. This
8357    // leads to the ADD being left around and reselected, with the result being
8358    // two adds in the output.  Alas, even if none our users are stores, that
8359    // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8360    // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8361    // climbing the DAG back to the root, and it doesn't seem to be worth the
8362    // effort.
8363    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8364         UE = Op.getNode()->use_end(); UI != UE; ++UI)
8365      if (UI->getOpcode() != ISD::CopyToReg &&
8366          UI->getOpcode() != ISD::SETCC &&
8367          UI->getOpcode() != ISD::STORE)
8368        goto default_case;
8369
8370    if (ConstantSDNode *C =
8371        dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8372      // An add of one will be selected as an INC.
8373      if (C->getAPIntValue() == 1) {
8374        Opcode = X86ISD::INC;
8375        NumOperands = 1;
8376        break;
8377      }
8378
8379      // An add of negative one (subtract of one) will be selected as a DEC.
8380      if (C->getAPIntValue().isAllOnesValue()) {
8381        Opcode = X86ISD::DEC;
8382        NumOperands = 1;
8383        break;
8384      }
8385    }
8386
8387    // Otherwise use a regular EFLAGS-setting add.
8388    Opcode = X86ISD::ADD;
8389    NumOperands = 2;
8390    break;
8391  case ISD::AND: {
8392    // If the primary and result isn't used, don't bother using X86ISD::AND,
8393    // because a TEST instruction will be better.
8394    bool NonFlagUse = false;
8395    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8396           UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8397      SDNode *User = *UI;
8398      unsigned UOpNo = UI.getOperandNo();
8399      if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8400        // Look pass truncate.
8401        UOpNo = User->use_begin().getOperandNo();
8402        User = *User->use_begin();
8403      }
8404
8405      if (User->getOpcode() != ISD::BRCOND &&
8406          User->getOpcode() != ISD::SETCC &&
8407          (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8408        NonFlagUse = true;
8409        break;
8410      }
8411    }
8412
8413    if (!NonFlagUse)
8414      break;
8415  }
8416    // FALL THROUGH
8417  case ISD::SUB:
8418  case ISD::OR:
8419  case ISD::XOR:
8420    // Due to the ISEL shortcoming noted above, be conservative if this op is
8421    // likely to be selected as part of a load-modify-store instruction.
8422    for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8423           UE = Op.getNode()->use_end(); UI != UE; ++UI)
8424      if (UI->getOpcode() == ISD::STORE)
8425        goto default_case;
8426
8427    // Otherwise use a regular EFLAGS-setting instruction.
8428    switch (Op.getNode()->getOpcode()) {
8429    default: llvm_unreachable("unexpected operator!");
8430    case ISD::SUB: Opcode = X86ISD::SUB; break;
8431    case ISD::OR:  Opcode = X86ISD::OR;  break;
8432    case ISD::XOR: Opcode = X86ISD::XOR; break;
8433    case ISD::AND: Opcode = X86ISD::AND; break;
8434    }
8435
8436    NumOperands = 2;
8437    break;
8438  case X86ISD::ADD:
8439  case X86ISD::SUB:
8440  case X86ISD::INC:
8441  case X86ISD::DEC:
8442  case X86ISD::OR:
8443  case X86ISD::XOR:
8444  case X86ISD::AND:
8445    return SDValue(Op.getNode(), 1);
8446  default:
8447  default_case:
8448    break;
8449  }
8450
8451  if (Opcode == 0)
8452    // Emit a CMP with 0, which is the TEST pattern.
8453    return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8454                       DAG.getConstant(0, Op.getValueType()));
8455
8456  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8457  SmallVector<SDValue, 4> Ops;
8458  for (unsigned i = 0; i != NumOperands; ++i)
8459    Ops.push_back(Op.getOperand(i));
8460
8461  SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8462  DAG.ReplaceAllUsesWith(Op, New);
8463  return SDValue(New.getNode(), 1);
8464}
8465
8466/// Emit nodes that will be selected as "cmp Op0,Op1", or something
8467/// equivalent.
8468SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8469                                   SelectionDAG &DAG) const {
8470  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8471    if (C->getAPIntValue() == 0)
8472      return EmitTest(Op0, X86CC, DAG);
8473
8474  DebugLoc dl = Op0.getDebugLoc();
8475  return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8476}
8477
8478/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8479/// if it's possible.
8480SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8481                                     DebugLoc dl, SelectionDAG &DAG) const {
8482  SDValue Op0 = And.getOperand(0);
8483  SDValue Op1 = And.getOperand(1);
8484  if (Op0.getOpcode() == ISD::TRUNCATE)
8485    Op0 = Op0.getOperand(0);
8486  if (Op1.getOpcode() == ISD::TRUNCATE)
8487    Op1 = Op1.getOperand(0);
8488
8489  SDValue LHS, RHS;
8490  if (Op1.getOpcode() == ISD::SHL)
8491    std::swap(Op0, Op1);
8492  if (Op0.getOpcode() == ISD::SHL) {
8493    if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8494      if (And00C->getZExtValue() == 1) {
8495        // If we looked past a truncate, check that it's only truncating away
8496        // known zeros.
8497        unsigned BitWidth = Op0.getValueSizeInBits();
8498        unsigned AndBitWidth = And.getValueSizeInBits();
8499        if (BitWidth > AndBitWidth) {
8500          APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8501          DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8502          if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8503            return SDValue();
8504        }
8505        LHS = Op1;
8506        RHS = Op0.getOperand(1);
8507      }
8508  } else if (Op1.getOpcode() == ISD::Constant) {
8509    ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8510    uint64_t AndRHSVal = AndRHS->getZExtValue();
8511    SDValue AndLHS = Op0;
8512
8513    if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8514      LHS = AndLHS.getOperand(0);
8515      RHS = AndLHS.getOperand(1);
8516    }
8517
8518    // Use BT if the immediate can't be encoded in a TEST instruction.
8519    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8520      LHS = AndLHS;
8521      RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8522    }
8523  }
8524
8525  if (LHS.getNode()) {
8526    // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8527    // instruction.  Since the shift amount is in-range-or-undefined, we know
8528    // that doing a bittest on the i32 value is ok.  We extend to i32 because
8529    // the encoding for the i16 version is larger than the i32 version.
8530    // Also promote i16 to i32 for performance / code size reason.
8531    if (LHS.getValueType() == MVT::i8 ||
8532        LHS.getValueType() == MVT::i16)
8533      LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8534
8535    // If the operand types disagree, extend the shift amount to match.  Since
8536    // BT ignores high bits (like shifts) we can use anyextend.
8537    if (LHS.getValueType() != RHS.getValueType())
8538      RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8539
8540    SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8541    unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8542    return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8543                       DAG.getConstant(Cond, MVT::i8), BT);
8544  }
8545
8546  return SDValue();
8547}
8548
8549SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8550
8551  if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8552
8553  assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8554  SDValue Op0 = Op.getOperand(0);
8555  SDValue Op1 = Op.getOperand(1);
8556  DebugLoc dl = Op.getDebugLoc();
8557  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8558
8559  // Optimize to BT if possible.
8560  // Lower (X & (1 << N)) == 0 to BT(X, N).
8561  // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8562  // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8563  if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8564      Op1.getOpcode() == ISD::Constant &&
8565      cast<ConstantSDNode>(Op1)->isNullValue() &&
8566      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8567    SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8568    if (NewSetCC.getNode())
8569      return NewSetCC;
8570  }
8571
8572  // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8573  // these.
8574  if (Op1.getOpcode() == ISD::Constant &&
8575      (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8576       cast<ConstantSDNode>(Op1)->isNullValue()) &&
8577      (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8578
8579    // If the input is a setcc, then reuse the input setcc or use a new one with
8580    // the inverted condition.
8581    if (Op0.getOpcode() == X86ISD::SETCC) {
8582      X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8583      bool Invert = (CC == ISD::SETNE) ^
8584        cast<ConstantSDNode>(Op1)->isNullValue();
8585      if (!Invert) return Op0;
8586
8587      CCode = X86::GetOppositeBranchCondition(CCode);
8588      return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8589                         DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8590    }
8591  }
8592
8593  bool isFP = Op1.getValueType().isFloatingPoint();
8594  unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8595  if (X86CC == X86::COND_INVALID)
8596    return SDValue();
8597
8598  SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8599  return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8600                     DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8601}
8602
8603// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8604// ones, and then concatenate the result back.
8605static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8606  EVT VT = Op.getValueType();
8607
8608  assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8609         "Unsupported value type for operation");
8610
8611  int NumElems = VT.getVectorNumElements();
8612  DebugLoc dl = Op.getDebugLoc();
8613  SDValue CC = Op.getOperand(2);
8614  SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8615  SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8616
8617  // Extract the LHS vectors
8618  SDValue LHS = Op.getOperand(0);
8619  SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8620  SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8621
8622  // Extract the RHS vectors
8623  SDValue RHS = Op.getOperand(1);
8624  SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8625  SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8626
8627  // Issue the operation on the smaller types and concatenate the result back
8628  MVT EltVT = VT.getVectorElementType().getSimpleVT();
8629  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8630  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8631                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8632                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8633}
8634
8635
8636SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8637  SDValue Cond;
8638  SDValue Op0 = Op.getOperand(0);
8639  SDValue Op1 = Op.getOperand(1);
8640  SDValue CC = Op.getOperand(2);
8641  EVT VT = Op.getValueType();
8642  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8643  bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8644  DebugLoc dl = Op.getDebugLoc();
8645
8646  if (isFP) {
8647    unsigned SSECC = 8;
8648    EVT EltVT = Op0.getValueType().getVectorElementType();
8649    assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8650
8651    unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8652    bool Swap = false;
8653
8654    // SSE Condition code mapping:
8655    //  0 - EQ
8656    //  1 - LT
8657    //  2 - LE
8658    //  3 - UNORD
8659    //  4 - NEQ
8660    //  5 - NLT
8661    //  6 - NLE
8662    //  7 - ORD
8663    switch (SetCCOpcode) {
8664    default: break;
8665    case ISD::SETOEQ:
8666    case ISD::SETEQ:  SSECC = 0; break;
8667    case ISD::SETOGT:
8668    case ISD::SETGT: Swap = true; // Fallthrough
8669    case ISD::SETLT:
8670    case ISD::SETOLT: SSECC = 1; break;
8671    case ISD::SETOGE:
8672    case ISD::SETGE: Swap = true; // Fallthrough
8673    case ISD::SETLE:
8674    case ISD::SETOLE: SSECC = 2; break;
8675    case ISD::SETUO:  SSECC = 3; break;
8676    case ISD::SETUNE:
8677    case ISD::SETNE:  SSECC = 4; break;
8678    case ISD::SETULE: Swap = true;
8679    case ISD::SETUGE: SSECC = 5; break;
8680    case ISD::SETULT: Swap = true;
8681    case ISD::SETUGT: SSECC = 6; break;
8682    case ISD::SETO:   SSECC = 7; break;
8683    }
8684    if (Swap)
8685      std::swap(Op0, Op1);
8686
8687    // In the two special cases we can't handle, emit two comparisons.
8688    if (SSECC == 8) {
8689      if (SetCCOpcode == ISD::SETUEQ) {
8690        SDValue UNORD, EQ;
8691        UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8692        EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8693        return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8694      } else if (SetCCOpcode == ISD::SETONE) {
8695        SDValue ORD, NEQ;
8696        ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8697        NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8698        return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8699      }
8700      llvm_unreachable("Illegal FP comparison");
8701    }
8702    // Handle all other FP comparisons here.
8703    return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8704  }
8705
8706  // Break 256-bit integer vector compare into smaller ones.
8707  if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8708    return Lower256IntVSETCC(Op, DAG);
8709
8710  // We are handling one of the integer comparisons here.  Since SSE only has
8711  // GT and EQ comparisons for integer, swapping operands and multiple
8712  // operations may be required for some comparisons.
8713  unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8714  bool Swap = false, Invert = false, FlipSigns = false;
8715
8716  switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8717  default: break;
8718  case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8719  case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8720  case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8721  case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8722  }
8723
8724  switch (SetCCOpcode) {
8725  default: break;
8726  case ISD::SETNE:  Invert = true;
8727  case ISD::SETEQ:  Opc = EQOpc; break;
8728  case ISD::SETLT:  Swap = true;
8729  case ISD::SETGT:  Opc = GTOpc; break;
8730  case ISD::SETGE:  Swap = true;
8731  case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8732  case ISD::SETULT: Swap = true;
8733  case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8734  case ISD::SETUGE: Swap = true;
8735  case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8736  }
8737  if (Swap)
8738    std::swap(Op0, Op1);
8739
8740  // Check that the operation in question is available (most are plain SSE2,
8741  // but PCMPGTQ and PCMPEQQ have different requirements).
8742  if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8743    return SDValue();
8744  if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8745    return SDValue();
8746
8747  // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8748  // bits of the inputs before performing those operations.
8749  if (FlipSigns) {
8750    EVT EltVT = VT.getVectorElementType();
8751    SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8752                                      EltVT);
8753    std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8754    SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8755                                    SignBits.size());
8756    Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8757    Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8758  }
8759
8760  SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8761
8762  // If the logical-not of the result is required, perform that now.
8763  if (Invert)
8764    Result = DAG.getNOT(dl, Result, VT);
8765
8766  return Result;
8767}
8768
8769// isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8770static bool isX86LogicalCmp(SDValue Op) {
8771  unsigned Opc = Op.getNode()->getOpcode();
8772  if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8773    return true;
8774  if (Op.getResNo() == 1 &&
8775      (Opc == X86ISD::ADD ||
8776       Opc == X86ISD::SUB ||
8777       Opc == X86ISD::ADC ||
8778       Opc == X86ISD::SBB ||
8779       Opc == X86ISD::SMUL ||
8780       Opc == X86ISD::UMUL ||
8781       Opc == X86ISD::INC ||
8782       Opc == X86ISD::DEC ||
8783       Opc == X86ISD::OR ||
8784       Opc == X86ISD::XOR ||
8785       Opc == X86ISD::AND))
8786    return true;
8787
8788  if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8789    return true;
8790
8791  return false;
8792}
8793
8794static bool isZero(SDValue V) {
8795  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8796  return C && C->isNullValue();
8797}
8798
8799static bool isAllOnes(SDValue V) {
8800  ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8801  return C && C->isAllOnesValue();
8802}
8803
8804SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8805  bool addTest = true;
8806  SDValue Cond  = Op.getOperand(0);
8807  SDValue Op1 = Op.getOperand(1);
8808  SDValue Op2 = Op.getOperand(2);
8809  DebugLoc DL = Op.getDebugLoc();
8810  SDValue CC;
8811
8812  if (Cond.getOpcode() == ISD::SETCC) {
8813    SDValue NewCond = LowerSETCC(Cond, DAG);
8814    if (NewCond.getNode())
8815      Cond = NewCond;
8816  }
8817
8818  // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8819  // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8820  // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8821  // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8822  if (Cond.getOpcode() == X86ISD::SETCC &&
8823      Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8824      isZero(Cond.getOperand(1).getOperand(1))) {
8825    SDValue Cmp = Cond.getOperand(1);
8826
8827    unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8828
8829    if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8830        (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8831      SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8832
8833      SDValue CmpOp0 = Cmp.getOperand(0);
8834      Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8835                        CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8836
8837      SDValue Res =   // Res = 0 or -1.
8838        DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8839                    DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8840
8841      if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8842        Res = DAG.getNOT(DL, Res, Res.getValueType());
8843
8844      ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8845      if (N2C == 0 || !N2C->isNullValue())
8846        Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8847      return Res;
8848    }
8849  }
8850
8851  // Look past (and (setcc_carry (cmp ...)), 1).
8852  if (Cond.getOpcode() == ISD::AND &&
8853      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8854    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8855    if (C && C->getAPIntValue() == 1)
8856      Cond = Cond.getOperand(0);
8857  }
8858
8859  // If condition flag is set by a X86ISD::CMP, then use it as the condition
8860  // setting operand in place of the X86ISD::SETCC.
8861  unsigned CondOpcode = Cond.getOpcode();
8862  if (CondOpcode == X86ISD::SETCC ||
8863      CondOpcode == X86ISD::SETCC_CARRY) {
8864    CC = Cond.getOperand(0);
8865
8866    SDValue Cmp = Cond.getOperand(1);
8867    unsigned Opc = Cmp.getOpcode();
8868    EVT VT = Op.getValueType();
8869
8870    bool IllegalFPCMov = false;
8871    if (VT.isFloatingPoint() && !VT.isVector() &&
8872        !isScalarFPTypeInSSEReg(VT))  // FPStack?
8873      IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8874
8875    if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8876        Opc == X86ISD::BT) { // FIXME
8877      Cond = Cmp;
8878      addTest = false;
8879    }
8880  } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8881             CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8882             ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8883              Cond.getOperand(0).getValueType() != MVT::i8)) {
8884    SDValue LHS = Cond.getOperand(0);
8885    SDValue RHS = Cond.getOperand(1);
8886    unsigned X86Opcode;
8887    unsigned X86Cond;
8888    SDVTList VTs;
8889    switch (CondOpcode) {
8890    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8891    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8892    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8893    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8894    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8895    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8896    default: llvm_unreachable("unexpected overflowing operator");
8897    }
8898    if (CondOpcode == ISD::UMULO)
8899      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8900                          MVT::i32);
8901    else
8902      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8903
8904    SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8905
8906    if (CondOpcode == ISD::UMULO)
8907      Cond = X86Op.getValue(2);
8908    else
8909      Cond = X86Op.getValue(1);
8910
8911    CC = DAG.getConstant(X86Cond, MVT::i8);
8912    addTest = false;
8913  }
8914
8915  if (addTest) {
8916    // Look pass the truncate.
8917    if (Cond.getOpcode() == ISD::TRUNCATE)
8918      Cond = Cond.getOperand(0);
8919
8920    // We know the result of AND is compared against zero. Try to match
8921    // it to BT.
8922    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8923      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8924      if (NewSetCC.getNode()) {
8925        CC = NewSetCC.getOperand(0);
8926        Cond = NewSetCC.getOperand(1);
8927        addTest = false;
8928      }
8929    }
8930  }
8931
8932  if (addTest) {
8933    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8934    Cond = EmitTest(Cond, X86::COND_NE, DAG);
8935  }
8936
8937  // a <  b ? -1 :  0 -> RES = ~setcc_carry
8938  // a <  b ?  0 : -1 -> RES = setcc_carry
8939  // a >= b ? -1 :  0 -> RES = setcc_carry
8940  // a >= b ?  0 : -1 -> RES = ~setcc_carry
8941  if (Cond.getOpcode() == X86ISD::CMP) {
8942    unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8943
8944    if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8945        (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8946      SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8947                                DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8948      if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8949        return DAG.getNOT(DL, Res, Res.getValueType());
8950      return Res;
8951    }
8952  }
8953
8954  // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8955  // condition is true.
8956  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8957  SDValue Ops[] = { Op2, Op1, CC, Cond };
8958  return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8959}
8960
8961// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8962// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8963// from the AND / OR.
8964static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8965  Opc = Op.getOpcode();
8966  if (Opc != ISD::OR && Opc != ISD::AND)
8967    return false;
8968  return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8969          Op.getOperand(0).hasOneUse() &&
8970          Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8971          Op.getOperand(1).hasOneUse());
8972}
8973
8974// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8975// 1 and that the SETCC node has a single use.
8976static bool isXor1OfSetCC(SDValue Op) {
8977  if (Op.getOpcode() != ISD::XOR)
8978    return false;
8979  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8980  if (N1C && N1C->getAPIntValue() == 1) {
8981    return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8982      Op.getOperand(0).hasOneUse();
8983  }
8984  return false;
8985}
8986
8987SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8988  bool addTest = true;
8989  SDValue Chain = Op.getOperand(0);
8990  SDValue Cond  = Op.getOperand(1);
8991  SDValue Dest  = Op.getOperand(2);
8992  DebugLoc dl = Op.getDebugLoc();
8993  SDValue CC;
8994  bool Inverted = false;
8995
8996  if (Cond.getOpcode() == ISD::SETCC) {
8997    // Check for setcc([su]{add,sub,mul}o == 0).
8998    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8999        isa<ConstantSDNode>(Cond.getOperand(1)) &&
9000        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9001        Cond.getOperand(0).getResNo() == 1 &&
9002        (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9003         Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9004         Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9005         Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9006         Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9007         Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9008      Inverted = true;
9009      Cond = Cond.getOperand(0);
9010    } else {
9011      SDValue NewCond = LowerSETCC(Cond, DAG);
9012      if (NewCond.getNode())
9013        Cond = NewCond;
9014    }
9015  }
9016#if 0
9017  // FIXME: LowerXALUO doesn't handle these!!
9018  else if (Cond.getOpcode() == X86ISD::ADD  ||
9019           Cond.getOpcode() == X86ISD::SUB  ||
9020           Cond.getOpcode() == X86ISD::SMUL ||
9021           Cond.getOpcode() == X86ISD::UMUL)
9022    Cond = LowerXALUO(Cond, DAG);
9023#endif
9024
9025  // Look pass (and (setcc_carry (cmp ...)), 1).
9026  if (Cond.getOpcode() == ISD::AND &&
9027      Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9028    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9029    if (C && C->getAPIntValue() == 1)
9030      Cond = Cond.getOperand(0);
9031  }
9032
9033  // If condition flag is set by a X86ISD::CMP, then use it as the condition
9034  // setting operand in place of the X86ISD::SETCC.
9035  unsigned CondOpcode = Cond.getOpcode();
9036  if (CondOpcode == X86ISD::SETCC ||
9037      CondOpcode == X86ISD::SETCC_CARRY) {
9038    CC = Cond.getOperand(0);
9039
9040    SDValue Cmp = Cond.getOperand(1);
9041    unsigned Opc = Cmp.getOpcode();
9042    // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9043    if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9044      Cond = Cmp;
9045      addTest = false;
9046    } else {
9047      switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9048      default: break;
9049      case X86::COND_O:
9050      case X86::COND_B:
9051        // These can only come from an arithmetic instruction with overflow,
9052        // e.g. SADDO, UADDO.
9053        Cond = Cond.getNode()->getOperand(1);
9054        addTest = false;
9055        break;
9056      }
9057    }
9058  }
9059  CondOpcode = Cond.getOpcode();
9060  if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9061      CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9062      ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9063       Cond.getOperand(0).getValueType() != MVT::i8)) {
9064    SDValue LHS = Cond.getOperand(0);
9065    SDValue RHS = Cond.getOperand(1);
9066    unsigned X86Opcode;
9067    unsigned X86Cond;
9068    SDVTList VTs;
9069    switch (CondOpcode) {
9070    case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9071    case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9072    case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9073    case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9074    case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9075    case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9076    default: llvm_unreachable("unexpected overflowing operator");
9077    }
9078    if (Inverted)
9079      X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9080    if (CondOpcode == ISD::UMULO)
9081      VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9082                          MVT::i32);
9083    else
9084      VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9085
9086    SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9087
9088    if (CondOpcode == ISD::UMULO)
9089      Cond = X86Op.getValue(2);
9090    else
9091      Cond = X86Op.getValue(1);
9092
9093    CC = DAG.getConstant(X86Cond, MVT::i8);
9094    addTest = false;
9095  } else {
9096    unsigned CondOpc;
9097    if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9098      SDValue Cmp = Cond.getOperand(0).getOperand(1);
9099      if (CondOpc == ISD::OR) {
9100        // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9101        // two branches instead of an explicit OR instruction with a
9102        // separate test.
9103        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9104            isX86LogicalCmp(Cmp)) {
9105          CC = Cond.getOperand(0).getOperand(0);
9106          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9107                              Chain, Dest, CC, Cmp);
9108          CC = Cond.getOperand(1).getOperand(0);
9109          Cond = Cmp;
9110          addTest = false;
9111        }
9112      } else { // ISD::AND
9113        // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9114        // two branches instead of an explicit AND instruction with a
9115        // separate test. However, we only do this if this block doesn't
9116        // have a fall-through edge, because this requires an explicit
9117        // jmp when the condition is false.
9118        if (Cmp == Cond.getOperand(1).getOperand(1) &&
9119            isX86LogicalCmp(Cmp) &&
9120            Op.getNode()->hasOneUse()) {
9121          X86::CondCode CCode =
9122            (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9123          CCode = X86::GetOppositeBranchCondition(CCode);
9124          CC = DAG.getConstant(CCode, MVT::i8);
9125          SDNode *User = *Op.getNode()->use_begin();
9126          // Look for an unconditional branch following this conditional branch.
9127          // We need this because we need to reverse the successors in order
9128          // to implement FCMP_OEQ.
9129          if (User->getOpcode() == ISD::BR) {
9130            SDValue FalseBB = User->getOperand(1);
9131            SDNode *NewBR =
9132              DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9133            assert(NewBR == User);
9134            (void)NewBR;
9135            Dest = FalseBB;
9136
9137            Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9138                                Chain, Dest, CC, Cmp);
9139            X86::CondCode CCode =
9140              (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9141            CCode = X86::GetOppositeBranchCondition(CCode);
9142            CC = DAG.getConstant(CCode, MVT::i8);
9143            Cond = Cmp;
9144            addTest = false;
9145          }
9146        }
9147      }
9148    } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9149      // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9150      // It should be transformed during dag combiner except when the condition
9151      // is set by a arithmetics with overflow node.
9152      X86::CondCode CCode =
9153        (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9154      CCode = X86::GetOppositeBranchCondition(CCode);
9155      CC = DAG.getConstant(CCode, MVT::i8);
9156      Cond = Cond.getOperand(0).getOperand(1);
9157      addTest = false;
9158    } else if (Cond.getOpcode() == ISD::SETCC &&
9159               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9160      // For FCMP_OEQ, we can emit
9161      // two branches instead of an explicit AND instruction with a
9162      // separate test. However, we only do this if this block doesn't
9163      // have a fall-through edge, because this requires an explicit
9164      // jmp when the condition is false.
9165      if (Op.getNode()->hasOneUse()) {
9166        SDNode *User = *Op.getNode()->use_begin();
9167        // Look for an unconditional branch following this conditional branch.
9168        // We need this because we need to reverse the successors in order
9169        // to implement FCMP_OEQ.
9170        if (User->getOpcode() == ISD::BR) {
9171          SDValue FalseBB = User->getOperand(1);
9172          SDNode *NewBR =
9173            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9174          assert(NewBR == User);
9175          (void)NewBR;
9176          Dest = FalseBB;
9177
9178          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9179                                    Cond.getOperand(0), Cond.getOperand(1));
9180          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9181          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9182                              Chain, Dest, CC, Cmp);
9183          CC = DAG.getConstant(X86::COND_P, MVT::i8);
9184          Cond = Cmp;
9185          addTest = false;
9186        }
9187      }
9188    } else if (Cond.getOpcode() == ISD::SETCC &&
9189               cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9190      // For FCMP_UNE, we can emit
9191      // two branches instead of an explicit AND instruction with a
9192      // separate test. However, we only do this if this block doesn't
9193      // have a fall-through edge, because this requires an explicit
9194      // jmp when the condition is false.
9195      if (Op.getNode()->hasOneUse()) {
9196        SDNode *User = *Op.getNode()->use_begin();
9197        // Look for an unconditional branch following this conditional branch.
9198        // We need this because we need to reverse the successors in order
9199        // to implement FCMP_UNE.
9200        if (User->getOpcode() == ISD::BR) {
9201          SDValue FalseBB = User->getOperand(1);
9202          SDNode *NewBR =
9203            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9204          assert(NewBR == User);
9205          (void)NewBR;
9206
9207          SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9208                                    Cond.getOperand(0), Cond.getOperand(1));
9209          CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9210          Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9211                              Chain, Dest, CC, Cmp);
9212          CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9213          Cond = Cmp;
9214          addTest = false;
9215          Dest = FalseBB;
9216        }
9217      }
9218    }
9219  }
9220
9221  if (addTest) {
9222    // Look pass the truncate.
9223    if (Cond.getOpcode() == ISD::TRUNCATE)
9224      Cond = Cond.getOperand(0);
9225
9226    // We know the result of AND is compared against zero. Try to match
9227    // it to BT.
9228    if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9229      SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9230      if (NewSetCC.getNode()) {
9231        CC = NewSetCC.getOperand(0);
9232        Cond = NewSetCC.getOperand(1);
9233        addTest = false;
9234      }
9235    }
9236  }
9237
9238  if (addTest) {
9239    CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9240    Cond = EmitTest(Cond, X86::COND_NE, DAG);
9241  }
9242  return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9243                     Chain, Dest, CC, Cond);
9244}
9245
9246
9247// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9248// Calls to _alloca is needed to probe the stack when allocating more than 4k
9249// bytes in one go. Touching the stack at 4K increments is necessary to ensure
9250// that the guard pages used by the OS virtual memory manager are allocated in
9251// correct sequence.
9252SDValue
9253X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9254                                           SelectionDAG &DAG) const {
9255  assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9256          EnableSegmentedStacks) &&
9257         "This should be used only on Windows targets or when segmented stacks "
9258         "are being used");
9259  assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9260  DebugLoc dl = Op.getDebugLoc();
9261
9262  // Get the inputs.
9263  SDValue Chain = Op.getOperand(0);
9264  SDValue Size  = Op.getOperand(1);
9265  // FIXME: Ensure alignment here
9266
9267  bool Is64Bit = Subtarget->is64Bit();
9268  EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9269
9270  if (EnableSegmentedStacks) {
9271    MachineFunction &MF = DAG.getMachineFunction();
9272    MachineRegisterInfo &MRI = MF.getRegInfo();
9273
9274    if (Is64Bit) {
9275      // The 64 bit implementation of segmented stacks needs to clobber both r10
9276      // r11. This makes it impossible to use it along with nested parameters.
9277      const Function *F = MF.getFunction();
9278
9279      for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9280           I != E; I++)
9281        if (I->hasNestAttr())
9282          report_fatal_error("Cannot use segmented stacks with functions that "
9283                             "have nested arguments.");
9284    }
9285
9286    const TargetRegisterClass *AddrRegClass =
9287      getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9288    unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9289    Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9290    SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9291                                DAG.getRegister(Vreg, SPTy));
9292    SDValue Ops1[2] = { Value, Chain };
9293    return DAG.getMergeValues(Ops1, 2, dl);
9294  } else {
9295    SDValue Flag;
9296    unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9297
9298    Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9299    Flag = Chain.getValue(1);
9300    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9301
9302    Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9303    Flag = Chain.getValue(1);
9304
9305    Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9306
9307    SDValue Ops1[2] = { Chain.getValue(0), Chain };
9308    return DAG.getMergeValues(Ops1, 2, dl);
9309  }
9310}
9311
9312SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9313  MachineFunction &MF = DAG.getMachineFunction();
9314  X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9315
9316  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9317  DebugLoc DL = Op.getDebugLoc();
9318
9319  if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9320    // vastart just stores the address of the VarArgsFrameIndex slot into the
9321    // memory location argument.
9322    SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9323                                   getPointerTy());
9324    return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9325                        MachinePointerInfo(SV), false, false, 0);
9326  }
9327
9328  // __va_list_tag:
9329  //   gp_offset         (0 - 6 * 8)
9330  //   fp_offset         (48 - 48 + 8 * 16)
9331  //   overflow_arg_area (point to parameters coming in memory).
9332  //   reg_save_area
9333  SmallVector<SDValue, 8> MemOps;
9334  SDValue FIN = Op.getOperand(1);
9335  // Store gp_offset
9336  SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9337                               DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9338                                               MVT::i32),
9339                               FIN, MachinePointerInfo(SV), false, false, 0);
9340  MemOps.push_back(Store);
9341
9342  // Store fp_offset
9343  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9344                    FIN, DAG.getIntPtrConstant(4));
9345  Store = DAG.getStore(Op.getOperand(0), DL,
9346                       DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9347                                       MVT::i32),
9348                       FIN, MachinePointerInfo(SV, 4), false, false, 0);
9349  MemOps.push_back(Store);
9350
9351  // Store ptr to overflow_arg_area
9352  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9353                    FIN, DAG.getIntPtrConstant(4));
9354  SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9355                                    getPointerTy());
9356  Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9357                       MachinePointerInfo(SV, 8),
9358                       false, false, 0);
9359  MemOps.push_back(Store);
9360
9361  // Store ptr to reg_save_area.
9362  FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9363                    FIN, DAG.getIntPtrConstant(8));
9364  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9365                                    getPointerTy());
9366  Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9367                       MachinePointerInfo(SV, 16), false, false, 0);
9368  MemOps.push_back(Store);
9369  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9370                     &MemOps[0], MemOps.size());
9371}
9372
9373SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9374  assert(Subtarget->is64Bit() &&
9375         "LowerVAARG only handles 64-bit va_arg!");
9376  assert((Subtarget->isTargetLinux() ||
9377          Subtarget->isTargetDarwin()) &&
9378          "Unhandled target in LowerVAARG");
9379  assert(Op.getNode()->getNumOperands() == 4);
9380  SDValue Chain = Op.getOperand(0);
9381  SDValue SrcPtr = Op.getOperand(1);
9382  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9383  unsigned Align = Op.getConstantOperandVal(3);
9384  DebugLoc dl = Op.getDebugLoc();
9385
9386  EVT ArgVT = Op.getNode()->getValueType(0);
9387  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9388  uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9389  uint8_t ArgMode;
9390
9391  // Decide which area this value should be read from.
9392  // TODO: Implement the AMD64 ABI in its entirety. This simple
9393  // selection mechanism works only for the basic types.
9394  if (ArgVT == MVT::f80) {
9395    llvm_unreachable("va_arg for f80 not yet implemented");
9396  } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9397    ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9398  } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9399    ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9400  } else {
9401    llvm_unreachable("Unhandled argument type in LowerVAARG");
9402  }
9403
9404  if (ArgMode == 2) {
9405    // Sanity Check: Make sure using fp_offset makes sense.
9406    assert(!UseSoftFloat &&
9407           !(DAG.getMachineFunction()
9408                .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9409           Subtarget->hasXMM());
9410  }
9411
9412  // Insert VAARG_64 node into the DAG
9413  // VAARG_64 returns two values: Variable Argument Address, Chain
9414  SmallVector<SDValue, 11> InstOps;
9415  InstOps.push_back(Chain);
9416  InstOps.push_back(SrcPtr);
9417  InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9418  InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9419  InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9420  SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9421  SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9422                                          VTs, &InstOps[0], InstOps.size(),
9423                                          MVT::i64,
9424                                          MachinePointerInfo(SV),
9425                                          /*Align=*/0,
9426                                          /*Volatile=*/false,
9427                                          /*ReadMem=*/true,
9428                                          /*WriteMem=*/true);
9429  Chain = VAARG.getValue(1);
9430
9431  // Load the next argument and return it
9432  return DAG.getLoad(ArgVT, dl,
9433                     Chain,
9434                     VAARG,
9435                     MachinePointerInfo(),
9436                     false, false, false, 0);
9437}
9438
9439SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9440  // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9441  assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9442  SDValue Chain = Op.getOperand(0);
9443  SDValue DstPtr = Op.getOperand(1);
9444  SDValue SrcPtr = Op.getOperand(2);
9445  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9446  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9447  DebugLoc DL = Op.getDebugLoc();
9448
9449  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9450                       DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9451                       false,
9452                       MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9453}
9454
9455SDValue
9456X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9457  DebugLoc dl = Op.getDebugLoc();
9458  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9459  switch (IntNo) {
9460  default: return SDValue();    // Don't custom lower most intrinsics.
9461  // Comparison intrinsics.
9462  case Intrinsic::x86_sse_comieq_ss:
9463  case Intrinsic::x86_sse_comilt_ss:
9464  case Intrinsic::x86_sse_comile_ss:
9465  case Intrinsic::x86_sse_comigt_ss:
9466  case Intrinsic::x86_sse_comige_ss:
9467  case Intrinsic::x86_sse_comineq_ss:
9468  case Intrinsic::x86_sse_ucomieq_ss:
9469  case Intrinsic::x86_sse_ucomilt_ss:
9470  case Intrinsic::x86_sse_ucomile_ss:
9471  case Intrinsic::x86_sse_ucomigt_ss:
9472  case Intrinsic::x86_sse_ucomige_ss:
9473  case Intrinsic::x86_sse_ucomineq_ss:
9474  case Intrinsic::x86_sse2_comieq_sd:
9475  case Intrinsic::x86_sse2_comilt_sd:
9476  case Intrinsic::x86_sse2_comile_sd:
9477  case Intrinsic::x86_sse2_comigt_sd:
9478  case Intrinsic::x86_sse2_comige_sd:
9479  case Intrinsic::x86_sse2_comineq_sd:
9480  case Intrinsic::x86_sse2_ucomieq_sd:
9481  case Intrinsic::x86_sse2_ucomilt_sd:
9482  case Intrinsic::x86_sse2_ucomile_sd:
9483  case Intrinsic::x86_sse2_ucomigt_sd:
9484  case Intrinsic::x86_sse2_ucomige_sd:
9485  case Intrinsic::x86_sse2_ucomineq_sd: {
9486    unsigned Opc = 0;
9487    ISD::CondCode CC = ISD::SETCC_INVALID;
9488    switch (IntNo) {
9489    default: break;
9490    case Intrinsic::x86_sse_comieq_ss:
9491    case Intrinsic::x86_sse2_comieq_sd:
9492      Opc = X86ISD::COMI;
9493      CC = ISD::SETEQ;
9494      break;
9495    case Intrinsic::x86_sse_comilt_ss:
9496    case Intrinsic::x86_sse2_comilt_sd:
9497      Opc = X86ISD::COMI;
9498      CC = ISD::SETLT;
9499      break;
9500    case Intrinsic::x86_sse_comile_ss:
9501    case Intrinsic::x86_sse2_comile_sd:
9502      Opc = X86ISD::COMI;
9503      CC = ISD::SETLE;
9504      break;
9505    case Intrinsic::x86_sse_comigt_ss:
9506    case Intrinsic::x86_sse2_comigt_sd:
9507      Opc = X86ISD::COMI;
9508      CC = ISD::SETGT;
9509      break;
9510    case Intrinsic::x86_sse_comige_ss:
9511    case Intrinsic::x86_sse2_comige_sd:
9512      Opc = X86ISD::COMI;
9513      CC = ISD::SETGE;
9514      break;
9515    case Intrinsic::x86_sse_comineq_ss:
9516    case Intrinsic::x86_sse2_comineq_sd:
9517      Opc = X86ISD::COMI;
9518      CC = ISD::SETNE;
9519      break;
9520    case Intrinsic::x86_sse_ucomieq_ss:
9521    case Intrinsic::x86_sse2_ucomieq_sd:
9522      Opc = X86ISD::UCOMI;
9523      CC = ISD::SETEQ;
9524      break;
9525    case Intrinsic::x86_sse_ucomilt_ss:
9526    case Intrinsic::x86_sse2_ucomilt_sd:
9527      Opc = X86ISD::UCOMI;
9528      CC = ISD::SETLT;
9529      break;
9530    case Intrinsic::x86_sse_ucomile_ss:
9531    case Intrinsic::x86_sse2_ucomile_sd:
9532      Opc = X86ISD::UCOMI;
9533      CC = ISD::SETLE;
9534      break;
9535    case Intrinsic::x86_sse_ucomigt_ss:
9536    case Intrinsic::x86_sse2_ucomigt_sd:
9537      Opc = X86ISD::UCOMI;
9538      CC = ISD::SETGT;
9539      break;
9540    case Intrinsic::x86_sse_ucomige_ss:
9541    case Intrinsic::x86_sse2_ucomige_sd:
9542      Opc = X86ISD::UCOMI;
9543      CC = ISD::SETGE;
9544      break;
9545    case Intrinsic::x86_sse_ucomineq_ss:
9546    case Intrinsic::x86_sse2_ucomineq_sd:
9547      Opc = X86ISD::UCOMI;
9548      CC = ISD::SETNE;
9549      break;
9550    }
9551
9552    SDValue LHS = Op.getOperand(1);
9553    SDValue RHS = Op.getOperand(2);
9554    unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9555    assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9556    SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9557    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9558                                DAG.getConstant(X86CC, MVT::i8), Cond);
9559    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9560  }
9561  // Arithmetic intrinsics.
9562  case Intrinsic::x86_sse3_hadd_ps:
9563  case Intrinsic::x86_sse3_hadd_pd:
9564  case Intrinsic::x86_avx_hadd_ps_256:
9565  case Intrinsic::x86_avx_hadd_pd_256:
9566    return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9567                       Op.getOperand(1), Op.getOperand(2));
9568  case Intrinsic::x86_sse3_hsub_ps:
9569  case Intrinsic::x86_sse3_hsub_pd:
9570  case Intrinsic::x86_avx_hsub_ps_256:
9571  case Intrinsic::x86_avx_hsub_pd_256:
9572    return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9573                       Op.getOperand(1), Op.getOperand(2));
9574  case Intrinsic::x86_avx2_psllv_d:
9575  case Intrinsic::x86_avx2_psllv_q:
9576  case Intrinsic::x86_avx2_psllv_d_256:
9577  case Intrinsic::x86_avx2_psllv_q_256:
9578    return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9579                      Op.getOperand(1), Op.getOperand(2));
9580  case Intrinsic::x86_avx2_psrlv_d:
9581  case Intrinsic::x86_avx2_psrlv_q:
9582  case Intrinsic::x86_avx2_psrlv_d_256:
9583  case Intrinsic::x86_avx2_psrlv_q_256:
9584    return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9585                      Op.getOperand(1), Op.getOperand(2));
9586  case Intrinsic::x86_avx2_psrav_d:
9587  case Intrinsic::x86_avx2_psrav_d_256:
9588    return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9589                      Op.getOperand(1), Op.getOperand(2));
9590
9591  // ptest and testp intrinsics. The intrinsic these come from are designed to
9592  // return an integer value, not just an instruction so lower it to the ptest
9593  // or testp pattern and a setcc for the result.
9594  case Intrinsic::x86_sse41_ptestz:
9595  case Intrinsic::x86_sse41_ptestc:
9596  case Intrinsic::x86_sse41_ptestnzc:
9597  case Intrinsic::x86_avx_ptestz_256:
9598  case Intrinsic::x86_avx_ptestc_256:
9599  case Intrinsic::x86_avx_ptestnzc_256:
9600  case Intrinsic::x86_avx_vtestz_ps:
9601  case Intrinsic::x86_avx_vtestc_ps:
9602  case Intrinsic::x86_avx_vtestnzc_ps:
9603  case Intrinsic::x86_avx_vtestz_pd:
9604  case Intrinsic::x86_avx_vtestc_pd:
9605  case Intrinsic::x86_avx_vtestnzc_pd:
9606  case Intrinsic::x86_avx_vtestz_ps_256:
9607  case Intrinsic::x86_avx_vtestc_ps_256:
9608  case Intrinsic::x86_avx_vtestnzc_ps_256:
9609  case Intrinsic::x86_avx_vtestz_pd_256:
9610  case Intrinsic::x86_avx_vtestc_pd_256:
9611  case Intrinsic::x86_avx_vtestnzc_pd_256: {
9612    bool IsTestPacked = false;
9613    unsigned X86CC = 0;
9614    switch (IntNo) {
9615    default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9616    case Intrinsic::x86_avx_vtestz_ps:
9617    case Intrinsic::x86_avx_vtestz_pd:
9618    case Intrinsic::x86_avx_vtestz_ps_256:
9619    case Intrinsic::x86_avx_vtestz_pd_256:
9620      IsTestPacked = true; // Fallthrough
9621    case Intrinsic::x86_sse41_ptestz:
9622    case Intrinsic::x86_avx_ptestz_256:
9623      // ZF = 1
9624      X86CC = X86::COND_E;
9625      break;
9626    case Intrinsic::x86_avx_vtestc_ps:
9627    case Intrinsic::x86_avx_vtestc_pd:
9628    case Intrinsic::x86_avx_vtestc_ps_256:
9629    case Intrinsic::x86_avx_vtestc_pd_256:
9630      IsTestPacked = true; // Fallthrough
9631    case Intrinsic::x86_sse41_ptestc:
9632    case Intrinsic::x86_avx_ptestc_256:
9633      // CF = 1
9634      X86CC = X86::COND_B;
9635      break;
9636    case Intrinsic::x86_avx_vtestnzc_ps:
9637    case Intrinsic::x86_avx_vtestnzc_pd:
9638    case Intrinsic::x86_avx_vtestnzc_ps_256:
9639    case Intrinsic::x86_avx_vtestnzc_pd_256:
9640      IsTestPacked = true; // Fallthrough
9641    case Intrinsic::x86_sse41_ptestnzc:
9642    case Intrinsic::x86_avx_ptestnzc_256:
9643      // ZF and CF = 0
9644      X86CC = X86::COND_A;
9645      break;
9646    }
9647
9648    SDValue LHS = Op.getOperand(1);
9649    SDValue RHS = Op.getOperand(2);
9650    unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9651    SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9652    SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9653    SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9654    return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9655  }
9656
9657  // Fix vector shift instructions where the last operand is a non-immediate
9658  // i32 value.
9659  case Intrinsic::x86_avx2_pslli_w:
9660  case Intrinsic::x86_avx2_pslli_d:
9661  case Intrinsic::x86_avx2_pslli_q:
9662  case Intrinsic::x86_avx2_psrli_w:
9663  case Intrinsic::x86_avx2_psrli_d:
9664  case Intrinsic::x86_avx2_psrli_q:
9665  case Intrinsic::x86_avx2_psrai_w:
9666  case Intrinsic::x86_avx2_psrai_d:
9667  case Intrinsic::x86_sse2_pslli_w:
9668  case Intrinsic::x86_sse2_pslli_d:
9669  case Intrinsic::x86_sse2_pslli_q:
9670  case Intrinsic::x86_sse2_psrli_w:
9671  case Intrinsic::x86_sse2_psrli_d:
9672  case Intrinsic::x86_sse2_psrli_q:
9673  case Intrinsic::x86_sse2_psrai_w:
9674  case Intrinsic::x86_sse2_psrai_d:
9675  case Intrinsic::x86_mmx_pslli_w:
9676  case Intrinsic::x86_mmx_pslli_d:
9677  case Intrinsic::x86_mmx_pslli_q:
9678  case Intrinsic::x86_mmx_psrli_w:
9679  case Intrinsic::x86_mmx_psrli_d:
9680  case Intrinsic::x86_mmx_psrli_q:
9681  case Intrinsic::x86_mmx_psrai_w:
9682  case Intrinsic::x86_mmx_psrai_d: {
9683    SDValue ShAmt = Op.getOperand(2);
9684    if (isa<ConstantSDNode>(ShAmt))
9685      return SDValue();
9686
9687    unsigned NewIntNo = 0;
9688    EVT ShAmtVT = MVT::v4i32;
9689    switch (IntNo) {
9690    case Intrinsic::x86_sse2_pslli_w:
9691      NewIntNo = Intrinsic::x86_sse2_psll_w;
9692      break;
9693    case Intrinsic::x86_sse2_pslli_d:
9694      NewIntNo = Intrinsic::x86_sse2_psll_d;
9695      break;
9696    case Intrinsic::x86_sse2_pslli_q:
9697      NewIntNo = Intrinsic::x86_sse2_psll_q;
9698      break;
9699    case Intrinsic::x86_sse2_psrli_w:
9700      NewIntNo = Intrinsic::x86_sse2_psrl_w;
9701      break;
9702    case Intrinsic::x86_sse2_psrli_d:
9703      NewIntNo = Intrinsic::x86_sse2_psrl_d;
9704      break;
9705    case Intrinsic::x86_sse2_psrli_q:
9706      NewIntNo = Intrinsic::x86_sse2_psrl_q;
9707      break;
9708    case Intrinsic::x86_sse2_psrai_w:
9709      NewIntNo = Intrinsic::x86_sse2_psra_w;
9710      break;
9711    case Intrinsic::x86_sse2_psrai_d:
9712      NewIntNo = Intrinsic::x86_sse2_psra_d;
9713      break;
9714    case Intrinsic::x86_avx2_pslli_w:
9715      NewIntNo = Intrinsic::x86_avx2_psll_w;
9716      break;
9717    case Intrinsic::x86_avx2_pslli_d:
9718      NewIntNo = Intrinsic::x86_avx2_psll_d;
9719      break;
9720    case Intrinsic::x86_avx2_pslli_q:
9721      NewIntNo = Intrinsic::x86_avx2_psll_q;
9722      break;
9723    case Intrinsic::x86_avx2_psrli_w:
9724      NewIntNo = Intrinsic::x86_avx2_psrl_w;
9725      break;
9726    case Intrinsic::x86_avx2_psrli_d:
9727      NewIntNo = Intrinsic::x86_avx2_psrl_d;
9728      break;
9729    case Intrinsic::x86_avx2_psrli_q:
9730      NewIntNo = Intrinsic::x86_avx2_psrl_q;
9731      break;
9732    case Intrinsic::x86_avx2_psrai_w:
9733      NewIntNo = Intrinsic::x86_avx2_psra_w;
9734      break;
9735    case Intrinsic::x86_avx2_psrai_d:
9736      NewIntNo = Intrinsic::x86_avx2_psra_d;
9737      break;
9738    default: {
9739      ShAmtVT = MVT::v2i32;
9740      switch (IntNo) {
9741      case Intrinsic::x86_mmx_pslli_w:
9742        NewIntNo = Intrinsic::x86_mmx_psll_w;
9743        break;
9744      case Intrinsic::x86_mmx_pslli_d:
9745        NewIntNo = Intrinsic::x86_mmx_psll_d;
9746        break;
9747      case Intrinsic::x86_mmx_pslli_q:
9748        NewIntNo = Intrinsic::x86_mmx_psll_q;
9749        break;
9750      case Intrinsic::x86_mmx_psrli_w:
9751        NewIntNo = Intrinsic::x86_mmx_psrl_w;
9752        break;
9753      case Intrinsic::x86_mmx_psrli_d:
9754        NewIntNo = Intrinsic::x86_mmx_psrl_d;
9755        break;
9756      case Intrinsic::x86_mmx_psrli_q:
9757        NewIntNo = Intrinsic::x86_mmx_psrl_q;
9758        break;
9759      case Intrinsic::x86_mmx_psrai_w:
9760        NewIntNo = Intrinsic::x86_mmx_psra_w;
9761        break;
9762      case Intrinsic::x86_mmx_psrai_d:
9763        NewIntNo = Intrinsic::x86_mmx_psra_d;
9764        break;
9765      default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9766      }
9767      break;
9768    }
9769    }
9770
9771    // The vector shift intrinsics with scalars uses 32b shift amounts but
9772    // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9773    // to be zero.
9774    SDValue ShOps[4];
9775    ShOps[0] = ShAmt;
9776    ShOps[1] = DAG.getConstant(0, MVT::i32);
9777    if (ShAmtVT == MVT::v4i32) {
9778      ShOps[2] = DAG.getUNDEF(MVT::i32);
9779      ShOps[3] = DAG.getUNDEF(MVT::i32);
9780      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9781    } else {
9782      ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9783// FIXME this must be lowered to get rid of the invalid type.
9784    }
9785
9786    EVT VT = Op.getValueType();
9787    ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9788    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9789                       DAG.getConstant(NewIntNo, MVT::i32),
9790                       Op.getOperand(1), ShAmt);
9791  }
9792  }
9793}
9794
9795SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9796                                           SelectionDAG &DAG) const {
9797  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9798  MFI->setReturnAddressIsTaken(true);
9799
9800  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9801  DebugLoc dl = Op.getDebugLoc();
9802
9803  if (Depth > 0) {
9804    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9805    SDValue Offset =
9806      DAG.getConstant(TD->getPointerSize(),
9807                      Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9808    return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9809                       DAG.getNode(ISD::ADD, dl, getPointerTy(),
9810                                   FrameAddr, Offset),
9811                       MachinePointerInfo(), false, false, false, 0);
9812  }
9813
9814  // Just load the return address.
9815  SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9816  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9817                     RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9818}
9819
9820SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9821  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9822  MFI->setFrameAddressIsTaken(true);
9823
9824  EVT VT = Op.getValueType();
9825  DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9826  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9827  unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9828  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9829  while (Depth--)
9830    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9831                            MachinePointerInfo(),
9832                            false, false, false, 0);
9833  return FrameAddr;
9834}
9835
9836SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9837                                                     SelectionDAG &DAG) const {
9838  return DAG.getIntPtrConstant(2*TD->getPointerSize());
9839}
9840
9841SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9842  MachineFunction &MF = DAG.getMachineFunction();
9843  SDValue Chain     = Op.getOperand(0);
9844  SDValue Offset    = Op.getOperand(1);
9845  SDValue Handler   = Op.getOperand(2);
9846  DebugLoc dl       = Op.getDebugLoc();
9847
9848  SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9849                                     Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9850                                     getPointerTy());
9851  unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9852
9853  SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9854                                  DAG.getIntPtrConstant(TD->getPointerSize()));
9855  StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9856  Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9857                       false, false, 0);
9858  Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9859  MF.getRegInfo().addLiveOut(StoreAddrReg);
9860
9861  return DAG.getNode(X86ISD::EH_RETURN, dl,
9862                     MVT::Other,
9863                     Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9864}
9865
9866SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9867                                                  SelectionDAG &DAG) const {
9868  return Op.getOperand(0);
9869}
9870
9871SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9872                                                SelectionDAG &DAG) const {
9873  SDValue Root = Op.getOperand(0);
9874  SDValue Trmp = Op.getOperand(1); // trampoline
9875  SDValue FPtr = Op.getOperand(2); // nested function
9876  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9877  DebugLoc dl  = Op.getDebugLoc();
9878
9879  const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9880
9881  if (Subtarget->is64Bit()) {
9882    SDValue OutChains[6];
9883
9884    // Large code-model.
9885    const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9886    const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9887
9888    const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9889    const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9890
9891    const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9892
9893    // Load the pointer to the nested function into R11.
9894    unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9895    SDValue Addr = Trmp;
9896    OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9897                                Addr, MachinePointerInfo(TrmpAddr),
9898                                false, false, 0);
9899
9900    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9901                       DAG.getConstant(2, MVT::i64));
9902    OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9903                                MachinePointerInfo(TrmpAddr, 2),
9904                                false, false, 2);
9905
9906    // Load the 'nest' parameter value into R10.
9907    // R10 is specified in X86CallingConv.td
9908    OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9909    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9910                       DAG.getConstant(10, MVT::i64));
9911    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9912                                Addr, MachinePointerInfo(TrmpAddr, 10),
9913                                false, false, 0);
9914
9915    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9916                       DAG.getConstant(12, MVT::i64));
9917    OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9918                                MachinePointerInfo(TrmpAddr, 12),
9919                                false, false, 2);
9920
9921    // Jump to the nested function.
9922    OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9923    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9924                       DAG.getConstant(20, MVT::i64));
9925    OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9926                                Addr, MachinePointerInfo(TrmpAddr, 20),
9927                                false, false, 0);
9928
9929    unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9930    Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9931                       DAG.getConstant(22, MVT::i64));
9932    OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9933                                MachinePointerInfo(TrmpAddr, 22),
9934                                false, false, 0);
9935
9936    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9937  } else {
9938    const Function *Func =
9939      cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9940    CallingConv::ID CC = Func->getCallingConv();
9941    unsigned NestReg;
9942
9943    switch (CC) {
9944    default:
9945      llvm_unreachable("Unsupported calling convention");
9946    case CallingConv::C:
9947    case CallingConv::X86_StdCall: {
9948      // Pass 'nest' parameter in ECX.
9949      // Must be kept in sync with X86CallingConv.td
9950      NestReg = X86::ECX;
9951
9952      // Check that ECX wasn't needed by an 'inreg' parameter.
9953      FunctionType *FTy = Func->getFunctionType();
9954      const AttrListPtr &Attrs = Func->getAttributes();
9955
9956      if (!Attrs.isEmpty() && !Func->isVarArg()) {
9957        unsigned InRegCount = 0;
9958        unsigned Idx = 1;
9959
9960        for (FunctionType::param_iterator I = FTy->param_begin(),
9961             E = FTy->param_end(); I != E; ++I, ++Idx)
9962          if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9963            // FIXME: should only count parameters that are lowered to integers.
9964            InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9965
9966        if (InRegCount > 2) {
9967          report_fatal_error("Nest register in use - reduce number of inreg"
9968                             " parameters!");
9969        }
9970      }
9971      break;
9972    }
9973    case CallingConv::X86_FastCall:
9974    case CallingConv::X86_ThisCall:
9975    case CallingConv::Fast:
9976      // Pass 'nest' parameter in EAX.
9977      // Must be kept in sync with X86CallingConv.td
9978      NestReg = X86::EAX;
9979      break;
9980    }
9981
9982    SDValue OutChains[4];
9983    SDValue Addr, Disp;
9984
9985    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9986                       DAG.getConstant(10, MVT::i32));
9987    Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9988
9989    // This is storing the opcode for MOV32ri.
9990    const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9991    const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9992    OutChains[0] = DAG.getStore(Root, dl,
9993                                DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9994                                Trmp, MachinePointerInfo(TrmpAddr),
9995                                false, false, 0);
9996
9997    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9998                       DAG.getConstant(1, MVT::i32));
9999    OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10000                                MachinePointerInfo(TrmpAddr, 1),
10001                                false, false, 1);
10002
10003    const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10004    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10005                       DAG.getConstant(5, MVT::i32));
10006    OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10007                                MachinePointerInfo(TrmpAddr, 5),
10008                                false, false, 1);
10009
10010    Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10011                       DAG.getConstant(6, MVT::i32));
10012    OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10013                                MachinePointerInfo(TrmpAddr, 6),
10014                                false, false, 1);
10015
10016    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10017  }
10018}
10019
10020SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10021                                            SelectionDAG &DAG) const {
10022  /*
10023   The rounding mode is in bits 11:10 of FPSR, and has the following
10024   settings:
10025     00 Round to nearest
10026     01 Round to -inf
10027     10 Round to +inf
10028     11 Round to 0
10029
10030  FLT_ROUNDS, on the other hand, expects the following:
10031    -1 Undefined
10032     0 Round to 0
10033     1 Round to nearest
10034     2 Round to +inf
10035     3 Round to -inf
10036
10037  To perform the conversion, we do:
10038    (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10039  */
10040
10041  MachineFunction &MF = DAG.getMachineFunction();
10042  const TargetMachine &TM = MF.getTarget();
10043  const TargetFrameLowering &TFI = *TM.getFrameLowering();
10044  unsigned StackAlignment = TFI.getStackAlignment();
10045  EVT VT = Op.getValueType();
10046  DebugLoc DL = Op.getDebugLoc();
10047
10048  // Save FP Control Word to stack slot
10049  int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10050  SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10051
10052
10053  MachineMemOperand *MMO =
10054   MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10055                           MachineMemOperand::MOStore, 2, 2);
10056
10057  SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10058  SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10059                                          DAG.getVTList(MVT::Other),
10060                                          Ops, 2, MVT::i16, MMO);
10061
10062  // Load FP Control Word from stack slot
10063  SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10064                            MachinePointerInfo(), false, false, false, 0);
10065
10066  // Transform as necessary
10067  SDValue CWD1 =
10068    DAG.getNode(ISD::SRL, DL, MVT::i16,
10069                DAG.getNode(ISD::AND, DL, MVT::i16,
10070                            CWD, DAG.getConstant(0x800, MVT::i16)),
10071                DAG.getConstant(11, MVT::i8));
10072  SDValue CWD2 =
10073    DAG.getNode(ISD::SRL, DL, MVT::i16,
10074                DAG.getNode(ISD::AND, DL, MVT::i16,
10075                            CWD, DAG.getConstant(0x400, MVT::i16)),
10076                DAG.getConstant(9, MVT::i8));
10077
10078  SDValue RetVal =
10079    DAG.getNode(ISD::AND, DL, MVT::i16,
10080                DAG.getNode(ISD::ADD, DL, MVT::i16,
10081                            DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10082                            DAG.getConstant(1, MVT::i16)),
10083                DAG.getConstant(3, MVT::i16));
10084
10085
10086  return DAG.getNode((VT.getSizeInBits() < 16 ?
10087                      ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10088}
10089
10090SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10091  EVT VT = Op.getValueType();
10092  EVT OpVT = VT;
10093  unsigned NumBits = VT.getSizeInBits();
10094  DebugLoc dl = Op.getDebugLoc();
10095
10096  Op = Op.getOperand(0);
10097  if (VT == MVT::i8) {
10098    // Zero extend to i32 since there is not an i8 bsr.
10099    OpVT = MVT::i32;
10100    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10101  }
10102
10103  // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10104  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10105  Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10106
10107  // If src is zero (i.e. bsr sets ZF), returns NumBits.
10108  SDValue Ops[] = {
10109    Op,
10110    DAG.getConstant(NumBits+NumBits-1, OpVT),
10111    DAG.getConstant(X86::COND_E, MVT::i8),
10112    Op.getValue(1)
10113  };
10114  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10115
10116  // Finally xor with NumBits-1.
10117  Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10118
10119  if (VT == MVT::i8)
10120    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10121  return Op;
10122}
10123
10124SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10125  EVT VT = Op.getValueType();
10126  EVT OpVT = VT;
10127  unsigned NumBits = VT.getSizeInBits();
10128  DebugLoc dl = Op.getDebugLoc();
10129
10130  Op = Op.getOperand(0);
10131  if (VT == MVT::i8) {
10132    OpVT = MVT::i32;
10133    Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10134  }
10135
10136  // Issue a bsf (scan bits forward) which also sets EFLAGS.
10137  SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10138  Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10139
10140  // If src is zero (i.e. bsf sets ZF), returns NumBits.
10141  SDValue Ops[] = {
10142    Op,
10143    DAG.getConstant(NumBits, OpVT),
10144    DAG.getConstant(X86::COND_E, MVT::i8),
10145    Op.getValue(1)
10146  };
10147  Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10148
10149  if (VT == MVT::i8)
10150    Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10151  return Op;
10152}
10153
10154// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10155// ones, and then concatenate the result back.
10156static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10157  EVT VT = Op.getValueType();
10158
10159  assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10160         "Unsupported value type for operation");
10161
10162  int NumElems = VT.getVectorNumElements();
10163  DebugLoc dl = Op.getDebugLoc();
10164  SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10165  SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10166
10167  // Extract the LHS vectors
10168  SDValue LHS = Op.getOperand(0);
10169  SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10170  SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10171
10172  // Extract the RHS vectors
10173  SDValue RHS = Op.getOperand(1);
10174  SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10175  SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10176
10177  MVT EltVT = VT.getVectorElementType().getSimpleVT();
10178  EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10179
10180  return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10181                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10182                     DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10183}
10184
10185SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10186  assert(Op.getValueType().getSizeInBits() == 256 &&
10187         Op.getValueType().isInteger() &&
10188         "Only handle AVX 256-bit vector integer operation");
10189  return Lower256IntArith(Op, DAG);
10190}
10191
10192SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10193  assert(Op.getValueType().getSizeInBits() == 256 &&
10194         Op.getValueType().isInteger() &&
10195         "Only handle AVX 256-bit vector integer operation");
10196  return Lower256IntArith(Op, DAG);
10197}
10198
10199SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10200  EVT VT = Op.getValueType();
10201
10202  // Decompose 256-bit ops into smaller 128-bit ops.
10203  if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10204    return Lower256IntArith(Op, DAG);
10205
10206  DebugLoc dl = Op.getDebugLoc();
10207
10208  SDValue A = Op.getOperand(0);
10209  SDValue B = Op.getOperand(1);
10210
10211  if (VT == MVT::v4i64) {
10212    assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10213
10214    //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10215    //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10216    //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10217    //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10218    //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10219    //
10220    //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10221    //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10222    //  return AloBlo + AloBhi + AhiBlo;
10223
10224    SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10225                         DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10226                         A, DAG.getConstant(32, MVT::i32));
10227    SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10228                         DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10229                         B, DAG.getConstant(32, MVT::i32));
10230    SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10231                         DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10232                         A, B);
10233    SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10234                         DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10235                         A, Bhi);
10236    SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10237                         DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10238                         Ahi, B);
10239    AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10240                         DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10241                         AloBhi, DAG.getConstant(32, MVT::i32));
10242    AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10243                         DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10244                         AhiBlo, DAG.getConstant(32, MVT::i32));
10245    SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10246    Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10247    return Res;
10248  }
10249
10250  assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10251
10252  //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10253  //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10254  //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10255  //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10256  //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10257  //
10258  //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10259  //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10260  //  return AloBlo + AloBhi + AhiBlo;
10261
10262  SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10263                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10264                       A, DAG.getConstant(32, MVT::i32));
10265  SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10266                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10267                       B, DAG.getConstant(32, MVT::i32));
10268  SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10269                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10270                       A, B);
10271  SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10272                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10273                       A, Bhi);
10274  SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10275                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10276                       Ahi, B);
10277  AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10278                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10279                       AloBhi, DAG.getConstant(32, MVT::i32));
10280  AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10281                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10282                       AhiBlo, DAG.getConstant(32, MVT::i32));
10283  SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10284  Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10285  return Res;
10286}
10287
10288SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10289
10290  EVT VT = Op.getValueType();
10291  DebugLoc dl = Op.getDebugLoc();
10292  SDValue R = Op.getOperand(0);
10293  SDValue Amt = Op.getOperand(1);
10294  LLVMContext *Context = DAG.getContext();
10295
10296  if (!Subtarget->hasXMMInt())
10297    return SDValue();
10298
10299  // Optimize shl/srl/sra with constant shift amount.
10300  if (isSplatVector(Amt.getNode())) {
10301    SDValue SclrAmt = Amt->getOperand(0);
10302    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10303      uint64_t ShiftAmt = C->getZExtValue();
10304
10305      if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10306        // Make a large shift.
10307        SDValue SHL =
10308          DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10309                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10310                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10311        // Zero out the rightmost bits.
10312        SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10313                                                       MVT::i8));
10314        return DAG.getNode(ISD::AND, dl, VT, SHL,
10315                           DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10316      }
10317
10318      if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10319       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10320                     DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10321                     R, DAG.getConstant(ShiftAmt, MVT::i32));
10322
10323      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10324       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10325                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10326                     R, DAG.getConstant(ShiftAmt, MVT::i32));
10327
10328      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10329       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10330                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10331                     R, DAG.getConstant(ShiftAmt, MVT::i32));
10332
10333      if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10334        // Make a large shift.
10335        SDValue SRL =
10336          DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10337                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10338                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10339        // Zero out the leftmost bits.
10340        SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10341                                                       MVT::i8));
10342        return DAG.getNode(ISD::AND, dl, VT, SRL,
10343                           DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10344      }
10345
10346      if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10347       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10348                     DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10349                     R, DAG.getConstant(ShiftAmt, MVT::i32));
10350
10351      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10352       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10353                     DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10354                     R, DAG.getConstant(ShiftAmt, MVT::i32));
10355
10356      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10357       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10358                     DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10359                     R, DAG.getConstant(ShiftAmt, MVT::i32));
10360
10361      if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10362       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10363                     DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10364                     R, DAG.getConstant(ShiftAmt, MVT::i32));
10365
10366      if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10367       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10368                     DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10369                     R, DAG.getConstant(ShiftAmt, MVT::i32));
10370
10371      if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10372        if (ShiftAmt == 7) {
10373          // R s>> 7  ===  R s< 0
10374          SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10375          return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10376        }
10377
10378        // R s>> a === ((R u>> a) ^ m) - m
10379        SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10380        SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10381                                                       MVT::i8));
10382        SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10383        Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10384        Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10385        return Res;
10386      }
10387
10388      if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10389        if (Op.getOpcode() == ISD::SHL) {
10390          // Make a large shift.
10391          SDValue SHL =
10392            DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10393                        DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10394                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10395          // Zero out the rightmost bits.
10396          SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10397                                                         MVT::i8));
10398          return DAG.getNode(ISD::AND, dl, VT, SHL,
10399                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10400        }
10401        if (Op.getOpcode() == ISD::SRL) {
10402          // Make a large shift.
10403          SDValue SRL =
10404            DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10405                        DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10406                        R, DAG.getConstant(ShiftAmt, MVT::i32));
10407          // Zero out the leftmost bits.
10408          SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10409                                                         MVT::i8));
10410          return DAG.getNode(ISD::AND, dl, VT, SRL,
10411                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10412        }
10413        if (Op.getOpcode() == ISD::SRA) {
10414          if (ShiftAmt == 7) {
10415            // R s>> 7  ===  R s< 0
10416            SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10417            return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10418          }
10419
10420          // R s>> a === ((R u>> a) ^ m) - m
10421          SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10422          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10423                                                         MVT::i8));
10424          SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10425          Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10426          Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10427          return Res;
10428        }
10429      }
10430    }
10431  }
10432
10433  // Lower SHL with variable shift amount.
10434  if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10435    Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10436                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10437                     Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10438
10439    ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10440
10441    std::vector<Constant*> CV(4, CI);
10442    Constant *C = ConstantVector::get(CV);
10443    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10444    SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10445                                 MachinePointerInfo::getConstantPool(),
10446                                 false, false, false, 16);
10447
10448    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10449    Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10450    Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10451    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10452  }
10453  if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10454    // a = a << 5;
10455    Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10456                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10457                     Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10458
10459    ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10460    ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10461
10462    std::vector<Constant*> CVM1(16, CM1);
10463    std::vector<Constant*> CVM2(16, CM2);
10464    Constant *C = ConstantVector::get(CVM1);
10465    SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10466    SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10467                            MachinePointerInfo::getConstantPool(),
10468                            false, false, false, 16);
10469
10470    // r = pblendv(r, psllw(r & (char16)15, 4), a);
10471    M = DAG.getNode(ISD::AND, dl, VT, R, M);
10472    M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10473                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10474                    DAG.getConstant(4, MVT::i32));
10475    R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10476    // a += a
10477    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10478
10479    C = ConstantVector::get(CVM2);
10480    CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10481    M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10482                    MachinePointerInfo::getConstantPool(),
10483                    false, false, false, 16);
10484
10485    // r = pblendv(r, psllw(r & (char16)63, 2), a);
10486    M = DAG.getNode(ISD::AND, dl, VT, R, M);
10487    M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10488                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10489                    DAG.getConstant(2, MVT::i32));
10490    R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10491    // a += a
10492    Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10493
10494    // return pblendv(r, r+r, a);
10495    R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10496                    R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10497    return R;
10498  }
10499
10500  // Decompose 256-bit shifts into smaller 128-bit shifts.
10501  if (VT.getSizeInBits() == 256) {
10502    int NumElems = VT.getVectorNumElements();
10503    MVT EltVT = VT.getVectorElementType().getSimpleVT();
10504    EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10505
10506    // Extract the two vectors
10507    SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10508    SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10509                                     DAG, dl);
10510
10511    // Recreate the shift amount vectors
10512    SDValue Amt1, Amt2;
10513    if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10514      // Constant shift amount
10515      SmallVector<SDValue, 4> Amt1Csts;
10516      SmallVector<SDValue, 4> Amt2Csts;
10517      for (int i = 0; i < NumElems/2; ++i)
10518        Amt1Csts.push_back(Amt->getOperand(i));
10519      for (int i = NumElems/2; i < NumElems; ++i)
10520        Amt2Csts.push_back(Amt->getOperand(i));
10521
10522      Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10523                                 &Amt1Csts[0], NumElems/2);
10524      Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10525                                 &Amt2Csts[0], NumElems/2);
10526    } else {
10527      // Variable shift amount
10528      Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10529      Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10530                                 DAG, dl);
10531    }
10532
10533    // Issue new vector shifts for the smaller types
10534    V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10535    V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10536
10537    // Concatenate the result back
10538    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10539  }
10540
10541  return SDValue();
10542}
10543
10544SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10545  // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10546  // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10547  // looks for this combo and may remove the "setcc" instruction if the "setcc"
10548  // has only one use.
10549  SDNode *N = Op.getNode();
10550  SDValue LHS = N->getOperand(0);
10551  SDValue RHS = N->getOperand(1);
10552  unsigned BaseOp = 0;
10553  unsigned Cond = 0;
10554  DebugLoc DL = Op.getDebugLoc();
10555  switch (Op.getOpcode()) {
10556  default: llvm_unreachable("Unknown ovf instruction!");
10557  case ISD::SADDO:
10558    // A subtract of one will be selected as a INC. Note that INC doesn't
10559    // set CF, so we can't do this for UADDO.
10560    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10561      if (C->isOne()) {
10562        BaseOp = X86ISD::INC;
10563        Cond = X86::COND_O;
10564        break;
10565      }
10566    BaseOp = X86ISD::ADD;
10567    Cond = X86::COND_O;
10568    break;
10569  case ISD::UADDO:
10570    BaseOp = X86ISD::ADD;
10571    Cond = X86::COND_B;
10572    break;
10573  case ISD::SSUBO:
10574    // A subtract of one will be selected as a DEC. Note that DEC doesn't
10575    // set CF, so we can't do this for USUBO.
10576    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10577      if (C->isOne()) {
10578        BaseOp = X86ISD::DEC;
10579        Cond = X86::COND_O;
10580        break;
10581      }
10582    BaseOp = X86ISD::SUB;
10583    Cond = X86::COND_O;
10584    break;
10585  case ISD::USUBO:
10586    BaseOp = X86ISD::SUB;
10587    Cond = X86::COND_B;
10588    break;
10589  case ISD::SMULO:
10590    BaseOp = X86ISD::SMUL;
10591    Cond = X86::COND_O;
10592    break;
10593  case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10594    SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10595                                 MVT::i32);
10596    SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10597
10598    SDValue SetCC =
10599      DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10600                  DAG.getConstant(X86::COND_O, MVT::i32),
10601                  SDValue(Sum.getNode(), 2));
10602
10603    return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10604  }
10605  }
10606
10607  // Also sets EFLAGS.
10608  SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10609  SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10610
10611  SDValue SetCC =
10612    DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10613                DAG.getConstant(Cond, MVT::i32),
10614                SDValue(Sum.getNode(), 1));
10615
10616  return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10617}
10618
10619SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10620  DebugLoc dl = Op.getDebugLoc();
10621  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10622  EVT VT = Op.getValueType();
10623
10624  if (Subtarget->hasXMMInt() && VT.isVector()) {
10625    unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10626                        ExtraVT.getScalarType().getSizeInBits();
10627    SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10628
10629    unsigned SHLIntrinsicsID = 0;
10630    unsigned SRAIntrinsicsID = 0;
10631    switch (VT.getSimpleVT().SimpleTy) {
10632      default:
10633        return SDValue();
10634      case MVT::v4i32:
10635        SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10636        SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10637        break;
10638      case MVT::v8i16:
10639        SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10640        SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10641        break;
10642      case MVT::v8i32:
10643      case MVT::v16i16:
10644        if (!Subtarget->hasAVX())
10645          return SDValue();
10646        if (!Subtarget->hasAVX2()) {
10647          // needs to be split
10648          int NumElems = VT.getVectorNumElements();
10649          SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10650          SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10651
10652          // Extract the LHS vectors
10653          SDValue LHS = Op.getOperand(0);
10654          SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10655          SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10656
10657          MVT EltVT = VT.getVectorElementType().getSimpleVT();
10658          EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10659
10660          EVT ExtraEltVT = ExtraVT.getVectorElementType();
10661          int ExtraNumElems = ExtraVT.getVectorNumElements();
10662          ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10663                                     ExtraNumElems/2);
10664          SDValue Extra = DAG.getValueType(ExtraVT);
10665
10666          LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10667          LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10668
10669          return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10670        }
10671        if (VT == MVT::v8i32) {
10672          SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10673          SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10674        } else {
10675          SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10676          SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10677        }
10678    }
10679
10680    SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10681                         DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10682                         Op.getOperand(0), ShAmt);
10683
10684    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10685                       DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10686                       Tmp1, ShAmt);
10687  }
10688
10689  return SDValue();
10690}
10691
10692
10693SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10694  DebugLoc dl = Op.getDebugLoc();
10695
10696  // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10697  // There isn't any reason to disable it if the target processor supports it.
10698  if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10699    SDValue Chain = Op.getOperand(0);
10700    SDValue Zero = DAG.getConstant(0, MVT::i32);
10701    SDValue Ops[] = {
10702      DAG.getRegister(X86::ESP, MVT::i32), // Base
10703      DAG.getTargetConstant(1, MVT::i8),   // Scale
10704      DAG.getRegister(0, MVT::i32),        // Index
10705      DAG.getTargetConstant(0, MVT::i32),  // Disp
10706      DAG.getRegister(0, MVT::i32),        // Segment.
10707      Zero,
10708      Chain
10709    };
10710    SDNode *Res =
10711      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10712                          array_lengthof(Ops));
10713    return SDValue(Res, 0);
10714  }
10715
10716  unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10717  if (!isDev)
10718    return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10719
10720  unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10721  unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10722  unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10723  unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10724
10725  // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10726  if (!Op1 && !Op2 && !Op3 && Op4)
10727    return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10728
10729  // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10730  if (Op1 && !Op2 && !Op3 && !Op4)
10731    return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10732
10733  // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10734  //           (MFENCE)>;
10735  return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10736}
10737
10738SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10739                                             SelectionDAG &DAG) const {
10740  DebugLoc dl = Op.getDebugLoc();
10741  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10742    cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10743  SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10744    cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10745
10746  // The only fence that needs an instruction is a sequentially-consistent
10747  // cross-thread fence.
10748  if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10749    // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10750    // no-sse2). There isn't any reason to disable it if the target processor
10751    // supports it.
10752    if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10753      return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10754
10755    SDValue Chain = Op.getOperand(0);
10756    SDValue Zero = DAG.getConstant(0, MVT::i32);
10757    SDValue Ops[] = {
10758      DAG.getRegister(X86::ESP, MVT::i32), // Base
10759      DAG.getTargetConstant(1, MVT::i8),   // Scale
10760      DAG.getRegister(0, MVT::i32),        // Index
10761      DAG.getTargetConstant(0, MVT::i32),  // Disp
10762      DAG.getRegister(0, MVT::i32),        // Segment.
10763      Zero,
10764      Chain
10765    };
10766    SDNode *Res =
10767      DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10768                         array_lengthof(Ops));
10769    return SDValue(Res, 0);
10770  }
10771
10772  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10773  return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10774}
10775
10776
10777SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10778  EVT T = Op.getValueType();
10779  DebugLoc DL = Op.getDebugLoc();
10780  unsigned Reg = 0;
10781  unsigned size = 0;
10782  switch(T.getSimpleVT().SimpleTy) {
10783  default:
10784    assert(false && "Invalid value type!");
10785  case MVT::i8:  Reg = X86::AL;  size = 1; break;
10786  case MVT::i16: Reg = X86::AX;  size = 2; break;
10787  case MVT::i32: Reg = X86::EAX; size = 4; break;
10788  case MVT::i64:
10789    assert(Subtarget->is64Bit() && "Node not type legal!");
10790    Reg = X86::RAX; size = 8;
10791    break;
10792  }
10793  SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10794                                    Op.getOperand(2), SDValue());
10795  SDValue Ops[] = { cpIn.getValue(0),
10796                    Op.getOperand(1),
10797                    Op.getOperand(3),
10798                    DAG.getTargetConstant(size, MVT::i8),
10799                    cpIn.getValue(1) };
10800  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10801  MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10802  SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10803                                           Ops, 5, T, MMO);
10804  SDValue cpOut =
10805    DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10806  return cpOut;
10807}
10808
10809SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10810                                                 SelectionDAG &DAG) const {
10811  assert(Subtarget->is64Bit() && "Result not type legalized?");
10812  SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10813  SDValue TheChain = Op.getOperand(0);
10814  DebugLoc dl = Op.getDebugLoc();
10815  SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10816  SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10817  SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10818                                   rax.getValue(2));
10819  SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10820                            DAG.getConstant(32, MVT::i8));
10821  SDValue Ops[] = {
10822    DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10823    rdx.getValue(1)
10824  };
10825  return DAG.getMergeValues(Ops, 2, dl);
10826}
10827
10828SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10829                                            SelectionDAG &DAG) const {
10830  EVT SrcVT = Op.getOperand(0).getValueType();
10831  EVT DstVT = Op.getValueType();
10832  assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10833         Subtarget->hasMMX() && "Unexpected custom BITCAST");
10834  assert((DstVT == MVT::i64 ||
10835          (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10836         "Unexpected custom BITCAST");
10837  // i64 <=> MMX conversions are Legal.
10838  if (SrcVT==MVT::i64 && DstVT.isVector())
10839    return Op;
10840  if (DstVT==MVT::i64 && SrcVT.isVector())
10841    return Op;
10842  // MMX <=> MMX conversions are Legal.
10843  if (SrcVT.isVector() && DstVT.isVector())
10844    return Op;
10845  // All other conversions need to be expanded.
10846  return SDValue();
10847}
10848
10849SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10850  SDNode *Node = Op.getNode();
10851  DebugLoc dl = Node->getDebugLoc();
10852  EVT T = Node->getValueType(0);
10853  SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10854                              DAG.getConstant(0, T), Node->getOperand(2));
10855  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10856                       cast<AtomicSDNode>(Node)->getMemoryVT(),
10857                       Node->getOperand(0),
10858                       Node->getOperand(1), negOp,
10859                       cast<AtomicSDNode>(Node)->getSrcValue(),
10860                       cast<AtomicSDNode>(Node)->getAlignment(),
10861                       cast<AtomicSDNode>(Node)->getOrdering(),
10862                       cast<AtomicSDNode>(Node)->getSynchScope());
10863}
10864
10865static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10866  SDNode *Node = Op.getNode();
10867  DebugLoc dl = Node->getDebugLoc();
10868  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10869
10870  // Convert seq_cst store -> xchg
10871  // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10872  // FIXME: On 32-bit, store -> fist or movq would be more efficient
10873  //        (The only way to get a 16-byte store is cmpxchg16b)
10874  // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10875  if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10876      !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10877    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10878                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
10879                                 Node->getOperand(0),
10880                                 Node->getOperand(1), Node->getOperand(2),
10881                                 cast<AtomicSDNode>(Node)->getMemOperand(),
10882                                 cast<AtomicSDNode>(Node)->getOrdering(),
10883                                 cast<AtomicSDNode>(Node)->getSynchScope());
10884    return Swap.getValue(1);
10885  }
10886  // Other atomic stores have a simple pattern.
10887  return Op;
10888}
10889
10890static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10891  EVT VT = Op.getNode()->getValueType(0);
10892
10893  // Let legalize expand this if it isn't a legal type yet.
10894  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10895    return SDValue();
10896
10897  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10898
10899  unsigned Opc;
10900  bool ExtraOp = false;
10901  switch (Op.getOpcode()) {
10902  default: assert(0 && "Invalid code");
10903  case ISD::ADDC: Opc = X86ISD::ADD; break;
10904  case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10905  case ISD::SUBC: Opc = X86ISD::SUB; break;
10906  case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10907  }
10908
10909  if (!ExtraOp)
10910    return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10911                       Op.getOperand(1));
10912  return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10913                     Op.getOperand(1), Op.getOperand(2));
10914}
10915
10916/// LowerOperation - Provide custom lowering hooks for some operations.
10917///
10918SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10919  switch (Op.getOpcode()) {
10920  default: llvm_unreachable("Should not custom lower this!");
10921  case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10922  case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10923  case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10924  case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10925  case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10926  case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10927  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10928  case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10929  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10930  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10931  case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10932  case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10933  case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10934  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10935  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10936  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10937  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10938  case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10939  case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10940  case ISD::SHL_PARTS:
10941  case ISD::SRA_PARTS:
10942  case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10943  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10944  case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10945  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10946  case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10947  case ISD::FABS:               return LowerFABS(Op, DAG);
10948  case ISD::FNEG:               return LowerFNEG(Op, DAG);
10949  case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10950  case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10951  case ISD::SETCC:              return LowerSETCC(Op, DAG);
10952  case ISD::SELECT:             return LowerSELECT(Op, DAG);
10953  case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10954  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10955  case ISD::VASTART:            return LowerVASTART(Op, DAG);
10956  case ISD::VAARG:              return LowerVAARG(Op, DAG);
10957  case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10958  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10959  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10960  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10961  case ISD::FRAME_TO_ARGS_OFFSET:
10962                                return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10963  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10964  case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10965  case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10966  case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10967  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10968  case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10969  case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10970  case ISD::MUL:                return LowerMUL(Op, DAG);
10971  case ISD::SRA:
10972  case ISD::SRL:
10973  case ISD::SHL:                return LowerShift(Op, DAG);
10974  case ISD::SADDO:
10975  case ISD::UADDO:
10976  case ISD::SSUBO:
10977  case ISD::USUBO:
10978  case ISD::SMULO:
10979  case ISD::UMULO:              return LowerXALUO(Op, DAG);
10980  case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10981  case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10982  case ISD::ADDC:
10983  case ISD::ADDE:
10984  case ISD::SUBC:
10985  case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10986  case ISD::ADD:                return LowerADD(Op, DAG);
10987  case ISD::SUB:                return LowerSUB(Op, DAG);
10988  }
10989}
10990
10991static void ReplaceATOMIC_LOAD(SDNode *Node,
10992                                  SmallVectorImpl<SDValue> &Results,
10993                                  SelectionDAG &DAG) {
10994  DebugLoc dl = Node->getDebugLoc();
10995  EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10996
10997  // Convert wide load -> cmpxchg8b/cmpxchg16b
10998  // FIXME: On 32-bit, load -> fild or movq would be more efficient
10999  //        (The only way to get a 16-byte load is cmpxchg16b)
11000  // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11001  SDValue Zero = DAG.getConstant(0, VT);
11002  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11003                               Node->getOperand(0),
11004                               Node->getOperand(1), Zero, Zero,
11005                               cast<AtomicSDNode>(Node)->getMemOperand(),
11006                               cast<AtomicSDNode>(Node)->getOrdering(),
11007                               cast<AtomicSDNode>(Node)->getSynchScope());
11008  Results.push_back(Swap.getValue(0));
11009  Results.push_back(Swap.getValue(1));
11010}
11011
11012void X86TargetLowering::
11013ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11014                        SelectionDAG &DAG, unsigned NewOp) const {
11015  DebugLoc dl = Node->getDebugLoc();
11016  assert (Node->getValueType(0) == MVT::i64 &&
11017          "Only know how to expand i64 atomics");
11018
11019  SDValue Chain = Node->getOperand(0);
11020  SDValue In1 = Node->getOperand(1);
11021  SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11022                             Node->getOperand(2), DAG.getIntPtrConstant(0));
11023  SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11024                             Node->getOperand(2), DAG.getIntPtrConstant(1));
11025  SDValue Ops[] = { Chain, In1, In2L, In2H };
11026  SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11027  SDValue Result =
11028    DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11029                            cast<MemSDNode>(Node)->getMemOperand());
11030  SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11031  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11032  Results.push_back(Result.getValue(2));
11033}
11034
11035/// ReplaceNodeResults - Replace a node with an illegal result type
11036/// with a new node built out of custom code.
11037void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11038                                           SmallVectorImpl<SDValue>&Results,
11039                                           SelectionDAG &DAG) const {
11040  DebugLoc dl = N->getDebugLoc();
11041  switch (N->getOpcode()) {
11042  default:
11043    assert(false && "Do not know how to custom type legalize this operation!");
11044    return;
11045  case ISD::SIGN_EXTEND_INREG:
11046  case ISD::ADDC:
11047  case ISD::ADDE:
11048  case ISD::SUBC:
11049  case ISD::SUBE:
11050    // We don't want to expand or promote these.
11051    return;
11052  case ISD::FP_TO_SINT: {
11053    std::pair<SDValue,SDValue> Vals =
11054        FP_TO_INTHelper(SDValue(N, 0), DAG, true);
11055    SDValue FIST = Vals.first, StackSlot = Vals.second;
11056    if (FIST.getNode() != 0) {
11057      EVT VT = N->getValueType(0);
11058      // Return a load from the stack slot.
11059      Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11060                                    MachinePointerInfo(),
11061                                    false, false, false, 0));
11062    }
11063    return;
11064  }
11065  case ISD::READCYCLECOUNTER: {
11066    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11067    SDValue TheChain = N->getOperand(0);
11068    SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11069    SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11070                                     rd.getValue(1));
11071    SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11072                                     eax.getValue(2));
11073    // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11074    SDValue Ops[] = { eax, edx };
11075    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11076    Results.push_back(edx.getValue(1));
11077    return;
11078  }
11079  case ISD::ATOMIC_CMP_SWAP: {
11080    EVT T = N->getValueType(0);
11081    assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11082    bool Regs64bit = T == MVT::i128;
11083    EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11084    SDValue cpInL, cpInH;
11085    cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11086                        DAG.getConstant(0, HalfT));
11087    cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11088                        DAG.getConstant(1, HalfT));
11089    cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11090                             Regs64bit ? X86::RAX : X86::EAX,
11091                             cpInL, SDValue());
11092    cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11093                             Regs64bit ? X86::RDX : X86::EDX,
11094                             cpInH, cpInL.getValue(1));
11095    SDValue swapInL, swapInH;
11096    swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11097                          DAG.getConstant(0, HalfT));
11098    swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11099                          DAG.getConstant(1, HalfT));
11100    swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11101                               Regs64bit ? X86::RBX : X86::EBX,
11102                               swapInL, cpInH.getValue(1));
11103    swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11104                               Regs64bit ? X86::RCX : X86::ECX,
11105                               swapInH, swapInL.getValue(1));
11106    SDValue Ops[] = { swapInH.getValue(0),
11107                      N->getOperand(1),
11108                      swapInH.getValue(1) };
11109    SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11110    MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11111    unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11112                                  X86ISD::LCMPXCHG8_DAG;
11113    SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11114                                             Ops, 3, T, MMO);
11115    SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11116                                        Regs64bit ? X86::RAX : X86::EAX,
11117                                        HalfT, Result.getValue(1));
11118    SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11119                                        Regs64bit ? X86::RDX : X86::EDX,
11120                                        HalfT, cpOutL.getValue(2));
11121    SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11122    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11123    Results.push_back(cpOutH.getValue(1));
11124    return;
11125  }
11126  case ISD::ATOMIC_LOAD_ADD:
11127    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11128    return;
11129  case ISD::ATOMIC_LOAD_AND:
11130    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11131    return;
11132  case ISD::ATOMIC_LOAD_NAND:
11133    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11134    return;
11135  case ISD::ATOMIC_LOAD_OR:
11136    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11137    return;
11138  case ISD::ATOMIC_LOAD_SUB:
11139    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11140    return;
11141  case ISD::ATOMIC_LOAD_XOR:
11142    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11143    return;
11144  case ISD::ATOMIC_SWAP:
11145    ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11146    return;
11147  case ISD::ATOMIC_LOAD:
11148    ReplaceATOMIC_LOAD(N, Results, DAG);
11149  }
11150}
11151
11152const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11153  switch (Opcode) {
11154  default: return NULL;
11155  case X86ISD::BSF:                return "X86ISD::BSF";
11156  case X86ISD::BSR:                return "X86ISD::BSR";
11157  case X86ISD::SHLD:               return "X86ISD::SHLD";
11158  case X86ISD::SHRD:               return "X86ISD::SHRD";
11159  case X86ISD::FAND:               return "X86ISD::FAND";
11160  case X86ISD::FOR:                return "X86ISD::FOR";
11161  case X86ISD::FXOR:               return "X86ISD::FXOR";
11162  case X86ISD::FSRL:               return "X86ISD::FSRL";
11163  case X86ISD::FILD:               return "X86ISD::FILD";
11164  case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11165  case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11166  case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11167  case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11168  case X86ISD::FLD:                return "X86ISD::FLD";
11169  case X86ISD::FST:                return "X86ISD::FST";
11170  case X86ISD::CALL:               return "X86ISD::CALL";
11171  case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11172  case X86ISD::BT:                 return "X86ISD::BT";
11173  case X86ISD::CMP:                return "X86ISD::CMP";
11174  case X86ISD::COMI:               return "X86ISD::COMI";
11175  case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11176  case X86ISD::SETCC:              return "X86ISD::SETCC";
11177  case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11178  case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11179  case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11180  case X86ISD::CMOV:               return "X86ISD::CMOV";
11181  case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11182  case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11183  case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11184  case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11185  case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11186  case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11187  case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11188  case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11189  case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11190  case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11191  case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11192  case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11193  case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11194  case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11195  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11196  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11197  case X86ISD::FHADD:              return "X86ISD::FHADD";
11198  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11199  case X86ISD::FMAX:               return "X86ISD::FMAX";
11200  case X86ISD::FMIN:               return "X86ISD::FMIN";
11201  case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11202  case X86ISD::FRCP:               return "X86ISD::FRCP";
11203  case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11204  case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11205  case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11206  case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11207  case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11208  case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11209  case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11210  case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11211  case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11212  case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11213  case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11214  case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11215  case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11216  case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11217  case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11218  case X86ISD::VSHL:               return "X86ISD::VSHL";
11219  case X86ISD::VSRL:               return "X86ISD::VSRL";
11220  case X86ISD::CMPPD:              return "X86ISD::CMPPD";
11221  case X86ISD::CMPPS:              return "X86ISD::CMPPS";
11222  case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
11223  case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
11224  case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
11225  case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
11226  case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
11227  case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
11228  case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
11229  case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
11230  case X86ISD::ADD:                return "X86ISD::ADD";
11231  case X86ISD::SUB:                return "X86ISD::SUB";
11232  case X86ISD::ADC:                return "X86ISD::ADC";
11233  case X86ISD::SBB:                return "X86ISD::SBB";
11234  case X86ISD::SMUL:               return "X86ISD::SMUL";
11235  case X86ISD::UMUL:               return "X86ISD::UMUL";
11236  case X86ISD::INC:                return "X86ISD::INC";
11237  case X86ISD::DEC:                return "X86ISD::DEC";
11238  case X86ISD::OR:                 return "X86ISD::OR";
11239  case X86ISD::XOR:                return "X86ISD::XOR";
11240  case X86ISD::AND:                return "X86ISD::AND";
11241  case X86ISD::ANDN:               return "X86ISD::ANDN";
11242  case X86ISD::BLSI:               return "X86ISD::BLSI";
11243  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11244  case X86ISD::BLSR:               return "X86ISD::BLSR";
11245  case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11246  case X86ISD::PTEST:              return "X86ISD::PTEST";
11247  case X86ISD::TESTP:              return "X86ISD::TESTP";
11248  case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11249  case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11250  case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11251  case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
11252  case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11253  case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
11254  case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
11255  case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
11256  case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11257  case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11258  case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11259  case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
11260  case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11261  case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11262  case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11263  case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11264  case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11265  case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
11266  case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
11267  case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11268  case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11269  case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
11270  case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
11271  case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
11272  case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
11273  case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
11274  case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
11275  case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
11276  case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
11277  case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
11278  case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
11279  case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
11280  case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
11281  case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11282  case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
11283  case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
11284  case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
11285  case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
11286  case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
11287  case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11288  case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11289  case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11290  case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11291  case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11292  }
11293}
11294
11295// isLegalAddressingMode - Return true if the addressing mode represented
11296// by AM is legal for this target, for a load/store of the specified type.
11297bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11298                                              Type *Ty) const {
11299  // X86 supports extremely general addressing modes.
11300  CodeModel::Model M = getTargetMachine().getCodeModel();
11301  Reloc::Model R = getTargetMachine().getRelocationModel();
11302
11303  // X86 allows a sign-extended 32-bit immediate field as a displacement.
11304  if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11305    return false;
11306
11307  if (AM.BaseGV) {
11308    unsigned GVFlags =
11309      Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11310
11311    // If a reference to this global requires an extra load, we can't fold it.
11312    if (isGlobalStubReference(GVFlags))
11313      return false;
11314
11315    // If BaseGV requires a register for the PIC base, we cannot also have a
11316    // BaseReg specified.
11317    if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11318      return false;
11319
11320    // If lower 4G is not available, then we must use rip-relative addressing.
11321    if ((M != CodeModel::Small || R != Reloc::Static) &&
11322        Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11323      return false;
11324  }
11325
11326  switch (AM.Scale) {
11327  case 0:
11328  case 1:
11329  case 2:
11330  case 4:
11331  case 8:
11332    // These scales always work.
11333    break;
11334  case 3:
11335  case 5:
11336  case 9:
11337    // These scales are formed with basereg+scalereg.  Only accept if there is
11338    // no basereg yet.
11339    if (AM.HasBaseReg)
11340      return false;
11341    break;
11342  default:  // Other stuff never works.
11343    return false;
11344  }
11345
11346  return true;
11347}
11348
11349
11350bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11351  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11352    return false;
11353  unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11354  unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11355  if (NumBits1 <= NumBits2)
11356    return false;
11357  return true;
11358}
11359
11360bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11361  if (!VT1.isInteger() || !VT2.isInteger())
11362    return false;
11363  unsigned NumBits1 = VT1.getSizeInBits();
11364  unsigned NumBits2 = VT2.getSizeInBits();
11365  if (NumBits1 <= NumBits2)
11366    return false;
11367  return true;
11368}
11369
11370bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11371  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11372  return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11373}
11374
11375bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11376  // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11377  return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11378}
11379
11380bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11381  // i16 instructions are longer (0x66 prefix) and potentially slower.
11382  return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11383}
11384
11385/// isShuffleMaskLegal - Targets can use this to indicate that they only
11386/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11387/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11388/// are assumed to be legal.
11389bool
11390X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11391                                      EVT VT) const {
11392  // Very little shuffling can be done for 64-bit vectors right now.
11393  if (VT.getSizeInBits() == 64)
11394    return isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX());
11395
11396  // FIXME: pshufb, blends, shifts.
11397  return (VT.getVectorNumElements() == 2 ||
11398          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11399          isMOVLMask(M, VT) ||
11400          isSHUFPMask(M, VT) ||
11401          isPSHUFDMask(M, VT) ||
11402          isPSHUFHWMask(M, VT) ||
11403          isPSHUFLWMask(M, VT) ||
11404          isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11405          isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11406          isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11407          isUNPCKL_v_undef_Mask(M, VT) ||
11408          isUNPCKH_v_undef_Mask(M, VT));
11409}
11410
11411bool
11412X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11413                                          EVT VT) const {
11414  unsigned NumElts = VT.getVectorNumElements();
11415  // FIXME: This collection of masks seems suspect.
11416  if (NumElts == 2)
11417    return true;
11418  if (NumElts == 4 && VT.getSizeInBits() == 128) {
11419    return (isMOVLMask(Mask, VT)  ||
11420            isCommutedMOVLMask(Mask, VT, true) ||
11421            isSHUFPMask(Mask, VT) ||
11422            isCommutedSHUFPMask(Mask, VT));
11423  }
11424  return false;
11425}
11426
11427//===----------------------------------------------------------------------===//
11428//                           X86 Scheduler Hooks
11429//===----------------------------------------------------------------------===//
11430
11431// private utility function
11432MachineBasicBlock *
11433X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11434                                                       MachineBasicBlock *MBB,
11435                                                       unsigned regOpc,
11436                                                       unsigned immOpc,
11437                                                       unsigned LoadOpc,
11438                                                       unsigned CXchgOpc,
11439                                                       unsigned notOpc,
11440                                                       unsigned EAXreg,
11441                                                       TargetRegisterClass *RC,
11442                                                       bool invSrc) const {
11443  // For the atomic bitwise operator, we generate
11444  //   thisMBB:
11445  //   newMBB:
11446  //     ld  t1 = [bitinstr.addr]
11447  //     op  t2 = t1, [bitinstr.val]
11448  //     mov EAX = t1
11449  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11450  //     bz  newMBB
11451  //     fallthrough -->nextMBB
11452  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11453  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11454  MachineFunction::iterator MBBIter = MBB;
11455  ++MBBIter;
11456
11457  /// First build the CFG
11458  MachineFunction *F = MBB->getParent();
11459  MachineBasicBlock *thisMBB = MBB;
11460  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11461  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11462  F->insert(MBBIter, newMBB);
11463  F->insert(MBBIter, nextMBB);
11464
11465  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11466  nextMBB->splice(nextMBB->begin(), thisMBB,
11467                  llvm::next(MachineBasicBlock::iterator(bInstr)),
11468                  thisMBB->end());
11469  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11470
11471  // Update thisMBB to fall through to newMBB
11472  thisMBB->addSuccessor(newMBB);
11473
11474  // newMBB jumps to itself and fall through to nextMBB
11475  newMBB->addSuccessor(nextMBB);
11476  newMBB->addSuccessor(newMBB);
11477
11478  // Insert instructions into newMBB based on incoming instruction
11479  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11480         "unexpected number of operands");
11481  DebugLoc dl = bInstr->getDebugLoc();
11482  MachineOperand& destOper = bInstr->getOperand(0);
11483  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11484  int numArgs = bInstr->getNumOperands() - 1;
11485  for (int i=0; i < numArgs; ++i)
11486    argOpers[i] = &bInstr->getOperand(i+1);
11487
11488  // x86 address has 4 operands: base, index, scale, and displacement
11489  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11490  int valArgIndx = lastAddrIndx + 1;
11491
11492  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11493  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11494  for (int i=0; i <= lastAddrIndx; ++i)
11495    (*MIB).addOperand(*argOpers[i]);
11496
11497  unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11498  if (invSrc) {
11499    MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11500  }
11501  else
11502    tt = t1;
11503
11504  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11505  assert((argOpers[valArgIndx]->isReg() ||
11506          argOpers[valArgIndx]->isImm()) &&
11507         "invalid operand");
11508  if (argOpers[valArgIndx]->isReg())
11509    MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11510  else
11511    MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11512  MIB.addReg(tt);
11513  (*MIB).addOperand(*argOpers[valArgIndx]);
11514
11515  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11516  MIB.addReg(t1);
11517
11518  MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11519  for (int i=0; i <= lastAddrIndx; ++i)
11520    (*MIB).addOperand(*argOpers[i]);
11521  MIB.addReg(t2);
11522  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11523  (*MIB).setMemRefs(bInstr->memoperands_begin(),
11524                    bInstr->memoperands_end());
11525
11526  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11527  MIB.addReg(EAXreg);
11528
11529  // insert branch
11530  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11531
11532  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11533  return nextMBB;
11534}
11535
11536// private utility function:  64 bit atomics on 32 bit host.
11537MachineBasicBlock *
11538X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11539                                                       MachineBasicBlock *MBB,
11540                                                       unsigned regOpcL,
11541                                                       unsigned regOpcH,
11542                                                       unsigned immOpcL,
11543                                                       unsigned immOpcH,
11544                                                       bool invSrc) const {
11545  // For the atomic bitwise operator, we generate
11546  //   thisMBB (instructions are in pairs, except cmpxchg8b)
11547  //     ld t1,t2 = [bitinstr.addr]
11548  //   newMBB:
11549  //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11550  //     op  t5, t6 <- out1, out2, [bitinstr.val]
11551  //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11552  //     mov ECX, EBX <- t5, t6
11553  //     mov EAX, EDX <- t1, t2
11554  //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11555  //     mov t3, t4 <- EAX, EDX
11556  //     bz  newMBB
11557  //     result in out1, out2
11558  //     fallthrough -->nextMBB
11559
11560  const TargetRegisterClass *RC = X86::GR32RegisterClass;
11561  const unsigned LoadOpc = X86::MOV32rm;
11562  const unsigned NotOpc = X86::NOT32r;
11563  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11564  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11565  MachineFunction::iterator MBBIter = MBB;
11566  ++MBBIter;
11567
11568  /// First build the CFG
11569  MachineFunction *F = MBB->getParent();
11570  MachineBasicBlock *thisMBB = MBB;
11571  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11572  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11573  F->insert(MBBIter, newMBB);
11574  F->insert(MBBIter, nextMBB);
11575
11576  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11577  nextMBB->splice(nextMBB->begin(), thisMBB,
11578                  llvm::next(MachineBasicBlock::iterator(bInstr)),
11579                  thisMBB->end());
11580  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11581
11582  // Update thisMBB to fall through to newMBB
11583  thisMBB->addSuccessor(newMBB);
11584
11585  // newMBB jumps to itself and fall through to nextMBB
11586  newMBB->addSuccessor(nextMBB);
11587  newMBB->addSuccessor(newMBB);
11588
11589  DebugLoc dl = bInstr->getDebugLoc();
11590  // Insert instructions into newMBB based on incoming instruction
11591  // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11592  assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11593         "unexpected number of operands");
11594  MachineOperand& dest1Oper = bInstr->getOperand(0);
11595  MachineOperand& dest2Oper = bInstr->getOperand(1);
11596  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11597  for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11598    argOpers[i] = &bInstr->getOperand(i+2);
11599
11600    // We use some of the operands multiple times, so conservatively just
11601    // clear any kill flags that might be present.
11602    if (argOpers[i]->isReg() && argOpers[i]->isUse())
11603      argOpers[i]->setIsKill(false);
11604  }
11605
11606  // x86 address has 5 operands: base, index, scale, displacement, and segment.
11607  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11608
11609  unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11610  MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11611  for (int i=0; i <= lastAddrIndx; ++i)
11612    (*MIB).addOperand(*argOpers[i]);
11613  unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11614  MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11615  // add 4 to displacement.
11616  for (int i=0; i <= lastAddrIndx-2; ++i)
11617    (*MIB).addOperand(*argOpers[i]);
11618  MachineOperand newOp3 = *(argOpers[3]);
11619  if (newOp3.isImm())
11620    newOp3.setImm(newOp3.getImm()+4);
11621  else
11622    newOp3.setOffset(newOp3.getOffset()+4);
11623  (*MIB).addOperand(newOp3);
11624  (*MIB).addOperand(*argOpers[lastAddrIndx]);
11625
11626  // t3/4 are defined later, at the bottom of the loop
11627  unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11628  unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11629  BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11630    .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11631  BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11632    .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11633
11634  // The subsequent operations should be using the destination registers of
11635  //the PHI instructions.
11636  if (invSrc) {
11637    t1 = F->getRegInfo().createVirtualRegister(RC);
11638    t2 = F->getRegInfo().createVirtualRegister(RC);
11639    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11640    MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11641  } else {
11642    t1 = dest1Oper.getReg();
11643    t2 = dest2Oper.getReg();
11644  }
11645
11646  int valArgIndx = lastAddrIndx + 1;
11647  assert((argOpers[valArgIndx]->isReg() ||
11648          argOpers[valArgIndx]->isImm()) &&
11649         "invalid operand");
11650  unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11651  unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11652  if (argOpers[valArgIndx]->isReg())
11653    MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11654  else
11655    MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11656  if (regOpcL != X86::MOV32rr)
11657    MIB.addReg(t1);
11658  (*MIB).addOperand(*argOpers[valArgIndx]);
11659  assert(argOpers[valArgIndx + 1]->isReg() ==
11660         argOpers[valArgIndx]->isReg());
11661  assert(argOpers[valArgIndx + 1]->isImm() ==
11662         argOpers[valArgIndx]->isImm());
11663  if (argOpers[valArgIndx + 1]->isReg())
11664    MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11665  else
11666    MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11667  if (regOpcH != X86::MOV32rr)
11668    MIB.addReg(t2);
11669  (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11670
11671  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11672  MIB.addReg(t1);
11673  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11674  MIB.addReg(t2);
11675
11676  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11677  MIB.addReg(t5);
11678  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11679  MIB.addReg(t6);
11680
11681  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11682  for (int i=0; i <= lastAddrIndx; ++i)
11683    (*MIB).addOperand(*argOpers[i]);
11684
11685  assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11686  (*MIB).setMemRefs(bInstr->memoperands_begin(),
11687                    bInstr->memoperands_end());
11688
11689  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11690  MIB.addReg(X86::EAX);
11691  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11692  MIB.addReg(X86::EDX);
11693
11694  // insert branch
11695  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11696
11697  bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11698  return nextMBB;
11699}
11700
11701// private utility function
11702MachineBasicBlock *
11703X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11704                                                      MachineBasicBlock *MBB,
11705                                                      unsigned cmovOpc) const {
11706  // For the atomic min/max operator, we generate
11707  //   thisMBB:
11708  //   newMBB:
11709  //     ld t1 = [min/max.addr]
11710  //     mov t2 = [min/max.val]
11711  //     cmp  t1, t2
11712  //     cmov[cond] t2 = t1
11713  //     mov EAX = t1
11714  //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11715  //     bz   newMBB
11716  //     fallthrough -->nextMBB
11717  //
11718  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11719  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11720  MachineFunction::iterator MBBIter = MBB;
11721  ++MBBIter;
11722
11723  /// First build the CFG
11724  MachineFunction *F = MBB->getParent();
11725  MachineBasicBlock *thisMBB = MBB;
11726  MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11727  MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11728  F->insert(MBBIter, newMBB);
11729  F->insert(MBBIter, nextMBB);
11730
11731  // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11732  nextMBB->splice(nextMBB->begin(), thisMBB,
11733                  llvm::next(MachineBasicBlock::iterator(mInstr)),
11734                  thisMBB->end());
11735  nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11736
11737  // Update thisMBB to fall through to newMBB
11738  thisMBB->addSuccessor(newMBB);
11739
11740  // newMBB jumps to newMBB and fall through to nextMBB
11741  newMBB->addSuccessor(nextMBB);
11742  newMBB->addSuccessor(newMBB);
11743
11744  DebugLoc dl = mInstr->getDebugLoc();
11745  // Insert instructions into newMBB based on incoming instruction
11746  assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11747         "unexpected number of operands");
11748  MachineOperand& destOper = mInstr->getOperand(0);
11749  MachineOperand* argOpers[2 + X86::AddrNumOperands];
11750  int numArgs = mInstr->getNumOperands() - 1;
11751  for (int i=0; i < numArgs; ++i)
11752    argOpers[i] = &mInstr->getOperand(i+1);
11753
11754  // x86 address has 4 operands: base, index, scale, and displacement
11755  int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11756  int valArgIndx = lastAddrIndx + 1;
11757
11758  unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11759  MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11760  for (int i=0; i <= lastAddrIndx; ++i)
11761    (*MIB).addOperand(*argOpers[i]);
11762
11763  // We only support register and immediate values
11764  assert((argOpers[valArgIndx]->isReg() ||
11765          argOpers[valArgIndx]->isImm()) &&
11766         "invalid operand");
11767
11768  unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11769  if (argOpers[valArgIndx]->isReg())
11770    MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11771  else
11772    MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11773  (*MIB).addOperand(*argOpers[valArgIndx]);
11774
11775  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11776  MIB.addReg(t1);
11777
11778  MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11779  MIB.addReg(t1);
11780  MIB.addReg(t2);
11781
11782  // Generate movc
11783  unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11784  MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11785  MIB.addReg(t2);
11786  MIB.addReg(t1);
11787
11788  // Cmp and exchange if none has modified the memory location
11789  MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11790  for (int i=0; i <= lastAddrIndx; ++i)
11791    (*MIB).addOperand(*argOpers[i]);
11792  MIB.addReg(t3);
11793  assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11794  (*MIB).setMemRefs(mInstr->memoperands_begin(),
11795                    mInstr->memoperands_end());
11796
11797  MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11798  MIB.addReg(X86::EAX);
11799
11800  // insert branch
11801  BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11802
11803  mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11804  return nextMBB;
11805}
11806
11807// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11808// or XMM0_V32I8 in AVX all of this code can be replaced with that
11809// in the .td file.
11810MachineBasicBlock *
11811X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11812                            unsigned numArgs, bool memArg) const {
11813  assert(Subtarget->hasSSE42orAVX() &&
11814         "Target must have SSE4.2 or AVX features enabled");
11815
11816  DebugLoc dl = MI->getDebugLoc();
11817  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11818  unsigned Opc;
11819  if (!Subtarget->hasAVX()) {
11820    if (memArg)
11821      Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11822    else
11823      Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11824  } else {
11825    if (memArg)
11826      Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11827    else
11828      Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11829  }
11830
11831  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11832  for (unsigned i = 0; i < numArgs; ++i) {
11833    MachineOperand &Op = MI->getOperand(i+1);
11834    if (!(Op.isReg() && Op.isImplicit()))
11835      MIB.addOperand(Op);
11836  }
11837  BuildMI(*BB, MI, dl,
11838    TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11839             MI->getOperand(0).getReg())
11840    .addReg(X86::XMM0);
11841
11842  MI->eraseFromParent();
11843  return BB;
11844}
11845
11846MachineBasicBlock *
11847X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11848  DebugLoc dl = MI->getDebugLoc();
11849  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11850
11851  // Address into RAX/EAX, other two args into ECX, EDX.
11852  unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11853  unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11854  MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11855  for (int i = 0; i < X86::AddrNumOperands; ++i)
11856    MIB.addOperand(MI->getOperand(i));
11857
11858  unsigned ValOps = X86::AddrNumOperands;
11859  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11860    .addReg(MI->getOperand(ValOps).getReg());
11861  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11862    .addReg(MI->getOperand(ValOps+1).getReg());
11863
11864  // The instruction doesn't actually take any operands though.
11865  BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11866
11867  MI->eraseFromParent(); // The pseudo is gone now.
11868  return BB;
11869}
11870
11871MachineBasicBlock *
11872X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11873  DebugLoc dl = MI->getDebugLoc();
11874  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11875
11876  // First arg in ECX, the second in EAX.
11877  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11878    .addReg(MI->getOperand(0).getReg());
11879  BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11880    .addReg(MI->getOperand(1).getReg());
11881
11882  // The instruction doesn't actually take any operands though.
11883  BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11884
11885  MI->eraseFromParent(); // The pseudo is gone now.
11886  return BB;
11887}
11888
11889MachineBasicBlock *
11890X86TargetLowering::EmitVAARG64WithCustomInserter(
11891                   MachineInstr *MI,
11892                   MachineBasicBlock *MBB) const {
11893  // Emit va_arg instruction on X86-64.
11894
11895  // Operands to this pseudo-instruction:
11896  // 0  ) Output        : destination address (reg)
11897  // 1-5) Input         : va_list address (addr, i64mem)
11898  // 6  ) ArgSize       : Size (in bytes) of vararg type
11899  // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11900  // 8  ) Align         : Alignment of type
11901  // 9  ) EFLAGS (implicit-def)
11902
11903  assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11904  assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11905
11906  unsigned DestReg = MI->getOperand(0).getReg();
11907  MachineOperand &Base = MI->getOperand(1);
11908  MachineOperand &Scale = MI->getOperand(2);
11909  MachineOperand &Index = MI->getOperand(3);
11910  MachineOperand &Disp = MI->getOperand(4);
11911  MachineOperand &Segment = MI->getOperand(5);
11912  unsigned ArgSize = MI->getOperand(6).getImm();
11913  unsigned ArgMode = MI->getOperand(7).getImm();
11914  unsigned Align = MI->getOperand(8).getImm();
11915
11916  // Memory Reference
11917  assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11918  MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11919  MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11920
11921  // Machine Information
11922  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11923  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11924  const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11925  const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11926  DebugLoc DL = MI->getDebugLoc();
11927
11928  // struct va_list {
11929  //   i32   gp_offset
11930  //   i32   fp_offset
11931  //   i64   overflow_area (address)
11932  //   i64   reg_save_area (address)
11933  // }
11934  // sizeof(va_list) = 24
11935  // alignment(va_list) = 8
11936
11937  unsigned TotalNumIntRegs = 6;
11938  unsigned TotalNumXMMRegs = 8;
11939  bool UseGPOffset = (ArgMode == 1);
11940  bool UseFPOffset = (ArgMode == 2);
11941  unsigned MaxOffset = TotalNumIntRegs * 8 +
11942                       (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11943
11944  /* Align ArgSize to a multiple of 8 */
11945  unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11946  bool NeedsAlign = (Align > 8);
11947
11948  MachineBasicBlock *thisMBB = MBB;
11949  MachineBasicBlock *overflowMBB;
11950  MachineBasicBlock *offsetMBB;
11951  MachineBasicBlock *endMBB;
11952
11953  unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11954  unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11955  unsigned OffsetReg = 0;
11956
11957  if (!UseGPOffset && !UseFPOffset) {
11958    // If we only pull from the overflow region, we don't create a branch.
11959    // We don't need to alter control flow.
11960    OffsetDestReg = 0; // unused
11961    OverflowDestReg = DestReg;
11962
11963    offsetMBB = NULL;
11964    overflowMBB = thisMBB;
11965    endMBB = thisMBB;
11966  } else {
11967    // First emit code to check if gp_offset (or fp_offset) is below the bound.
11968    // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11969    // If not, pull from overflow_area. (branch to overflowMBB)
11970    //
11971    //       thisMBB
11972    //         |     .
11973    //         |        .
11974    //     offsetMBB   overflowMBB
11975    //         |        .
11976    //         |     .
11977    //        endMBB
11978
11979    // Registers for the PHI in endMBB
11980    OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11981    OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11982
11983    const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11984    MachineFunction *MF = MBB->getParent();
11985    overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11986    offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11987    endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11988
11989    MachineFunction::iterator MBBIter = MBB;
11990    ++MBBIter;
11991
11992    // Insert the new basic blocks
11993    MF->insert(MBBIter, offsetMBB);
11994    MF->insert(MBBIter, overflowMBB);
11995    MF->insert(MBBIter, endMBB);
11996
11997    // Transfer the remainder of MBB and its successor edges to endMBB.
11998    endMBB->splice(endMBB->begin(), thisMBB,
11999                    llvm::next(MachineBasicBlock::iterator(MI)),
12000                    thisMBB->end());
12001    endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12002
12003    // Make offsetMBB and overflowMBB successors of thisMBB
12004    thisMBB->addSuccessor(offsetMBB);
12005    thisMBB->addSuccessor(overflowMBB);
12006
12007    // endMBB is a successor of both offsetMBB and overflowMBB
12008    offsetMBB->addSuccessor(endMBB);
12009    overflowMBB->addSuccessor(endMBB);
12010
12011    // Load the offset value into a register
12012    OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12013    BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12014      .addOperand(Base)
12015      .addOperand(Scale)
12016      .addOperand(Index)
12017      .addDisp(Disp, UseFPOffset ? 4 : 0)
12018      .addOperand(Segment)
12019      .setMemRefs(MMOBegin, MMOEnd);
12020
12021    // Check if there is enough room left to pull this argument.
12022    BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12023      .addReg(OffsetReg)
12024      .addImm(MaxOffset + 8 - ArgSizeA8);
12025
12026    // Branch to "overflowMBB" if offset >= max
12027    // Fall through to "offsetMBB" otherwise
12028    BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12029      .addMBB(overflowMBB);
12030  }
12031
12032  // In offsetMBB, emit code to use the reg_save_area.
12033  if (offsetMBB) {
12034    assert(OffsetReg != 0);
12035
12036    // Read the reg_save_area address.
12037    unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12038    BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12039      .addOperand(Base)
12040      .addOperand(Scale)
12041      .addOperand(Index)
12042      .addDisp(Disp, 16)
12043      .addOperand(Segment)
12044      .setMemRefs(MMOBegin, MMOEnd);
12045
12046    // Zero-extend the offset
12047    unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12048      BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12049        .addImm(0)
12050        .addReg(OffsetReg)
12051        .addImm(X86::sub_32bit);
12052
12053    // Add the offset to the reg_save_area to get the final address.
12054    BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12055      .addReg(OffsetReg64)
12056      .addReg(RegSaveReg);
12057
12058    // Compute the offset for the next argument
12059    unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12060    BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12061      .addReg(OffsetReg)
12062      .addImm(UseFPOffset ? 16 : 8);
12063
12064    // Store it back into the va_list.
12065    BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12066      .addOperand(Base)
12067      .addOperand(Scale)
12068      .addOperand(Index)
12069      .addDisp(Disp, UseFPOffset ? 4 : 0)
12070      .addOperand(Segment)
12071      .addReg(NextOffsetReg)
12072      .setMemRefs(MMOBegin, MMOEnd);
12073
12074    // Jump to endMBB
12075    BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12076      .addMBB(endMBB);
12077  }
12078
12079  //
12080  // Emit code to use overflow area
12081  //
12082
12083  // Load the overflow_area address into a register.
12084  unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12085  BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12086    .addOperand(Base)
12087    .addOperand(Scale)
12088    .addOperand(Index)
12089    .addDisp(Disp, 8)
12090    .addOperand(Segment)
12091    .setMemRefs(MMOBegin, MMOEnd);
12092
12093  // If we need to align it, do so. Otherwise, just copy the address
12094  // to OverflowDestReg.
12095  if (NeedsAlign) {
12096    // Align the overflow address
12097    assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12098    unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12099
12100    // aligned_addr = (addr + (align-1)) & ~(align-1)
12101    BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12102      .addReg(OverflowAddrReg)
12103      .addImm(Align-1);
12104
12105    BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12106      .addReg(TmpReg)
12107      .addImm(~(uint64_t)(Align-1));
12108  } else {
12109    BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12110      .addReg(OverflowAddrReg);
12111  }
12112
12113  // Compute the next overflow address after this argument.
12114  // (the overflow address should be kept 8-byte aligned)
12115  unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12116  BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12117    .addReg(OverflowDestReg)
12118    .addImm(ArgSizeA8);
12119
12120  // Store the new overflow address.
12121  BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12122    .addOperand(Base)
12123    .addOperand(Scale)
12124    .addOperand(Index)
12125    .addDisp(Disp, 8)
12126    .addOperand(Segment)
12127    .addReg(NextAddrReg)
12128    .setMemRefs(MMOBegin, MMOEnd);
12129
12130  // If we branched, emit the PHI to the front of endMBB.
12131  if (offsetMBB) {
12132    BuildMI(*endMBB, endMBB->begin(), DL,
12133            TII->get(X86::PHI), DestReg)
12134      .addReg(OffsetDestReg).addMBB(offsetMBB)
12135      .addReg(OverflowDestReg).addMBB(overflowMBB);
12136  }
12137
12138  // Erase the pseudo instruction
12139  MI->eraseFromParent();
12140
12141  return endMBB;
12142}
12143
12144MachineBasicBlock *
12145X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12146                                                 MachineInstr *MI,
12147                                                 MachineBasicBlock *MBB) const {
12148  // Emit code to save XMM registers to the stack. The ABI says that the
12149  // number of registers to save is given in %al, so it's theoretically
12150  // possible to do an indirect jump trick to avoid saving all of them,
12151  // however this code takes a simpler approach and just executes all
12152  // of the stores if %al is non-zero. It's less code, and it's probably
12153  // easier on the hardware branch predictor, and stores aren't all that
12154  // expensive anyway.
12155
12156  // Create the new basic blocks. One block contains all the XMM stores,
12157  // and one block is the final destination regardless of whether any
12158  // stores were performed.
12159  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12160  MachineFunction *F = MBB->getParent();
12161  MachineFunction::iterator MBBIter = MBB;
12162  ++MBBIter;
12163  MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12164  MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12165  F->insert(MBBIter, XMMSaveMBB);
12166  F->insert(MBBIter, EndMBB);
12167
12168  // Transfer the remainder of MBB and its successor edges to EndMBB.
12169  EndMBB->splice(EndMBB->begin(), MBB,
12170                 llvm::next(MachineBasicBlock::iterator(MI)),
12171                 MBB->end());
12172  EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12173
12174  // The original block will now fall through to the XMM save block.
12175  MBB->addSuccessor(XMMSaveMBB);
12176  // The XMMSaveMBB will fall through to the end block.
12177  XMMSaveMBB->addSuccessor(EndMBB);
12178
12179  // Now add the instructions.
12180  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12181  DebugLoc DL = MI->getDebugLoc();
12182
12183  unsigned CountReg = MI->getOperand(0).getReg();
12184  int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12185  int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12186
12187  if (!Subtarget->isTargetWin64()) {
12188    // If %al is 0, branch around the XMM save block.
12189    BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12190    BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12191    MBB->addSuccessor(EndMBB);
12192  }
12193
12194  unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12195  // In the XMM save block, save all the XMM argument registers.
12196  for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12197    int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12198    MachineMemOperand *MMO =
12199      F->getMachineMemOperand(
12200          MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12201        MachineMemOperand::MOStore,
12202        /*Size=*/16, /*Align=*/16);
12203    BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12204      .addFrameIndex(RegSaveFrameIndex)
12205      .addImm(/*Scale=*/1)
12206      .addReg(/*IndexReg=*/0)
12207      .addImm(/*Disp=*/Offset)
12208      .addReg(/*Segment=*/0)
12209      .addReg(MI->getOperand(i).getReg())
12210      .addMemOperand(MMO);
12211  }
12212
12213  MI->eraseFromParent();   // The pseudo instruction is gone now.
12214
12215  return EndMBB;
12216}
12217
12218MachineBasicBlock *
12219X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12220                                     MachineBasicBlock *BB) const {
12221  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12222  DebugLoc DL = MI->getDebugLoc();
12223
12224  // To "insert" a SELECT_CC instruction, we actually have to insert the
12225  // diamond control-flow pattern.  The incoming instruction knows the
12226  // destination vreg to set, the condition code register to branch on, the
12227  // true/false values to select between, and a branch opcode to use.
12228  const BasicBlock *LLVM_BB = BB->getBasicBlock();
12229  MachineFunction::iterator It = BB;
12230  ++It;
12231
12232  //  thisMBB:
12233  //  ...
12234  //   TrueVal = ...
12235  //   cmpTY ccX, r1, r2
12236  //   bCC copy1MBB
12237  //   fallthrough --> copy0MBB
12238  MachineBasicBlock *thisMBB = BB;
12239  MachineFunction *F = BB->getParent();
12240  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12241  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12242  F->insert(It, copy0MBB);
12243  F->insert(It, sinkMBB);
12244
12245  // If the EFLAGS register isn't dead in the terminator, then claim that it's
12246  // live into the sink and copy blocks.
12247  if (!MI->killsRegister(X86::EFLAGS)) {
12248    copy0MBB->addLiveIn(X86::EFLAGS);
12249    sinkMBB->addLiveIn(X86::EFLAGS);
12250  }
12251
12252  // Transfer the remainder of BB and its successor edges to sinkMBB.
12253  sinkMBB->splice(sinkMBB->begin(), BB,
12254                  llvm::next(MachineBasicBlock::iterator(MI)),
12255                  BB->end());
12256  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12257
12258  // Add the true and fallthrough blocks as its successors.
12259  BB->addSuccessor(copy0MBB);
12260  BB->addSuccessor(sinkMBB);
12261
12262  // Create the conditional branch instruction.
12263  unsigned Opc =
12264    X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12265  BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12266
12267  //  copy0MBB:
12268  //   %FalseValue = ...
12269  //   # fallthrough to sinkMBB
12270  copy0MBB->addSuccessor(sinkMBB);
12271
12272  //  sinkMBB:
12273  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12274  //  ...
12275  BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12276          TII->get(X86::PHI), MI->getOperand(0).getReg())
12277    .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12278    .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12279
12280  MI->eraseFromParent();   // The pseudo instruction is gone now.
12281  return sinkMBB;
12282}
12283
12284MachineBasicBlock *
12285X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12286                                        bool Is64Bit) const {
12287  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12288  DebugLoc DL = MI->getDebugLoc();
12289  MachineFunction *MF = BB->getParent();
12290  const BasicBlock *LLVM_BB = BB->getBasicBlock();
12291
12292  assert(EnableSegmentedStacks);
12293
12294  unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12295  unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12296
12297  // BB:
12298  //  ... [Till the alloca]
12299  // If stacklet is not large enough, jump to mallocMBB
12300  //
12301  // bumpMBB:
12302  //  Allocate by subtracting from RSP
12303  //  Jump to continueMBB
12304  //
12305  // mallocMBB:
12306  //  Allocate by call to runtime
12307  //
12308  // continueMBB:
12309  //  ...
12310  //  [rest of original BB]
12311  //
12312
12313  MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12314  MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12315  MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12316
12317  MachineRegisterInfo &MRI = MF->getRegInfo();
12318  const TargetRegisterClass *AddrRegClass =
12319    getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12320
12321  unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12322    bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12323    tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12324    SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12325    sizeVReg = MI->getOperand(1).getReg(),
12326    physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12327
12328  MachineFunction::iterator MBBIter = BB;
12329  ++MBBIter;
12330
12331  MF->insert(MBBIter, bumpMBB);
12332  MF->insert(MBBIter, mallocMBB);
12333  MF->insert(MBBIter, continueMBB);
12334
12335  continueMBB->splice(continueMBB->begin(), BB, llvm::next
12336                      (MachineBasicBlock::iterator(MI)), BB->end());
12337  continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12338
12339  // Add code to the main basic block to check if the stack limit has been hit,
12340  // and if so, jump to mallocMBB otherwise to bumpMBB.
12341  BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12342  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12343    .addReg(tmpSPVReg).addReg(sizeVReg);
12344  BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12345    .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12346    .addReg(SPLimitVReg);
12347  BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12348
12349  // bumpMBB simply decreases the stack pointer, since we know the current
12350  // stacklet has enough space.
12351  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12352    .addReg(SPLimitVReg);
12353  BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12354    .addReg(SPLimitVReg);
12355  BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12356
12357  // Calls into a routine in libgcc to allocate more space from the heap.
12358  if (Is64Bit) {
12359    BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12360      .addReg(sizeVReg);
12361    BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12362    .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12363  } else {
12364    BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12365      .addImm(12);
12366    BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12367    BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12368      .addExternalSymbol("__morestack_allocate_stack_space");
12369  }
12370
12371  if (!Is64Bit)
12372    BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12373      .addImm(16);
12374
12375  BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12376    .addReg(Is64Bit ? X86::RAX : X86::EAX);
12377  BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12378
12379  // Set up the CFG correctly.
12380  BB->addSuccessor(bumpMBB);
12381  BB->addSuccessor(mallocMBB);
12382  mallocMBB->addSuccessor(continueMBB);
12383  bumpMBB->addSuccessor(continueMBB);
12384
12385  // Take care of the PHI nodes.
12386  BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12387          MI->getOperand(0).getReg())
12388    .addReg(mallocPtrVReg).addMBB(mallocMBB)
12389    .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12390
12391  // Delete the original pseudo instruction.
12392  MI->eraseFromParent();
12393
12394  // And we're done.
12395  return continueMBB;
12396}
12397
12398MachineBasicBlock *
12399X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12400                                          MachineBasicBlock *BB) const {
12401  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12402  DebugLoc DL = MI->getDebugLoc();
12403
12404  assert(!Subtarget->isTargetEnvMacho());
12405
12406  // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12407  // non-trivial part is impdef of ESP.
12408
12409  if (Subtarget->isTargetWin64()) {
12410    if (Subtarget->isTargetCygMing()) {
12411      // ___chkstk(Mingw64):
12412      // Clobbers R10, R11, RAX and EFLAGS.
12413      // Updates RSP.
12414      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12415        .addExternalSymbol("___chkstk")
12416        .addReg(X86::RAX, RegState::Implicit)
12417        .addReg(X86::RSP, RegState::Implicit)
12418        .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12419        .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12420        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12421    } else {
12422      // __chkstk(MSVCRT): does not update stack pointer.
12423      // Clobbers R10, R11 and EFLAGS.
12424      // FIXME: RAX(allocated size) might be reused and not killed.
12425      BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12426        .addExternalSymbol("__chkstk")
12427        .addReg(X86::RAX, RegState::Implicit)
12428        .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12429      // RAX has the offset to subtracted from RSP.
12430      BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12431        .addReg(X86::RSP)
12432        .addReg(X86::RAX);
12433    }
12434  } else {
12435    const char *StackProbeSymbol =
12436      Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12437
12438    BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12439      .addExternalSymbol(StackProbeSymbol)
12440      .addReg(X86::EAX, RegState::Implicit)
12441      .addReg(X86::ESP, RegState::Implicit)
12442      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12443      .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12444      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12445  }
12446
12447  MI->eraseFromParent();   // The pseudo instruction is gone now.
12448  return BB;
12449}
12450
12451MachineBasicBlock *
12452X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12453                                      MachineBasicBlock *BB) const {
12454  // This is pretty easy.  We're taking the value that we received from
12455  // our load from the relocation, sticking it in either RDI (x86-64)
12456  // or EAX and doing an indirect call.  The return value will then
12457  // be in the normal return register.
12458  const X86InstrInfo *TII
12459    = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12460  DebugLoc DL = MI->getDebugLoc();
12461  MachineFunction *F = BB->getParent();
12462
12463  assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12464  assert(MI->getOperand(3).isGlobal() && "This should be a global");
12465
12466  if (Subtarget->is64Bit()) {
12467    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12468                                      TII->get(X86::MOV64rm), X86::RDI)
12469    .addReg(X86::RIP)
12470    .addImm(0).addReg(0)
12471    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12472                      MI->getOperand(3).getTargetFlags())
12473    .addReg(0);
12474    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12475    addDirectMem(MIB, X86::RDI);
12476  } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12477    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12478                                      TII->get(X86::MOV32rm), X86::EAX)
12479    .addReg(0)
12480    .addImm(0).addReg(0)
12481    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12482                      MI->getOperand(3).getTargetFlags())
12483    .addReg(0);
12484    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12485    addDirectMem(MIB, X86::EAX);
12486  } else {
12487    MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12488                                      TII->get(X86::MOV32rm), X86::EAX)
12489    .addReg(TII->getGlobalBaseReg(F))
12490    .addImm(0).addReg(0)
12491    .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12492                      MI->getOperand(3).getTargetFlags())
12493    .addReg(0);
12494    MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12495    addDirectMem(MIB, X86::EAX);
12496  }
12497
12498  MI->eraseFromParent(); // The pseudo instruction is gone now.
12499  return BB;
12500}
12501
12502MachineBasicBlock *
12503X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12504                                               MachineBasicBlock *BB) const {
12505  switch (MI->getOpcode()) {
12506  default: assert(0 && "Unexpected instr type to insert");
12507  case X86::TAILJMPd64:
12508  case X86::TAILJMPr64:
12509  case X86::TAILJMPm64:
12510    assert(0 && "TAILJMP64 would not be touched here.");
12511  case X86::TCRETURNdi64:
12512  case X86::TCRETURNri64:
12513  case X86::TCRETURNmi64:
12514    // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12515    // On AMD64, additional defs should be added before register allocation.
12516    if (!Subtarget->isTargetWin64()) {
12517      MI->addRegisterDefined(X86::RSI);
12518      MI->addRegisterDefined(X86::RDI);
12519      MI->addRegisterDefined(X86::XMM6);
12520      MI->addRegisterDefined(X86::XMM7);
12521      MI->addRegisterDefined(X86::XMM8);
12522      MI->addRegisterDefined(X86::XMM9);
12523      MI->addRegisterDefined(X86::XMM10);
12524      MI->addRegisterDefined(X86::XMM11);
12525      MI->addRegisterDefined(X86::XMM12);
12526      MI->addRegisterDefined(X86::XMM13);
12527      MI->addRegisterDefined(X86::XMM14);
12528      MI->addRegisterDefined(X86::XMM15);
12529    }
12530    return BB;
12531  case X86::WIN_ALLOCA:
12532    return EmitLoweredWinAlloca(MI, BB);
12533  case X86::SEG_ALLOCA_32:
12534    return EmitLoweredSegAlloca(MI, BB, false);
12535  case X86::SEG_ALLOCA_64:
12536    return EmitLoweredSegAlloca(MI, BB, true);
12537  case X86::TLSCall_32:
12538  case X86::TLSCall_64:
12539    return EmitLoweredTLSCall(MI, BB);
12540  case X86::CMOV_GR8:
12541  case X86::CMOV_FR32:
12542  case X86::CMOV_FR64:
12543  case X86::CMOV_V4F32:
12544  case X86::CMOV_V2F64:
12545  case X86::CMOV_V2I64:
12546  case X86::CMOV_V8F32:
12547  case X86::CMOV_V4F64:
12548  case X86::CMOV_V4I64:
12549  case X86::CMOV_GR16:
12550  case X86::CMOV_GR32:
12551  case X86::CMOV_RFP32:
12552  case X86::CMOV_RFP64:
12553  case X86::CMOV_RFP80:
12554    return EmitLoweredSelect(MI, BB);
12555
12556  case X86::FP32_TO_INT16_IN_MEM:
12557  case X86::FP32_TO_INT32_IN_MEM:
12558  case X86::FP32_TO_INT64_IN_MEM:
12559  case X86::FP64_TO_INT16_IN_MEM:
12560  case X86::FP64_TO_INT32_IN_MEM:
12561  case X86::FP64_TO_INT64_IN_MEM:
12562  case X86::FP80_TO_INT16_IN_MEM:
12563  case X86::FP80_TO_INT32_IN_MEM:
12564  case X86::FP80_TO_INT64_IN_MEM: {
12565    const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12566    DebugLoc DL = MI->getDebugLoc();
12567
12568    // Change the floating point control register to use "round towards zero"
12569    // mode when truncating to an integer value.
12570    MachineFunction *F = BB->getParent();
12571    int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12572    addFrameReference(BuildMI(*BB, MI, DL,
12573                              TII->get(X86::FNSTCW16m)), CWFrameIdx);
12574
12575    // Load the old value of the high byte of the control word...
12576    unsigned OldCW =
12577      F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12578    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12579                      CWFrameIdx);
12580
12581    // Set the high part to be round to zero...
12582    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12583      .addImm(0xC7F);
12584
12585    // Reload the modified control word now...
12586    addFrameReference(BuildMI(*BB, MI, DL,
12587                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12588
12589    // Restore the memory image of control word to original value
12590    addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12591      .addReg(OldCW);
12592
12593    // Get the X86 opcode to use.
12594    unsigned Opc;
12595    switch (MI->getOpcode()) {
12596    default: llvm_unreachable("illegal opcode!");
12597    case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12598    case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12599    case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12600    case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12601    case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12602    case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12603    case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12604    case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12605    case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12606    }
12607
12608    X86AddressMode AM;
12609    MachineOperand &Op = MI->getOperand(0);
12610    if (Op.isReg()) {
12611      AM.BaseType = X86AddressMode::RegBase;
12612      AM.Base.Reg = Op.getReg();
12613    } else {
12614      AM.BaseType = X86AddressMode::FrameIndexBase;
12615      AM.Base.FrameIndex = Op.getIndex();
12616    }
12617    Op = MI->getOperand(1);
12618    if (Op.isImm())
12619      AM.Scale = Op.getImm();
12620    Op = MI->getOperand(2);
12621    if (Op.isImm())
12622      AM.IndexReg = Op.getImm();
12623    Op = MI->getOperand(3);
12624    if (Op.isGlobal()) {
12625      AM.GV = Op.getGlobal();
12626    } else {
12627      AM.Disp = Op.getImm();
12628    }
12629    addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12630                      .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12631
12632    // Reload the original control word now.
12633    addFrameReference(BuildMI(*BB, MI, DL,
12634                              TII->get(X86::FLDCW16m)), CWFrameIdx);
12635
12636    MI->eraseFromParent();   // The pseudo instruction is gone now.
12637    return BB;
12638  }
12639    // String/text processing lowering.
12640  case X86::PCMPISTRM128REG:
12641  case X86::VPCMPISTRM128REG:
12642    return EmitPCMP(MI, BB, 3, false /* in-mem */);
12643  case X86::PCMPISTRM128MEM:
12644  case X86::VPCMPISTRM128MEM:
12645    return EmitPCMP(MI, BB, 3, true /* in-mem */);
12646  case X86::PCMPESTRM128REG:
12647  case X86::VPCMPESTRM128REG:
12648    return EmitPCMP(MI, BB, 5, false /* in mem */);
12649  case X86::PCMPESTRM128MEM:
12650  case X86::VPCMPESTRM128MEM:
12651    return EmitPCMP(MI, BB, 5, true /* in mem */);
12652
12653    // Thread synchronization.
12654  case X86::MONITOR:
12655    return EmitMonitor(MI, BB);
12656  case X86::MWAIT:
12657    return EmitMwait(MI, BB);
12658
12659    // Atomic Lowering.
12660  case X86::ATOMAND32:
12661    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12662                                               X86::AND32ri, X86::MOV32rm,
12663                                               X86::LCMPXCHG32,
12664                                               X86::NOT32r, X86::EAX,
12665                                               X86::GR32RegisterClass);
12666  case X86::ATOMOR32:
12667    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12668                                               X86::OR32ri, X86::MOV32rm,
12669                                               X86::LCMPXCHG32,
12670                                               X86::NOT32r, X86::EAX,
12671                                               X86::GR32RegisterClass);
12672  case X86::ATOMXOR32:
12673    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12674                                               X86::XOR32ri, X86::MOV32rm,
12675                                               X86::LCMPXCHG32,
12676                                               X86::NOT32r, X86::EAX,
12677                                               X86::GR32RegisterClass);
12678  case X86::ATOMNAND32:
12679    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12680                                               X86::AND32ri, X86::MOV32rm,
12681                                               X86::LCMPXCHG32,
12682                                               X86::NOT32r, X86::EAX,
12683                                               X86::GR32RegisterClass, true);
12684  case X86::ATOMMIN32:
12685    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12686  case X86::ATOMMAX32:
12687    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12688  case X86::ATOMUMIN32:
12689    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12690  case X86::ATOMUMAX32:
12691    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12692
12693  case X86::ATOMAND16:
12694    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12695                                               X86::AND16ri, X86::MOV16rm,
12696                                               X86::LCMPXCHG16,
12697                                               X86::NOT16r, X86::AX,
12698                                               X86::GR16RegisterClass);
12699  case X86::ATOMOR16:
12700    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12701                                               X86::OR16ri, X86::MOV16rm,
12702                                               X86::LCMPXCHG16,
12703                                               X86::NOT16r, X86::AX,
12704                                               X86::GR16RegisterClass);
12705  case X86::ATOMXOR16:
12706    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12707                                               X86::XOR16ri, X86::MOV16rm,
12708                                               X86::LCMPXCHG16,
12709                                               X86::NOT16r, X86::AX,
12710                                               X86::GR16RegisterClass);
12711  case X86::ATOMNAND16:
12712    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12713                                               X86::AND16ri, X86::MOV16rm,
12714                                               X86::LCMPXCHG16,
12715                                               X86::NOT16r, X86::AX,
12716                                               X86::GR16RegisterClass, true);
12717  case X86::ATOMMIN16:
12718    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12719  case X86::ATOMMAX16:
12720    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12721  case X86::ATOMUMIN16:
12722    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12723  case X86::ATOMUMAX16:
12724    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12725
12726  case X86::ATOMAND8:
12727    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12728                                               X86::AND8ri, X86::MOV8rm,
12729                                               X86::LCMPXCHG8,
12730                                               X86::NOT8r, X86::AL,
12731                                               X86::GR8RegisterClass);
12732  case X86::ATOMOR8:
12733    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12734                                               X86::OR8ri, X86::MOV8rm,
12735                                               X86::LCMPXCHG8,
12736                                               X86::NOT8r, X86::AL,
12737                                               X86::GR8RegisterClass);
12738  case X86::ATOMXOR8:
12739    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12740                                               X86::XOR8ri, X86::MOV8rm,
12741                                               X86::LCMPXCHG8,
12742                                               X86::NOT8r, X86::AL,
12743                                               X86::GR8RegisterClass);
12744  case X86::ATOMNAND8:
12745    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12746                                               X86::AND8ri, X86::MOV8rm,
12747                                               X86::LCMPXCHG8,
12748                                               X86::NOT8r, X86::AL,
12749                                               X86::GR8RegisterClass, true);
12750  // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12751  // This group is for 64-bit host.
12752  case X86::ATOMAND64:
12753    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12754                                               X86::AND64ri32, X86::MOV64rm,
12755                                               X86::LCMPXCHG64,
12756                                               X86::NOT64r, X86::RAX,
12757                                               X86::GR64RegisterClass);
12758  case X86::ATOMOR64:
12759    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12760                                               X86::OR64ri32, X86::MOV64rm,
12761                                               X86::LCMPXCHG64,
12762                                               X86::NOT64r, X86::RAX,
12763                                               X86::GR64RegisterClass);
12764  case X86::ATOMXOR64:
12765    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12766                                               X86::XOR64ri32, X86::MOV64rm,
12767                                               X86::LCMPXCHG64,
12768                                               X86::NOT64r, X86::RAX,
12769                                               X86::GR64RegisterClass);
12770  case X86::ATOMNAND64:
12771    return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12772                                               X86::AND64ri32, X86::MOV64rm,
12773                                               X86::LCMPXCHG64,
12774                                               X86::NOT64r, X86::RAX,
12775                                               X86::GR64RegisterClass, true);
12776  case X86::ATOMMIN64:
12777    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12778  case X86::ATOMMAX64:
12779    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12780  case X86::ATOMUMIN64:
12781    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12782  case X86::ATOMUMAX64:
12783    return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12784
12785  // This group does 64-bit operations on a 32-bit host.
12786  case X86::ATOMAND6432:
12787    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12788                                               X86::AND32rr, X86::AND32rr,
12789                                               X86::AND32ri, X86::AND32ri,
12790                                               false);
12791  case X86::ATOMOR6432:
12792    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12793                                               X86::OR32rr, X86::OR32rr,
12794                                               X86::OR32ri, X86::OR32ri,
12795                                               false);
12796  case X86::ATOMXOR6432:
12797    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12798                                               X86::XOR32rr, X86::XOR32rr,
12799                                               X86::XOR32ri, X86::XOR32ri,
12800                                               false);
12801  case X86::ATOMNAND6432:
12802    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12803                                               X86::AND32rr, X86::AND32rr,
12804                                               X86::AND32ri, X86::AND32ri,
12805                                               true);
12806  case X86::ATOMADD6432:
12807    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12808                                               X86::ADD32rr, X86::ADC32rr,
12809                                               X86::ADD32ri, X86::ADC32ri,
12810                                               false);
12811  case X86::ATOMSUB6432:
12812    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12813                                               X86::SUB32rr, X86::SBB32rr,
12814                                               X86::SUB32ri, X86::SBB32ri,
12815                                               false);
12816  case X86::ATOMSWAP6432:
12817    return EmitAtomicBit6432WithCustomInserter(MI, BB,
12818                                               X86::MOV32rr, X86::MOV32rr,
12819                                               X86::MOV32ri, X86::MOV32ri,
12820                                               false);
12821  case X86::VASTART_SAVE_XMM_REGS:
12822    return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12823
12824  case X86::VAARG_64:
12825    return EmitVAARG64WithCustomInserter(MI, BB);
12826  }
12827}
12828
12829//===----------------------------------------------------------------------===//
12830//                           X86 Optimization Hooks
12831//===----------------------------------------------------------------------===//
12832
12833void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12834                                                       const APInt &Mask,
12835                                                       APInt &KnownZero,
12836                                                       APInt &KnownOne,
12837                                                       const SelectionDAG &DAG,
12838                                                       unsigned Depth) const {
12839  unsigned Opc = Op.getOpcode();
12840  assert((Opc >= ISD::BUILTIN_OP_END ||
12841          Opc == ISD::INTRINSIC_WO_CHAIN ||
12842          Opc == ISD::INTRINSIC_W_CHAIN ||
12843          Opc == ISD::INTRINSIC_VOID) &&
12844         "Should use MaskedValueIsZero if you don't know whether Op"
12845         " is a target node!");
12846
12847  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12848  switch (Opc) {
12849  default: break;
12850  case X86ISD::ADD:
12851  case X86ISD::SUB:
12852  case X86ISD::ADC:
12853  case X86ISD::SBB:
12854  case X86ISD::SMUL:
12855  case X86ISD::UMUL:
12856  case X86ISD::INC:
12857  case X86ISD::DEC:
12858  case X86ISD::OR:
12859  case X86ISD::XOR:
12860  case X86ISD::AND:
12861    // These nodes' second result is a boolean.
12862    if (Op.getResNo() == 0)
12863      break;
12864    // Fallthrough
12865  case X86ISD::SETCC:
12866    KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12867                                       Mask.getBitWidth() - 1);
12868    break;
12869  case ISD::INTRINSIC_WO_CHAIN: {
12870    unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12871    unsigned NumLoBits = 0;
12872    switch (IntId) {
12873    default: break;
12874    case Intrinsic::x86_sse_movmsk_ps:
12875    case Intrinsic::x86_avx_movmsk_ps_256:
12876    case Intrinsic::x86_sse2_movmsk_pd:
12877    case Intrinsic::x86_avx_movmsk_pd_256:
12878    case Intrinsic::x86_mmx_pmovmskb:
12879    case Intrinsic::x86_sse2_pmovmskb_128: {
12880      // High bits of movmskp{s|d}, pmovmskb are known zero.
12881      switch (IntId) {
12882        case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12883        case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12884        case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12885        case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12886        case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12887        case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12888      }
12889      KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12890                                        Mask.getBitWidth() - NumLoBits);
12891      break;
12892    }
12893    }
12894    break;
12895  }
12896  }
12897}
12898
12899unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12900                                                         unsigned Depth) const {
12901  // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12902  if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12903    return Op.getValueType().getScalarType().getSizeInBits();
12904
12905  // Fallback case.
12906  return 1;
12907}
12908
12909/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12910/// node is a GlobalAddress + offset.
12911bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12912                                       const GlobalValue* &GA,
12913                                       int64_t &Offset) const {
12914  if (N->getOpcode() == X86ISD::Wrapper) {
12915    if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12916      GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12917      Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12918      return true;
12919    }
12920  }
12921  return TargetLowering::isGAPlusOffset(N, GA, Offset);
12922}
12923
12924/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12925/// same as extracting the high 128-bit part of 256-bit vector and then
12926/// inserting the result into the low part of a new 256-bit vector
12927static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12928  EVT VT = SVOp->getValueType(0);
12929  int NumElems = VT.getVectorNumElements();
12930
12931  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12932  for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12933    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12934        SVOp->getMaskElt(j) >= 0)
12935      return false;
12936
12937  return true;
12938}
12939
12940/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12941/// same as extracting the low 128-bit part of 256-bit vector and then
12942/// inserting the result into the high part of a new 256-bit vector
12943static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12944  EVT VT = SVOp->getValueType(0);
12945  int NumElems = VT.getVectorNumElements();
12946
12947  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12948  for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12949    if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12950        SVOp->getMaskElt(j) >= 0)
12951      return false;
12952
12953  return true;
12954}
12955
12956/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12957static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12958                                        TargetLowering::DAGCombinerInfo &DCI) {
12959  DebugLoc dl = N->getDebugLoc();
12960  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12961  SDValue V1 = SVOp->getOperand(0);
12962  SDValue V2 = SVOp->getOperand(1);
12963  EVT VT = SVOp->getValueType(0);
12964  int NumElems = VT.getVectorNumElements();
12965
12966  if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12967      V2.getOpcode() == ISD::CONCAT_VECTORS) {
12968    //
12969    //                   0,0,0,...
12970    //                      |
12971    //    V      UNDEF    BUILD_VECTOR    UNDEF
12972    //     \      /           \           /
12973    //  CONCAT_VECTOR         CONCAT_VECTOR
12974    //         \                  /
12975    //          \                /
12976    //          RESULT: V + zero extended
12977    //
12978    if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12979        V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12980        V1.getOperand(1).getOpcode() != ISD::UNDEF)
12981      return SDValue();
12982
12983    if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12984      return SDValue();
12985
12986    // To match the shuffle mask, the first half of the mask should
12987    // be exactly the first vector, and all the rest a splat with the
12988    // first element of the second one.
12989    for (int i = 0; i < NumElems/2; ++i)
12990      if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12991          !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12992        return SDValue();
12993
12994    // Emit a zeroed vector and insert the desired subvector on its
12995    // first half.
12996    SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12997    SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12998                         DAG.getConstant(0, MVT::i32), DAG, dl);
12999    return DCI.CombineTo(N, InsV);
13000  }
13001
13002  //===--------------------------------------------------------------------===//
13003  // Combine some shuffles into subvector extracts and inserts:
13004  //
13005
13006  // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13007  if (isShuffleHigh128VectorInsertLow(SVOp)) {
13008    SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
13009                                    DAG, dl);
13010    SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13011                                      V, DAG.getConstant(0, MVT::i32), DAG, dl);
13012    return DCI.CombineTo(N, InsV);
13013  }
13014
13015  // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13016  if (isShuffleLow128VectorInsertHigh(SVOp)) {
13017    SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
13018    SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13019                             V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
13020    return DCI.CombineTo(N, InsV);
13021  }
13022
13023  return SDValue();
13024}
13025
13026/// PerformShuffleCombine - Performs several different shuffle combines.
13027static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13028                                     TargetLowering::DAGCombinerInfo &DCI,
13029                                     const X86Subtarget *Subtarget) {
13030  DebugLoc dl = N->getDebugLoc();
13031  EVT VT = N->getValueType(0);
13032
13033  // Don't create instructions with illegal types after legalize types has run.
13034  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13035  if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13036    return SDValue();
13037
13038  // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13039  if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13040      N->getOpcode() == ISD::VECTOR_SHUFFLE)
13041    return PerformShuffleCombine256(N, DAG, DCI);
13042
13043  // Only handle 128 wide vector from here on.
13044  if (VT.getSizeInBits() != 128)
13045    return SDValue();
13046
13047  // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13048  // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13049  // consecutive, non-overlapping, and in the right order.
13050  SmallVector<SDValue, 16> Elts;
13051  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13052    Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13053
13054  return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13055}
13056
13057/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13058/// generation and convert it from being a bunch of shuffles and extracts
13059/// to a simple store and scalar loads to extract the elements.
13060static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13061                                                const TargetLowering &TLI) {
13062  SDValue InputVector = N->getOperand(0);
13063
13064  // Only operate on vectors of 4 elements, where the alternative shuffling
13065  // gets to be more expensive.
13066  if (InputVector.getValueType() != MVT::v4i32)
13067    return SDValue();
13068
13069  // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13070  // single use which is a sign-extend or zero-extend, and all elements are
13071  // used.
13072  SmallVector<SDNode *, 4> Uses;
13073  unsigned ExtractedElements = 0;
13074  for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13075       UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13076    if (UI.getUse().getResNo() != InputVector.getResNo())
13077      return SDValue();
13078
13079    SDNode *Extract = *UI;
13080    if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13081      return SDValue();
13082
13083    if (Extract->getValueType(0) != MVT::i32)
13084      return SDValue();
13085    if (!Extract->hasOneUse())
13086      return SDValue();
13087    if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13088        Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13089      return SDValue();
13090    if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13091      return SDValue();
13092
13093    // Record which element was extracted.
13094    ExtractedElements |=
13095      1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13096
13097    Uses.push_back(Extract);
13098  }
13099
13100  // If not all the elements were used, this may not be worthwhile.
13101  if (ExtractedElements != 15)
13102    return SDValue();
13103
13104  // Ok, we've now decided to do the transformation.
13105  DebugLoc dl = InputVector.getDebugLoc();
13106
13107  // Store the value to a temporary stack slot.
13108  SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13109  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13110                            MachinePointerInfo(), false, false, 0);
13111
13112  // Replace each use (extract) with a load of the appropriate element.
13113  for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13114       UE = Uses.end(); UI != UE; ++UI) {
13115    SDNode *Extract = *UI;
13116
13117    // cOMpute the element's address.
13118    SDValue Idx = Extract->getOperand(1);
13119    unsigned EltSize =
13120        InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13121    uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13122    SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13123
13124    SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13125                                     StackPtr, OffsetVal);
13126
13127    // Load the scalar.
13128    SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13129                                     ScalarAddr, MachinePointerInfo(),
13130                                     false, false, false, 0);
13131
13132    // Replace the exact with the load.
13133    DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13134  }
13135
13136  // The replacement was made in place; don't return anything.
13137  return SDValue();
13138}
13139
13140/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13141/// nodes.
13142static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13143                                    const X86Subtarget *Subtarget) {
13144  DebugLoc DL = N->getDebugLoc();
13145  SDValue Cond = N->getOperand(0);
13146  // Get the LHS/RHS of the select.
13147  SDValue LHS = N->getOperand(1);
13148  SDValue RHS = N->getOperand(2);
13149  EVT VT = LHS.getValueType();
13150
13151  // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13152  // instructions match the semantics of the common C idiom x<y?x:y but not
13153  // x<=y?x:y, because of how they handle negative zero (which can be
13154  // ignored in unsafe-math mode).
13155  if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13156      VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13157      (Subtarget->hasXMMInt() ||
13158       (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13159    ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13160
13161    unsigned Opcode = 0;
13162    // Check for x CC y ? x : y.
13163    if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13164        DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13165      switch (CC) {
13166      default: break;
13167      case ISD::SETULT:
13168        // Converting this to a min would handle NaNs incorrectly, and swapping
13169        // the operands would cause it to handle comparisons between positive
13170        // and negative zero incorrectly.
13171        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13172          if (!UnsafeFPMath &&
13173              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13174            break;
13175          std::swap(LHS, RHS);
13176        }
13177        Opcode = X86ISD::FMIN;
13178        break;
13179      case ISD::SETOLE:
13180        // Converting this to a min would handle comparisons between positive
13181        // and negative zero incorrectly.
13182        if (!UnsafeFPMath &&
13183            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13184          break;
13185        Opcode = X86ISD::FMIN;
13186        break;
13187      case ISD::SETULE:
13188        // Converting this to a min would handle both negative zeros and NaNs
13189        // incorrectly, but we can swap the operands to fix both.
13190        std::swap(LHS, RHS);
13191      case ISD::SETOLT:
13192      case ISD::SETLT:
13193      case ISD::SETLE:
13194        Opcode = X86ISD::FMIN;
13195        break;
13196
13197      case ISD::SETOGE:
13198        // Converting this to a max would handle comparisons between positive
13199        // and negative zero incorrectly.
13200        if (!UnsafeFPMath &&
13201            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13202          break;
13203        Opcode = X86ISD::FMAX;
13204        break;
13205      case ISD::SETUGT:
13206        // Converting this to a max would handle NaNs incorrectly, and swapping
13207        // the operands would cause it to handle comparisons between positive
13208        // and negative zero incorrectly.
13209        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13210          if (!UnsafeFPMath &&
13211              !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13212            break;
13213          std::swap(LHS, RHS);
13214        }
13215        Opcode = X86ISD::FMAX;
13216        break;
13217      case ISD::SETUGE:
13218        // Converting this to a max would handle both negative zeros and NaNs
13219        // incorrectly, but we can swap the operands to fix both.
13220        std::swap(LHS, RHS);
13221      case ISD::SETOGT:
13222      case ISD::SETGT:
13223      case ISD::SETGE:
13224        Opcode = X86ISD::FMAX;
13225        break;
13226      }
13227    // Check for x CC y ? y : x -- a min/max with reversed arms.
13228    } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13229               DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13230      switch (CC) {
13231      default: break;
13232      case ISD::SETOGE:
13233        // Converting this to a min would handle comparisons between positive
13234        // and negative zero incorrectly, and swapping the operands would
13235        // cause it to handle NaNs incorrectly.
13236        if (!UnsafeFPMath &&
13237            !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13238          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13239            break;
13240          std::swap(LHS, RHS);
13241        }
13242        Opcode = X86ISD::FMIN;
13243        break;
13244      case ISD::SETUGT:
13245        // Converting this to a min would handle NaNs incorrectly.
13246        if (!UnsafeFPMath &&
13247            (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13248          break;
13249        Opcode = X86ISD::FMIN;
13250        break;
13251      case ISD::SETUGE:
13252        // Converting this to a min would handle both negative zeros and NaNs
13253        // incorrectly, but we can swap the operands to fix both.
13254        std::swap(LHS, RHS);
13255      case ISD::SETOGT:
13256      case ISD::SETGT:
13257      case ISD::SETGE:
13258        Opcode = X86ISD::FMIN;
13259        break;
13260
13261      case ISD::SETULT:
13262        // Converting this to a max would handle NaNs incorrectly.
13263        if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13264          break;
13265        Opcode = X86ISD::FMAX;
13266        break;
13267      case ISD::SETOLE:
13268        // Converting this to a max would handle comparisons between positive
13269        // and negative zero incorrectly, and swapping the operands would
13270        // cause it to handle NaNs incorrectly.
13271        if (!UnsafeFPMath &&
13272            !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13273          if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13274            break;
13275          std::swap(LHS, RHS);
13276        }
13277        Opcode = X86ISD::FMAX;
13278        break;
13279      case ISD::SETULE:
13280        // Converting this to a max would handle both negative zeros and NaNs
13281        // incorrectly, but we can swap the operands to fix both.
13282        std::swap(LHS, RHS);
13283      case ISD::SETOLT:
13284      case ISD::SETLT:
13285      case ISD::SETLE:
13286        Opcode = X86ISD::FMAX;
13287        break;
13288      }
13289    }
13290
13291    if (Opcode)
13292      return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13293  }
13294
13295  // If this is a select between two integer constants, try to do some
13296  // optimizations.
13297  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13298    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13299      // Don't do this for crazy integer types.
13300      if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13301        // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13302        // so that TrueC (the true value) is larger than FalseC.
13303        bool NeedsCondInvert = false;
13304
13305        if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13306            // Efficiently invertible.
13307            (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13308             (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13309              isa<ConstantSDNode>(Cond.getOperand(1))))) {
13310          NeedsCondInvert = true;
13311          std::swap(TrueC, FalseC);
13312        }
13313
13314        // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13315        if (FalseC->getAPIntValue() == 0 &&
13316            TrueC->getAPIntValue().isPowerOf2()) {
13317          if (NeedsCondInvert) // Invert the condition if needed.
13318            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13319                               DAG.getConstant(1, Cond.getValueType()));
13320
13321          // Zero extend the condition if needed.
13322          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13323
13324          unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13325          return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13326                             DAG.getConstant(ShAmt, MVT::i8));
13327        }
13328
13329        // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13330        if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13331          if (NeedsCondInvert) // Invert the condition if needed.
13332            Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13333                               DAG.getConstant(1, Cond.getValueType()));
13334
13335          // Zero extend the condition if needed.
13336          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13337                             FalseC->getValueType(0), Cond);
13338          return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13339                             SDValue(FalseC, 0));
13340        }
13341
13342        // Optimize cases that will turn into an LEA instruction.  This requires
13343        // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13344        if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13345          uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13346          if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13347
13348          bool isFastMultiplier = false;
13349          if (Diff < 10) {
13350            switch ((unsigned char)Diff) {
13351              default: break;
13352              case 1:  // result = add base, cond
13353              case 2:  // result = lea base(    , cond*2)
13354              case 3:  // result = lea base(cond, cond*2)
13355              case 4:  // result = lea base(    , cond*4)
13356              case 5:  // result = lea base(cond, cond*4)
13357              case 8:  // result = lea base(    , cond*8)
13358              case 9:  // result = lea base(cond, cond*8)
13359                isFastMultiplier = true;
13360                break;
13361            }
13362          }
13363
13364          if (isFastMultiplier) {
13365            APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13366            if (NeedsCondInvert) // Invert the condition if needed.
13367              Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13368                                 DAG.getConstant(1, Cond.getValueType()));
13369
13370            // Zero extend the condition if needed.
13371            Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13372                               Cond);
13373            // Scale the condition by the difference.
13374            if (Diff != 1)
13375              Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13376                                 DAG.getConstant(Diff, Cond.getValueType()));
13377
13378            // Add the base if non-zero.
13379            if (FalseC->getAPIntValue() != 0)
13380              Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13381                                 SDValue(FalseC, 0));
13382            return Cond;
13383          }
13384        }
13385      }
13386  }
13387
13388  return SDValue();
13389}
13390
13391/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13392static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13393                                  TargetLowering::DAGCombinerInfo &DCI) {
13394  DebugLoc DL = N->getDebugLoc();
13395
13396  // If the flag operand isn't dead, don't touch this CMOV.
13397  if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13398    return SDValue();
13399
13400  SDValue FalseOp = N->getOperand(0);
13401  SDValue TrueOp = N->getOperand(1);
13402  X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13403  SDValue Cond = N->getOperand(3);
13404  if (CC == X86::COND_E || CC == X86::COND_NE) {
13405    switch (Cond.getOpcode()) {
13406    default: break;
13407    case X86ISD::BSR:
13408    case X86ISD::BSF:
13409      // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13410      if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13411        return (CC == X86::COND_E) ? FalseOp : TrueOp;
13412    }
13413  }
13414
13415  // If this is a select between two integer constants, try to do some
13416  // optimizations.  Note that the operands are ordered the opposite of SELECT
13417  // operands.
13418  if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13419    if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13420      // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13421      // larger than FalseC (the false value).
13422      if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13423        CC = X86::GetOppositeBranchCondition(CC);
13424        std::swap(TrueC, FalseC);
13425      }
13426
13427      // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13428      // This is efficient for any integer data type (including i8/i16) and
13429      // shift amount.
13430      if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13431        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13432                           DAG.getConstant(CC, MVT::i8), Cond);
13433
13434        // Zero extend the condition if needed.
13435        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13436
13437        unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13438        Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13439                           DAG.getConstant(ShAmt, MVT::i8));
13440        if (N->getNumValues() == 2)  // Dead flag value?
13441          return DCI.CombineTo(N, Cond, SDValue());
13442        return Cond;
13443      }
13444
13445      // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13446      // for any integer data type, including i8/i16.
13447      if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13448        Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13449                           DAG.getConstant(CC, MVT::i8), Cond);
13450
13451        // Zero extend the condition if needed.
13452        Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13453                           FalseC->getValueType(0), Cond);
13454        Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13455                           SDValue(FalseC, 0));
13456
13457        if (N->getNumValues() == 2)  // Dead flag value?
13458          return DCI.CombineTo(N, Cond, SDValue());
13459        return Cond;
13460      }
13461
13462      // Optimize cases that will turn into an LEA instruction.  This requires
13463      // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13464      if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13465        uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13466        if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13467
13468        bool isFastMultiplier = false;
13469        if (Diff < 10) {
13470          switch ((unsigned char)Diff) {
13471          default: break;
13472          case 1:  // result = add base, cond
13473          case 2:  // result = lea base(    , cond*2)
13474          case 3:  // result = lea base(cond, cond*2)
13475          case 4:  // result = lea base(    , cond*4)
13476          case 5:  // result = lea base(cond, cond*4)
13477          case 8:  // result = lea base(    , cond*8)
13478          case 9:  // result = lea base(cond, cond*8)
13479            isFastMultiplier = true;
13480            break;
13481          }
13482        }
13483
13484        if (isFastMultiplier) {
13485          APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13486          Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13487                             DAG.getConstant(CC, MVT::i8), Cond);
13488          // Zero extend the condition if needed.
13489          Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13490                             Cond);
13491          // Scale the condition by the difference.
13492          if (Diff != 1)
13493            Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13494                               DAG.getConstant(Diff, Cond.getValueType()));
13495
13496          // Add the base if non-zero.
13497          if (FalseC->getAPIntValue() != 0)
13498            Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13499                               SDValue(FalseC, 0));
13500          if (N->getNumValues() == 2)  // Dead flag value?
13501            return DCI.CombineTo(N, Cond, SDValue());
13502          return Cond;
13503        }
13504      }
13505    }
13506  }
13507  return SDValue();
13508}
13509
13510
13511/// PerformMulCombine - Optimize a single multiply with constant into two
13512/// in order to implement it with two cheaper instructions, e.g.
13513/// LEA + SHL, LEA + LEA.
13514static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13515                                 TargetLowering::DAGCombinerInfo &DCI) {
13516  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13517    return SDValue();
13518
13519  EVT VT = N->getValueType(0);
13520  if (VT != MVT::i64)
13521    return SDValue();
13522
13523  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13524  if (!C)
13525    return SDValue();
13526  uint64_t MulAmt = C->getZExtValue();
13527  if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13528    return SDValue();
13529
13530  uint64_t MulAmt1 = 0;
13531  uint64_t MulAmt2 = 0;
13532  if ((MulAmt % 9) == 0) {
13533    MulAmt1 = 9;
13534    MulAmt2 = MulAmt / 9;
13535  } else if ((MulAmt % 5) == 0) {
13536    MulAmt1 = 5;
13537    MulAmt2 = MulAmt / 5;
13538  } else if ((MulAmt % 3) == 0) {
13539    MulAmt1 = 3;
13540    MulAmt2 = MulAmt / 3;
13541  }
13542  if (MulAmt2 &&
13543      (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13544    DebugLoc DL = N->getDebugLoc();
13545
13546    if (isPowerOf2_64(MulAmt2) &&
13547        !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13548      // If second multiplifer is pow2, issue it first. We want the multiply by
13549      // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13550      // is an add.
13551      std::swap(MulAmt1, MulAmt2);
13552
13553    SDValue NewMul;
13554    if (isPowerOf2_64(MulAmt1))
13555      NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13556                           DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13557    else
13558      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13559                           DAG.getConstant(MulAmt1, VT));
13560
13561    if (isPowerOf2_64(MulAmt2))
13562      NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13563                           DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13564    else
13565      NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13566                           DAG.getConstant(MulAmt2, VT));
13567
13568    // Do not add new nodes to DAG combiner worklist.
13569    DCI.CombineTo(N, NewMul, false);
13570  }
13571  return SDValue();
13572}
13573
13574static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13575  SDValue N0 = N->getOperand(0);
13576  SDValue N1 = N->getOperand(1);
13577  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13578  EVT VT = N0.getValueType();
13579
13580  // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13581  // since the result of setcc_c is all zero's or all ones.
13582  if (VT.isInteger() && !VT.isVector() &&
13583      N1C && N0.getOpcode() == ISD::AND &&
13584      N0.getOperand(1).getOpcode() == ISD::Constant) {
13585    SDValue N00 = N0.getOperand(0);
13586    if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13587        ((N00.getOpcode() == ISD::ANY_EXTEND ||
13588          N00.getOpcode() == ISD::ZERO_EXTEND) &&
13589         N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13590      APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13591      APInt ShAmt = N1C->getAPIntValue();
13592      Mask = Mask.shl(ShAmt);
13593      if (Mask != 0)
13594        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13595                           N00, DAG.getConstant(Mask, VT));
13596    }
13597  }
13598
13599
13600  // Hardware support for vector shifts is sparse which makes us scalarize the
13601  // vector operations in many cases. Also, on sandybridge ADD is faster than
13602  // shl.
13603  // (shl V, 1) -> add V,V
13604  if (isSplatVector(N1.getNode())) {
13605    assert(N0.getValueType().isVector() && "Invalid vector shift type");
13606    ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13607    // We shift all of the values by one. In many cases we do not have
13608    // hardware support for this operation. This is better expressed as an ADD
13609    // of two values.
13610    if (N1C && (1 == N1C->getZExtValue())) {
13611      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13612    }
13613  }
13614
13615  return SDValue();
13616}
13617
13618/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13619///                       when possible.
13620static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13621                                   const X86Subtarget *Subtarget) {
13622  EVT VT = N->getValueType(0);
13623  if (N->getOpcode() == ISD::SHL) {
13624    SDValue V = PerformSHLCombine(N, DAG);
13625    if (V.getNode()) return V;
13626  }
13627
13628  // On X86 with SSE2 support, we can transform this to a vector shift if
13629  // all elements are shifted by the same amount.  We can't do this in legalize
13630  // because the a constant vector is typically transformed to a constant pool
13631  // so we have no knowledge of the shift amount.
13632  if (!Subtarget->hasXMMInt())
13633    return SDValue();
13634
13635  if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13636      (!Subtarget->hasAVX2() ||
13637       (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13638    return SDValue();
13639
13640  SDValue ShAmtOp = N->getOperand(1);
13641  EVT EltVT = VT.getVectorElementType();
13642  DebugLoc DL = N->getDebugLoc();
13643  SDValue BaseShAmt = SDValue();
13644  if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13645    unsigned NumElts = VT.getVectorNumElements();
13646    unsigned i = 0;
13647    for (; i != NumElts; ++i) {
13648      SDValue Arg = ShAmtOp.getOperand(i);
13649      if (Arg.getOpcode() == ISD::UNDEF) continue;
13650      BaseShAmt = Arg;
13651      break;
13652    }
13653    for (; i != NumElts; ++i) {
13654      SDValue Arg = ShAmtOp.getOperand(i);
13655      if (Arg.getOpcode() == ISD::UNDEF) continue;
13656      if (Arg != BaseShAmt) {
13657        return SDValue();
13658      }
13659    }
13660  } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13661             cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13662    SDValue InVec = ShAmtOp.getOperand(0);
13663    if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13664      unsigned NumElts = InVec.getValueType().getVectorNumElements();
13665      unsigned i = 0;
13666      for (; i != NumElts; ++i) {
13667        SDValue Arg = InVec.getOperand(i);
13668        if (Arg.getOpcode() == ISD::UNDEF) continue;
13669        BaseShAmt = Arg;
13670        break;
13671      }
13672    } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13673       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13674         unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13675         if (C->getZExtValue() == SplatIdx)
13676           BaseShAmt = InVec.getOperand(1);
13677       }
13678    }
13679    if (BaseShAmt.getNode() == 0)
13680      BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13681                              DAG.getIntPtrConstant(0));
13682  } else
13683    return SDValue();
13684
13685  // The shift amount is an i32.
13686  if (EltVT.bitsGT(MVT::i32))
13687    BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13688  else if (EltVT.bitsLT(MVT::i32))
13689    BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13690
13691  // The shift amount is identical so we can do a vector shift.
13692  SDValue  ValOp = N->getOperand(0);
13693  switch (N->getOpcode()) {
13694  default:
13695    llvm_unreachable("Unknown shift opcode!");
13696    break;
13697  case ISD::SHL:
13698    if (VT == MVT::v2i64)
13699      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13700                         DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13701                         ValOp, BaseShAmt);
13702    if (VT == MVT::v4i32)
13703      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13704                         DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13705                         ValOp, BaseShAmt);
13706    if (VT == MVT::v8i16)
13707      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13708                         DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13709                         ValOp, BaseShAmt);
13710    if (VT == MVT::v4i64)
13711      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13712                         DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13713                         ValOp, BaseShAmt);
13714    if (VT == MVT::v8i32)
13715      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13716                         DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13717                         ValOp, BaseShAmt);
13718    if (VT == MVT::v16i16)
13719      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13720                         DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13721                         ValOp, BaseShAmt);
13722    break;
13723  case ISD::SRA:
13724    if (VT == MVT::v4i32)
13725      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13726                         DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13727                         ValOp, BaseShAmt);
13728    if (VT == MVT::v8i16)
13729      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13730                         DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13731                         ValOp, BaseShAmt);
13732    if (VT == MVT::v8i32)
13733      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13734                         DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13735                         ValOp, BaseShAmt);
13736    if (VT == MVT::v16i16)
13737      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13738                         DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13739                         ValOp, BaseShAmt);
13740    break;
13741  case ISD::SRL:
13742    if (VT == MVT::v2i64)
13743      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13744                         DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13745                         ValOp, BaseShAmt);
13746    if (VT == MVT::v4i32)
13747      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13748                         DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13749                         ValOp, BaseShAmt);
13750    if (VT ==  MVT::v8i16)
13751      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13752                         DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13753                         ValOp, BaseShAmt);
13754    if (VT == MVT::v4i64)
13755      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13756                         DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13757                         ValOp, BaseShAmt);
13758    if (VT == MVT::v8i32)
13759      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13760                         DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13761                         ValOp, BaseShAmt);
13762    if (VT ==  MVT::v16i16)
13763      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13764                         DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13765                         ValOp, BaseShAmt);
13766    break;
13767  }
13768  return SDValue();
13769}
13770
13771
13772// CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13773// where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13774// and friends.  Likewise for OR -> CMPNEQSS.
13775static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13776                            TargetLowering::DAGCombinerInfo &DCI,
13777                            const X86Subtarget *Subtarget) {
13778  unsigned opcode;
13779
13780  // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13781  // we're requiring SSE2 for both.
13782  if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13783    SDValue N0 = N->getOperand(0);
13784    SDValue N1 = N->getOperand(1);
13785    SDValue CMP0 = N0->getOperand(1);
13786    SDValue CMP1 = N1->getOperand(1);
13787    DebugLoc DL = N->getDebugLoc();
13788
13789    // The SETCCs should both refer to the same CMP.
13790    if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13791      return SDValue();
13792
13793    SDValue CMP00 = CMP0->getOperand(0);
13794    SDValue CMP01 = CMP0->getOperand(1);
13795    EVT     VT    = CMP00.getValueType();
13796
13797    if (VT == MVT::f32 || VT == MVT::f64) {
13798      bool ExpectingFlags = false;
13799      // Check for any users that want flags:
13800      for (SDNode::use_iterator UI = N->use_begin(),
13801             UE = N->use_end();
13802           !ExpectingFlags && UI != UE; ++UI)
13803        switch (UI->getOpcode()) {
13804        default:
13805        case ISD::BR_CC:
13806        case ISD::BRCOND:
13807        case ISD::SELECT:
13808          ExpectingFlags = true;
13809          break;
13810        case ISD::CopyToReg:
13811        case ISD::SIGN_EXTEND:
13812        case ISD::ZERO_EXTEND:
13813        case ISD::ANY_EXTEND:
13814          break;
13815        }
13816
13817      if (!ExpectingFlags) {
13818        enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13819        enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13820
13821        if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13822          X86::CondCode tmp = cc0;
13823          cc0 = cc1;
13824          cc1 = tmp;
13825        }
13826
13827        if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13828            (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13829          bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13830          X86ISD::NodeType NTOperator = is64BitFP ?
13831            X86ISD::FSETCCsd : X86ISD::FSETCCss;
13832          // FIXME: need symbolic constants for these magic numbers.
13833          // See X86ATTInstPrinter.cpp:printSSECC().
13834          unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13835          SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13836                                              DAG.getConstant(x86cc, MVT::i8));
13837          SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13838                                              OnesOrZeroesF);
13839          SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13840                                      DAG.getConstant(1, MVT::i32));
13841          SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13842          return OneBitOfTruth;
13843        }
13844      }
13845    }
13846  }
13847  return SDValue();
13848}
13849
13850/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13851/// so it can be folded inside ANDNP.
13852static bool CanFoldXORWithAllOnes(const SDNode *N) {
13853  EVT VT = N->getValueType(0);
13854
13855  // Match direct AllOnes for 128 and 256-bit vectors
13856  if (ISD::isBuildVectorAllOnes(N))
13857    return true;
13858
13859  // Look through a bit convert.
13860  if (N->getOpcode() == ISD::BITCAST)
13861    N = N->getOperand(0).getNode();
13862
13863  // Sometimes the operand may come from a insert_subvector building a 256-bit
13864  // allones vector
13865  if (VT.getSizeInBits() == 256 &&
13866      N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13867    SDValue V1 = N->getOperand(0);
13868    SDValue V2 = N->getOperand(1);
13869
13870    if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13871        V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13872        ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13873        ISD::isBuildVectorAllOnes(V2.getNode()))
13874      return true;
13875  }
13876
13877  return false;
13878}
13879
13880static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13881                                 TargetLowering::DAGCombinerInfo &DCI,
13882                                 const X86Subtarget *Subtarget) {
13883  if (DCI.isBeforeLegalizeOps())
13884    return SDValue();
13885
13886  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13887  if (R.getNode())
13888    return R;
13889
13890  EVT VT = N->getValueType(0);
13891
13892  // Create ANDN, BLSI, and BLSR instructions
13893  // BLSI is X & (-X)
13894  // BLSR is X & (X-1)
13895  if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13896    SDValue N0 = N->getOperand(0);
13897    SDValue N1 = N->getOperand(1);
13898    DebugLoc DL = N->getDebugLoc();
13899
13900    // Check LHS for not
13901    if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13902      return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13903    // Check RHS for not
13904    if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13905      return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13906
13907    // Check LHS for neg
13908    if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13909        isZero(N0.getOperand(0)))
13910      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13911
13912    // Check RHS for neg
13913    if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13914        isZero(N1.getOperand(0)))
13915      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13916
13917    // Check LHS for X-1
13918    if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13919        isAllOnes(N0.getOperand(1)))
13920      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13921
13922    // Check RHS for X-1
13923    if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13924        isAllOnes(N1.getOperand(1)))
13925      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13926
13927    return SDValue();
13928  }
13929
13930  // Want to form ANDNP nodes:
13931  // 1) In the hopes of then easily combining them with OR and AND nodes
13932  //    to form PBLEND/PSIGN.
13933  // 2) To match ANDN packed intrinsics
13934  if (VT != MVT::v2i64 && VT != MVT::v4i64)
13935    return SDValue();
13936
13937  SDValue N0 = N->getOperand(0);
13938  SDValue N1 = N->getOperand(1);
13939  DebugLoc DL = N->getDebugLoc();
13940
13941  // Check LHS for vnot
13942  if (N0.getOpcode() == ISD::XOR &&
13943      //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13944      CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13945    return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13946
13947  // Check RHS for vnot
13948  if (N1.getOpcode() == ISD::XOR &&
13949      //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13950      CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13951    return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13952
13953  return SDValue();
13954}
13955
13956static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13957                                TargetLowering::DAGCombinerInfo &DCI,
13958                                const X86Subtarget *Subtarget) {
13959  if (DCI.isBeforeLegalizeOps())
13960    return SDValue();
13961
13962  SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13963  if (R.getNode())
13964    return R;
13965
13966  EVT VT = N->getValueType(0);
13967
13968  SDValue N0 = N->getOperand(0);
13969  SDValue N1 = N->getOperand(1);
13970
13971  // look for psign/blend
13972  if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13973    if (!Subtarget->hasSSSE3orAVX() ||
13974        (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13975      return SDValue();
13976
13977    // Canonicalize pandn to RHS
13978    if (N0.getOpcode() == X86ISD::ANDNP)
13979      std::swap(N0, N1);
13980    // or (and (m, x), (pandn m, y))
13981    if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13982      SDValue Mask = N1.getOperand(0);
13983      SDValue X    = N1.getOperand(1);
13984      SDValue Y;
13985      if (N0.getOperand(0) == Mask)
13986        Y = N0.getOperand(1);
13987      if (N0.getOperand(1) == Mask)
13988        Y = N0.getOperand(0);
13989
13990      // Check to see if the mask appeared in both the AND and ANDNP and
13991      if (!Y.getNode())
13992        return SDValue();
13993
13994      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13995      if (Mask.getOpcode() != ISD::BITCAST ||
13996          X.getOpcode() != ISD::BITCAST ||
13997          Y.getOpcode() != ISD::BITCAST)
13998        return SDValue();
13999
14000      // Look through mask bitcast.
14001      Mask = Mask.getOperand(0);
14002      EVT MaskVT = Mask.getValueType();
14003
14004      // Validate that the Mask operand is a vector sra node.  The sra node
14005      // will be an intrinsic.
14006      if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
14007        return SDValue();
14008
14009      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14010      // there is no psrai.b
14011      switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
14012      case Intrinsic::x86_sse2_psrai_w:
14013      case Intrinsic::x86_sse2_psrai_d:
14014      case Intrinsic::x86_avx2_psrai_w:
14015      case Intrinsic::x86_avx2_psrai_d:
14016        break;
14017      default: return SDValue();
14018      }
14019
14020      // Check that the SRA is all signbits.
14021      SDValue SraC = Mask.getOperand(2);
14022      unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14023      unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14024      if ((SraAmt + 1) != EltBits)
14025        return SDValue();
14026
14027      DebugLoc DL = N->getDebugLoc();
14028
14029      // Now we know we at least have a plendvb with the mask val.  See if
14030      // we can form a psignb/w/d.
14031      // psign = x.type == y.type == mask.type && y = sub(0, x);
14032      X = X.getOperand(0);
14033      Y = Y.getOperand(0);
14034      if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14035          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14036          X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
14037          (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
14038        SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
14039                                   Mask.getOperand(1));
14040        return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
14041      }
14042      // PBLENDVB only available on SSE 4.1
14043      if (!Subtarget->hasSSE41orAVX())
14044        return SDValue();
14045
14046      EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14047
14048      X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14049      Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14050      Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14051      Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, X, Y);
14052      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14053    }
14054  }
14055
14056  if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14057    return SDValue();
14058
14059  // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14060  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14061    std::swap(N0, N1);
14062  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14063    return SDValue();
14064  if (!N0.hasOneUse() || !N1.hasOneUse())
14065    return SDValue();
14066
14067  SDValue ShAmt0 = N0.getOperand(1);
14068  if (ShAmt0.getValueType() != MVT::i8)
14069    return SDValue();
14070  SDValue ShAmt1 = N1.getOperand(1);
14071  if (ShAmt1.getValueType() != MVT::i8)
14072    return SDValue();
14073  if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14074    ShAmt0 = ShAmt0.getOperand(0);
14075  if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14076    ShAmt1 = ShAmt1.getOperand(0);
14077
14078  DebugLoc DL = N->getDebugLoc();
14079  unsigned Opc = X86ISD::SHLD;
14080  SDValue Op0 = N0.getOperand(0);
14081  SDValue Op1 = N1.getOperand(0);
14082  if (ShAmt0.getOpcode() == ISD::SUB) {
14083    Opc = X86ISD::SHRD;
14084    std::swap(Op0, Op1);
14085    std::swap(ShAmt0, ShAmt1);
14086  }
14087
14088  unsigned Bits = VT.getSizeInBits();
14089  if (ShAmt1.getOpcode() == ISD::SUB) {
14090    SDValue Sum = ShAmt1.getOperand(0);
14091    if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14092      SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14093      if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14094        ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14095      if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14096        return DAG.getNode(Opc, DL, VT,
14097                           Op0, Op1,
14098                           DAG.getNode(ISD::TRUNCATE, DL,
14099                                       MVT::i8, ShAmt0));
14100    }
14101  } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14102    ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14103    if (ShAmt0C &&
14104        ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14105      return DAG.getNode(Opc, DL, VT,
14106                         N0.getOperand(0), N1.getOperand(0),
14107                         DAG.getNode(ISD::TRUNCATE, DL,
14108                                       MVT::i8, ShAmt0));
14109  }
14110
14111  return SDValue();
14112}
14113
14114static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14115                                 TargetLowering::DAGCombinerInfo &DCI,
14116                                 const X86Subtarget *Subtarget) {
14117  if (DCI.isBeforeLegalizeOps())
14118    return SDValue();
14119
14120  EVT VT = N->getValueType(0);
14121
14122  if (VT != MVT::i32 && VT != MVT::i64)
14123    return SDValue();
14124
14125  // Create BLSMSK instructions by finding X ^ (X-1)
14126  SDValue N0 = N->getOperand(0);
14127  SDValue N1 = N->getOperand(1);
14128  DebugLoc DL = N->getDebugLoc();
14129
14130  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14131      isAllOnes(N0.getOperand(1)))
14132    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14133
14134  if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14135      isAllOnes(N1.getOperand(1)))
14136    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14137
14138  return SDValue();
14139}
14140
14141/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14142static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14143                                   const X86Subtarget *Subtarget) {
14144  LoadSDNode *Ld = cast<LoadSDNode>(N);
14145  EVT RegVT = Ld->getValueType(0);
14146  EVT MemVT = Ld->getMemoryVT();
14147  DebugLoc dl = Ld->getDebugLoc();
14148  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14149
14150  ISD::LoadExtType Ext = Ld->getExtensionType();
14151
14152  // If this is a vector EXT Load then attempt to optimize it using a
14153  // shuffle. We need SSE4 for the shuffles.
14154  // TODO: It is possible to support ZExt by zeroing the undef values
14155  // during the shuffle phase or after the shuffle.
14156  if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14157    assert(MemVT != RegVT && "Cannot extend to the same type");
14158    assert(MemVT.isVector() && "Must load a vector from memory");
14159
14160    unsigned NumElems = RegVT.getVectorNumElements();
14161    unsigned RegSz = RegVT.getSizeInBits();
14162    unsigned MemSz = MemVT.getSizeInBits();
14163    assert(RegSz > MemSz && "Register size must be greater than the mem size");
14164    // All sizes must be a power of two
14165    if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14166
14167    // Attempt to load the original value using a single load op.
14168    // Find a scalar type which is equal to the loaded word size.
14169    MVT SclrLoadTy = MVT::i8;
14170    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14171         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14172      MVT Tp = (MVT::SimpleValueType)tp;
14173      if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14174        SclrLoadTy = Tp;
14175        break;
14176      }
14177    }
14178
14179    // Proceed if a load word is found.
14180    if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14181
14182    EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14183      RegSz/SclrLoadTy.getSizeInBits());
14184
14185    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14186                                  RegSz/MemVT.getScalarType().getSizeInBits());
14187    // Can't shuffle using an illegal type.
14188    if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14189
14190    // Perform a single load.
14191    SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14192                                  Ld->getBasePtr(),
14193                                  Ld->getPointerInfo(), Ld->isVolatile(),
14194                                  Ld->isNonTemporal(), Ld->isInvariant(),
14195                                  Ld->getAlignment());
14196
14197    // Insert the word loaded into a vector.
14198    SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14199      LoadUnitVecVT, ScalarLoad);
14200
14201    // Bitcast the loaded value to a vector of the original element type, in
14202    // the size of the target vector type.
14203    SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14204    unsigned SizeRatio = RegSz/MemSz;
14205
14206    // Redistribute the loaded elements into the different locations.
14207    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14208    for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14209
14210    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14211                                DAG.getUNDEF(SlicedVec.getValueType()),
14212                                ShuffleVec.data());
14213
14214    // Bitcast to the requested type.
14215    Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14216    // Replace the original load with the new sequence
14217    // and return the new chain.
14218    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14219    return SDValue(ScalarLoad.getNode(), 1);
14220  }
14221
14222  return SDValue();
14223}
14224
14225/// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14226static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14227                                   const X86Subtarget *Subtarget) {
14228  StoreSDNode *St = cast<StoreSDNode>(N);
14229  EVT VT = St->getValue().getValueType();
14230  EVT StVT = St->getMemoryVT();
14231  DebugLoc dl = St->getDebugLoc();
14232  SDValue StoredVal = St->getOperand(1);
14233  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14234
14235  // If we are saving a concatination of two XMM registers, perform two stores.
14236  // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14237  // 128-bit ones. If in the future the cost becomes only one memory access the
14238  // first version would be better.
14239  if (VT.getSizeInBits() == 256 &&
14240    StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14241    StoredVal.getNumOperands() == 2) {
14242
14243    SDValue Value0 = StoredVal.getOperand(0);
14244    SDValue Value1 = StoredVal.getOperand(1);
14245
14246    SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14247    SDValue Ptr0 = St->getBasePtr();
14248    SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14249
14250    SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14251                                St->getPointerInfo(), St->isVolatile(),
14252                                St->isNonTemporal(), St->getAlignment());
14253    SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14254                                St->getPointerInfo(), St->isVolatile(),
14255                                St->isNonTemporal(), St->getAlignment());
14256    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14257  }
14258
14259  // Optimize trunc store (of multiple scalars) to shuffle and store.
14260  // First, pack all of the elements in one place. Next, store to memory
14261  // in fewer chunks.
14262  if (St->isTruncatingStore() && VT.isVector()) {
14263    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14264    unsigned NumElems = VT.getVectorNumElements();
14265    assert(StVT != VT && "Cannot truncate to the same type");
14266    unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14267    unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14268
14269    // From, To sizes and ElemCount must be pow of two
14270    if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14271    // We are going to use the original vector elt for storing.
14272    // Accumulated smaller vector elements must be a multiple of the store size.
14273    if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14274
14275    unsigned SizeRatio  = FromSz / ToSz;
14276
14277    assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14278
14279    // Create a type on which we perform the shuffle
14280    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14281            StVT.getScalarType(), NumElems*SizeRatio);
14282
14283    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14284
14285    SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14286    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14287    for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14288
14289    // Can't shuffle using an illegal type
14290    if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14291
14292    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14293                                DAG.getUNDEF(WideVec.getValueType()),
14294                                ShuffleVec.data());
14295    // At this point all of the data is stored at the bottom of the
14296    // register. We now need to save it to mem.
14297
14298    // Find the largest store unit
14299    MVT StoreType = MVT::i8;
14300    for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14301         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14302      MVT Tp = (MVT::SimpleValueType)tp;
14303      if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14304        StoreType = Tp;
14305    }
14306
14307    // Bitcast the original vector into a vector of store-size units
14308    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14309            StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14310    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14311    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14312    SmallVector<SDValue, 8> Chains;
14313    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14314                                        TLI.getPointerTy());
14315    SDValue Ptr = St->getBasePtr();
14316
14317    // Perform one or more big stores into memory.
14318    for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14319      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14320                                   StoreType, ShuffWide,
14321                                   DAG.getIntPtrConstant(i));
14322      SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14323                                St->getPointerInfo(), St->isVolatile(),
14324                                St->isNonTemporal(), St->getAlignment());
14325      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14326      Chains.push_back(Ch);
14327    }
14328
14329    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14330                               Chains.size());
14331  }
14332
14333
14334  // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14335  // the FP state in cases where an emms may be missing.
14336  // A preferable solution to the general problem is to figure out the right
14337  // places to insert EMMS.  This qualifies as a quick hack.
14338
14339  // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14340  if (VT.getSizeInBits() != 64)
14341    return SDValue();
14342
14343  const Function *F = DAG.getMachineFunction().getFunction();
14344  bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14345  bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14346                     && Subtarget->hasXMMInt();
14347  if ((VT.isVector() ||
14348       (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14349      isa<LoadSDNode>(St->getValue()) &&
14350      !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14351      St->getChain().hasOneUse() && !St->isVolatile()) {
14352    SDNode* LdVal = St->getValue().getNode();
14353    LoadSDNode *Ld = 0;
14354    int TokenFactorIndex = -1;
14355    SmallVector<SDValue, 8> Ops;
14356    SDNode* ChainVal = St->getChain().getNode();
14357    // Must be a store of a load.  We currently handle two cases:  the load
14358    // is a direct child, and it's under an intervening TokenFactor.  It is
14359    // possible to dig deeper under nested TokenFactors.
14360    if (ChainVal == LdVal)
14361      Ld = cast<LoadSDNode>(St->getChain());
14362    else if (St->getValue().hasOneUse() &&
14363             ChainVal->getOpcode() == ISD::TokenFactor) {
14364      for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14365        if (ChainVal->getOperand(i).getNode() == LdVal) {
14366          TokenFactorIndex = i;
14367          Ld = cast<LoadSDNode>(St->getValue());
14368        } else
14369          Ops.push_back(ChainVal->getOperand(i));
14370      }
14371    }
14372
14373    if (!Ld || !ISD::isNormalLoad(Ld))
14374      return SDValue();
14375
14376    // If this is not the MMX case, i.e. we are just turning i64 load/store
14377    // into f64 load/store, avoid the transformation if there are multiple
14378    // uses of the loaded value.
14379    if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14380      return SDValue();
14381
14382    DebugLoc LdDL = Ld->getDebugLoc();
14383    DebugLoc StDL = N->getDebugLoc();
14384    // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14385    // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14386    // pair instead.
14387    if (Subtarget->is64Bit() || F64IsLegal) {
14388      EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14389      SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14390                                  Ld->getPointerInfo(), Ld->isVolatile(),
14391                                  Ld->isNonTemporal(), Ld->isInvariant(),
14392                                  Ld->getAlignment());
14393      SDValue NewChain = NewLd.getValue(1);
14394      if (TokenFactorIndex != -1) {
14395        Ops.push_back(NewChain);
14396        NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14397                               Ops.size());
14398      }
14399      return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14400                          St->getPointerInfo(),
14401                          St->isVolatile(), St->isNonTemporal(),
14402                          St->getAlignment());
14403    }
14404
14405    // Otherwise, lower to two pairs of 32-bit loads / stores.
14406    SDValue LoAddr = Ld->getBasePtr();
14407    SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14408                                 DAG.getConstant(4, MVT::i32));
14409
14410    SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14411                               Ld->getPointerInfo(),
14412                               Ld->isVolatile(), Ld->isNonTemporal(),
14413                               Ld->isInvariant(), Ld->getAlignment());
14414    SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14415                               Ld->getPointerInfo().getWithOffset(4),
14416                               Ld->isVolatile(), Ld->isNonTemporal(),
14417                               Ld->isInvariant(),
14418                               MinAlign(Ld->getAlignment(), 4));
14419
14420    SDValue NewChain = LoLd.getValue(1);
14421    if (TokenFactorIndex != -1) {
14422      Ops.push_back(LoLd);
14423      Ops.push_back(HiLd);
14424      NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14425                             Ops.size());
14426    }
14427
14428    LoAddr = St->getBasePtr();
14429    HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14430                         DAG.getConstant(4, MVT::i32));
14431
14432    SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14433                                St->getPointerInfo(),
14434                                St->isVolatile(), St->isNonTemporal(),
14435                                St->getAlignment());
14436    SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14437                                St->getPointerInfo().getWithOffset(4),
14438                                St->isVolatile(),
14439                                St->isNonTemporal(),
14440                                MinAlign(St->getAlignment(), 4));
14441    return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14442  }
14443  return SDValue();
14444}
14445
14446/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14447/// and return the operands for the horizontal operation in LHS and RHS.  A
14448/// horizontal operation performs the binary operation on successive elements
14449/// of its first operand, then on successive elements of its second operand,
14450/// returning the resulting values in a vector.  For example, if
14451///   A = < float a0, float a1, float a2, float a3 >
14452/// and
14453///   B = < float b0, float b1, float b2, float b3 >
14454/// then the result of doing a horizontal operation on A and B is
14455///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14456/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14457/// A horizontal-op B, for some already available A and B, and if so then LHS is
14458/// set to A, RHS to B, and the routine returns 'true'.
14459/// Note that the binary operation should have the property that if one of the
14460/// operands is UNDEF then the result is UNDEF.
14461static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14462  // Look for the following pattern: if
14463  //   A = < float a0, float a1, float a2, float a3 >
14464  //   B = < float b0, float b1, float b2, float b3 >
14465  // and
14466  //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14467  //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14468  // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14469  // which is A horizontal-op B.
14470
14471  // At least one of the operands should be a vector shuffle.
14472  if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14473      RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14474    return false;
14475
14476  EVT VT = LHS.getValueType();
14477  unsigned N = VT.getVectorNumElements();
14478
14479  // View LHS in the form
14480  //   LHS = VECTOR_SHUFFLE A, B, LMask
14481  // If LHS is not a shuffle then pretend it is the shuffle
14482  //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14483  // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14484  // type VT.
14485  SDValue A, B;
14486  SmallVector<int, 8> LMask(N);
14487  if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14488    if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14489      A = LHS.getOperand(0);
14490    if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14491      B = LHS.getOperand(1);
14492    cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14493  } else {
14494    if (LHS.getOpcode() != ISD::UNDEF)
14495      A = LHS;
14496    for (unsigned i = 0; i != N; ++i)
14497      LMask[i] = i;
14498  }
14499
14500  // Likewise, view RHS in the form
14501  //   RHS = VECTOR_SHUFFLE C, D, RMask
14502  SDValue C, D;
14503  SmallVector<int, 8> RMask(N);
14504  if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14505    if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14506      C = RHS.getOperand(0);
14507    if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14508      D = RHS.getOperand(1);
14509    cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14510  } else {
14511    if (RHS.getOpcode() != ISD::UNDEF)
14512      C = RHS;
14513    for (unsigned i = 0; i != N; ++i)
14514      RMask[i] = i;
14515  }
14516
14517  // Check that the shuffles are both shuffling the same vectors.
14518  if (!(A == C && B == D) && !(A == D && B == C))
14519    return false;
14520
14521  // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14522  if (!A.getNode() && !B.getNode())
14523    return false;
14524
14525  // If A and B occur in reverse order in RHS, then "swap" them (which means
14526  // rewriting the mask).
14527  if (A != C)
14528    for (unsigned i = 0; i != N; ++i) {
14529      unsigned Idx = RMask[i];
14530      if (Idx < N)
14531        RMask[i] += N;
14532      else if (Idx < 2*N)
14533        RMask[i] -= N;
14534    }
14535
14536  // At this point LHS and RHS are equivalent to
14537  //   LHS = VECTOR_SHUFFLE A, B, LMask
14538  //   RHS = VECTOR_SHUFFLE A, B, RMask
14539  // Check that the masks correspond to performing a horizontal operation.
14540  for (unsigned i = 0; i != N; ++i) {
14541    unsigned LIdx = LMask[i], RIdx = RMask[i];
14542
14543    // Ignore any UNDEF components.
14544    if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14545        || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14546      continue;
14547
14548    // Check that successive elements are being operated on.  If not, this is
14549    // not a horizontal operation.
14550    if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14551        !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14552      return false;
14553  }
14554
14555  LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14556  RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14557  return true;
14558}
14559
14560/// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14561static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14562                                  const X86Subtarget *Subtarget) {
14563  EVT VT = N->getValueType(0);
14564  SDValue LHS = N->getOperand(0);
14565  SDValue RHS = N->getOperand(1);
14566
14567  // Try to synthesize horizontal adds from adds of shuffles.
14568  if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14569      isHorizontalBinOp(LHS, RHS, true))
14570    return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14571  return SDValue();
14572}
14573
14574/// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14575static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14576                                  const X86Subtarget *Subtarget) {
14577  EVT VT = N->getValueType(0);
14578  SDValue LHS = N->getOperand(0);
14579  SDValue RHS = N->getOperand(1);
14580
14581  // Try to synthesize horizontal subs from subs of shuffles.
14582  if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14583      isHorizontalBinOp(LHS, RHS, false))
14584    return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14585  return SDValue();
14586}
14587
14588/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14589/// X86ISD::FXOR nodes.
14590static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14591  assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14592  // F[X]OR(0.0, x) -> x
14593  // F[X]OR(x, 0.0) -> x
14594  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14595    if (C->getValueAPF().isPosZero())
14596      return N->getOperand(1);
14597  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14598    if (C->getValueAPF().isPosZero())
14599      return N->getOperand(0);
14600  return SDValue();
14601}
14602
14603/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14604static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14605  // FAND(0.0, x) -> 0.0
14606  // FAND(x, 0.0) -> 0.0
14607  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14608    if (C->getValueAPF().isPosZero())
14609      return N->getOperand(0);
14610  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14611    if (C->getValueAPF().isPosZero())
14612      return N->getOperand(1);
14613  return SDValue();
14614}
14615
14616static SDValue PerformBTCombine(SDNode *N,
14617                                SelectionDAG &DAG,
14618                                TargetLowering::DAGCombinerInfo &DCI) {
14619  // BT ignores high bits in the bit index operand.
14620  SDValue Op1 = N->getOperand(1);
14621  if (Op1.hasOneUse()) {
14622    unsigned BitWidth = Op1.getValueSizeInBits();
14623    APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14624    APInt KnownZero, KnownOne;
14625    TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14626                                          !DCI.isBeforeLegalizeOps());
14627    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14628    if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14629        TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14630      DCI.CommitTargetLoweringOpt(TLO);
14631  }
14632  return SDValue();
14633}
14634
14635static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14636  SDValue Op = N->getOperand(0);
14637  if (Op.getOpcode() == ISD::BITCAST)
14638    Op = Op.getOperand(0);
14639  EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14640  if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14641      VT.getVectorElementType().getSizeInBits() ==
14642      OpVT.getVectorElementType().getSizeInBits()) {
14643    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14644  }
14645  return SDValue();
14646}
14647
14648static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14649  // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14650  //           (and (i32 x86isd::setcc_carry), 1)
14651  // This eliminates the zext. This transformation is necessary because
14652  // ISD::SETCC is always legalized to i8.
14653  DebugLoc dl = N->getDebugLoc();
14654  SDValue N0 = N->getOperand(0);
14655  EVT VT = N->getValueType(0);
14656  if (N0.getOpcode() == ISD::AND &&
14657      N0.hasOneUse() &&
14658      N0.getOperand(0).hasOneUse()) {
14659    SDValue N00 = N0.getOperand(0);
14660    if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14661      return SDValue();
14662    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14663    if (!C || C->getZExtValue() != 1)
14664      return SDValue();
14665    return DAG.getNode(ISD::AND, dl, VT,
14666                       DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14667                                   N00.getOperand(0), N00.getOperand(1)),
14668                       DAG.getConstant(1, VT));
14669  }
14670
14671  return SDValue();
14672}
14673
14674// Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14675static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14676  unsigned X86CC = N->getConstantOperandVal(0);
14677  SDValue EFLAG = N->getOperand(1);
14678  DebugLoc DL = N->getDebugLoc();
14679
14680  // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14681  // a zext and produces an all-ones bit which is more useful than 0/1 in some
14682  // cases.
14683  if (X86CC == X86::COND_B)
14684    return DAG.getNode(ISD::AND, DL, MVT::i8,
14685                       DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14686                                   DAG.getConstant(X86CC, MVT::i8), EFLAG),
14687                       DAG.getConstant(1, MVT::i8));
14688
14689  return SDValue();
14690}
14691
14692static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14693                                        const X86TargetLowering *XTLI) {
14694  SDValue Op0 = N->getOperand(0);
14695  // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14696  // a 32-bit target where SSE doesn't support i64->FP operations.
14697  if (Op0.getOpcode() == ISD::LOAD) {
14698    LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14699    EVT VT = Ld->getValueType(0);
14700    if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14701        ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14702        !XTLI->getSubtarget()->is64Bit() &&
14703        !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14704      SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14705                                          Ld->getChain(), Op0, DAG);
14706      DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14707      return FILDChain;
14708    }
14709  }
14710  return SDValue();
14711}
14712
14713// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14714static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14715                                 X86TargetLowering::DAGCombinerInfo &DCI) {
14716  // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14717  // the result is either zero or one (depending on the input carry bit).
14718  // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14719  if (X86::isZeroNode(N->getOperand(0)) &&
14720      X86::isZeroNode(N->getOperand(1)) &&
14721      // We don't have a good way to replace an EFLAGS use, so only do this when
14722      // dead right now.
14723      SDValue(N, 1).use_empty()) {
14724    DebugLoc DL = N->getDebugLoc();
14725    EVT VT = N->getValueType(0);
14726    SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14727    SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14728                               DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14729                                           DAG.getConstant(X86::COND_B,MVT::i8),
14730                                           N->getOperand(2)),
14731                               DAG.getConstant(1, VT));
14732    return DCI.CombineTo(N, Res1, CarryOut);
14733  }
14734
14735  return SDValue();
14736}
14737
14738// fold (add Y, (sete  X, 0)) -> adc  0, Y
14739//      (add Y, (setne X, 0)) -> sbb -1, Y
14740//      (sub (sete  X, 0), Y) -> sbb  0, Y
14741//      (sub (setne X, 0), Y) -> adc -1, Y
14742static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14743  DebugLoc DL = N->getDebugLoc();
14744
14745  // Look through ZExts.
14746  SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14747  if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14748    return SDValue();
14749
14750  SDValue SetCC = Ext.getOperand(0);
14751  if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14752    return SDValue();
14753
14754  X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14755  if (CC != X86::COND_E && CC != X86::COND_NE)
14756    return SDValue();
14757
14758  SDValue Cmp = SetCC.getOperand(1);
14759  if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14760      !X86::isZeroNode(Cmp.getOperand(1)) ||
14761      !Cmp.getOperand(0).getValueType().isInteger())
14762    return SDValue();
14763
14764  SDValue CmpOp0 = Cmp.getOperand(0);
14765  SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14766                               DAG.getConstant(1, CmpOp0.getValueType()));
14767
14768  SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14769  if (CC == X86::COND_NE)
14770    return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14771                       DL, OtherVal.getValueType(), OtherVal,
14772                       DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14773  return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14774                     DL, OtherVal.getValueType(), OtherVal,
14775                     DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14776}
14777
14778/// PerformADDCombine - Do target-specific dag combines on integer adds.
14779static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14780                                 const X86Subtarget *Subtarget) {
14781  EVT VT = N->getValueType(0);
14782  SDValue Op0 = N->getOperand(0);
14783  SDValue Op1 = N->getOperand(1);
14784
14785  // Try to synthesize horizontal adds from adds of shuffles.
14786  if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14787      isHorizontalBinOp(Op0, Op1, true))
14788    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14789
14790  return OptimizeConditionalInDecrement(N, DAG);
14791}
14792
14793static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14794                                 const X86Subtarget *Subtarget) {
14795  SDValue Op0 = N->getOperand(0);
14796  SDValue Op1 = N->getOperand(1);
14797
14798  // X86 can't encode an immediate LHS of a sub. See if we can push the
14799  // negation into a preceding instruction.
14800  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14801    // If the RHS of the sub is a XOR with one use and a constant, invert the
14802    // immediate. Then add one to the LHS of the sub so we can turn
14803    // X-Y -> X+~Y+1, saving one register.
14804    if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14805        isa<ConstantSDNode>(Op1.getOperand(1))) {
14806      APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14807      EVT VT = Op0.getValueType();
14808      SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14809                                   Op1.getOperand(0),
14810                                   DAG.getConstant(~XorC, VT));
14811      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14812                         DAG.getConstant(C->getAPIntValue()+1, VT));
14813    }
14814  }
14815
14816  // Try to synthesize horizontal adds from adds of shuffles.
14817  EVT VT = N->getValueType(0);
14818  if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14819      isHorizontalBinOp(Op0, Op1, false))
14820    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14821
14822  return OptimizeConditionalInDecrement(N, DAG);
14823}
14824
14825SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14826                                             DAGCombinerInfo &DCI) const {
14827  SelectionDAG &DAG = DCI.DAG;
14828  switch (N->getOpcode()) {
14829  default: break;
14830  case ISD::EXTRACT_VECTOR_ELT:
14831    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14832  case ISD::VSELECT:
14833  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14834  case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14835  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
14836  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
14837  case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14838  case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14839  case ISD::SHL:
14840  case ISD::SRA:
14841  case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14842  case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14843  case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14844  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14845  case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14846  case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14847  case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14848  case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14849  case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14850  case X86ISD::FXOR:
14851  case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14852  case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14853  case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14854  case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14855  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14856  case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14857  case X86ISD::SHUFPS:      // Handle all target specific shuffles
14858  case X86ISD::SHUFPD:
14859  case X86ISD::PALIGN:
14860  case X86ISD::PUNPCKHBW:
14861  case X86ISD::PUNPCKHWD:
14862  case X86ISD::PUNPCKHDQ:
14863  case X86ISD::PUNPCKHQDQ:
14864  case X86ISD::UNPCKHPS:
14865  case X86ISD::UNPCKHPD:
14866  case X86ISD::PUNPCKLBW:
14867  case X86ISD::PUNPCKLWD:
14868  case X86ISD::PUNPCKLDQ:
14869  case X86ISD::PUNPCKLQDQ:
14870  case X86ISD::UNPCKLPS:
14871  case X86ISD::UNPCKLPD:
14872  case X86ISD::MOVHLPS:
14873  case X86ISD::MOVLHPS:
14874  case X86ISD::PSHUFD:
14875  case X86ISD::PSHUFHW:
14876  case X86ISD::PSHUFLW:
14877  case X86ISD::MOVSS:
14878  case X86ISD::MOVSD:
14879  case X86ISD::VPERMILPS:
14880  case X86ISD::VPERMILPSY:
14881  case X86ISD::VPERMILPD:
14882  case X86ISD::VPERMILPDY:
14883  case X86ISD::VPERM2F128:
14884  case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14885  }
14886
14887  return SDValue();
14888}
14889
14890/// isTypeDesirableForOp - Return true if the target has native support for
14891/// the specified value type and it is 'desirable' to use the type for the
14892/// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14893/// instruction encodings are longer and some i16 instructions are slow.
14894bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14895  if (!isTypeLegal(VT))
14896    return false;
14897  if (VT != MVT::i16)
14898    return true;
14899
14900  switch (Opc) {
14901  default:
14902    return true;
14903  case ISD::LOAD:
14904  case ISD::SIGN_EXTEND:
14905  case ISD::ZERO_EXTEND:
14906  case ISD::ANY_EXTEND:
14907  case ISD::SHL:
14908  case ISD::SRL:
14909  case ISD::SUB:
14910  case ISD::ADD:
14911  case ISD::MUL:
14912  case ISD::AND:
14913  case ISD::OR:
14914  case ISD::XOR:
14915    return false;
14916  }
14917}
14918
14919/// IsDesirableToPromoteOp - This method query the target whether it is
14920/// beneficial for dag combiner to promote the specified node. If true, it
14921/// should return the desired promotion type by reference.
14922bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14923  EVT VT = Op.getValueType();
14924  if (VT != MVT::i16)
14925    return false;
14926
14927  bool Promote = false;
14928  bool Commute = false;
14929  switch (Op.getOpcode()) {
14930  default: break;
14931  case ISD::LOAD: {
14932    LoadSDNode *LD = cast<LoadSDNode>(Op);
14933    // If the non-extending load has a single use and it's not live out, then it
14934    // might be folded.
14935    if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14936                                                     Op.hasOneUse()*/) {
14937      for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14938             UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14939        // The only case where we'd want to promote LOAD (rather then it being
14940        // promoted as an operand is when it's only use is liveout.
14941        if (UI->getOpcode() != ISD::CopyToReg)
14942          return false;
14943      }
14944    }
14945    Promote = true;
14946    break;
14947  }
14948  case ISD::SIGN_EXTEND:
14949  case ISD::ZERO_EXTEND:
14950  case ISD::ANY_EXTEND:
14951    Promote = true;
14952    break;
14953  case ISD::SHL:
14954  case ISD::SRL: {
14955    SDValue N0 = Op.getOperand(0);
14956    // Look out for (store (shl (load), x)).
14957    if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14958      return false;
14959    Promote = true;
14960    break;
14961  }
14962  case ISD::ADD:
14963  case ISD::MUL:
14964  case ISD::AND:
14965  case ISD::OR:
14966  case ISD::XOR:
14967    Commute = true;
14968    // fallthrough
14969  case ISD::SUB: {
14970    SDValue N0 = Op.getOperand(0);
14971    SDValue N1 = Op.getOperand(1);
14972    if (!Commute && MayFoldLoad(N1))
14973      return false;
14974    // Avoid disabling potential load folding opportunities.
14975    if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14976      return false;
14977    if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14978      return false;
14979    Promote = true;
14980  }
14981  }
14982
14983  PVT = MVT::i32;
14984  return Promote;
14985}
14986
14987//===----------------------------------------------------------------------===//
14988//                           X86 Inline Assembly Support
14989//===----------------------------------------------------------------------===//
14990
14991bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14992  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14993
14994  std::string AsmStr = IA->getAsmString();
14995
14996  // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14997  SmallVector<StringRef, 4> AsmPieces;
14998  SplitString(AsmStr, AsmPieces, ";\n");
14999
15000  switch (AsmPieces.size()) {
15001  default: return false;
15002  case 1:
15003    AsmStr = AsmPieces[0];
15004    AsmPieces.clear();
15005    SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
15006
15007    // FIXME: this should verify that we are targeting a 486 or better.  If not,
15008    // we will turn this bswap into something that will be lowered to logical ops
15009    // instead of emitting the bswap asm.  For now, we don't support 486 or lower
15010    // so don't worry about this.
15011    // bswap $0
15012    if (AsmPieces.size() == 2 &&
15013        (AsmPieces[0] == "bswap" ||
15014         AsmPieces[0] == "bswapq" ||
15015         AsmPieces[0] == "bswapl") &&
15016        (AsmPieces[1] == "$0" ||
15017         AsmPieces[1] == "${0:q}")) {
15018      // No need to check constraints, nothing other than the equivalent of
15019      // "=r,0" would be valid here.
15020      IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15021      if (!Ty || Ty->getBitWidth() % 16 != 0)
15022        return false;
15023      return IntrinsicLowering::LowerToByteSwap(CI);
15024    }
15025    // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15026    if (CI->getType()->isIntegerTy(16) &&
15027        AsmPieces.size() == 3 &&
15028        (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
15029        AsmPieces[1] == "$$8," &&
15030        AsmPieces[2] == "${0:w}" &&
15031        IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15032      AsmPieces.clear();
15033      const std::string &ConstraintsStr = IA->getConstraintString();
15034      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15035      std::sort(AsmPieces.begin(), AsmPieces.end());
15036      if (AsmPieces.size() == 4 &&
15037          AsmPieces[0] == "~{cc}" &&
15038          AsmPieces[1] == "~{dirflag}" &&
15039          AsmPieces[2] == "~{flags}" &&
15040          AsmPieces[3] == "~{fpsr}") {
15041        IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15042        if (!Ty || Ty->getBitWidth() % 16 != 0)
15043          return false;
15044        return IntrinsicLowering::LowerToByteSwap(CI);
15045      }
15046    }
15047    break;
15048  case 3:
15049    if (CI->getType()->isIntegerTy(32) &&
15050        IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15051      SmallVector<StringRef, 4> Words;
15052      SplitString(AsmPieces[0], Words, " \t,");
15053      if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15054          Words[2] == "${0:w}") {
15055        Words.clear();
15056        SplitString(AsmPieces[1], Words, " \t,");
15057        if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
15058            Words[2] == "$0") {
15059          Words.clear();
15060          SplitString(AsmPieces[2], Words, " \t,");
15061          if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15062              Words[2] == "${0:w}") {
15063            AsmPieces.clear();
15064            const std::string &ConstraintsStr = IA->getConstraintString();
15065            SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15066            std::sort(AsmPieces.begin(), AsmPieces.end());
15067            if (AsmPieces.size() == 4 &&
15068                AsmPieces[0] == "~{cc}" &&
15069                AsmPieces[1] == "~{dirflag}" &&
15070                AsmPieces[2] == "~{flags}" &&
15071                AsmPieces[3] == "~{fpsr}") {
15072              IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15073              if (!Ty || Ty->getBitWidth() % 16 != 0)
15074                return false;
15075              return IntrinsicLowering::LowerToByteSwap(CI);
15076            }
15077          }
15078        }
15079      }
15080    }
15081
15082    if (CI->getType()->isIntegerTy(64)) {
15083      InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15084      if (Constraints.size() >= 2 &&
15085          Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15086          Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15087        // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15088        SmallVector<StringRef, 4> Words;
15089        SplitString(AsmPieces[0], Words, " \t");
15090        if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
15091          Words.clear();
15092          SplitString(AsmPieces[1], Words, " \t");
15093          if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
15094            Words.clear();
15095            SplitString(AsmPieces[2], Words, " \t,");
15096            if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
15097                Words[2] == "%edx") {
15098              IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15099              if (!Ty || Ty->getBitWidth() % 16 != 0)
15100                return false;
15101              return IntrinsicLowering::LowerToByteSwap(CI);
15102            }
15103          }
15104        }
15105      }
15106    }
15107    break;
15108  }
15109  return false;
15110}
15111
15112
15113
15114/// getConstraintType - Given a constraint letter, return the type of
15115/// constraint it is for this target.
15116X86TargetLowering::ConstraintType
15117X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15118  if (Constraint.size() == 1) {
15119    switch (Constraint[0]) {
15120    case 'R':
15121    case 'q':
15122    case 'Q':
15123    case 'f':
15124    case 't':
15125    case 'u':
15126    case 'y':
15127    case 'x':
15128    case 'Y':
15129    case 'l':
15130      return C_RegisterClass;
15131    case 'a':
15132    case 'b':
15133    case 'c':
15134    case 'd':
15135    case 'S':
15136    case 'D':
15137    case 'A':
15138      return C_Register;
15139    case 'I':
15140    case 'J':
15141    case 'K':
15142    case 'L':
15143    case 'M':
15144    case 'N':
15145    case 'G':
15146    case 'C':
15147    case 'e':
15148    case 'Z':
15149      return C_Other;
15150    default:
15151      break;
15152    }
15153  }
15154  return TargetLowering::getConstraintType(Constraint);
15155}
15156
15157/// Examine constraint type and operand type and determine a weight value.
15158/// This object must already have been set up with the operand type
15159/// and the current alternative constraint selected.
15160TargetLowering::ConstraintWeight
15161  X86TargetLowering::getSingleConstraintMatchWeight(
15162    AsmOperandInfo &info, const char *constraint) const {
15163  ConstraintWeight weight = CW_Invalid;
15164  Value *CallOperandVal = info.CallOperandVal;
15165    // If we don't have a value, we can't do a match,
15166    // but allow it at the lowest weight.
15167  if (CallOperandVal == NULL)
15168    return CW_Default;
15169  Type *type = CallOperandVal->getType();
15170  // Look at the constraint type.
15171  switch (*constraint) {
15172  default:
15173    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15174  case 'R':
15175  case 'q':
15176  case 'Q':
15177  case 'a':
15178  case 'b':
15179  case 'c':
15180  case 'd':
15181  case 'S':
15182  case 'D':
15183  case 'A':
15184    if (CallOperandVal->getType()->isIntegerTy())
15185      weight = CW_SpecificReg;
15186    break;
15187  case 'f':
15188  case 't':
15189  case 'u':
15190      if (type->isFloatingPointTy())
15191        weight = CW_SpecificReg;
15192      break;
15193  case 'y':
15194      if (type->isX86_MMXTy() && Subtarget->hasMMX())
15195        weight = CW_SpecificReg;
15196      break;
15197  case 'x':
15198  case 'Y':
15199    if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15200      weight = CW_Register;
15201    break;
15202  case 'I':
15203    if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15204      if (C->getZExtValue() <= 31)
15205        weight = CW_Constant;
15206    }
15207    break;
15208  case 'J':
15209    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15210      if (C->getZExtValue() <= 63)
15211        weight = CW_Constant;
15212    }
15213    break;
15214  case 'K':
15215    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15216      if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15217        weight = CW_Constant;
15218    }
15219    break;
15220  case 'L':
15221    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15222      if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15223        weight = CW_Constant;
15224    }
15225    break;
15226  case 'M':
15227    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15228      if (C->getZExtValue() <= 3)
15229        weight = CW_Constant;
15230    }
15231    break;
15232  case 'N':
15233    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15234      if (C->getZExtValue() <= 0xff)
15235        weight = CW_Constant;
15236    }
15237    break;
15238  case 'G':
15239  case 'C':
15240    if (dyn_cast<ConstantFP>(CallOperandVal)) {
15241      weight = CW_Constant;
15242    }
15243    break;
15244  case 'e':
15245    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15246      if ((C->getSExtValue() >= -0x80000000LL) &&
15247          (C->getSExtValue() <= 0x7fffffffLL))
15248        weight = CW_Constant;
15249    }
15250    break;
15251  case 'Z':
15252    if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15253      if (C->getZExtValue() <= 0xffffffff)
15254        weight = CW_Constant;
15255    }
15256    break;
15257  }
15258  return weight;
15259}
15260
15261/// LowerXConstraint - try to replace an X constraint, which matches anything,
15262/// with another that has more specific requirements based on the type of the
15263/// corresponding operand.
15264const char *X86TargetLowering::
15265LowerXConstraint(EVT ConstraintVT) const {
15266  // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15267  // 'f' like normal targets.
15268  if (ConstraintVT.isFloatingPoint()) {
15269    if (Subtarget->hasXMMInt())
15270      return "Y";
15271    if (Subtarget->hasXMM())
15272      return "x";
15273  }
15274
15275  return TargetLowering::LowerXConstraint(ConstraintVT);
15276}
15277
15278/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15279/// vector.  If it is invalid, don't add anything to Ops.
15280void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15281                                                     std::string &Constraint,
15282                                                     std::vector<SDValue>&Ops,
15283                                                     SelectionDAG &DAG) const {
15284  SDValue Result(0, 0);
15285
15286  // Only support length 1 constraints for now.
15287  if (Constraint.length() > 1) return;
15288
15289  char ConstraintLetter = Constraint[0];
15290  switch (ConstraintLetter) {
15291  default: break;
15292  case 'I':
15293    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15294      if (C->getZExtValue() <= 31) {
15295        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15296        break;
15297      }
15298    }
15299    return;
15300  case 'J':
15301    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15302      if (C->getZExtValue() <= 63) {
15303        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15304        break;
15305      }
15306    }
15307    return;
15308  case 'K':
15309    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15310      if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15311        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15312        break;
15313      }
15314    }
15315    return;
15316  case 'N':
15317    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15318      if (C->getZExtValue() <= 255) {
15319        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15320        break;
15321      }
15322    }
15323    return;
15324  case 'e': {
15325    // 32-bit signed value
15326    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15327      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15328                                           C->getSExtValue())) {
15329        // Widen to 64 bits here to get it sign extended.
15330        Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15331        break;
15332      }
15333    // FIXME gcc accepts some relocatable values here too, but only in certain
15334    // memory models; it's complicated.
15335    }
15336    return;
15337  }
15338  case 'Z': {
15339    // 32-bit unsigned value
15340    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15341      if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15342                                           C->getZExtValue())) {
15343        Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15344        break;
15345      }
15346    }
15347    // FIXME gcc accepts some relocatable values here too, but only in certain
15348    // memory models; it's complicated.
15349    return;
15350  }
15351  case 'i': {
15352    // Literal immediates are always ok.
15353    if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15354      // Widen to 64 bits here to get it sign extended.
15355      Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15356      break;
15357    }
15358
15359    // In any sort of PIC mode addresses need to be computed at runtime by
15360    // adding in a register or some sort of table lookup.  These can't
15361    // be used as immediates.
15362    if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15363      return;
15364
15365    // If we are in non-pic codegen mode, we allow the address of a global (with
15366    // an optional displacement) to be used with 'i'.
15367    GlobalAddressSDNode *GA = 0;
15368    int64_t Offset = 0;
15369
15370    // Match either (GA), (GA+C), (GA+C1+C2), etc.
15371    while (1) {
15372      if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15373        Offset += GA->getOffset();
15374        break;
15375      } else if (Op.getOpcode() == ISD::ADD) {
15376        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15377          Offset += C->getZExtValue();
15378          Op = Op.getOperand(0);
15379          continue;
15380        }
15381      } else if (Op.getOpcode() == ISD::SUB) {
15382        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15383          Offset += -C->getZExtValue();
15384          Op = Op.getOperand(0);
15385          continue;
15386        }
15387      }
15388
15389      // Otherwise, this isn't something we can handle, reject it.
15390      return;
15391    }
15392
15393    const GlobalValue *GV = GA->getGlobal();
15394    // If we require an extra load to get this address, as in PIC mode, we
15395    // can't accept it.
15396    if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15397                                                        getTargetMachine())))
15398      return;
15399
15400    Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15401                                        GA->getValueType(0), Offset);
15402    break;
15403  }
15404  }
15405
15406  if (Result.getNode()) {
15407    Ops.push_back(Result);
15408    return;
15409  }
15410  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15411}
15412
15413std::pair<unsigned, const TargetRegisterClass*>
15414X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15415                                                EVT VT) const {
15416  // First, see if this is a constraint that directly corresponds to an LLVM
15417  // register class.
15418  if (Constraint.size() == 1) {
15419    // GCC Constraint Letters
15420    switch (Constraint[0]) {
15421    default: break;
15422      // TODO: Slight differences here in allocation order and leaving
15423      // RIP in the class. Do they matter any more here than they do
15424      // in the normal allocation?
15425    case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15426      if (Subtarget->is64Bit()) {
15427	if (VT == MVT::i32 || VT == MVT::f32)
15428	  return std::make_pair(0U, X86::GR32RegisterClass);
15429	else if (VT == MVT::i16)
15430	  return std::make_pair(0U, X86::GR16RegisterClass);
15431	else if (VT == MVT::i8 || VT == MVT::i1)
15432	  return std::make_pair(0U, X86::GR8RegisterClass);
15433	else if (VT == MVT::i64 || VT == MVT::f64)
15434	  return std::make_pair(0U, X86::GR64RegisterClass);
15435	break;
15436      }
15437      // 32-bit fallthrough
15438    case 'Q':   // Q_REGS
15439      if (VT == MVT::i32 || VT == MVT::f32)
15440	return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15441      else if (VT == MVT::i16)
15442	return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15443      else if (VT == MVT::i8 || VT == MVT::i1)
15444	return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15445      else if (VT == MVT::i64)
15446	return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15447      break;
15448    case 'r':   // GENERAL_REGS
15449    case 'l':   // INDEX_REGS
15450      if (VT == MVT::i8 || VT == MVT::i1)
15451        return std::make_pair(0U, X86::GR8RegisterClass);
15452      if (VT == MVT::i16)
15453        return std::make_pair(0U, X86::GR16RegisterClass);
15454      if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15455        return std::make_pair(0U, X86::GR32RegisterClass);
15456      return std::make_pair(0U, X86::GR64RegisterClass);
15457    case 'R':   // LEGACY_REGS
15458      if (VT == MVT::i8 || VT == MVT::i1)
15459        return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15460      if (VT == MVT::i16)
15461        return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15462      if (VT == MVT::i32 || !Subtarget->is64Bit())
15463        return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15464      return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15465    case 'f':  // FP Stack registers.
15466      // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15467      // value to the correct fpstack register class.
15468      if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15469        return std::make_pair(0U, X86::RFP32RegisterClass);
15470      if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15471        return std::make_pair(0U, X86::RFP64RegisterClass);
15472      return std::make_pair(0U, X86::RFP80RegisterClass);
15473    case 'y':   // MMX_REGS if MMX allowed.
15474      if (!Subtarget->hasMMX()) break;
15475      return std::make_pair(0U, X86::VR64RegisterClass);
15476    case 'Y':   // SSE_REGS if SSE2 allowed
15477      if (!Subtarget->hasXMMInt()) break;
15478      // FALL THROUGH.
15479    case 'x':   // SSE_REGS if SSE1 allowed
15480      if (!Subtarget->hasXMM()) break;
15481
15482      switch (VT.getSimpleVT().SimpleTy) {
15483      default: break;
15484      // Scalar SSE types.
15485      case MVT::f32:
15486      case MVT::i32:
15487        return std::make_pair(0U, X86::FR32RegisterClass);
15488      case MVT::f64:
15489      case MVT::i64:
15490        return std::make_pair(0U, X86::FR64RegisterClass);
15491      // Vector types.
15492      case MVT::v16i8:
15493      case MVT::v8i16:
15494      case MVT::v4i32:
15495      case MVT::v2i64:
15496      case MVT::v4f32:
15497      case MVT::v2f64:
15498        return std::make_pair(0U, X86::VR128RegisterClass);
15499      }
15500      break;
15501    }
15502  }
15503
15504  // Use the default implementation in TargetLowering to convert the register
15505  // constraint into a member of a register class.
15506  std::pair<unsigned, const TargetRegisterClass*> Res;
15507  Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15508
15509  // Not found as a standard register?
15510  if (Res.second == 0) {
15511    // Map st(0) -> st(7) -> ST0
15512    if (Constraint.size() == 7 && Constraint[0] == '{' &&
15513        tolower(Constraint[1]) == 's' &&
15514        tolower(Constraint[2]) == 't' &&
15515        Constraint[3] == '(' &&
15516        (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15517        Constraint[5] == ')' &&
15518        Constraint[6] == '}') {
15519
15520      Res.first = X86::ST0+Constraint[4]-'0';
15521      Res.second = X86::RFP80RegisterClass;
15522      return Res;
15523    }
15524
15525    // GCC allows "st(0)" to be called just plain "st".
15526    if (StringRef("{st}").equals_lower(Constraint)) {
15527      Res.first = X86::ST0;
15528      Res.second = X86::RFP80RegisterClass;
15529      return Res;
15530    }
15531
15532    // flags -> EFLAGS
15533    if (StringRef("{flags}").equals_lower(Constraint)) {
15534      Res.first = X86::EFLAGS;
15535      Res.second = X86::CCRRegisterClass;
15536      return Res;
15537    }
15538
15539    // 'A' means EAX + EDX.
15540    if (Constraint == "A") {
15541      Res.first = X86::EAX;
15542      Res.second = X86::GR32_ADRegisterClass;
15543      return Res;
15544    }
15545    return Res;
15546  }
15547
15548  // Otherwise, check to see if this is a register class of the wrong value
15549  // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15550  // turn into {ax},{dx}.
15551  if (Res.second->hasType(VT))
15552    return Res;   // Correct type already, nothing to do.
15553
15554  // All of the single-register GCC register classes map their values onto
15555  // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15556  // really want an 8-bit or 32-bit register, map to the appropriate register
15557  // class and return the appropriate register.
15558  if (Res.second == X86::GR16RegisterClass) {
15559    if (VT == MVT::i8) {
15560      unsigned DestReg = 0;
15561      switch (Res.first) {
15562      default: break;
15563      case X86::AX: DestReg = X86::AL; break;
15564      case X86::DX: DestReg = X86::DL; break;
15565      case X86::CX: DestReg = X86::CL; break;
15566      case X86::BX: DestReg = X86::BL; break;
15567      }
15568      if (DestReg) {
15569        Res.first = DestReg;
15570        Res.second = X86::GR8RegisterClass;
15571      }
15572    } else if (VT == MVT::i32) {
15573      unsigned DestReg = 0;
15574      switch (Res.first) {
15575      default: break;
15576      case X86::AX: DestReg = X86::EAX; break;
15577      case X86::DX: DestReg = X86::EDX; break;
15578      case X86::CX: DestReg = X86::ECX; break;
15579      case X86::BX: DestReg = X86::EBX; break;
15580      case X86::SI: DestReg = X86::ESI; break;
15581      case X86::DI: DestReg = X86::EDI; break;
15582      case X86::BP: DestReg = X86::EBP; break;
15583      case X86::SP: DestReg = X86::ESP; break;
15584      }
15585      if (DestReg) {
15586        Res.first = DestReg;
15587        Res.second = X86::GR32RegisterClass;
15588      }
15589    } else if (VT == MVT::i64) {
15590      unsigned DestReg = 0;
15591      switch (Res.first) {
15592      default: break;
15593      case X86::AX: DestReg = X86::RAX; break;
15594      case X86::DX: DestReg = X86::RDX; break;
15595      case X86::CX: DestReg = X86::RCX; break;
15596      case X86::BX: DestReg = X86::RBX; break;
15597      case X86::SI: DestReg = X86::RSI; break;
15598      case X86::DI: DestReg = X86::RDI; break;
15599      case X86::BP: DestReg = X86::RBP; break;
15600      case X86::SP: DestReg = X86::RSP; break;
15601      }
15602      if (DestReg) {
15603        Res.first = DestReg;
15604        Res.second = X86::GR64RegisterClass;
15605      }
15606    }
15607  } else if (Res.second == X86::FR32RegisterClass ||
15608             Res.second == X86::FR64RegisterClass ||
15609             Res.second == X86::VR128RegisterClass) {
15610    // Handle references to XMM physical registers that got mapped into the
15611    // wrong class.  This can happen with constraints like {xmm0} where the
15612    // target independent register mapper will just pick the first match it can
15613    // find, ignoring the required type.
15614    if (VT == MVT::f32)
15615      Res.second = X86::FR32RegisterClass;
15616    else if (VT == MVT::f64)
15617      Res.second = X86::FR64RegisterClass;
15618    else if (X86::VR128RegisterClass->hasType(VT))
15619      Res.second = X86::VR128RegisterClass;
15620  }
15621
15622  return Res;
15623}
15624