X86: elide comparisons after cmpxchg instructions.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 #define DEBUG_TYPE "x86-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64                                 SelectionDAG &DAG, SDLoc dl,
65                                 unsigned vectorWidth) {
66   assert((vectorWidth == 128 || vectorWidth == 256) &&
67          "Unsupported vector width");
68   EVT VT = Vec.getValueType();
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/vectorWidth;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
79   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80
81   // This is the index of the first element of the vectorWidth-bit chunk
82   // we want.
83   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84                                * ElemsPerChunk);
85
86   // If the input is a buildvector just emit a smaller one.
87   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
90                                     ElemsPerChunk));
91
92   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94                                VecIdx);
95
96   return Result;
97
98 }
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106                                    SelectionDAG &DAG, SDLoc dl) {
107   assert((Vec.getValueType().is256BitVector() ||
108           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 }
111
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114                                    SelectionDAG &DAG, SDLoc dl) {
115   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 }
118
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120                                unsigned IdxVal, SelectionDAG &DAG,
121                                SDLoc dl, unsigned vectorWidth) {
122   assert((vectorWidth == 128 || vectorWidth == 256) &&
123          "Unsupported vector width");
124   // Inserting UNDEF is Result
125   if (Vec.getOpcode() == ISD::UNDEF)
126     return Result;
127   EVT VT = Vec.getValueType();
128   EVT ElVT = VT.getVectorElementType();
129   EVT ResultVT = Result.getValueType();
130
131   // Insert the relevant vectorWidth bits.
132   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133
134   // This is the index of the first element of the vectorWidth-bit chunk
135   // we want.
136   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137                                * ElemsPerChunk);
138
139   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141                      VecIdx);
142 }
143 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference.  Idx is an index in the 128 bits
147 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150                                   unsigned IdxVal, SelectionDAG &DAG,
151                                   SDLoc dl) {
152   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 }
155
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 }
162
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168                                    unsigned NumElems, SelectionDAG &DAG,
169                                    SDLoc dl) {
170   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 }
173
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
182   if (TT.isOSBinFormatMachO()) {
183     if (TT.getArch() == Triple::x86_64)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (TT.isOSLinux())
189     return new X86LinuxTargetObjectFile();
190   if (TT.isOSBinFormatELF())
191     return new TargetLoweringObjectFileELF();
192   if (TT.isKnownWindowsMSVCEnvironment())
193     return new X86WindowsTargetObjectFile();
194   if (TT.isOSBinFormatCOFF())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird, it always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit since we have so many registers use the ILP scheduler, for
234   // 32-bit code use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2
247   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248     addBypassSlowDiv(32, 8);
249     if (Subtarget->is64Bit())
250       addBypassSlowDiv(64, 16);
251   }
252
253   if (Subtarget->isTargetKnownWindowsMSVC()) {
254     // Setup Windows compiler runtime calls.
255     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257     setLibcallName(RTLIB::SREM_I64, "_allrem");
258     setLibcallName(RTLIB::UREM_I64, "_aullrem");
259     setLibcallName(RTLIB::MUL_I64, "_allmul");
260     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
265
266     // The _ftol2 runtime function has an unusual calling conv, which
267     // is modeled by a special pseudo-instruction.
268     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
269     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
272   }
273
274   if (Subtarget->isTargetDarwin()) {
275     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276     setUseUnderscoreSetJmp(false);
277     setUseUnderscoreLongJmp(false);
278   } else if (Subtarget->isTargetWindowsGNU()) {
279     // MS runtime is weird: it exports _setjmp, but longjmp!
280     setUseUnderscoreSetJmp(true);
281     setUseUnderscoreLongJmp(false);
282   } else {
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(true);
285   }
286
287   // Set up the register classes.
288   addRegisterClass(MVT::i8, &X86::GR8RegClass);
289   addRegisterClass(MVT::i16, &X86::GR16RegClass);
290   addRegisterClass(MVT::i32, &X86::GR32RegClass);
291   if (Subtarget->is64Bit())
292     addRegisterClass(MVT::i64, &X86::GR64RegClass);
293
294   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
295
296   // We don't accept any truncstore of integer registers.
297   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
303
304   // SETOEQ and SETUNE require checking two conditions.
305   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
311
312   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
313   // operation.
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
317
318   if (Subtarget->is64Bit()) {
319     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
321   } else if (!TM.Options.UseSoftFloat) {
322     // We have an algorithm for SSE2->double, and we turn this into a
323     // 64-bit FILD followed by conditional FADD for other targets.
324     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
325     // We have an algorithm for SSE2, and we turn this into a 64-bit
326     // FILD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
328   }
329
330   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
331   // this operation.
332   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
334
335   if (!TM.Options.UseSoftFloat) {
336     // SSE has no i16 to fp conversion, only i32
337     if (X86ScalarSSEf32) {
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
339       // f32 and f64 cases are Legal, f80 case is not
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
341     } else {
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     }
345   } else {
346     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
348   }
349
350   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
351   // are Legal, f80 is custom lowered.
352   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
353   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
354
355   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
356   // this operation.
357   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
359
360   if (X86ScalarSSEf32) {
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
362     // f32 and f64 cases are Legal, f80 case is not
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
364   } else {
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   }
368
369   // Handle FP_TO_UINT by promoting the destination to a larger signed
370   // conversion.
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
374
375   if (Subtarget->is64Bit()) {
376     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
378   } else if (!TM.Options.UseSoftFloat) {
379     // Since AVX is a superset of SSE3, only check for SSE here.
380     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381       // Expand FP_TO_UINT into a select.
382       // FIXME: We would like to use a Custom expander here eventually to do
383       // the optimal thing for SSE vs. the default expansion in the legalizer.
384       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
385     else
386       // With SSE3 we can use fisttpll to convert to a signed i64; without
387       // SSE, we're stuck with a fistpll.
388       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
389   }
390
391   if (isTargetFTOL()) {
392     // Use the _ftol2 runtime function, which has a pseudo-instruction
393     // to handle its weird calling convention.
394     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
395   }
396
397   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398   if (!X86ScalarSSEf64) {
399     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
400     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
401     if (Subtarget->is64Bit()) {
402       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
403       // Without SSE, i64->f64 goes through memory.
404       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
405     }
406   }
407
408   // Scalar integer divide and remainder are lowered to use operations that
409   // produce two results, to match the available instructions. This exposes
410   // the two-result form to trivial CSE, which is able to combine x/y and x%y
411   // into a single instruction.
412   //
413   // Scalar integer multiply-high is also lowered to use two-result
414   // operations, to match the available instructions. However, plain multiply
415   // (low) operations are left as Legal, as there are single-result
416   // instructions for this in x86. Using the two-result multiply instructions
417   // when both high and low results are needed must be arranged by dagcombine.
418   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
419     MVT VT = IntVTs[i];
420     setOperationAction(ISD::MULHS, VT, Expand);
421     setOperationAction(ISD::MULHU, VT, Expand);
422     setOperationAction(ISD::SDIV, VT, Expand);
423     setOperationAction(ISD::UDIV, VT, Expand);
424     setOperationAction(ISD::SREM, VT, Expand);
425     setOperationAction(ISD::UREM, VT, Expand);
426
427     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428     setOperationAction(ISD::ADDC, VT, Custom);
429     setOperationAction(ISD::ADDE, VT, Custom);
430     setOperationAction(ISD::SUBC, VT, Custom);
431     setOperationAction(ISD::SUBE, VT, Custom);
432   }
433
434   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
435   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
436   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
443   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
444   if (Subtarget->is64Bit())
445     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
449   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
453   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
454
455   // Promote the i8 variants and force them on up to i32 which has a shorter
456   // encoding.
457   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
459   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
460   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
461   if (Subtarget->hasBMI()) {
462     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
464     if (Subtarget->is64Bit())
465       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
466   } else {
467     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
468     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
469     if (Subtarget->is64Bit())
470       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
471   }
472
473   if (Subtarget->hasLZCNT()) {
474     // When promoting the i8 variants, force them to i32 for a shorter
475     // encoding.
476     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
479     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
480     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
482     if (Subtarget->is64Bit())
483       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
484   } else {
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
486     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
491     if (Subtarget->is64Bit()) {
492       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
493       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
494     }
495   }
496
497   if (Subtarget->hasPOPCNT()) {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
499   } else {
500     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
501     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
505   }
506
507   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
508
509   if (!Subtarget->hasMOVBE())
510     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
511
512   // These should be promoted to a larger select which is supported.
513   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
514   // X86 wants to expand cmov itself.
515   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
516   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
527   if (Subtarget->is64Bit()) {
528     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
529     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
530   }
531   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
532   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534   // support continuation, user-level threading, and etc.. As a result, no
535   // other SjLj exception interfaces are implemented and please don't build
536   // your own exception handling based on them.
537   // LLVM/Clang supports zero-cost DWARF exception handling.
538   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
540
541   // Darwin ABI issue.
542   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
543   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
544   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
546   if (Subtarget->is64Bit())
547     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
549   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
550   if (Subtarget->is64Bit()) {
551     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
552     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
553     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
554     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
555     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
556   }
557   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
559   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
561   if (Subtarget->is64Bit()) {
562     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
563     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
565   }
566
567   if (Subtarget->hasSSE1())
568     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
569
570   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
571
572   // Expand certain atomics
573   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
574     MVT VT = IntVTs[i];
575     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
578   }
579
580   if (!Subtarget->is64Bit()) {
581     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
593   }
594
595   if (Subtarget->hasCmpxchg16b()) {
596     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
597   }
598
599   // FIXME - use subtarget debug flags
600   if (!Subtarget->isTargetDarwin() &&
601       !Subtarget->isTargetELF() &&
602       !Subtarget->isTargetCygMing()) {
603     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
604   }
605
606   if (Subtarget->is64Bit()) {
607     setExceptionPointerRegister(X86::RAX);
608     setExceptionSelectorRegister(X86::RDX);
609   } else {
610     setExceptionPointerRegister(X86::EAX);
611     setExceptionSelectorRegister(X86::EDX);
612   }
613   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
615
616   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
618
619   setOperationAction(ISD::TRAP, MVT::Other, Legal);
620   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
621
622   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
624   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
625   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626     // TargetInfo::X86_64ABIBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
629   } else {
630     // TargetInfo::CharPtrBuiltinVaList
631     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
632     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
633   }
634
635   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
636   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
637
638   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639                      MVT::i64 : MVT::i32, Custom);
640
641   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
642     // f32 and f64 use SSE.
643     // Set up the FP register classes.
644     addRegisterClass(MVT::f32, &X86::FR32RegClass);
645     addRegisterClass(MVT::f64, &X86::FR64RegClass);
646
647     // Use ANDPD to simulate FABS.
648     setOperationAction(ISD::FABS , MVT::f64, Custom);
649     setOperationAction(ISD::FABS , MVT::f32, Custom);
650
651     // Use XORP to simulate FNEG.
652     setOperationAction(ISD::FNEG , MVT::f64, Custom);
653     setOperationAction(ISD::FNEG , MVT::f32, Custom);
654
655     // Use ANDPD and ORPD to simulate FCOPYSIGN.
656     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
657     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
658
659     // Lower this to FGETSIGNx86 plus an AND.
660     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
661     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
662
663     // We don't support sin/cos/fmod
664     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
665     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
666     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
667     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
670
671     // Expand FP immediates into loads from the stack, except for the special
672     // cases we handle.
673     addLegalFPImmediate(APFloat(+0.0)); // xorpd
674     addLegalFPImmediate(APFloat(+0.0f)); // xorps
675   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
676     // Use SSE for f32, x87 for f64.
677     // Set up the FP register classes.
678     addRegisterClass(MVT::f32, &X86::FR32RegClass);
679     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
680
681     // Use ANDPS to simulate FABS.
682     setOperationAction(ISD::FABS , MVT::f32, Custom);
683
684     // Use XORP to simulate FNEG.
685     setOperationAction(ISD::FNEG , MVT::f32, Custom);
686
687     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
688
689     // Use ANDPS and ORPS to simulate FCOPYSIGN.
690     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
691     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
692
693     // We don't support sin/cos/fmod
694     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
695     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
696     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
697
698     // Special cases we handle for FP constants.
699     addLegalFPImmediate(APFloat(+0.0f)); // xorps
700     addLegalFPImmediate(APFloat(+0.0)); // FLD0
701     addLegalFPImmediate(APFloat(+1.0)); // FLD1
702     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
703     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
704
705     if (!TM.Options.UnsafeFPMath) {
706       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
707       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
708       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
709     }
710   } else if (!TM.Options.UseSoftFloat) {
711     // f32 and f64 in x87.
712     // Set up the FP register classes.
713     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
714     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
715
716     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
717     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
718     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
720
721     if (!TM.Options.UnsafeFPMath) {
722       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
723       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
724       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
726       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
728     }
729     addLegalFPImmediate(APFloat(+0.0)); // FLD0
730     addLegalFPImmediate(APFloat(+1.0)); // FLD1
731     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
732     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
733     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
734     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
735     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
736     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
737   }
738
739   // We don't support FMA.
740   setOperationAction(ISD::FMA, MVT::f64, Expand);
741   setOperationAction(ISD::FMA, MVT::f32, Expand);
742
743   // Long double always uses X87.
744   if (!TM.Options.UseSoftFloat) {
745     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
746     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
747     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
748     {
749       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
750       addLegalFPImmediate(TmpFlt);  // FLD0
751       TmpFlt.changeSign();
752       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
753
754       bool ignored;
755       APFloat TmpFlt2(+1.0);
756       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
757                       &ignored);
758       addLegalFPImmediate(TmpFlt2);  // FLD1
759       TmpFlt2.changeSign();
760       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
761     }
762
763     if (!TM.Options.UnsafeFPMath) {
764       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
765       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
766       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
767     }
768
769     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
770     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
771     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
772     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
773     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
774     setOperationAction(ISD::FMA, MVT::f80, Expand);
775   }
776
777   // Always use a library call for pow.
778   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
779   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
781
782   setOperationAction(ISD::FLOG, MVT::f80, Expand);
783   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
785   setOperationAction(ISD::FEXP, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
787
788   // First set operation action for all vector types to either promote
789   // (for widening) or expand (for scalarization). Then we will selectively
790   // turn on ones that can be effectively codegen'd.
791   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
792            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
793     MVT VT = (MVT::SimpleValueType)i;
794     setOperationAction(ISD::ADD , VT, Expand);
795     setOperationAction(ISD::SUB , VT, Expand);
796     setOperationAction(ISD::FADD, VT, Expand);
797     setOperationAction(ISD::FNEG, VT, Expand);
798     setOperationAction(ISD::FSUB, VT, Expand);
799     setOperationAction(ISD::MUL , VT, Expand);
800     setOperationAction(ISD::FMUL, VT, Expand);
801     setOperationAction(ISD::SDIV, VT, Expand);
802     setOperationAction(ISD::UDIV, VT, Expand);
803     setOperationAction(ISD::FDIV, VT, Expand);
804     setOperationAction(ISD::SREM, VT, Expand);
805     setOperationAction(ISD::UREM, VT, Expand);
806     setOperationAction(ISD::LOAD, VT, Expand);
807     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
808     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
809     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
810     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
811     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::FABS, VT, Expand);
813     setOperationAction(ISD::FSIN, VT, Expand);
814     setOperationAction(ISD::FSINCOS, VT, Expand);
815     setOperationAction(ISD::FCOS, VT, Expand);
816     setOperationAction(ISD::FSINCOS, VT, Expand);
817     setOperationAction(ISD::FREM, VT, Expand);
818     setOperationAction(ISD::FMA,  VT, Expand);
819     setOperationAction(ISD::FPOWI, VT, Expand);
820     setOperationAction(ISD::FSQRT, VT, Expand);
821     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
822     setOperationAction(ISD::FFLOOR, VT, Expand);
823     setOperationAction(ISD::FCEIL, VT, Expand);
824     setOperationAction(ISD::FTRUNC, VT, Expand);
825     setOperationAction(ISD::FRINT, VT, Expand);
826     setOperationAction(ISD::FNEARBYINT, VT, Expand);
827     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
828     setOperationAction(ISD::MULHS, VT, Expand);
829     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830     setOperationAction(ISD::MULHU, VT, Expand);
831     setOperationAction(ISD::SDIVREM, VT, Expand);
832     setOperationAction(ISD::UDIVREM, VT, Expand);
833     setOperationAction(ISD::FPOW, VT, Expand);
834     setOperationAction(ISD::CTPOP, VT, Expand);
835     setOperationAction(ISD::CTTZ, VT, Expand);
836     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
837     setOperationAction(ISD::CTLZ, VT, Expand);
838     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
839     setOperationAction(ISD::SHL, VT, Expand);
840     setOperationAction(ISD::SRA, VT, Expand);
841     setOperationAction(ISD::SRL, VT, Expand);
842     setOperationAction(ISD::ROTL, VT, Expand);
843     setOperationAction(ISD::ROTR, VT, Expand);
844     setOperationAction(ISD::BSWAP, VT, Expand);
845     setOperationAction(ISD::SETCC, VT, Expand);
846     setOperationAction(ISD::FLOG, VT, Expand);
847     setOperationAction(ISD::FLOG2, VT, Expand);
848     setOperationAction(ISD::FLOG10, VT, Expand);
849     setOperationAction(ISD::FEXP, VT, Expand);
850     setOperationAction(ISD::FEXP2, VT, Expand);
851     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
852     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
853     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
854     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
856     setOperationAction(ISD::TRUNCATE, VT, Expand);
857     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
858     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
859     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
860     setOperationAction(ISD::VSELECT, VT, Expand);
861     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
862              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
863       setTruncStoreAction(VT,
864                           (MVT::SimpleValueType)InnerVT, Expand);
865     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
866     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
868   }
869
870   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
871   // with -msoft-float, disable use of MMX as well.
872   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
873     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
874     // No operations on x86mmx supported, everything uses intrinsics.
875   }
876
877   // MMX-sized vectors (other than x86mmx) are expected to be expanded
878   // into smaller operations.
879   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
880   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
881   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
883   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
884   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
885   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
886   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
887   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
888   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
889   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
890   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
891   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
892   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
893   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
894   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
895   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
899   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
900   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
901   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
904   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
908
909   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
910     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
911
912     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
913     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
917     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
918     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
919     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
920     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
921     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
922     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
923     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
924   }
925
926   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
927     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
928
929     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
930     // registers cannot be used even for integer operations.
931     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
932     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
933     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
934     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
935
936     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
937     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
938     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
939     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
940     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
941     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
942     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
943     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
944     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
945     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
946     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
947     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
948     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
949     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
950     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
951     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
956     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
957     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
958
959     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
962     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
963
964     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
965     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
969
970     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972       MVT VT = (MVT::SimpleValueType)i;
973       // Do not attempt to custom lower non-power-of-2 vectors
974       if (!isPowerOf2_32(VT.getVectorNumElements()))
975         continue;
976       // Do not attempt to custom lower non-128-bit vectors
977       if (!VT.is128BitVector())
978         continue;
979       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
980       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
981       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
982     }
983
984     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
985     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
986     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
987     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
990
991     if (Subtarget->is64Bit()) {
992       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
993       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
994     }
995
996     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998       MVT VT = (MVT::SimpleValueType)i;
999
1000       // Do not attempt to promote non-128-bit vectors
1001       if (!VT.is128BitVector())
1002         continue;
1003
1004       setOperationAction(ISD::AND,    VT, Promote);
1005       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1006       setOperationAction(ISD::OR,     VT, Promote);
1007       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1008       setOperationAction(ISD::XOR,    VT, Promote);
1009       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1010       setOperationAction(ISD::LOAD,   VT, Promote);
1011       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1012       setOperationAction(ISD::SELECT, VT, Promote);
1013       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1014     }
1015
1016     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1017
1018     // Custom lower v2i64 and v2f64 selects.
1019     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1020     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1021     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1022     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1023
1024     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1025     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1026
1027     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1028     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1029     // As there is no 64-bit GPR available, we need build a special custom
1030     // sequence to convert from v2i32 to v2f32.
1031     if (!Subtarget->is64Bit())
1032       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1033
1034     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1035     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1036
1037     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1038
1039     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1040     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1041     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1042   }
1043
1044   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1045     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1046     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1047     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1048     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1049     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1050     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1051     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1052     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1053     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1054     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1055
1056     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1062     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1063     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1064     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1065     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1066
1067     // FIXME: Do we need to handle scalar-to-vector here?
1068     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1069
1070     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1071     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1072     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1073     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1074     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1075     // There is no BLENDI for byte vectors. We don't need to custom lower
1076     // some vselects for now.
1077     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1078
1079     // i8 and i16 vectors are custom , because the source register and source
1080     // source memory operand types are not the same width.  f32 vectors are
1081     // custom since the immediate controlling the insert encodes additional
1082     // information.
1083     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1084     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1085     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1086     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1087
1088     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1089     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1090     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1091     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1092
1093     // FIXME: these should be Legal but thats only for the case where
1094     // the index is constant.  For now custom expand to deal with that.
1095     if (Subtarget->is64Bit()) {
1096       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1097       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1098     }
1099   }
1100
1101   if (Subtarget->hasSSE2()) {
1102     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1103     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1104
1105     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1106     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1107
1108     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1109     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1110
1111     // In the customized shift lowering, the legal cases in AVX2 will be
1112     // recognized.
1113     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1114     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1115
1116     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1117     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1118
1119     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1120   }
1121
1122   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1123     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1124     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1125     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1126     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1127     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1128     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1129
1130     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1132     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1133
1134     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1135     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1136     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1137     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1138     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1139     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1140     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1141     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1142     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1143     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1144     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1145     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1146
1147     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1148     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1149     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1150     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1151     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1152     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1153     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1154     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1155     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1156     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1157     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1158     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1159
1160     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1161     // even though v8i16 is a legal type.
1162     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1163     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1164     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1165
1166     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1167     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1168     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1169
1170     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1171     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1172
1173     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1174
1175     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1179     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1180
1181     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1182     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1183
1184     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1185     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1186     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1187     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1188
1189     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1190     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1191     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1192
1193     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1194     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1195     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1196     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1197
1198     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1199     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1200     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1201     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1202     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1203     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1204     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1205     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1206     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1207     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1208     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1209     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1210
1211     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1212       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1213       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1214       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1215       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1216       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1217       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1218     }
1219
1220     if (Subtarget->hasInt256()) {
1221       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1222       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1223       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1224       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1225
1226       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1227       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1228       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1229       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1230
1231       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1232       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1233       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1234       // Don't lower v32i8 because there is no 128-bit byte mul
1235
1236       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1237       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1238       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1239       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1240
1241       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1242       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1243     } else {
1244       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1245       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1246       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1247       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1248
1249       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1250       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1251       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1252       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1253
1254       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1255       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1256       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1257       // Don't lower v32i8 because there is no 128-bit byte mul
1258     }
1259
1260     // In the customized shift lowering, the legal cases in AVX2 will be
1261     // recognized.
1262     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1263     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1264
1265     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1266     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1267
1268     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1269
1270     // Custom lower several nodes for 256-bit types.
1271     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1272              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1273       MVT VT = (MVT::SimpleValueType)i;
1274
1275       // Extract subvector is special because the value type
1276       // (result) is 128-bit but the source is 256-bit wide.
1277       if (VT.is128BitVector())
1278         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1279
1280       // Do not attempt to custom lower other non-256-bit vectors
1281       if (!VT.is256BitVector())
1282         continue;
1283
1284       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1285       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1286       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1287       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1288       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1289       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1290       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1291     }
1292
1293     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1295       MVT VT = (MVT::SimpleValueType)i;
1296
1297       // Do not attempt to promote non-256-bit vectors
1298       if (!VT.is256BitVector())
1299         continue;
1300
1301       setOperationAction(ISD::AND,    VT, Promote);
1302       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1303       setOperationAction(ISD::OR,     VT, Promote);
1304       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1305       setOperationAction(ISD::XOR,    VT, Promote);
1306       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1307       setOperationAction(ISD::LOAD,   VT, Promote);
1308       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1309       setOperationAction(ISD::SELECT, VT, Promote);
1310       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1311     }
1312   }
1313
1314   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1315     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1316     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1317     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1318     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1319
1320     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1321     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1322     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1323
1324     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1325     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1326     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1327     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1328     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1329     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1330     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1331     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1333     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1334     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1335
1336     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1337     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1339     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1340     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1341     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1342
1343     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1344     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1345     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1348     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1349     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1350     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1351
1352     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1353     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1356     if (Subtarget->is64Bit()) {
1357       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1358       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1359       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1360       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1361     }
1362     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1363     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1365     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1366     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1367     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1368     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1370     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1371     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1372
1373     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1374     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1375     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1376     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1377     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1378     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1379     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1380     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1381     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1382     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1383     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1384     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1385     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1386
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1390     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1391     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1392     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1393
1394     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1395     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1396
1397     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1398
1399     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1400     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1401     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1402     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1403     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1404     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1405     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1406     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1407     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1408
1409     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1410     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1411
1412     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1413     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1414
1415     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1416
1417     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1418     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1419
1420     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1421     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1422
1423     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1424     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1425
1426     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1427     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1428     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1429     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1430     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1431     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1432
1433     // Custom lower several nodes.
1434     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1435              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1436       MVT VT = (MVT::SimpleValueType)i;
1437
1438       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1439       // Extract subvector is special because the value type
1440       // (result) is 256/128-bit but the source is 512-bit wide.
1441       if (VT.is128BitVector() || VT.is256BitVector())
1442         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1443
1444       if (VT.getVectorElementType() == MVT::i1)
1445         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1446
1447       // Do not attempt to custom lower other non-512-bit vectors
1448       if (!VT.is512BitVector())
1449         continue;
1450
1451       if ( EltSize >= 32) {
1452         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1453         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1454         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1455         setOperationAction(ISD::VSELECT,             VT, Legal);
1456         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1457         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1458         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1459       }
1460     }
1461     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1462       MVT VT = (MVT::SimpleValueType)i;
1463
1464       // Do not attempt to promote non-256-bit vectors
1465       if (!VT.is512BitVector())
1466         continue;
1467
1468       setOperationAction(ISD::SELECT, VT, Promote);
1469       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1470     }
1471   }// has  AVX-512
1472
1473   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1474   // of this type with custom code.
1475   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1476            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1477     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1478                        Custom);
1479   }
1480
1481   // We want to custom lower some of our intrinsics.
1482   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1483   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1484   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1485   if (!Subtarget->is64Bit())
1486     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1487
1488   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1489   // handle type legalization for these operations here.
1490   //
1491   // FIXME: We really should do custom legalization for addition and
1492   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1493   // than generic legalization for 64-bit multiplication-with-overflow, though.
1494   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1495     // Add/Sub/Mul with overflow operations are custom lowered.
1496     MVT VT = IntVTs[i];
1497     setOperationAction(ISD::SADDO, VT, Custom);
1498     setOperationAction(ISD::UADDO, VT, Custom);
1499     setOperationAction(ISD::SSUBO, VT, Custom);
1500     setOperationAction(ISD::USUBO, VT, Custom);
1501     setOperationAction(ISD::SMULO, VT, Custom);
1502     setOperationAction(ISD::UMULO, VT, Custom);
1503   }
1504
1505   // There are no 8-bit 3-address imul/mul instructions
1506   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1507   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1508
1509   if (!Subtarget->is64Bit()) {
1510     // These libcalls are not available in 32-bit.
1511     setLibcallName(RTLIB::SHL_I128, nullptr);
1512     setLibcallName(RTLIB::SRL_I128, nullptr);
1513     setLibcallName(RTLIB::SRA_I128, nullptr);
1514   }
1515
1516   // Combine sin / cos into one node or libcall if possible.
1517   if (Subtarget->hasSinCos()) {
1518     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1519     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1520     if (Subtarget->isTargetDarwin()) {
1521       // For MacOSX, we don't want to the normal expansion of a libcall to
1522       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1523       // traffic.
1524       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1525       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1526     }
1527   }
1528
1529   if (Subtarget->isTargetWin64()) {
1530     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1531     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1532     setOperationAction(ISD::SREM, MVT::i128, Custom);
1533     setOperationAction(ISD::UREM, MVT::i128, Custom);
1534     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1535     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1536   }
1537
1538   // We have target-specific dag combine patterns for the following nodes:
1539   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1540   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1541   setTargetDAGCombine(ISD::VSELECT);
1542   setTargetDAGCombine(ISD::SELECT);
1543   setTargetDAGCombine(ISD::SHL);
1544   setTargetDAGCombine(ISD::SRA);
1545   setTargetDAGCombine(ISD::SRL);
1546   setTargetDAGCombine(ISD::OR);
1547   setTargetDAGCombine(ISD::AND);
1548   setTargetDAGCombine(ISD::ADD);
1549   setTargetDAGCombine(ISD::FADD);
1550   setTargetDAGCombine(ISD::FSUB);
1551   setTargetDAGCombine(ISD::FMA);
1552   setTargetDAGCombine(ISD::SUB);
1553   setTargetDAGCombine(ISD::LOAD);
1554   setTargetDAGCombine(ISD::STORE);
1555   setTargetDAGCombine(ISD::ZERO_EXTEND);
1556   setTargetDAGCombine(ISD::ANY_EXTEND);
1557   setTargetDAGCombine(ISD::SIGN_EXTEND);
1558   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1559   setTargetDAGCombine(ISD::TRUNCATE);
1560   setTargetDAGCombine(ISD::SINT_TO_FP);
1561   setTargetDAGCombine(ISD::SETCC);
1562   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1563   setTargetDAGCombine(ISD::BUILD_VECTOR);
1564   if (Subtarget->is64Bit())
1565     setTargetDAGCombine(ISD::MUL);
1566   setTargetDAGCombine(ISD::XOR);
1567
1568   computeRegisterProperties();
1569
1570   // On Darwin, -Os means optimize for size without hurting performance,
1571   // do not reduce the limit.
1572   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1573   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1574   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1575   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1576   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1577   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1578   setPrefLoopAlignment(4); // 2^4 bytes.
1579
1580   // Predictable cmov don't hurt on atom because it's in-order.
1581   PredictableSelectIsExpensive = !Subtarget->isAtom();
1582
1583   setPrefFunctionAlignment(4); // 2^4 bytes.
1584 }
1585
1586 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1587   if (!VT.isVector())
1588     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1589
1590   if (Subtarget->hasAVX512())
1591     switch(VT.getVectorNumElements()) {
1592     case  8: return MVT::v8i1;
1593     case 16: return MVT::v16i1;
1594   }
1595
1596   return VT.changeVectorElementTypeToInteger();
1597 }
1598
1599 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1600 /// the desired ByVal argument alignment.
1601 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1602   if (MaxAlign == 16)
1603     return;
1604   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1605     if (VTy->getBitWidth() == 128)
1606       MaxAlign = 16;
1607   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1608     unsigned EltAlign = 0;
1609     getMaxByValAlign(ATy->getElementType(), EltAlign);
1610     if (EltAlign > MaxAlign)
1611       MaxAlign = EltAlign;
1612   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1613     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1614       unsigned EltAlign = 0;
1615       getMaxByValAlign(STy->getElementType(i), EltAlign);
1616       if (EltAlign > MaxAlign)
1617         MaxAlign = EltAlign;
1618       if (MaxAlign == 16)
1619         break;
1620     }
1621   }
1622 }
1623
1624 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1625 /// function arguments in the caller parameter area. For X86, aggregates
1626 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1627 /// are at 4-byte boundaries.
1628 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1629   if (Subtarget->is64Bit()) {
1630     // Max of 8 and alignment of type.
1631     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1632     if (TyAlign > 8)
1633       return TyAlign;
1634     return 8;
1635   }
1636
1637   unsigned Align = 4;
1638   if (Subtarget->hasSSE1())
1639     getMaxByValAlign(Ty, Align);
1640   return Align;
1641 }
1642
1643 /// getOptimalMemOpType - Returns the target specific optimal type for load
1644 /// and store operations as a result of memset, memcpy, and memmove
1645 /// lowering. If DstAlign is zero that means it's safe to destination
1646 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1647 /// means there isn't a need to check it against alignment requirement,
1648 /// probably because the source does not need to be loaded. If 'IsMemset' is
1649 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1650 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1651 /// source is constant so it does not need to be loaded.
1652 /// It returns EVT::Other if the type should be determined using generic
1653 /// target-independent logic.
1654 EVT
1655 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1656                                        unsigned DstAlign, unsigned SrcAlign,
1657                                        bool IsMemset, bool ZeroMemset,
1658                                        bool MemcpyStrSrc,
1659                                        MachineFunction &MF) const {
1660   const Function *F = MF.getFunction();
1661   if ((!IsMemset || ZeroMemset) &&
1662       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1663                                        Attribute::NoImplicitFloat)) {
1664     if (Size >= 16 &&
1665         (Subtarget->isUnalignedMemAccessFast() ||
1666          ((DstAlign == 0 || DstAlign >= 16) &&
1667           (SrcAlign == 0 || SrcAlign >= 16)))) {
1668       if (Size >= 32) {
1669         if (Subtarget->hasInt256())
1670           return MVT::v8i32;
1671         if (Subtarget->hasFp256())
1672           return MVT::v8f32;
1673       }
1674       if (Subtarget->hasSSE2())
1675         return MVT::v4i32;
1676       if (Subtarget->hasSSE1())
1677         return MVT::v4f32;
1678     } else if (!MemcpyStrSrc && Size >= 8 &&
1679                !Subtarget->is64Bit() &&
1680                Subtarget->hasSSE2()) {
1681       // Do not use f64 to lower memcpy if source is string constant. It's
1682       // better to use i32 to avoid the loads.
1683       return MVT::f64;
1684     }
1685   }
1686   if (Subtarget->is64Bit() && Size >= 8)
1687     return MVT::i64;
1688   return MVT::i32;
1689 }
1690
1691 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1692   if (VT == MVT::f32)
1693     return X86ScalarSSEf32;
1694   else if (VT == MVT::f64)
1695     return X86ScalarSSEf64;
1696   return true;
1697 }
1698
1699 bool
1700 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1701                                                  unsigned,
1702                                                  bool *Fast) const {
1703   if (Fast)
1704     *Fast = Subtarget->isUnalignedMemAccessFast();
1705   return true;
1706 }
1707
1708 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1709 /// current function.  The returned value is a member of the
1710 /// MachineJumpTableInfo::JTEntryKind enum.
1711 unsigned X86TargetLowering::getJumpTableEncoding() const {
1712   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1713   // symbol.
1714   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1715       Subtarget->isPICStyleGOT())
1716     return MachineJumpTableInfo::EK_Custom32;
1717
1718   // Otherwise, use the normal jump table encoding heuristics.
1719   return TargetLowering::getJumpTableEncoding();
1720 }
1721
1722 const MCExpr *
1723 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1724                                              const MachineBasicBlock *MBB,
1725                                              unsigned uid,MCContext &Ctx) const{
1726   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1727          Subtarget->isPICStyleGOT());
1728   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1729   // entries.
1730   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1731                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1732 }
1733
1734 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1735 /// jumptable.
1736 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1737                                                     SelectionDAG &DAG) const {
1738   if (!Subtarget->is64Bit())
1739     // This doesn't have SDLoc associated with it, but is not really the
1740     // same as a Register.
1741     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1742   return Table;
1743 }
1744
1745 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1746 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1747 /// MCExpr.
1748 const MCExpr *X86TargetLowering::
1749 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1750                              MCContext &Ctx) const {
1751   // X86-64 uses RIP relative addressing based on the jump table label.
1752   if (Subtarget->isPICStyleRIPRel())
1753     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1754
1755   // Otherwise, the reference is relative to the PIC base.
1756   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1757 }
1758
1759 // FIXME: Why this routine is here? Move to RegInfo!
1760 std::pair<const TargetRegisterClass*, uint8_t>
1761 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1762   const TargetRegisterClass *RRC = nullptr;
1763   uint8_t Cost = 1;
1764   switch (VT.SimpleTy) {
1765   default:
1766     return TargetLowering::findRepresentativeClass(VT);
1767   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1768     RRC = Subtarget->is64Bit() ?
1769       (const TargetRegisterClass*)&X86::GR64RegClass :
1770       (const TargetRegisterClass*)&X86::GR32RegClass;
1771     break;
1772   case MVT::x86mmx:
1773     RRC = &X86::VR64RegClass;
1774     break;
1775   case MVT::f32: case MVT::f64:
1776   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1777   case MVT::v4f32: case MVT::v2f64:
1778   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1779   case MVT::v4f64:
1780     RRC = &X86::VR128RegClass;
1781     break;
1782   }
1783   return std::make_pair(RRC, Cost);
1784 }
1785
1786 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1787                                                unsigned &Offset) const {
1788   if (!Subtarget->isTargetLinux())
1789     return false;
1790
1791   if (Subtarget->is64Bit()) {
1792     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1793     Offset = 0x28;
1794     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1795       AddressSpace = 256;
1796     else
1797       AddressSpace = 257;
1798   } else {
1799     // %gs:0x14 on i386
1800     Offset = 0x14;
1801     AddressSpace = 256;
1802   }
1803   return true;
1804 }
1805
1806 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1807                                             unsigned DestAS) const {
1808   assert(SrcAS != DestAS && "Expected different address spaces!");
1809
1810   return SrcAS < 256 && DestAS < 256;
1811 }
1812
1813 //===----------------------------------------------------------------------===//
1814 //               Return Value Calling Convention Implementation
1815 //===----------------------------------------------------------------------===//
1816
1817 #include "X86GenCallingConv.inc"
1818
1819 bool
1820 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1821                                   MachineFunction &MF, bool isVarArg,
1822                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1823                         LLVMContext &Context) const {
1824   SmallVector<CCValAssign, 16> RVLocs;
1825   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1826                  RVLocs, Context);
1827   return CCInfo.CheckReturn(Outs, RetCC_X86);
1828 }
1829
1830 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1831   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1832   return ScratchRegs;
1833 }
1834
1835 SDValue
1836 X86TargetLowering::LowerReturn(SDValue Chain,
1837                                CallingConv::ID CallConv, bool isVarArg,
1838                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1839                                const SmallVectorImpl<SDValue> &OutVals,
1840                                SDLoc dl, SelectionDAG &DAG) const {
1841   MachineFunction &MF = DAG.getMachineFunction();
1842   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1843
1844   SmallVector<CCValAssign, 16> RVLocs;
1845   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1846                  RVLocs, *DAG.getContext());
1847   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1848
1849   SDValue Flag;
1850   SmallVector<SDValue, 6> RetOps;
1851   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1852   // Operand #1 = Bytes To Pop
1853   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1854                    MVT::i16));
1855
1856   // Copy the result values into the output registers.
1857   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1858     CCValAssign &VA = RVLocs[i];
1859     assert(VA.isRegLoc() && "Can only return in registers!");
1860     SDValue ValToCopy = OutVals[i];
1861     EVT ValVT = ValToCopy.getValueType();
1862
1863     // Promote values to the appropriate types
1864     if (VA.getLocInfo() == CCValAssign::SExt)
1865       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1866     else if (VA.getLocInfo() == CCValAssign::ZExt)
1867       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1868     else if (VA.getLocInfo() == CCValAssign::AExt)
1869       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1870     else if (VA.getLocInfo() == CCValAssign::BCvt)
1871       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1872
1873     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1874            "Unexpected FP-extend for return value.");  
1875
1876     // If this is x86-64, and we disabled SSE, we can't return FP values,
1877     // or SSE or MMX vectors.
1878     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1879          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1880           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1881       report_fatal_error("SSE register return with SSE disabled");
1882     }
1883     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1884     // llvm-gcc has never done it right and no one has noticed, so this
1885     // should be OK for now.
1886     if (ValVT == MVT::f64 &&
1887         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1888       report_fatal_error("SSE2 register return with SSE2 disabled");
1889
1890     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1891     // the RET instruction and handled by the FP Stackifier.
1892     if (VA.getLocReg() == X86::ST0 ||
1893         VA.getLocReg() == X86::ST1) {
1894       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1895       // change the value to the FP stack register class.
1896       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1897         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1898       RetOps.push_back(ValToCopy);
1899       // Don't emit a copytoreg.
1900       continue;
1901     }
1902
1903     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1904     // which is returned in RAX / RDX.
1905     if (Subtarget->is64Bit()) {
1906       if (ValVT == MVT::x86mmx) {
1907         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1908           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1909           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1910                                   ValToCopy);
1911           // If we don't have SSE2 available, convert to v4f32 so the generated
1912           // register is legal.
1913           if (!Subtarget->hasSSE2())
1914             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1915         }
1916       }
1917     }
1918
1919     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1920     Flag = Chain.getValue(1);
1921     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1922   }
1923
1924   // The x86-64 ABIs require that for returning structs by value we copy
1925   // the sret argument into %rax/%eax (depending on ABI) for the return.
1926   // Win32 requires us to put the sret argument to %eax as well.
1927   // We saved the argument into a virtual register in the entry block,
1928   // so now we copy the value out and into %rax/%eax.
1929   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1930       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1931     MachineFunction &MF = DAG.getMachineFunction();
1932     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1933     unsigned Reg = FuncInfo->getSRetReturnReg();
1934     assert(Reg &&
1935            "SRetReturnReg should have been set in LowerFormalArguments().");
1936     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1937
1938     unsigned RetValReg
1939         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1940           X86::RAX : X86::EAX;
1941     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1942     Flag = Chain.getValue(1);
1943
1944     // RAX/EAX now acts like a return value.
1945     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1946   }
1947
1948   RetOps[0] = Chain;  // Update chain.
1949
1950   // Add the flag if we have it.
1951   if (Flag.getNode())
1952     RetOps.push_back(Flag);
1953
1954   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1955 }
1956
1957 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1958   if (N->getNumValues() != 1)
1959     return false;
1960   if (!N->hasNUsesOfValue(1, 0))
1961     return false;
1962
1963   SDValue TCChain = Chain;
1964   SDNode *Copy = *N->use_begin();
1965   if (Copy->getOpcode() == ISD::CopyToReg) {
1966     // If the copy has a glue operand, we conservatively assume it isn't safe to
1967     // perform a tail call.
1968     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1969       return false;
1970     TCChain = Copy->getOperand(0);
1971   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1972     return false;
1973
1974   bool HasRet = false;
1975   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1976        UI != UE; ++UI) {
1977     if (UI->getOpcode() != X86ISD::RET_FLAG)
1978       return false;
1979     HasRet = true;
1980   }
1981
1982   if (!HasRet)
1983     return false;
1984
1985   Chain = TCChain;
1986   return true;
1987 }
1988
1989 MVT
1990 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1991                                             ISD::NodeType ExtendKind) const {
1992   MVT ReturnMVT;
1993   // TODO: Is this also valid on 32-bit?
1994   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1995     ReturnMVT = MVT::i8;
1996   else
1997     ReturnMVT = MVT::i32;
1998
1999   MVT MinVT = getRegisterType(ReturnMVT);
2000   return VT.bitsLT(MinVT) ? MinVT : VT;
2001 }
2002
2003 /// LowerCallResult - Lower the result values of a call into the
2004 /// appropriate copies out of appropriate physical registers.
2005 ///
2006 SDValue
2007 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2008                                    CallingConv::ID CallConv, bool isVarArg,
2009                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2010                                    SDLoc dl, SelectionDAG &DAG,
2011                                    SmallVectorImpl<SDValue> &InVals) const {
2012
2013   // Assign locations to each value returned by this call.
2014   SmallVector<CCValAssign, 16> RVLocs;
2015   bool Is64Bit = Subtarget->is64Bit();
2016   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2017                  getTargetMachine(), RVLocs, *DAG.getContext());
2018   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2019
2020   // Copy all of the result registers out of their specified physreg.
2021   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2022     CCValAssign &VA = RVLocs[i];
2023     EVT CopyVT = VA.getValVT();
2024
2025     // If this is x86-64, and we disabled SSE, we can't return FP values
2026     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2027         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2028       report_fatal_error("SSE register return with SSE disabled");
2029     }
2030
2031     SDValue Val;
2032
2033     // If this is a call to a function that returns an fp value on the floating
2034     // point stack, we must guarantee the value is popped from the stack, so
2035     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2036     // if the return value is not used. We use the FpPOP_RETVAL instruction
2037     // instead.
2038     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2039       // If we prefer to use the value in xmm registers, copy it out as f80 and
2040       // use a truncate to move it from fp stack reg to xmm reg.
2041       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2042       SDValue Ops[] = { Chain, InFlag };
2043       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2044                                          MVT::Other, MVT::Glue, Ops), 1);
2045       Val = Chain.getValue(0);
2046
2047       // Round the f80 to the right size, which also moves it to the appropriate
2048       // xmm register.
2049       if (CopyVT != VA.getValVT())
2050         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2051                           // This truncation won't change the value.
2052                           DAG.getIntPtrConstant(1));
2053     } else {
2054       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2055                                  CopyVT, InFlag).getValue(1);
2056       Val = Chain.getValue(0);
2057     }
2058     InFlag = Chain.getValue(2);
2059     InVals.push_back(Val);
2060   }
2061
2062   return Chain;
2063 }
2064
2065 //===----------------------------------------------------------------------===//
2066 //                C & StdCall & Fast Calling Convention implementation
2067 //===----------------------------------------------------------------------===//
2068 //  StdCall calling convention seems to be standard for many Windows' API
2069 //  routines and around. It differs from C calling convention just a little:
2070 //  callee should clean up the stack, not caller. Symbols should be also
2071 //  decorated in some fancy way :) It doesn't support any vector arguments.
2072 //  For info on fast calling convention see Fast Calling Convention (tail call)
2073 //  implementation LowerX86_32FastCCCallTo.
2074
2075 /// CallIsStructReturn - Determines whether a call uses struct return
2076 /// semantics.
2077 enum StructReturnType {
2078   NotStructReturn,
2079   RegStructReturn,
2080   StackStructReturn
2081 };
2082 static StructReturnType
2083 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2084   if (Outs.empty())
2085     return NotStructReturn;
2086
2087   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2088   if (!Flags.isSRet())
2089     return NotStructReturn;
2090   if (Flags.isInReg())
2091     return RegStructReturn;
2092   return StackStructReturn;
2093 }
2094
2095 /// ArgsAreStructReturn - Determines whether a function uses struct
2096 /// return semantics.
2097 static StructReturnType
2098 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2099   if (Ins.empty())
2100     return NotStructReturn;
2101
2102   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2103   if (!Flags.isSRet())
2104     return NotStructReturn;
2105   if (Flags.isInReg())
2106     return RegStructReturn;
2107   return StackStructReturn;
2108 }
2109
2110 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2111 /// by "Src" to address "Dst" with size and alignment information specified by
2112 /// the specific parameter attribute. The copy will be passed as a byval
2113 /// function parameter.
2114 static SDValue
2115 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2116                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2117                           SDLoc dl) {
2118   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2119
2120   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2121                        /*isVolatile*/false, /*AlwaysInline=*/true,
2122                        MachinePointerInfo(), MachinePointerInfo());
2123 }
2124
2125 /// IsTailCallConvention - Return true if the calling convention is one that
2126 /// supports tail call optimization.
2127 static bool IsTailCallConvention(CallingConv::ID CC) {
2128   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2129           CC == CallingConv::HiPE);
2130 }
2131
2132 /// \brief Return true if the calling convention is a C calling convention.
2133 static bool IsCCallConvention(CallingConv::ID CC) {
2134   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2135           CC == CallingConv::X86_64_SysV);
2136 }
2137
2138 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2139   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2140     return false;
2141
2142   CallSite CS(CI);
2143   CallingConv::ID CalleeCC = CS.getCallingConv();
2144   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2145     return false;
2146
2147   return true;
2148 }
2149
2150 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2151 /// a tailcall target by changing its ABI.
2152 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2153                                    bool GuaranteedTailCallOpt) {
2154   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2155 }
2156
2157 SDValue
2158 X86TargetLowering::LowerMemArgument(SDValue Chain,
2159                                     CallingConv::ID CallConv,
2160                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2161                                     SDLoc dl, SelectionDAG &DAG,
2162                                     const CCValAssign &VA,
2163                                     MachineFrameInfo *MFI,
2164                                     unsigned i) const {
2165   // Create the nodes corresponding to a load from this parameter slot.
2166   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2167   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2168                               getTargetMachine().Options.GuaranteedTailCallOpt);
2169   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2170   EVT ValVT;
2171
2172   // If value is passed by pointer we have address passed instead of the value
2173   // itself.
2174   if (VA.getLocInfo() == CCValAssign::Indirect)
2175     ValVT = VA.getLocVT();
2176   else
2177     ValVT = VA.getValVT();
2178
2179   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2180   // changed with more analysis.
2181   // In case of tail call optimization mark all arguments mutable. Since they
2182   // could be overwritten by lowering of arguments in case of a tail call.
2183   if (Flags.isByVal()) {
2184     unsigned Bytes = Flags.getByValSize();
2185     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2186     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2187     return DAG.getFrameIndex(FI, getPointerTy());
2188   } else {
2189     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2190                                     VA.getLocMemOffset(), isImmutable);
2191     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2192     return DAG.getLoad(ValVT, dl, Chain, FIN,
2193                        MachinePointerInfo::getFixedStack(FI),
2194                        false, false, false, 0);
2195   }
2196 }
2197
2198 SDValue
2199 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2200                                         CallingConv::ID CallConv,
2201                                         bool isVarArg,
2202                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2203                                         SDLoc dl,
2204                                         SelectionDAG &DAG,
2205                                         SmallVectorImpl<SDValue> &InVals)
2206                                           const {
2207   MachineFunction &MF = DAG.getMachineFunction();
2208   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2209
2210   const Function* Fn = MF.getFunction();
2211   if (Fn->hasExternalLinkage() &&
2212       Subtarget->isTargetCygMing() &&
2213       Fn->getName() == "main")
2214     FuncInfo->setForceFramePointer(true);
2215
2216   MachineFrameInfo *MFI = MF.getFrameInfo();
2217   bool Is64Bit = Subtarget->is64Bit();
2218   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2219
2220   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2221          "Var args not supported with calling convention fastcc, ghc or hipe");
2222
2223   // Assign locations to all of the incoming arguments.
2224   SmallVector<CCValAssign, 16> ArgLocs;
2225   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2226                  ArgLocs, *DAG.getContext());
2227
2228   // Allocate shadow area for Win64
2229   if (IsWin64)
2230     CCInfo.AllocateStack(32, 8);
2231
2232   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2233
2234   unsigned LastVal = ~0U;
2235   SDValue ArgValue;
2236   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2237     CCValAssign &VA = ArgLocs[i];
2238     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2239     // places.
2240     assert(VA.getValNo() != LastVal &&
2241            "Don't support value assigned to multiple locs yet");
2242     (void)LastVal;
2243     LastVal = VA.getValNo();
2244
2245     if (VA.isRegLoc()) {
2246       EVT RegVT = VA.getLocVT();
2247       const TargetRegisterClass *RC;
2248       if (RegVT == MVT::i32)
2249         RC = &X86::GR32RegClass;
2250       else if (Is64Bit && RegVT == MVT::i64)
2251         RC = &X86::GR64RegClass;
2252       else if (RegVT == MVT::f32)
2253         RC = &X86::FR32RegClass;
2254       else if (RegVT == MVT::f64)
2255         RC = &X86::FR64RegClass;
2256       else if (RegVT.is512BitVector())
2257         RC = &X86::VR512RegClass;
2258       else if (RegVT.is256BitVector())
2259         RC = &X86::VR256RegClass;
2260       else if (RegVT.is128BitVector())
2261         RC = &X86::VR128RegClass;
2262       else if (RegVT == MVT::x86mmx)
2263         RC = &X86::VR64RegClass;
2264       else if (RegVT == MVT::i1)
2265         RC = &X86::VK1RegClass;
2266       else if (RegVT == MVT::v8i1)
2267         RC = &X86::VK8RegClass;
2268       else if (RegVT == MVT::v16i1)
2269         RC = &X86::VK16RegClass;
2270       else
2271         llvm_unreachable("Unknown argument type!");
2272
2273       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2274       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2275
2276       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2277       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2278       // right size.
2279       if (VA.getLocInfo() == CCValAssign::SExt)
2280         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2281                                DAG.getValueType(VA.getValVT()));
2282       else if (VA.getLocInfo() == CCValAssign::ZExt)
2283         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2284                                DAG.getValueType(VA.getValVT()));
2285       else if (VA.getLocInfo() == CCValAssign::BCvt)
2286         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2287
2288       if (VA.isExtInLoc()) {
2289         // Handle MMX values passed in XMM regs.
2290         if (RegVT.isVector())
2291           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2292         else
2293           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2294       }
2295     } else {
2296       assert(VA.isMemLoc());
2297       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2298     }
2299
2300     // If value is passed via pointer - do a load.
2301     if (VA.getLocInfo() == CCValAssign::Indirect)
2302       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2303                              MachinePointerInfo(), false, false, false, 0);
2304
2305     InVals.push_back(ArgValue);
2306   }
2307
2308   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2309     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310       // The x86-64 ABIs require that for returning structs by value we copy
2311       // the sret argument into %rax/%eax (depending on ABI) for the return.
2312       // Win32 requires us to put the sret argument to %eax as well.
2313       // Save the argument into a virtual register so that we can access it
2314       // from the return points.
2315       if (Ins[i].Flags.isSRet()) {
2316         unsigned Reg = FuncInfo->getSRetReturnReg();
2317         if (!Reg) {
2318           MVT PtrTy = getPointerTy();
2319           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2320           FuncInfo->setSRetReturnReg(Reg);
2321         }
2322         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2323         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2324         break;
2325       }
2326     }
2327   }
2328
2329   unsigned StackSize = CCInfo.getNextStackOffset();
2330   // Align stack specially for tail calls.
2331   if (FuncIsMadeTailCallSafe(CallConv,
2332                              MF.getTarget().Options.GuaranteedTailCallOpt))
2333     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2334
2335   // If the function takes variable number of arguments, make a frame index for
2336   // the start of the first vararg value... for expansion of llvm.va_start.
2337   if (isVarArg) {
2338     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2339                     CallConv != CallingConv::X86_ThisCall)) {
2340       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2341     }
2342     if (Is64Bit) {
2343       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2344
2345       // FIXME: We should really autogenerate these arrays
2346       static const MCPhysReg GPR64ArgRegsWin64[] = {
2347         X86::RCX, X86::RDX, X86::R8,  X86::R9
2348       };
2349       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2350         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2351       };
2352       static const MCPhysReg XMMArgRegs64Bit[] = {
2353         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2354         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2355       };
2356       const MCPhysReg *GPR64ArgRegs;
2357       unsigned NumXMMRegs = 0;
2358
2359       if (IsWin64) {
2360         // The XMM registers which might contain var arg parameters are shadowed
2361         // in their paired GPR.  So we only need to save the GPR to their home
2362         // slots.
2363         TotalNumIntRegs = 4;
2364         GPR64ArgRegs = GPR64ArgRegsWin64;
2365       } else {
2366         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2367         GPR64ArgRegs = GPR64ArgRegs64Bit;
2368
2369         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2370                                                 TotalNumXMMRegs);
2371       }
2372       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2373                                                        TotalNumIntRegs);
2374
2375       bool NoImplicitFloatOps = Fn->getAttributes().
2376         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2377       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2378              "SSE register cannot be used when SSE is disabled!");
2379       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2380                NoImplicitFloatOps) &&
2381              "SSE register cannot be used when SSE is disabled!");
2382       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2383           !Subtarget->hasSSE1())
2384         // Kernel mode asks for SSE to be disabled, so don't push them
2385         // on the stack.
2386         TotalNumXMMRegs = 0;
2387
2388       if (IsWin64) {
2389         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2390         // Get to the caller-allocated home save location.  Add 8 to account
2391         // for the return address.
2392         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2393         FuncInfo->setRegSaveFrameIndex(
2394           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2395         // Fixup to set vararg frame on shadow area (4 x i64).
2396         if (NumIntRegs < 4)
2397           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2398       } else {
2399         // For X86-64, if there are vararg parameters that are passed via
2400         // registers, then we must store them to their spots on the stack so
2401         // they may be loaded by deferencing the result of va_next.
2402         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2403         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2404         FuncInfo->setRegSaveFrameIndex(
2405           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2406                                false));
2407       }
2408
2409       // Store the integer parameter registers.
2410       SmallVector<SDValue, 8> MemOps;
2411       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2412                                         getPointerTy());
2413       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2414       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2415         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2416                                   DAG.getIntPtrConstant(Offset));
2417         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2418                                      &X86::GR64RegClass);
2419         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2420         SDValue Store =
2421           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2422                        MachinePointerInfo::getFixedStack(
2423                          FuncInfo->getRegSaveFrameIndex(), Offset),
2424                        false, false, 0);
2425         MemOps.push_back(Store);
2426         Offset += 8;
2427       }
2428
2429       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2430         // Now store the XMM (fp + vector) parameter registers.
2431         SmallVector<SDValue, 11> SaveXMMOps;
2432         SaveXMMOps.push_back(Chain);
2433
2434         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2435         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2436         SaveXMMOps.push_back(ALVal);
2437
2438         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2439                                FuncInfo->getRegSaveFrameIndex()));
2440         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2441                                FuncInfo->getVarArgsFPOffset()));
2442
2443         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2444           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2445                                        &X86::VR128RegClass);
2446           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2447           SaveXMMOps.push_back(Val);
2448         }
2449         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2450                                      MVT::Other, SaveXMMOps));
2451       }
2452
2453       if (!MemOps.empty())
2454         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2455     }
2456   }
2457
2458   // Some CCs need callee pop.
2459   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2460                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2461     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2462   } else {
2463     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2464     // If this is an sret function, the return should pop the hidden pointer.
2465     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2466         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2467         argsAreStructReturn(Ins) == StackStructReturn)
2468       FuncInfo->setBytesToPopOnReturn(4);
2469   }
2470
2471   if (!Is64Bit) {
2472     // RegSaveFrameIndex is X86-64 only.
2473     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2474     if (CallConv == CallingConv::X86_FastCall ||
2475         CallConv == CallingConv::X86_ThisCall)
2476       // fastcc functions can't have varargs.
2477       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2478   }
2479
2480   FuncInfo->setArgumentStackSize(StackSize);
2481
2482   return Chain;
2483 }
2484
2485 SDValue
2486 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2487                                     SDValue StackPtr, SDValue Arg,
2488                                     SDLoc dl, SelectionDAG &DAG,
2489                                     const CCValAssign &VA,
2490                                     ISD::ArgFlagsTy Flags) const {
2491   unsigned LocMemOffset = VA.getLocMemOffset();
2492   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2493   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2494   if (Flags.isByVal())
2495     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2496
2497   return DAG.getStore(Chain, dl, Arg, PtrOff,
2498                       MachinePointerInfo::getStack(LocMemOffset),
2499                       false, false, 0);
2500 }
2501
2502 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2503 /// optimization is performed and it is required.
2504 SDValue
2505 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2506                                            SDValue &OutRetAddr, SDValue Chain,
2507                                            bool IsTailCall, bool Is64Bit,
2508                                            int FPDiff, SDLoc dl) const {
2509   // Adjust the Return address stack slot.
2510   EVT VT = getPointerTy();
2511   OutRetAddr = getReturnAddressFrameIndex(DAG);
2512
2513   // Load the "old" Return address.
2514   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2515                            false, false, false, 0);
2516   return SDValue(OutRetAddr.getNode(), 1);
2517 }
2518
2519 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2520 /// optimization is performed and it is required (FPDiff!=0).
2521 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2522                                         SDValue Chain, SDValue RetAddrFrIdx,
2523                                         EVT PtrVT, unsigned SlotSize,
2524                                         int FPDiff, SDLoc dl) {
2525   // Store the return address to the appropriate stack slot.
2526   if (!FPDiff) return Chain;
2527   // Calculate the new stack slot for the return address.
2528   int NewReturnAddrFI =
2529     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2530                                          false);
2531   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2532   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2533                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2534                        false, false, 0);
2535   return Chain;
2536 }
2537
2538 SDValue
2539 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2540                              SmallVectorImpl<SDValue> &InVals) const {
2541   SelectionDAG &DAG                     = CLI.DAG;
2542   SDLoc &dl                             = CLI.DL;
2543   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2544   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2545   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2546   SDValue Chain                         = CLI.Chain;
2547   SDValue Callee                        = CLI.Callee;
2548   CallingConv::ID CallConv              = CLI.CallConv;
2549   bool &isTailCall                      = CLI.IsTailCall;
2550   bool isVarArg                         = CLI.IsVarArg;
2551
2552   MachineFunction &MF = DAG.getMachineFunction();
2553   bool Is64Bit        = Subtarget->is64Bit();
2554   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2555   StructReturnType SR = callIsStructReturn(Outs);
2556   bool IsSibcall      = false;
2557
2558   if (MF.getTarget().Options.DisableTailCalls)
2559     isTailCall = false;
2560
2561   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2562   if (IsMustTail) {
2563     // Force this to be a tail call.  The verifier rules are enough to ensure
2564     // that we can lower this successfully without moving the return address
2565     // around.
2566     isTailCall = true;
2567   } else if (isTailCall) {
2568     // Check if it's really possible to do a tail call.
2569     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2570                     isVarArg, SR != NotStructReturn,
2571                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2572                     Outs, OutVals, Ins, DAG);
2573
2574     // Sibcalls are automatically detected tailcalls which do not require
2575     // ABI changes.
2576     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2577       IsSibcall = true;
2578
2579     if (isTailCall)
2580       ++NumTailCalls;
2581   }
2582
2583   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2584          "Var args not supported with calling convention fastcc, ghc or hipe");
2585
2586   // Analyze operands of the call, assigning locations to each operand.
2587   SmallVector<CCValAssign, 16> ArgLocs;
2588   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2589                  ArgLocs, *DAG.getContext());
2590
2591   // Allocate shadow area for Win64
2592   if (IsWin64)
2593     CCInfo.AllocateStack(32, 8);
2594
2595   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2596
2597   // Get a count of how many bytes are to be pushed on the stack.
2598   unsigned NumBytes = CCInfo.getNextStackOffset();
2599   if (IsSibcall)
2600     // This is a sibcall. The memory operands are available in caller's
2601     // own caller's stack.
2602     NumBytes = 0;
2603   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2604            IsTailCallConvention(CallConv))
2605     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2606
2607   int FPDiff = 0;
2608   if (isTailCall && !IsSibcall && !IsMustTail) {
2609     // Lower arguments at fp - stackoffset + fpdiff.
2610     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2611     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2612
2613     FPDiff = NumBytesCallerPushed - NumBytes;
2614
2615     // Set the delta of movement of the returnaddr stackslot.
2616     // But only set if delta is greater than previous delta.
2617     if (FPDiff < X86Info->getTCReturnAddrDelta())
2618       X86Info->setTCReturnAddrDelta(FPDiff);
2619   }
2620
2621   unsigned NumBytesToPush = NumBytes;
2622   unsigned NumBytesToPop = NumBytes;
2623
2624   // If we have an inalloca argument, all stack space has already been allocated
2625   // for us and be right at the top of the stack.  We don't support multiple
2626   // arguments passed in memory when using inalloca.
2627   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2628     NumBytesToPush = 0;
2629     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2630            "an inalloca argument must be the only memory argument");
2631   }
2632
2633   if (!IsSibcall)
2634     Chain = DAG.getCALLSEQ_START(
2635         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2636
2637   SDValue RetAddrFrIdx;
2638   // Load return address for tail calls.
2639   if (isTailCall && FPDiff)
2640     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2641                                     Is64Bit, FPDiff, dl);
2642
2643   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2644   SmallVector<SDValue, 8> MemOpChains;
2645   SDValue StackPtr;
2646
2647   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2648   // of tail call optimization arguments are handle later.
2649   const X86RegisterInfo *RegInfo =
2650     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2651   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2652     // Skip inalloca arguments, they have already been written.
2653     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2654     if (Flags.isInAlloca())
2655       continue;
2656
2657     CCValAssign &VA = ArgLocs[i];
2658     EVT RegVT = VA.getLocVT();
2659     SDValue Arg = OutVals[i];
2660     bool isByVal = Flags.isByVal();
2661
2662     // Promote the value if needed.
2663     switch (VA.getLocInfo()) {
2664     default: llvm_unreachable("Unknown loc info!");
2665     case CCValAssign::Full: break;
2666     case CCValAssign::SExt:
2667       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2668       break;
2669     case CCValAssign::ZExt:
2670       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2671       break;
2672     case CCValAssign::AExt:
2673       if (RegVT.is128BitVector()) {
2674         // Special case: passing MMX values in XMM registers.
2675         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2676         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2677         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2678       } else
2679         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2680       break;
2681     case CCValAssign::BCvt:
2682       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2683       break;
2684     case CCValAssign::Indirect: {
2685       // Store the argument.
2686       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2687       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2688       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2689                            MachinePointerInfo::getFixedStack(FI),
2690                            false, false, 0);
2691       Arg = SpillSlot;
2692       break;
2693     }
2694     }
2695
2696     if (VA.isRegLoc()) {
2697       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2698       if (isVarArg && IsWin64) {
2699         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2700         // shadow reg if callee is a varargs function.
2701         unsigned ShadowReg = 0;
2702         switch (VA.getLocReg()) {
2703         case X86::XMM0: ShadowReg = X86::RCX; break;
2704         case X86::XMM1: ShadowReg = X86::RDX; break;
2705         case X86::XMM2: ShadowReg = X86::R8; break;
2706         case X86::XMM3: ShadowReg = X86::R9; break;
2707         }
2708         if (ShadowReg)
2709           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2710       }
2711     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2712       assert(VA.isMemLoc());
2713       if (!StackPtr.getNode())
2714         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2715                                       getPointerTy());
2716       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2717                                              dl, DAG, VA, Flags));
2718     }
2719   }
2720
2721   if (!MemOpChains.empty())
2722     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2723
2724   if (Subtarget->isPICStyleGOT()) {
2725     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2726     // GOT pointer.
2727     if (!isTailCall) {
2728       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2729                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2730     } else {
2731       // If we are tail calling and generating PIC/GOT style code load the
2732       // address of the callee into ECX. The value in ecx is used as target of
2733       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2734       // for tail calls on PIC/GOT architectures. Normally we would just put the
2735       // address of GOT into ebx and then call target@PLT. But for tail calls
2736       // ebx would be restored (since ebx is callee saved) before jumping to the
2737       // target@PLT.
2738
2739       // Note: The actual moving to ECX is done further down.
2740       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2741       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2742           !G->getGlobal()->hasProtectedVisibility())
2743         Callee = LowerGlobalAddress(Callee, DAG);
2744       else if (isa<ExternalSymbolSDNode>(Callee))
2745         Callee = LowerExternalSymbol(Callee, DAG);
2746     }
2747   }
2748
2749   if (Is64Bit && isVarArg && !IsWin64) {
2750     // From AMD64 ABI document:
2751     // For calls that may call functions that use varargs or stdargs
2752     // (prototype-less calls or calls to functions containing ellipsis (...) in
2753     // the declaration) %al is used as hidden argument to specify the number
2754     // of SSE registers used. The contents of %al do not need to match exactly
2755     // the number of registers, but must be an ubound on the number of SSE
2756     // registers used and is in the range 0 - 8 inclusive.
2757
2758     // Count the number of XMM registers allocated.
2759     static const MCPhysReg XMMArgRegs[] = {
2760       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2761       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2762     };
2763     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2764     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2765            && "SSE registers cannot be used when SSE is disabled");
2766
2767     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2768                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2769   }
2770
2771   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2772   // don't need this because the eligibility check rejects calls that require
2773   // shuffling arguments passed in memory.
2774   if (!IsSibcall && isTailCall) {
2775     // Force all the incoming stack arguments to be loaded from the stack
2776     // before any new outgoing arguments are stored to the stack, because the
2777     // outgoing stack slots may alias the incoming argument stack slots, and
2778     // the alias isn't otherwise explicit. This is slightly more conservative
2779     // than necessary, because it means that each store effectively depends
2780     // on every argument instead of just those arguments it would clobber.
2781     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2782
2783     SmallVector<SDValue, 8> MemOpChains2;
2784     SDValue FIN;
2785     int FI = 0;
2786     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2787       CCValAssign &VA = ArgLocs[i];
2788       if (VA.isRegLoc())
2789         continue;
2790       assert(VA.isMemLoc());
2791       SDValue Arg = OutVals[i];
2792       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2793       // Skip inalloca arguments.  They don't require any work.
2794       if (Flags.isInAlloca())
2795         continue;
2796       // Create frame index.
2797       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2798       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2799       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2800       FIN = DAG.getFrameIndex(FI, getPointerTy());
2801
2802       if (Flags.isByVal()) {
2803         // Copy relative to framepointer.
2804         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2805         if (!StackPtr.getNode())
2806           StackPtr = DAG.getCopyFromReg(Chain, dl,
2807                                         RegInfo->getStackRegister(),
2808                                         getPointerTy());
2809         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2810
2811         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2812                                                          ArgChain,
2813                                                          Flags, DAG, dl));
2814       } else {
2815         // Store relative to framepointer.
2816         MemOpChains2.push_back(
2817           DAG.getStore(ArgChain, dl, Arg, FIN,
2818                        MachinePointerInfo::getFixedStack(FI),
2819                        false, false, 0));
2820       }
2821     }
2822
2823     if (!MemOpChains2.empty())
2824       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2825
2826     // Store the return address to the appropriate stack slot.
2827     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2828                                      getPointerTy(), RegInfo->getSlotSize(),
2829                                      FPDiff, dl);
2830   }
2831
2832   // Build a sequence of copy-to-reg nodes chained together with token chain
2833   // and flag operands which copy the outgoing args into registers.
2834   SDValue InFlag;
2835   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2836     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2837                              RegsToPass[i].second, InFlag);
2838     InFlag = Chain.getValue(1);
2839   }
2840
2841   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2842     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2843     // In the 64-bit large code model, we have to make all calls
2844     // through a register, since the call instruction's 32-bit
2845     // pc-relative offset may not be large enough to hold the whole
2846     // address.
2847   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2848     // If the callee is a GlobalAddress node (quite common, every direct call
2849     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2850     // it.
2851
2852     // We should use extra load for direct calls to dllimported functions in
2853     // non-JIT mode.
2854     const GlobalValue *GV = G->getGlobal();
2855     if (!GV->hasDLLImportStorageClass()) {
2856       unsigned char OpFlags = 0;
2857       bool ExtraLoad = false;
2858       unsigned WrapperKind = ISD::DELETED_NODE;
2859
2860       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2861       // external symbols most go through the PLT in PIC mode.  If the symbol
2862       // has hidden or protected visibility, or if it is static or local, then
2863       // we don't need to use the PLT - we can directly call it.
2864       if (Subtarget->isTargetELF() &&
2865           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2866           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2867         OpFlags = X86II::MO_PLT;
2868       } else if (Subtarget->isPICStyleStubAny() &&
2869                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2870                  (!Subtarget->getTargetTriple().isMacOSX() ||
2871                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2872         // PC-relative references to external symbols should go through $stub,
2873         // unless we're building with the leopard linker or later, which
2874         // automatically synthesizes these stubs.
2875         OpFlags = X86II::MO_DARWIN_STUB;
2876       } else if (Subtarget->isPICStyleRIPRel() &&
2877                  isa<Function>(GV) &&
2878                  cast<Function>(GV)->getAttributes().
2879                    hasAttribute(AttributeSet::FunctionIndex,
2880                                 Attribute::NonLazyBind)) {
2881         // If the function is marked as non-lazy, generate an indirect call
2882         // which loads from the GOT directly. This avoids runtime overhead
2883         // at the cost of eager binding (and one extra byte of encoding).
2884         OpFlags = X86II::MO_GOTPCREL;
2885         WrapperKind = X86ISD::WrapperRIP;
2886         ExtraLoad = true;
2887       }
2888
2889       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2890                                           G->getOffset(), OpFlags);
2891
2892       // Add a wrapper if needed.
2893       if (WrapperKind != ISD::DELETED_NODE)
2894         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2895       // Add extra indirection if needed.
2896       if (ExtraLoad)
2897         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2898                              MachinePointerInfo::getGOT(),
2899                              false, false, false, 0);
2900     }
2901   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2902     unsigned char OpFlags = 0;
2903
2904     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2905     // external symbols should go through the PLT.
2906     if (Subtarget->isTargetELF() &&
2907         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2908       OpFlags = X86II::MO_PLT;
2909     } else if (Subtarget->isPICStyleStubAny() &&
2910                (!Subtarget->getTargetTriple().isMacOSX() ||
2911                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2912       // PC-relative references to external symbols should go through $stub,
2913       // unless we're building with the leopard linker or later, which
2914       // automatically synthesizes these stubs.
2915       OpFlags = X86II::MO_DARWIN_STUB;
2916     }
2917
2918     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2919                                          OpFlags);
2920   }
2921
2922   // Returns a chain & a flag for retval copy to use.
2923   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2924   SmallVector<SDValue, 8> Ops;
2925
2926   if (!IsSibcall && isTailCall) {
2927     Chain = DAG.getCALLSEQ_END(Chain,
2928                                DAG.getIntPtrConstant(NumBytesToPop, true),
2929                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2930     InFlag = Chain.getValue(1);
2931   }
2932
2933   Ops.push_back(Chain);
2934   Ops.push_back(Callee);
2935
2936   if (isTailCall)
2937     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2938
2939   // Add argument registers to the end of the list so that they are known live
2940   // into the call.
2941   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2942     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2943                                   RegsToPass[i].second.getValueType()));
2944
2945   // Add a register mask operand representing the call-preserved registers.
2946   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2947   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2948   assert(Mask && "Missing call preserved mask for calling convention");
2949   Ops.push_back(DAG.getRegisterMask(Mask));
2950
2951   if (InFlag.getNode())
2952     Ops.push_back(InFlag);
2953
2954   if (isTailCall) {
2955     // We used to do:
2956     //// If this is the first return lowered for this function, add the regs
2957     //// to the liveout set for the function.
2958     // This isn't right, although it's probably harmless on x86; liveouts
2959     // should be computed from returns not tail calls.  Consider a void
2960     // function making a tail call to a function returning int.
2961     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2962   }
2963
2964   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2965   InFlag = Chain.getValue(1);
2966
2967   // Create the CALLSEQ_END node.
2968   unsigned NumBytesForCalleeToPop;
2969   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2970                        getTargetMachine().Options.GuaranteedTailCallOpt))
2971     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2972   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2973            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2974            SR == StackStructReturn)
2975     // If this is a call to a struct-return function, the callee
2976     // pops the hidden struct pointer, so we have to push it back.
2977     // This is common for Darwin/X86, Linux & Mingw32 targets.
2978     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2979     NumBytesForCalleeToPop = 4;
2980   else
2981     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2982
2983   // Returns a flag for retval copy to use.
2984   if (!IsSibcall) {
2985     Chain = DAG.getCALLSEQ_END(Chain,
2986                                DAG.getIntPtrConstant(NumBytesToPop, true),
2987                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2988                                                      true),
2989                                InFlag, dl);
2990     InFlag = Chain.getValue(1);
2991   }
2992
2993   // Handle result values, copying them out of physregs into vregs that we
2994   // return.
2995   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2996                          Ins, dl, DAG, InVals);
2997 }
2998
2999 //===----------------------------------------------------------------------===//
3000 //                Fast Calling Convention (tail call) implementation
3001 //===----------------------------------------------------------------------===//
3002
3003 //  Like std call, callee cleans arguments, convention except that ECX is
3004 //  reserved for storing the tail called function address. Only 2 registers are
3005 //  free for argument passing (inreg). Tail call optimization is performed
3006 //  provided:
3007 //                * tailcallopt is enabled
3008 //                * caller/callee are fastcc
3009 //  On X86_64 architecture with GOT-style position independent code only local
3010 //  (within module) calls are supported at the moment.
3011 //  To keep the stack aligned according to platform abi the function
3012 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3013 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3014 //  If a tail called function callee has more arguments than the caller the
3015 //  caller needs to make sure that there is room to move the RETADDR to. This is
3016 //  achieved by reserving an area the size of the argument delta right after the
3017 //  original REtADDR, but before the saved framepointer or the spilled registers
3018 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3019 //  stack layout:
3020 //    arg1
3021 //    arg2
3022 //    RETADDR
3023 //    [ new RETADDR
3024 //      move area ]
3025 //    (possible EBP)
3026 //    ESI
3027 //    EDI
3028 //    local1 ..
3029
3030 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3031 /// for a 16 byte align requirement.
3032 unsigned
3033 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3034                                                SelectionDAG& DAG) const {
3035   MachineFunction &MF = DAG.getMachineFunction();
3036   const TargetMachine &TM = MF.getTarget();
3037   const X86RegisterInfo *RegInfo =
3038     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3039   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3040   unsigned StackAlignment = TFI.getStackAlignment();
3041   uint64_t AlignMask = StackAlignment - 1;
3042   int64_t Offset = StackSize;
3043   unsigned SlotSize = RegInfo->getSlotSize();
3044   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3045     // Number smaller than 12 so just add the difference.
3046     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3047   } else {
3048     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3049     Offset = ((~AlignMask) & Offset) + StackAlignment +
3050       (StackAlignment-SlotSize);
3051   }
3052   return Offset;
3053 }
3054
3055 /// MatchingStackOffset - Return true if the given stack call argument is
3056 /// already available in the same position (relatively) of the caller's
3057 /// incoming argument stack.
3058 static
3059 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3060                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3061                          const X86InstrInfo *TII) {
3062   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3063   int FI = INT_MAX;
3064   if (Arg.getOpcode() == ISD::CopyFromReg) {
3065     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3066     if (!TargetRegisterInfo::isVirtualRegister(VR))
3067       return false;
3068     MachineInstr *Def = MRI->getVRegDef(VR);
3069     if (!Def)
3070       return false;
3071     if (!Flags.isByVal()) {
3072       if (!TII->isLoadFromStackSlot(Def, FI))
3073         return false;
3074     } else {
3075       unsigned Opcode = Def->getOpcode();
3076       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3077           Def->getOperand(1).isFI()) {
3078         FI = Def->getOperand(1).getIndex();
3079         Bytes = Flags.getByValSize();
3080       } else
3081         return false;
3082     }
3083   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3084     if (Flags.isByVal())
3085       // ByVal argument is passed in as a pointer but it's now being
3086       // dereferenced. e.g.
3087       // define @foo(%struct.X* %A) {
3088       //   tail call @bar(%struct.X* byval %A)
3089       // }
3090       return false;
3091     SDValue Ptr = Ld->getBasePtr();
3092     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3093     if (!FINode)
3094       return false;
3095     FI = FINode->getIndex();
3096   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3097     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3098     FI = FINode->getIndex();
3099     Bytes = Flags.getByValSize();
3100   } else
3101     return false;
3102
3103   assert(FI != INT_MAX);
3104   if (!MFI->isFixedObjectIndex(FI))
3105     return false;
3106   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3107 }
3108
3109 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3110 /// for tail call optimization. Targets which want to do tail call
3111 /// optimization should implement this function.
3112 bool
3113 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3114                                                      CallingConv::ID CalleeCC,
3115                                                      bool isVarArg,
3116                                                      bool isCalleeStructRet,
3117                                                      bool isCallerStructRet,
3118                                                      Type *RetTy,
3119                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3120                                     const SmallVectorImpl<SDValue> &OutVals,
3121                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3122                                                      SelectionDAG &DAG) const {
3123   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3124     return false;
3125
3126   // If -tailcallopt is specified, make fastcc functions tail-callable.
3127   const MachineFunction &MF = DAG.getMachineFunction();
3128   const Function *CallerF = MF.getFunction();
3129
3130   // If the function return type is x86_fp80 and the callee return type is not,
3131   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3132   // perform a tailcall optimization here.
3133   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3134     return false;
3135
3136   CallingConv::ID CallerCC = CallerF->getCallingConv();
3137   bool CCMatch = CallerCC == CalleeCC;
3138   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3139   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3140
3141   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3142     if (IsTailCallConvention(CalleeCC) && CCMatch)
3143       return true;
3144     return false;
3145   }
3146
3147   // Look for obvious safe cases to perform tail call optimization that do not
3148   // require ABI changes. This is what gcc calls sibcall.
3149
3150   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3151   // emit a special epilogue.
3152   const X86RegisterInfo *RegInfo =
3153     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3154   if (RegInfo->needsStackRealignment(MF))
3155     return false;
3156
3157   // Also avoid sibcall optimization if either caller or callee uses struct
3158   // return semantics.
3159   if (isCalleeStructRet || isCallerStructRet)
3160     return false;
3161
3162   // An stdcall/thiscall caller is expected to clean up its arguments; the
3163   // callee isn't going to do that.
3164   // FIXME: this is more restrictive than needed. We could produce a tailcall
3165   // when the stack adjustment matches. For example, with a thiscall that takes
3166   // only one argument.
3167   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3168                    CallerCC == CallingConv::X86_ThisCall))
3169     return false;
3170
3171   // Do not sibcall optimize vararg calls unless all arguments are passed via
3172   // registers.
3173   if (isVarArg && !Outs.empty()) {
3174
3175     // Optimizing for varargs on Win64 is unlikely to be safe without
3176     // additional testing.
3177     if (IsCalleeWin64 || IsCallerWin64)
3178       return false;
3179
3180     SmallVector<CCValAssign, 16> ArgLocs;
3181     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3182                    getTargetMachine(), ArgLocs, *DAG.getContext());
3183
3184     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3185     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3186       if (!ArgLocs[i].isRegLoc())
3187         return false;
3188   }
3189
3190   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3191   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3192   // this into a sibcall.
3193   bool Unused = false;
3194   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3195     if (!Ins[i].Used) {
3196       Unused = true;
3197       break;
3198     }
3199   }
3200   if (Unused) {
3201     SmallVector<CCValAssign, 16> RVLocs;
3202     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3203                    getTargetMachine(), RVLocs, *DAG.getContext());
3204     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3205     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3206       CCValAssign &VA = RVLocs[i];
3207       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3208         return false;
3209     }
3210   }
3211
3212   // If the calling conventions do not match, then we'd better make sure the
3213   // results are returned in the same way as what the caller expects.
3214   if (!CCMatch) {
3215     SmallVector<CCValAssign, 16> RVLocs1;
3216     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3217                     getTargetMachine(), RVLocs1, *DAG.getContext());
3218     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3219
3220     SmallVector<CCValAssign, 16> RVLocs2;
3221     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3222                     getTargetMachine(), RVLocs2, *DAG.getContext());
3223     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3224
3225     if (RVLocs1.size() != RVLocs2.size())
3226       return false;
3227     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3228       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3229         return false;
3230       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3231         return false;
3232       if (RVLocs1[i].isRegLoc()) {
3233         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3234           return false;
3235       } else {
3236         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3237           return false;
3238       }
3239     }
3240   }
3241
3242   // If the callee takes no arguments then go on to check the results of the
3243   // call.
3244   if (!Outs.empty()) {
3245     // Check if stack adjustment is needed. For now, do not do this if any
3246     // argument is passed on the stack.
3247     SmallVector<CCValAssign, 16> ArgLocs;
3248     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3249                    getTargetMachine(), ArgLocs, *DAG.getContext());
3250
3251     // Allocate shadow area for Win64
3252     if (IsCalleeWin64)
3253       CCInfo.AllocateStack(32, 8);
3254
3255     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3256     if (CCInfo.getNextStackOffset()) {
3257       MachineFunction &MF = DAG.getMachineFunction();
3258       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3259         return false;
3260
3261       // Check if the arguments are already laid out in the right way as
3262       // the caller's fixed stack objects.
3263       MachineFrameInfo *MFI = MF.getFrameInfo();
3264       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3265       const X86InstrInfo *TII =
3266         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3267       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3268         CCValAssign &VA = ArgLocs[i];
3269         SDValue Arg = OutVals[i];
3270         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3271         if (VA.getLocInfo() == CCValAssign::Indirect)
3272           return false;
3273         if (!VA.isRegLoc()) {
3274           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3275                                    MFI, MRI, TII))
3276             return false;
3277         }
3278       }
3279     }
3280
3281     // If the tailcall address may be in a register, then make sure it's
3282     // possible to register allocate for it. In 32-bit, the call address can
3283     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3284     // callee-saved registers are restored. These happen to be the same
3285     // registers used to pass 'inreg' arguments so watch out for those.
3286     if (!Subtarget->is64Bit() &&
3287         ((!isa<GlobalAddressSDNode>(Callee) &&
3288           !isa<ExternalSymbolSDNode>(Callee)) ||
3289          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3290       unsigned NumInRegs = 0;
3291       // In PIC we need an extra register to formulate the address computation
3292       // for the callee.
3293       unsigned MaxInRegs =
3294           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3295
3296       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3297         CCValAssign &VA = ArgLocs[i];
3298         if (!VA.isRegLoc())
3299           continue;
3300         unsigned Reg = VA.getLocReg();
3301         switch (Reg) {
3302         default: break;
3303         case X86::EAX: case X86::EDX: case X86::ECX:
3304           if (++NumInRegs == MaxInRegs)
3305             return false;
3306           break;
3307         }
3308       }
3309     }
3310   }
3311
3312   return true;
3313 }
3314
3315 FastISel *
3316 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3317                                   const TargetLibraryInfo *libInfo) const {
3318   return X86::createFastISel(funcInfo, libInfo);
3319 }
3320
3321 //===----------------------------------------------------------------------===//
3322 //                           Other Lowering Hooks
3323 //===----------------------------------------------------------------------===//
3324
3325 static bool MayFoldLoad(SDValue Op) {
3326   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3327 }
3328
3329 static bool MayFoldIntoStore(SDValue Op) {
3330   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3331 }
3332
3333 static bool isTargetShuffle(unsigned Opcode) {
3334   switch(Opcode) {
3335   default: return false;
3336   case X86ISD::PSHUFD:
3337   case X86ISD::PSHUFHW:
3338   case X86ISD::PSHUFLW:
3339   case X86ISD::SHUFP:
3340   case X86ISD::PALIGNR:
3341   case X86ISD::MOVLHPS:
3342   case X86ISD::MOVLHPD:
3343   case X86ISD::MOVHLPS:
3344   case X86ISD::MOVLPS:
3345   case X86ISD::MOVLPD:
3346   case X86ISD::MOVSHDUP:
3347   case X86ISD::MOVSLDUP:
3348   case X86ISD::MOVDDUP:
3349   case X86ISD::MOVSS:
3350   case X86ISD::MOVSD:
3351   case X86ISD::UNPCKL:
3352   case X86ISD::UNPCKH:
3353   case X86ISD::VPERMILP:
3354   case X86ISD::VPERM2X128:
3355   case X86ISD::VPERMI:
3356     return true;
3357   }
3358 }
3359
3360 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3361                                     SDValue V1, SelectionDAG &DAG) {
3362   switch(Opc) {
3363   default: llvm_unreachable("Unknown x86 shuffle node");
3364   case X86ISD::MOVSHDUP:
3365   case X86ISD::MOVSLDUP:
3366   case X86ISD::MOVDDUP:
3367     return DAG.getNode(Opc, dl, VT, V1);
3368   }
3369 }
3370
3371 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3372                                     SDValue V1, unsigned TargetMask,
3373                                     SelectionDAG &DAG) {
3374   switch(Opc) {
3375   default: llvm_unreachable("Unknown x86 shuffle node");
3376   case X86ISD::PSHUFD:
3377   case X86ISD::PSHUFHW:
3378   case X86ISD::PSHUFLW:
3379   case X86ISD::VPERMILP:
3380   case X86ISD::VPERMI:
3381     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3382   }
3383 }
3384
3385 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3386                                     SDValue V1, SDValue V2, unsigned TargetMask,
3387                                     SelectionDAG &DAG) {
3388   switch(Opc) {
3389   default: llvm_unreachable("Unknown x86 shuffle node");
3390   case X86ISD::PALIGNR:
3391   case X86ISD::SHUFP:
3392   case X86ISD::VPERM2X128:
3393     return DAG.getNode(Opc, dl, VT, V1, V2,
3394                        DAG.getConstant(TargetMask, MVT::i8));
3395   }
3396 }
3397
3398 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3399                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3400   switch(Opc) {
3401   default: llvm_unreachable("Unknown x86 shuffle node");
3402   case X86ISD::MOVLHPS:
3403   case X86ISD::MOVLHPD:
3404   case X86ISD::MOVHLPS:
3405   case X86ISD::MOVLPS:
3406   case X86ISD::MOVLPD:
3407   case X86ISD::MOVSS:
3408   case X86ISD::MOVSD:
3409   case X86ISD::UNPCKL:
3410   case X86ISD::UNPCKH:
3411     return DAG.getNode(Opc, dl, VT, V1, V2);
3412   }
3413 }
3414
3415 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3416   MachineFunction &MF = DAG.getMachineFunction();
3417   const X86RegisterInfo *RegInfo =
3418     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3419   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3420   int ReturnAddrIndex = FuncInfo->getRAIndex();
3421
3422   if (ReturnAddrIndex == 0) {
3423     // Set up a frame object for the return address.
3424     unsigned SlotSize = RegInfo->getSlotSize();
3425     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3426                                                            -(int64_t)SlotSize,
3427                                                            false);
3428     FuncInfo->setRAIndex(ReturnAddrIndex);
3429   }
3430
3431   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3432 }
3433
3434 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3435                                        bool hasSymbolicDisplacement) {
3436   // Offset should fit into 32 bit immediate field.
3437   if (!isInt<32>(Offset))
3438     return false;
3439
3440   // If we don't have a symbolic displacement - we don't have any extra
3441   // restrictions.
3442   if (!hasSymbolicDisplacement)
3443     return true;
3444
3445   // FIXME: Some tweaks might be needed for medium code model.
3446   if (M != CodeModel::Small && M != CodeModel::Kernel)
3447     return false;
3448
3449   // For small code model we assume that latest object is 16MB before end of 31
3450   // bits boundary. We may also accept pretty large negative constants knowing
3451   // that all objects are in the positive half of address space.
3452   if (M == CodeModel::Small && Offset < 16*1024*1024)
3453     return true;
3454
3455   // For kernel code model we know that all object resist in the negative half
3456   // of 32bits address space. We may not accept negative offsets, since they may
3457   // be just off and we may accept pretty large positive ones.
3458   if (M == CodeModel::Kernel && Offset > 0)
3459     return true;
3460
3461   return false;
3462 }
3463
3464 /// isCalleePop - Determines whether the callee is required to pop its
3465 /// own arguments. Callee pop is necessary to support tail calls.
3466 bool X86::isCalleePop(CallingConv::ID CallingConv,
3467                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3468   if (IsVarArg)
3469     return false;
3470
3471   switch (CallingConv) {
3472   default:
3473     return false;
3474   case CallingConv::X86_StdCall:
3475     return !is64Bit;
3476   case CallingConv::X86_FastCall:
3477     return !is64Bit;
3478   case CallingConv::X86_ThisCall:
3479     return !is64Bit;
3480   case CallingConv::Fast:
3481     return TailCallOpt;
3482   case CallingConv::GHC:
3483     return TailCallOpt;
3484   case CallingConv::HiPE:
3485     return TailCallOpt;
3486   }
3487 }
3488
3489 /// \brief Return true if the condition is an unsigned comparison operation.
3490 static bool isX86CCUnsigned(unsigned X86CC) {
3491   switch (X86CC) {
3492   default: llvm_unreachable("Invalid integer condition!");
3493   case X86::COND_E:     return true;
3494   case X86::COND_G:     return false;
3495   case X86::COND_GE:    return false;
3496   case X86::COND_L:     return false;
3497   case X86::COND_LE:    return false;
3498   case X86::COND_NE:    return true;
3499   case X86::COND_B:     return true;
3500   case X86::COND_A:     return true;
3501   case X86::COND_BE:    return true;
3502   case X86::COND_AE:    return true;
3503   }
3504   llvm_unreachable("covered switch fell through?!");
3505 }
3506
3507 /// Convert an integer condition code to an x86 one in the most straightforward
3508 /// way possible, with no optimisation attempt.
3509 static unsigned getSimpleX86IntCC(ISD::CondCode SetCCOpcode) {
3510   switch (SetCCOpcode) {
3511   default: llvm_unreachable("Invalid integer condition!");
3512   case ISD::SETEQ:  return X86::COND_E;
3513   case ISD::SETGT:  return X86::COND_G;
3514   case ISD::SETGE:  return X86::COND_GE;
3515   case ISD::SETLT:  return X86::COND_L;
3516   case ISD::SETLE:  return X86::COND_LE;
3517   case ISD::SETNE:  return X86::COND_NE;
3518   case ISD::SETULT: return X86::COND_B;
3519   case ISD::SETUGT: return X86::COND_A;
3520   case ISD::SETULE: return X86::COND_BE;
3521   case ISD::SETUGE: return X86::COND_AE;
3522   }
3523 }
3524
3525 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3526 /// specific condition code, returning the condition code and the LHS/RHS of the
3527 /// comparison to make.
3528 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3529                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3530   if (!isFP) {
3531     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3532       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3533         // X > -1   -> X == 0, jump !sign.
3534         RHS = DAG.getConstant(0, RHS.getValueType());
3535         return X86::COND_NS;
3536       }
3537       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3538         // X < 0   -> X == 0, jump on sign.
3539         return X86::COND_S;
3540       }
3541       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3542         // X < 1   -> X <= 0
3543         RHS = DAG.getConstant(0, RHS.getValueType());
3544         return X86::COND_LE;
3545       }
3546     }
3547
3548     return getSimpleX86IntCC(SetCCOpcode);
3549   }
3550
3551   // First determine if it is required or is profitable to flip the operands.
3552
3553   // If LHS is a foldable load, but RHS is not, flip the condition.
3554   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3555       !ISD::isNON_EXTLoad(RHS.getNode())) {
3556     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3557     std::swap(LHS, RHS);
3558   }
3559
3560   switch (SetCCOpcode) {
3561   default: break;
3562   case ISD::SETOLT:
3563   case ISD::SETOLE:
3564   case ISD::SETUGT:
3565   case ISD::SETUGE:
3566     std::swap(LHS, RHS);
3567     break;
3568   }
3569
3570   // On a floating point condition, the flags are set as follows:
3571   // ZF  PF  CF   op
3572   //  0 | 0 | 0 | X > Y
3573   //  0 | 0 | 1 | X < Y
3574   //  1 | 0 | 0 | X == Y
3575   //  1 | 1 | 1 | unordered
3576   switch (SetCCOpcode) {
3577   default: llvm_unreachable("Condcode should be pre-legalized away");
3578   case ISD::SETUEQ:
3579   case ISD::SETEQ:   return X86::COND_E;
3580   case ISD::SETOLT:              // flipped
3581   case ISD::SETOGT:
3582   case ISD::SETGT:   return X86::COND_A;
3583   case ISD::SETOLE:              // flipped
3584   case ISD::SETOGE:
3585   case ISD::SETGE:   return X86::COND_AE;
3586   case ISD::SETUGT:              // flipped
3587   case ISD::SETULT:
3588   case ISD::SETLT:   return X86::COND_B;
3589   case ISD::SETUGE:              // flipped
3590   case ISD::SETULE:
3591   case ISD::SETLE:   return X86::COND_BE;
3592   case ISD::SETONE:
3593   case ISD::SETNE:   return X86::COND_NE;
3594   case ISD::SETUO:   return X86::COND_P;
3595   case ISD::SETO:    return X86::COND_NP;
3596   case ISD::SETOEQ:
3597   case ISD::SETUNE:  return X86::COND_INVALID;
3598   }
3599 }
3600
3601 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3602 /// code. Current x86 isa includes the following FP cmov instructions:
3603 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3604 static bool hasFPCMov(unsigned X86CC) {
3605   switch (X86CC) {
3606   default:
3607     return false;
3608   case X86::COND_B:
3609   case X86::COND_BE:
3610   case X86::COND_E:
3611   case X86::COND_P:
3612   case X86::COND_A:
3613   case X86::COND_AE:
3614   case X86::COND_NE:
3615   case X86::COND_NP:
3616     return true;
3617   }
3618 }
3619
3620 /// isFPImmLegal - Returns true if the target can instruction select the
3621 /// specified FP immediate natively. If false, the legalizer will
3622 /// materialize the FP immediate as a load from a constant pool.
3623 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3624   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3625     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3626       return true;
3627   }
3628   return false;
3629 }
3630
3631 /// \brief Returns true if it is beneficial to convert a load of a constant
3632 /// to just the constant itself.
3633 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3634                                                           Type *Ty) const {
3635   assert(Ty->isIntegerTy());
3636
3637   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3638   if (BitSize == 0 || BitSize > 64)
3639     return false;
3640   return true;
3641 }
3642
3643 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3644 /// the specified range (L, H].
3645 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3646   return (Val < 0) || (Val >= Low && Val < Hi);
3647 }
3648
3649 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3650 /// specified value.
3651 static bool isUndefOrEqual(int Val, int CmpVal) {
3652   return (Val < 0 || Val == CmpVal);
3653 }
3654
3655 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3656 /// from position Pos and ending in Pos+Size, falls within the specified
3657 /// sequential range (L, L+Pos]. or is undef.
3658 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3659                                        unsigned Pos, unsigned Size, int Low) {
3660   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3661     if (!isUndefOrEqual(Mask[i], Low))
3662       return false;
3663   return true;
3664 }
3665
3666 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3667 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3668 /// the second operand.
3669 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3670   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3671     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3672   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3673     return (Mask[0] < 2 && Mask[1] < 2);
3674   return false;
3675 }
3676
3677 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3678 /// is suitable for input to PSHUFHW.
3679 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3680   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3681     return false;
3682
3683   // Lower quadword copied in order or undef.
3684   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3685     return false;
3686
3687   // Upper quadword shuffled.
3688   for (unsigned i = 4; i != 8; ++i)
3689     if (!isUndefOrInRange(Mask[i], 4, 8))
3690       return false;
3691
3692   if (VT == MVT::v16i16) {
3693     // Lower quadword copied in order or undef.
3694     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3695       return false;
3696
3697     // Upper quadword shuffled.
3698     for (unsigned i = 12; i != 16; ++i)
3699       if (!isUndefOrInRange(Mask[i], 12, 16))
3700         return false;
3701   }
3702
3703   return true;
3704 }
3705
3706 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3707 /// is suitable for input to PSHUFLW.
3708 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3709   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3710     return false;
3711
3712   // Upper quadword copied in order.
3713   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3714     return false;
3715
3716   // Lower quadword shuffled.
3717   for (unsigned i = 0; i != 4; ++i)
3718     if (!isUndefOrInRange(Mask[i], 0, 4))
3719       return false;
3720
3721   if (VT == MVT::v16i16) {
3722     // Upper quadword copied in order.
3723     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3724       return false;
3725
3726     // Lower quadword shuffled.
3727     for (unsigned i = 8; i != 12; ++i)
3728       if (!isUndefOrInRange(Mask[i], 8, 12))
3729         return false;
3730   }
3731
3732   return true;
3733 }
3734
3735 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3736 /// is suitable for input to PALIGNR.
3737 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3738                           const X86Subtarget *Subtarget) {
3739   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3740       (VT.is256BitVector() && !Subtarget->hasInt256()))
3741     return false;
3742
3743   unsigned NumElts = VT.getVectorNumElements();
3744   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3745   unsigned NumLaneElts = NumElts/NumLanes;
3746
3747   // Do not handle 64-bit element shuffles with palignr.
3748   if (NumLaneElts == 2)
3749     return false;
3750
3751   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3752     unsigned i;
3753     for (i = 0; i != NumLaneElts; ++i) {
3754       if (Mask[i+l] >= 0)
3755         break;
3756     }
3757
3758     // Lane is all undef, go to next lane
3759     if (i == NumLaneElts)
3760       continue;
3761
3762     int Start = Mask[i+l];
3763
3764     // Make sure its in this lane in one of the sources
3765     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3766         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3767       return false;
3768
3769     // If not lane 0, then we must match lane 0
3770     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3771       return false;
3772
3773     // Correct second source to be contiguous with first source
3774     if (Start >= (int)NumElts)
3775       Start -= NumElts - NumLaneElts;
3776
3777     // Make sure we're shifting in the right direction.
3778     if (Start <= (int)(i+l))
3779       return false;
3780
3781     Start -= i;
3782
3783     // Check the rest of the elements to see if they are consecutive.
3784     for (++i; i != NumLaneElts; ++i) {
3785       int Idx = Mask[i+l];
3786
3787       // Make sure its in this lane
3788       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3789           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3790         return false;
3791
3792       // If not lane 0, then we must match lane 0
3793       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3794         return false;
3795
3796       if (Idx >= (int)NumElts)
3797         Idx -= NumElts - NumLaneElts;
3798
3799       if (!isUndefOrEqual(Idx, Start+i))
3800         return false;
3801
3802     }
3803   }
3804
3805   return true;
3806 }
3807
3808 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3809 /// the two vector operands have swapped position.
3810 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3811                                      unsigned NumElems) {
3812   for (unsigned i = 0; i != NumElems; ++i) {
3813     int idx = Mask[i];
3814     if (idx < 0)
3815       continue;
3816     else if (idx < (int)NumElems)
3817       Mask[i] = idx + NumElems;
3818     else
3819       Mask[i] = idx - NumElems;
3820   }
3821 }
3822
3823 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3824 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3825 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3826 /// reverse of what x86 shuffles want.
3827 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3828
3829   unsigned NumElems = VT.getVectorNumElements();
3830   unsigned NumLanes = VT.getSizeInBits()/128;
3831   unsigned NumLaneElems = NumElems/NumLanes;
3832
3833   if (NumLaneElems != 2 && NumLaneElems != 4)
3834     return false;
3835
3836   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3837   bool symetricMaskRequired =
3838     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3839
3840   // VSHUFPSY divides the resulting vector into 4 chunks.
3841   // The sources are also splitted into 4 chunks, and each destination
3842   // chunk must come from a different source chunk.
3843   //
3844   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3845   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3846   //
3847   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3848   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3849   //
3850   // VSHUFPDY divides the resulting vector into 4 chunks.
3851   // The sources are also splitted into 4 chunks, and each destination
3852   // chunk must come from a different source chunk.
3853   //
3854   //  SRC1 =>      X3       X2       X1       X0
3855   //  SRC2 =>      Y3       Y2       Y1       Y0
3856   //
3857   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3858   //
3859   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3860   unsigned HalfLaneElems = NumLaneElems/2;
3861   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3862     for (unsigned i = 0; i != NumLaneElems; ++i) {
3863       int Idx = Mask[i+l];
3864       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3865       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3866         return false;
3867       // For VSHUFPSY, the mask of the second half must be the same as the
3868       // first but with the appropriate offsets. This works in the same way as
3869       // VPERMILPS works with masks.
3870       if (!symetricMaskRequired || Idx < 0)
3871         continue;
3872       if (MaskVal[i] < 0) {
3873         MaskVal[i] = Idx - l;
3874         continue;
3875       }
3876       if ((signed)(Idx - l) != MaskVal[i])
3877         return false;
3878     }
3879   }
3880
3881   return true;
3882 }
3883
3884 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3885 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3886 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3887   if (!VT.is128BitVector())
3888     return false;
3889
3890   unsigned NumElems = VT.getVectorNumElements();
3891
3892   if (NumElems != 4)
3893     return false;
3894
3895   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3896   return isUndefOrEqual(Mask[0], 6) &&
3897          isUndefOrEqual(Mask[1], 7) &&
3898          isUndefOrEqual(Mask[2], 2) &&
3899          isUndefOrEqual(Mask[3], 3);
3900 }
3901
3902 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3903 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3904 /// <2, 3, 2, 3>
3905 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3906   if (!VT.is128BitVector())
3907     return false;
3908
3909   unsigned NumElems = VT.getVectorNumElements();
3910
3911   if (NumElems != 4)
3912     return false;
3913
3914   return isUndefOrEqual(Mask[0], 2) &&
3915          isUndefOrEqual(Mask[1], 3) &&
3916          isUndefOrEqual(Mask[2], 2) &&
3917          isUndefOrEqual(Mask[3], 3);
3918 }
3919
3920 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3921 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3922 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3923   if (!VT.is128BitVector())
3924     return false;
3925
3926   unsigned NumElems = VT.getVectorNumElements();
3927
3928   if (NumElems != 2 && NumElems != 4)
3929     return false;
3930
3931   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3932     if (!isUndefOrEqual(Mask[i], i + NumElems))
3933       return false;
3934
3935   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3936     if (!isUndefOrEqual(Mask[i], i))
3937       return false;
3938
3939   return true;
3940 }
3941
3942 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3943 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3944 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3945   if (!VT.is128BitVector())
3946     return false;
3947
3948   unsigned NumElems = VT.getVectorNumElements();
3949
3950   if (NumElems != 2 && NumElems != 4)
3951     return false;
3952
3953   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3954     if (!isUndefOrEqual(Mask[i], i))
3955       return false;
3956
3957   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3958     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3959       return false;
3960
3961   return true;
3962 }
3963
3964 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3965 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3966 /// i. e: If all but one element come from the same vector.
3967 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3968   // TODO: Deal with AVX's VINSERTPS
3969   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3970     return false;
3971
3972   unsigned CorrectPosV1 = 0;
3973   unsigned CorrectPosV2 = 0;
3974   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3975     if (Mask[i] == -1) {
3976       ++CorrectPosV1;
3977       ++CorrectPosV2;
3978       continue;
3979     }
3980
3981     if (Mask[i] == i)
3982       ++CorrectPosV1;
3983     else if (Mask[i] == i + 4)
3984       ++CorrectPosV2;
3985   }
3986
3987   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3988     // We have 3 elements (undefs count as elements from any vector) from one
3989     // vector, and one from another.
3990     return true;
3991
3992   return false;
3993 }
3994
3995 //
3996 // Some special combinations that can be optimized.
3997 //
3998 static
3999 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4000                                SelectionDAG &DAG) {
4001   MVT VT = SVOp->getSimpleValueType(0);
4002   SDLoc dl(SVOp);
4003
4004   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4005     return SDValue();
4006
4007   ArrayRef<int> Mask = SVOp->getMask();
4008
4009   // These are the special masks that may be optimized.
4010   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4011   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4012   bool MatchEvenMask = true;
4013   bool MatchOddMask  = true;
4014   for (int i=0; i<8; ++i) {
4015     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4016       MatchEvenMask = false;
4017     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4018       MatchOddMask = false;
4019   }
4020
4021   if (!MatchEvenMask && !MatchOddMask)
4022     return SDValue();
4023
4024   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4025
4026   SDValue Op0 = SVOp->getOperand(0);
4027   SDValue Op1 = SVOp->getOperand(1);
4028
4029   if (MatchEvenMask) {
4030     // Shift the second operand right to 32 bits.
4031     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4032     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4033   } else {
4034     // Shift the first operand left to 32 bits.
4035     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4036     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4037   }
4038   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4039   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4040 }
4041
4042 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4043 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4044 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4045                          bool HasInt256, bool V2IsSplat = false) {
4046
4047   assert(VT.getSizeInBits() >= 128 &&
4048          "Unsupported vector type for unpckl");
4049
4050   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4051   unsigned NumLanes;
4052   unsigned NumOf256BitLanes;
4053   unsigned NumElts = VT.getVectorNumElements();
4054   if (VT.is256BitVector()) {
4055     if (NumElts != 4 && NumElts != 8 &&
4056         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4057     return false;
4058     NumLanes = 2;
4059     NumOf256BitLanes = 1;
4060   } else if (VT.is512BitVector()) {
4061     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4062            "Unsupported vector type for unpckh");
4063     NumLanes = 2;
4064     NumOf256BitLanes = 2;
4065   } else {
4066     NumLanes = 1;
4067     NumOf256BitLanes = 1;
4068   }
4069
4070   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4071   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4072
4073   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4074     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4075       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4076         int BitI  = Mask[l256*NumEltsInStride+l+i];
4077         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4078         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4079           return false;
4080         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4081           return false;
4082         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4083           return false;
4084       }
4085     }
4086   }
4087   return true;
4088 }
4089
4090 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4091 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4092 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4093                          bool HasInt256, bool V2IsSplat = false) {
4094   assert(VT.getSizeInBits() >= 128 &&
4095          "Unsupported vector type for unpckh");
4096
4097   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4098   unsigned NumLanes;
4099   unsigned NumOf256BitLanes;
4100   unsigned NumElts = VT.getVectorNumElements();
4101   if (VT.is256BitVector()) {
4102     if (NumElts != 4 && NumElts != 8 &&
4103         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4104     return false;
4105     NumLanes = 2;
4106     NumOf256BitLanes = 1;
4107   } else if (VT.is512BitVector()) {
4108     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4109            "Unsupported vector type for unpckh");
4110     NumLanes = 2;
4111     NumOf256BitLanes = 2;
4112   } else {
4113     NumLanes = 1;
4114     NumOf256BitLanes = 1;
4115   }
4116
4117   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4118   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4119
4120   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4121     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4122       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4123         int BitI  = Mask[l256*NumEltsInStride+l+i];
4124         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4125         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4126           return false;
4127         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4128           return false;
4129         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4130           return false;
4131       }
4132     }
4133   }
4134   return true;
4135 }
4136
4137 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4138 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4139 /// <0, 0, 1, 1>
4140 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4141   unsigned NumElts = VT.getVectorNumElements();
4142   bool Is256BitVec = VT.is256BitVector();
4143
4144   if (VT.is512BitVector())
4145     return false;
4146   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4147          "Unsupported vector type for unpckh");
4148
4149   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4150       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4151     return false;
4152
4153   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4154   // FIXME: Need a better way to get rid of this, there's no latency difference
4155   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4156   // the former later. We should also remove the "_undef" special mask.
4157   if (NumElts == 4 && Is256BitVec)
4158     return false;
4159
4160   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4161   // independently on 128-bit lanes.
4162   unsigned NumLanes = VT.getSizeInBits()/128;
4163   unsigned NumLaneElts = NumElts/NumLanes;
4164
4165   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4166     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4167       int BitI  = Mask[l+i];
4168       int BitI1 = Mask[l+i+1];
4169
4170       if (!isUndefOrEqual(BitI, j))
4171         return false;
4172       if (!isUndefOrEqual(BitI1, j))
4173         return false;
4174     }
4175   }
4176
4177   return true;
4178 }
4179
4180 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4181 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4182 /// <2, 2, 3, 3>
4183 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4184   unsigned NumElts = VT.getVectorNumElements();
4185
4186   if (VT.is512BitVector())
4187     return false;
4188
4189   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4190          "Unsupported vector type for unpckh");
4191
4192   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4193       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4194     return false;
4195
4196   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4197   // independently on 128-bit lanes.
4198   unsigned NumLanes = VT.getSizeInBits()/128;
4199   unsigned NumLaneElts = NumElts/NumLanes;
4200
4201   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4202     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4203       int BitI  = Mask[l+i];
4204       int BitI1 = Mask[l+i+1];
4205       if (!isUndefOrEqual(BitI, j))
4206         return false;
4207       if (!isUndefOrEqual(BitI1, j))
4208         return false;
4209     }
4210   }
4211   return true;
4212 }
4213
4214 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4215 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4216 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4217   if (!VT.is512BitVector())
4218     return false;
4219
4220   unsigned NumElts = VT.getVectorNumElements();
4221   unsigned HalfSize = NumElts/2;
4222   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4223     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4224       *Imm = 1;
4225       return true;
4226     }
4227   }
4228   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4229     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4230       *Imm = 0;
4231       return true;
4232     }
4233   }
4234   return false;
4235 }
4236
4237 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4238 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4239 /// MOVSD, and MOVD, i.e. setting the lowest element.
4240 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4241   if (VT.getVectorElementType().getSizeInBits() < 32)
4242     return false;
4243   if (!VT.is128BitVector())
4244     return false;
4245
4246   unsigned NumElts = VT.getVectorNumElements();
4247
4248   if (!isUndefOrEqual(Mask[0], NumElts))
4249     return false;
4250
4251   for (unsigned i = 1; i != NumElts; ++i)
4252     if (!isUndefOrEqual(Mask[i], i))
4253       return false;
4254
4255   return true;
4256 }
4257
4258 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4259 /// as permutations between 128-bit chunks or halves. As an example: this
4260 /// shuffle bellow:
4261 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4262 /// The first half comes from the second half of V1 and the second half from the
4263 /// the second half of V2.
4264 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4265   if (!HasFp256 || !VT.is256BitVector())
4266     return false;
4267
4268   // The shuffle result is divided into half A and half B. In total the two
4269   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4270   // B must come from C, D, E or F.
4271   unsigned HalfSize = VT.getVectorNumElements()/2;
4272   bool MatchA = false, MatchB = false;
4273
4274   // Check if A comes from one of C, D, E, F.
4275   for (unsigned Half = 0; Half != 4; ++Half) {
4276     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4277       MatchA = true;
4278       break;
4279     }
4280   }
4281
4282   // Check if B comes from one of C, D, E, F.
4283   for (unsigned Half = 0; Half != 4; ++Half) {
4284     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4285       MatchB = true;
4286       break;
4287     }
4288   }
4289
4290   return MatchA && MatchB;
4291 }
4292
4293 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4294 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4295 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4296   MVT VT = SVOp->getSimpleValueType(0);
4297
4298   unsigned HalfSize = VT.getVectorNumElements()/2;
4299
4300   unsigned FstHalf = 0, SndHalf = 0;
4301   for (unsigned i = 0; i < HalfSize; ++i) {
4302     if (SVOp->getMaskElt(i) > 0) {
4303       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4304       break;
4305     }
4306   }
4307   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4308     if (SVOp->getMaskElt(i) > 0) {
4309       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4310       break;
4311     }
4312   }
4313
4314   return (FstHalf | (SndHalf << 4));
4315 }
4316
4317 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4318 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4319   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4320   if (EltSize < 32)
4321     return false;
4322
4323   unsigned NumElts = VT.getVectorNumElements();
4324   Imm8 = 0;
4325   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4326     for (unsigned i = 0; i != NumElts; ++i) {
4327       if (Mask[i] < 0)
4328         continue;
4329       Imm8 |= Mask[i] << (i*2);
4330     }
4331     return true;
4332   }
4333
4334   unsigned LaneSize = 4;
4335   SmallVector<int, 4> MaskVal(LaneSize, -1);
4336
4337   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4338     for (unsigned i = 0; i != LaneSize; ++i) {
4339       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4340         return false;
4341       if (Mask[i+l] < 0)
4342         continue;
4343       if (MaskVal[i] < 0) {
4344         MaskVal[i] = Mask[i+l] - l;
4345         Imm8 |= MaskVal[i] << (i*2);
4346         continue;
4347       }
4348       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4349         return false;
4350     }
4351   }
4352   return true;
4353 }
4354
4355 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4356 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4357 /// Note that VPERMIL mask matching is different depending whether theunderlying
4358 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4359 /// to the same elements of the low, but to the higher half of the source.
4360 /// In VPERMILPD the two lanes could be shuffled independently of each other
4361 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4362 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4363   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4364   if (VT.getSizeInBits() < 256 || EltSize < 32)
4365     return false;
4366   bool symetricMaskRequired = (EltSize == 32);
4367   unsigned NumElts = VT.getVectorNumElements();
4368
4369   unsigned NumLanes = VT.getSizeInBits()/128;
4370   unsigned LaneSize = NumElts/NumLanes;
4371   // 2 or 4 elements in one lane
4372
4373   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4374   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4375     for (unsigned i = 0; i != LaneSize; ++i) {
4376       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4377         return false;
4378       if (symetricMaskRequired) {
4379         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4380           ExpectedMaskVal[i] = Mask[i+l] - l;
4381           continue;
4382         }
4383         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4384           return false;
4385       }
4386     }
4387   }
4388   return true;
4389 }
4390
4391 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4392 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4393 /// element of vector 2 and the other elements to come from vector 1 in order.
4394 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4395                                bool V2IsSplat = false, bool V2IsUndef = false) {
4396   if (!VT.is128BitVector())
4397     return false;
4398
4399   unsigned NumOps = VT.getVectorNumElements();
4400   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4401     return false;
4402
4403   if (!isUndefOrEqual(Mask[0], 0))
4404     return false;
4405
4406   for (unsigned i = 1; i != NumOps; ++i)
4407     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4408           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4409           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4410       return false;
4411
4412   return true;
4413 }
4414
4415 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4416 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4417 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4418 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4419                            const X86Subtarget *Subtarget) {
4420   if (!Subtarget->hasSSE3())
4421     return false;
4422
4423   unsigned NumElems = VT.getVectorNumElements();
4424
4425   if ((VT.is128BitVector() && NumElems != 4) ||
4426       (VT.is256BitVector() && NumElems != 8) ||
4427       (VT.is512BitVector() && NumElems != 16))
4428     return false;
4429
4430   // "i+1" is the value the indexed mask element must have
4431   for (unsigned i = 0; i != NumElems; i += 2)
4432     if (!isUndefOrEqual(Mask[i], i+1) ||
4433         !isUndefOrEqual(Mask[i+1], i+1))
4434       return false;
4435
4436   return true;
4437 }
4438
4439 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4440 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4441 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4442 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4443                            const X86Subtarget *Subtarget) {
4444   if (!Subtarget->hasSSE3())
4445     return false;
4446
4447   unsigned NumElems = VT.getVectorNumElements();
4448
4449   if ((VT.is128BitVector() && NumElems != 4) ||
4450       (VT.is256BitVector() && NumElems != 8) ||
4451       (VT.is512BitVector() && NumElems != 16))
4452     return false;
4453
4454   // "i" is the value the indexed mask element must have
4455   for (unsigned i = 0; i != NumElems; i += 2)
4456     if (!isUndefOrEqual(Mask[i], i) ||
4457         !isUndefOrEqual(Mask[i+1], i))
4458       return false;
4459
4460   return true;
4461 }
4462
4463 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4464 /// specifies a shuffle of elements that is suitable for input to 256-bit
4465 /// version of MOVDDUP.
4466 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4467   if (!HasFp256 || !VT.is256BitVector())
4468     return false;
4469
4470   unsigned NumElts = VT.getVectorNumElements();
4471   if (NumElts != 4)
4472     return false;
4473
4474   for (unsigned i = 0; i != NumElts/2; ++i)
4475     if (!isUndefOrEqual(Mask[i], 0))
4476       return false;
4477   for (unsigned i = NumElts/2; i != NumElts; ++i)
4478     if (!isUndefOrEqual(Mask[i], NumElts/2))
4479       return false;
4480   return true;
4481 }
4482
4483 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4484 /// specifies a shuffle of elements that is suitable for input to 128-bit
4485 /// version of MOVDDUP.
4486 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4487   if (!VT.is128BitVector())
4488     return false;
4489
4490   unsigned e = VT.getVectorNumElements() / 2;
4491   for (unsigned i = 0; i != e; ++i)
4492     if (!isUndefOrEqual(Mask[i], i))
4493       return false;
4494   for (unsigned i = 0; i != e; ++i)
4495     if (!isUndefOrEqual(Mask[e+i], i))
4496       return false;
4497   return true;
4498 }
4499
4500 /// isVEXTRACTIndex - Return true if the specified
4501 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4502 /// suitable for instruction that extract 128 or 256 bit vectors
4503 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4504   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4505   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4506     return false;
4507
4508   // The index should be aligned on a vecWidth-bit boundary.
4509   uint64_t Index =
4510     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4511
4512   MVT VT = N->getSimpleValueType(0);
4513   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4514   bool Result = (Index * ElSize) % vecWidth == 0;
4515
4516   return Result;
4517 }
4518
4519 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4520 /// operand specifies a subvector insert that is suitable for input to
4521 /// insertion of 128 or 256-bit subvectors
4522 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4523   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4524   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4525     return false;
4526   // The index should be aligned on a vecWidth-bit boundary.
4527   uint64_t Index =
4528     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4529
4530   MVT VT = N->getSimpleValueType(0);
4531   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4532   bool Result = (Index * ElSize) % vecWidth == 0;
4533
4534   return Result;
4535 }
4536
4537 bool X86::isVINSERT128Index(SDNode *N) {
4538   return isVINSERTIndex(N, 128);
4539 }
4540
4541 bool X86::isVINSERT256Index(SDNode *N) {
4542   return isVINSERTIndex(N, 256);
4543 }
4544
4545 bool X86::isVEXTRACT128Index(SDNode *N) {
4546   return isVEXTRACTIndex(N, 128);
4547 }
4548
4549 bool X86::isVEXTRACT256Index(SDNode *N) {
4550   return isVEXTRACTIndex(N, 256);
4551 }
4552
4553 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4554 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4555 /// Handles 128-bit and 256-bit.
4556 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4557   MVT VT = N->getSimpleValueType(0);
4558
4559   assert((VT.getSizeInBits() >= 128) &&
4560          "Unsupported vector type for PSHUF/SHUFP");
4561
4562   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4563   // independently on 128-bit lanes.
4564   unsigned NumElts = VT.getVectorNumElements();
4565   unsigned NumLanes = VT.getSizeInBits()/128;
4566   unsigned NumLaneElts = NumElts/NumLanes;
4567
4568   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4569          "Only supports 2, 4 or 8 elements per lane");
4570
4571   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4572   unsigned Mask = 0;
4573   for (unsigned i = 0; i != NumElts; ++i) {
4574     int Elt = N->getMaskElt(i);
4575     if (Elt < 0) continue;
4576     Elt &= NumLaneElts - 1;
4577     unsigned ShAmt = (i << Shift) % 8;
4578     Mask |= Elt << ShAmt;
4579   }
4580
4581   return Mask;
4582 }
4583
4584 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4585 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4586 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4587   MVT VT = N->getSimpleValueType(0);
4588
4589   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4590          "Unsupported vector type for PSHUFHW");
4591
4592   unsigned NumElts = VT.getVectorNumElements();
4593
4594   unsigned Mask = 0;
4595   for (unsigned l = 0; l != NumElts; l += 8) {
4596     // 8 nodes per lane, but we only care about the last 4.
4597     for (unsigned i = 0; i < 4; ++i) {
4598       int Elt = N->getMaskElt(l+i+4);
4599       if (Elt < 0) continue;
4600       Elt &= 0x3; // only 2-bits.
4601       Mask |= Elt << (i * 2);
4602     }
4603   }
4604
4605   return Mask;
4606 }
4607
4608 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4609 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4610 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4611   MVT VT = N->getSimpleValueType(0);
4612
4613   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4614          "Unsupported vector type for PSHUFHW");
4615
4616   unsigned NumElts = VT.getVectorNumElements();
4617
4618   unsigned Mask = 0;
4619   for (unsigned l = 0; l != NumElts; l += 8) {
4620     // 8 nodes per lane, but we only care about the first 4.
4621     for (unsigned i = 0; i < 4; ++i) {
4622       int Elt = N->getMaskElt(l+i);
4623       if (Elt < 0) continue;
4624       Elt &= 0x3; // only 2-bits
4625       Mask |= Elt << (i * 2);
4626     }
4627   }
4628
4629   return Mask;
4630 }
4631
4632 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4633 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4634 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4635   MVT VT = SVOp->getSimpleValueType(0);
4636   unsigned EltSize = VT.is512BitVector() ? 1 :
4637     VT.getVectorElementType().getSizeInBits() >> 3;
4638
4639   unsigned NumElts = VT.getVectorNumElements();
4640   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4641   unsigned NumLaneElts = NumElts/NumLanes;
4642
4643   int Val = 0;
4644   unsigned i;
4645   for (i = 0; i != NumElts; ++i) {
4646     Val = SVOp->getMaskElt(i);
4647     if (Val >= 0)
4648       break;
4649   }
4650   if (Val >= (int)NumElts)
4651     Val -= NumElts - NumLaneElts;
4652
4653   assert(Val - i > 0 && "PALIGNR imm should be positive");
4654   return (Val - i) * EltSize;
4655 }
4656
4657 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4658   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4659   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4660     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4661
4662   uint64_t Index =
4663     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4664
4665   MVT VecVT = N->getOperand(0).getSimpleValueType();
4666   MVT ElVT = VecVT.getVectorElementType();
4667
4668   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4669   return Index / NumElemsPerChunk;
4670 }
4671
4672 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4673   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4674   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4675     llvm_unreachable("Illegal insert subvector for VINSERT");
4676
4677   uint64_t Index =
4678     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4679
4680   MVT VecVT = N->getSimpleValueType(0);
4681   MVT ElVT = VecVT.getVectorElementType();
4682
4683   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4684   return Index / NumElemsPerChunk;
4685 }
4686
4687 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4688 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4689 /// and VINSERTI128 instructions.
4690 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4691   return getExtractVEXTRACTImmediate(N, 128);
4692 }
4693
4694 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4695 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4696 /// and VINSERTI64x4 instructions.
4697 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4698   return getExtractVEXTRACTImmediate(N, 256);
4699 }
4700
4701 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4702 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4703 /// and VINSERTI128 instructions.
4704 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4705   return getInsertVINSERTImmediate(N, 128);
4706 }
4707
4708 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4709 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4710 /// and VINSERTI64x4 instructions.
4711 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4712   return getInsertVINSERTImmediate(N, 256);
4713 }
4714
4715 /// isZero - Returns true if Elt is a constant integer zero
4716 static bool isZero(SDValue V) {
4717   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4718   return C && C->isNullValue();
4719 }
4720
4721 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4722 /// constant +0.0.
4723 bool X86::isZeroNode(SDValue Elt) {
4724   if (isZero(Elt))
4725     return true;
4726   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4727     return CFP->getValueAPF().isPosZero();
4728   return false;
4729 }
4730
4731 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4732 /// their permute mask.
4733 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4734                                     SelectionDAG &DAG) {
4735   MVT VT = SVOp->getSimpleValueType(0);
4736   unsigned NumElems = VT.getVectorNumElements();
4737   SmallVector<int, 8> MaskVec;
4738
4739   for (unsigned i = 0; i != NumElems; ++i) {
4740     int Idx = SVOp->getMaskElt(i);
4741     if (Idx >= 0) {
4742       if (Idx < (int)NumElems)
4743         Idx += NumElems;
4744       else
4745         Idx -= NumElems;
4746     }
4747     MaskVec.push_back(Idx);
4748   }
4749   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4750                               SVOp->getOperand(0), &MaskVec[0]);
4751 }
4752
4753 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4754 /// match movhlps. The lower half elements should come from upper half of
4755 /// V1 (and in order), and the upper half elements should come from the upper
4756 /// half of V2 (and in order).
4757 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4758   if (!VT.is128BitVector())
4759     return false;
4760   if (VT.getVectorNumElements() != 4)
4761     return false;
4762   for (unsigned i = 0, e = 2; i != e; ++i)
4763     if (!isUndefOrEqual(Mask[i], i+2))
4764       return false;
4765   for (unsigned i = 2; i != 4; ++i)
4766     if (!isUndefOrEqual(Mask[i], i+4))
4767       return false;
4768   return true;
4769 }
4770
4771 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4772 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4773 /// required.
4774 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4775   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4776     return false;
4777   N = N->getOperand(0).getNode();
4778   if (!ISD::isNON_EXTLoad(N))
4779     return false;
4780   if (LD)
4781     *LD = cast<LoadSDNode>(N);
4782   return true;
4783 }
4784
4785 // Test whether the given value is a vector value which will be legalized
4786 // into a load.
4787 static bool WillBeConstantPoolLoad(SDNode *N) {
4788   if (N->getOpcode() != ISD::BUILD_VECTOR)
4789     return false;
4790
4791   // Check for any non-constant elements.
4792   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4793     switch (N->getOperand(i).getNode()->getOpcode()) {
4794     case ISD::UNDEF:
4795     case ISD::ConstantFP:
4796     case ISD::Constant:
4797       break;
4798     default:
4799       return false;
4800     }
4801
4802   // Vectors of all-zeros and all-ones are materialized with special
4803   // instructions rather than being loaded.
4804   return !ISD::isBuildVectorAllZeros(N) &&
4805          !ISD::isBuildVectorAllOnes(N);
4806 }
4807
4808 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4809 /// match movlp{s|d}. The lower half elements should come from lower half of
4810 /// V1 (and in order), and the upper half elements should come from the upper
4811 /// half of V2 (and in order). And since V1 will become the source of the
4812 /// MOVLP, it must be either a vector load or a scalar load to vector.
4813 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4814                                ArrayRef<int> Mask, MVT VT) {
4815   if (!VT.is128BitVector())
4816     return false;
4817
4818   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4819     return false;
4820   // Is V2 is a vector load, don't do this transformation. We will try to use
4821   // load folding shufps op.
4822   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4823     return false;
4824
4825   unsigned NumElems = VT.getVectorNumElements();
4826
4827   if (NumElems != 2 && NumElems != 4)
4828     return false;
4829   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4830     if (!isUndefOrEqual(Mask[i], i))
4831       return false;
4832   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4833     if (!isUndefOrEqual(Mask[i], i+NumElems))
4834       return false;
4835   return true;
4836 }
4837
4838 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4839 /// all the same.
4840 static bool isSplatVector(SDNode *N) {
4841   if (N->getOpcode() != ISD::BUILD_VECTOR)
4842     return false;
4843
4844   SDValue SplatValue = N->getOperand(0);
4845   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4846     if (N->getOperand(i) != SplatValue)
4847       return false;
4848   return true;
4849 }
4850
4851 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4852 /// to an zero vector.
4853 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4854 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4855   SDValue V1 = N->getOperand(0);
4856   SDValue V2 = N->getOperand(1);
4857   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4858   for (unsigned i = 0; i != NumElems; ++i) {
4859     int Idx = N->getMaskElt(i);
4860     if (Idx >= (int)NumElems) {
4861       unsigned Opc = V2.getOpcode();
4862       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4863         continue;
4864       if (Opc != ISD::BUILD_VECTOR ||
4865           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4866         return false;
4867     } else if (Idx >= 0) {
4868       unsigned Opc = V1.getOpcode();
4869       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4870         continue;
4871       if (Opc != ISD::BUILD_VECTOR ||
4872           !X86::isZeroNode(V1.getOperand(Idx)))
4873         return false;
4874     }
4875   }
4876   return true;
4877 }
4878
4879 /// getZeroVector - Returns a vector of specified type with all zero elements.
4880 ///
4881 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4882                              SelectionDAG &DAG, SDLoc dl) {
4883   assert(VT.isVector() && "Expected a vector type");
4884
4885   // Always build SSE zero vectors as <4 x i32> bitcasted
4886   // to their dest type. This ensures they get CSE'd.
4887   SDValue Vec;
4888   if (VT.is128BitVector()) {  // SSE
4889     if (Subtarget->hasSSE2()) {  // SSE2
4890       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4891       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4892     } else { // SSE1
4893       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4894       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4895     }
4896   } else if (VT.is256BitVector()) { // AVX
4897     if (Subtarget->hasInt256()) { // AVX2
4898       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4899       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4900       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4901     } else {
4902       // 256-bit logic and arithmetic instructions in AVX are all
4903       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4904       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4905       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4906       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4907     }
4908   } else if (VT.is512BitVector()) { // AVX-512
4909       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4910       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4911                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4912       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4913   } else if (VT.getScalarType() == MVT::i1) {
4914     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4915     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4916     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4917     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4918   } else
4919     llvm_unreachable("Unexpected vector type");
4920
4921   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4922 }
4923
4924 /// getOnesVector - Returns a vector of specified type with all bits set.
4925 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4926 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4927 /// Then bitcast to their original type, ensuring they get CSE'd.
4928 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4929                              SDLoc dl) {
4930   assert(VT.isVector() && "Expected a vector type");
4931
4932   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4933   SDValue Vec;
4934   if (VT.is256BitVector()) {
4935     if (HasInt256) { // AVX2
4936       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4937       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4938     } else { // AVX
4939       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4940       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4941     }
4942   } else if (VT.is128BitVector()) {
4943     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4944   } else
4945     llvm_unreachable("Unexpected vector type");
4946
4947   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4948 }
4949
4950 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4951 /// that point to V2 points to its first element.
4952 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4953   for (unsigned i = 0; i != NumElems; ++i) {
4954     if (Mask[i] > (int)NumElems) {
4955       Mask[i] = NumElems;
4956     }
4957   }
4958 }
4959
4960 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4961 /// operation of specified width.
4962 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4963                        SDValue V2) {
4964   unsigned NumElems = VT.getVectorNumElements();
4965   SmallVector<int, 8> Mask;
4966   Mask.push_back(NumElems);
4967   for (unsigned i = 1; i != NumElems; ++i)
4968     Mask.push_back(i);
4969   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4970 }
4971
4972 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4973 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4974                           SDValue V2) {
4975   unsigned NumElems = VT.getVectorNumElements();
4976   SmallVector<int, 8> Mask;
4977   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4978     Mask.push_back(i);
4979     Mask.push_back(i + NumElems);
4980   }
4981   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4982 }
4983
4984 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4985 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4986                           SDValue V2) {
4987   unsigned NumElems = VT.getVectorNumElements();
4988   SmallVector<int, 8> Mask;
4989   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4990     Mask.push_back(i + Half);
4991     Mask.push_back(i + NumElems + Half);
4992   }
4993   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4994 }
4995
4996 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4997 // a generic shuffle instruction because the target has no such instructions.
4998 // Generate shuffles which repeat i16 and i8 several times until they can be
4999 // represented by v4f32 and then be manipulated by target suported shuffles.
5000 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5001   MVT VT = V.getSimpleValueType();
5002   int NumElems = VT.getVectorNumElements();
5003   SDLoc dl(V);
5004
5005   while (NumElems > 4) {
5006     if (EltNo < NumElems/2) {
5007       V = getUnpackl(DAG, dl, VT, V, V);
5008     } else {
5009       V = getUnpackh(DAG, dl, VT, V, V);
5010       EltNo -= NumElems/2;
5011     }
5012     NumElems >>= 1;
5013   }
5014   return V;
5015 }
5016
5017 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5018 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5019   MVT VT = V.getSimpleValueType();
5020   SDLoc dl(V);
5021
5022   if (VT.is128BitVector()) {
5023     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5024     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5025     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5026                              &SplatMask[0]);
5027   } else if (VT.is256BitVector()) {
5028     // To use VPERMILPS to splat scalars, the second half of indicies must
5029     // refer to the higher part, which is a duplication of the lower one,
5030     // because VPERMILPS can only handle in-lane permutations.
5031     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5032                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5033
5034     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5035     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5036                              &SplatMask[0]);
5037   } else
5038     llvm_unreachable("Vector size not supported");
5039
5040   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5041 }
5042
5043 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5044 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5045   MVT SrcVT = SV->getSimpleValueType(0);
5046   SDValue V1 = SV->getOperand(0);
5047   SDLoc dl(SV);
5048
5049   int EltNo = SV->getSplatIndex();
5050   int NumElems = SrcVT.getVectorNumElements();
5051   bool Is256BitVec = SrcVT.is256BitVector();
5052
5053   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5054          "Unknown how to promote splat for type");
5055
5056   // Extract the 128-bit part containing the splat element and update
5057   // the splat element index when it refers to the higher register.
5058   if (Is256BitVec) {
5059     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5060     if (EltNo >= NumElems/2)
5061       EltNo -= NumElems/2;
5062   }
5063
5064   // All i16 and i8 vector types can't be used directly by a generic shuffle
5065   // instruction because the target has no such instruction. Generate shuffles
5066   // which repeat i16 and i8 several times until they fit in i32, and then can
5067   // be manipulated by target suported shuffles.
5068   MVT EltVT = SrcVT.getVectorElementType();
5069   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5070     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5071
5072   // Recreate the 256-bit vector and place the same 128-bit vector
5073   // into the low and high part. This is necessary because we want
5074   // to use VPERM* to shuffle the vectors
5075   if (Is256BitVec) {
5076     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5077   }
5078
5079   return getLegalSplat(DAG, V1, EltNo);
5080 }
5081
5082 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5083 /// vector of zero or undef vector.  This produces a shuffle where the low
5084 /// element of V2 is swizzled into the zero/undef vector, landing at element
5085 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5086 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5087                                            bool IsZero,
5088                                            const X86Subtarget *Subtarget,
5089                                            SelectionDAG &DAG) {
5090   MVT VT = V2.getSimpleValueType();
5091   SDValue V1 = IsZero
5092     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5093   unsigned NumElems = VT.getVectorNumElements();
5094   SmallVector<int, 16> MaskVec;
5095   for (unsigned i = 0; i != NumElems; ++i)
5096     // If this is the insertion idx, put the low elt of V2 here.
5097     MaskVec.push_back(i == Idx ? NumElems : i);
5098   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5099 }
5100
5101 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5102 /// target specific opcode. Returns true if the Mask could be calculated.
5103 /// Sets IsUnary to true if only uses one source.
5104 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5105                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5106   unsigned NumElems = VT.getVectorNumElements();
5107   SDValue ImmN;
5108
5109   IsUnary = false;
5110   switch(N->getOpcode()) {
5111   case X86ISD::SHUFP:
5112     ImmN = N->getOperand(N->getNumOperands()-1);
5113     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5114     break;
5115   case X86ISD::UNPCKH:
5116     DecodeUNPCKHMask(VT, Mask);
5117     break;
5118   case X86ISD::UNPCKL:
5119     DecodeUNPCKLMask(VT, Mask);
5120     break;
5121   case X86ISD::MOVHLPS:
5122     DecodeMOVHLPSMask(NumElems, Mask);
5123     break;
5124   case X86ISD::MOVLHPS:
5125     DecodeMOVLHPSMask(NumElems, Mask);
5126     break;
5127   case X86ISD::PALIGNR:
5128     ImmN = N->getOperand(N->getNumOperands()-1);
5129     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5130     break;
5131   case X86ISD::PSHUFD:
5132   case X86ISD::VPERMILP:
5133     ImmN = N->getOperand(N->getNumOperands()-1);
5134     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5135     IsUnary = true;
5136     break;
5137   case X86ISD::PSHUFHW:
5138     ImmN = N->getOperand(N->getNumOperands()-1);
5139     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5140     IsUnary = true;
5141     break;
5142   case X86ISD::PSHUFLW:
5143     ImmN = N->getOperand(N->getNumOperands()-1);
5144     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5145     IsUnary = true;
5146     break;
5147   case X86ISD::VPERMI:
5148     ImmN = N->getOperand(N->getNumOperands()-1);
5149     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5150     IsUnary = true;
5151     break;
5152   case X86ISD::MOVSS:
5153   case X86ISD::MOVSD: {
5154     // The index 0 always comes from the first element of the second source,
5155     // this is why MOVSS and MOVSD are used in the first place. The other
5156     // elements come from the other positions of the first source vector
5157     Mask.push_back(NumElems);
5158     for (unsigned i = 1; i != NumElems; ++i) {
5159       Mask.push_back(i);
5160     }
5161     break;
5162   }
5163   case X86ISD::VPERM2X128:
5164     ImmN = N->getOperand(N->getNumOperands()-1);
5165     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5166     if (Mask.empty()) return false;
5167     break;
5168   case X86ISD::MOVDDUP:
5169   case X86ISD::MOVLHPD:
5170   case X86ISD::MOVLPD:
5171   case X86ISD::MOVLPS:
5172   case X86ISD::MOVSHDUP:
5173   case X86ISD::MOVSLDUP:
5174     // Not yet implemented
5175     return false;
5176   default: llvm_unreachable("unknown target shuffle node");
5177   }
5178
5179   return true;
5180 }
5181
5182 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5183 /// element of the result of the vector shuffle.
5184 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5185                                    unsigned Depth) {
5186   if (Depth == 6)
5187     return SDValue();  // Limit search depth.
5188
5189   SDValue V = SDValue(N, 0);
5190   EVT VT = V.getValueType();
5191   unsigned Opcode = V.getOpcode();
5192
5193   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5194   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5195     int Elt = SV->getMaskElt(Index);
5196
5197     if (Elt < 0)
5198       return DAG.getUNDEF(VT.getVectorElementType());
5199
5200     unsigned NumElems = VT.getVectorNumElements();
5201     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5202                                          : SV->getOperand(1);
5203     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5204   }
5205
5206   // Recurse into target specific vector shuffles to find scalars.
5207   if (isTargetShuffle(Opcode)) {
5208     MVT ShufVT = V.getSimpleValueType();
5209     unsigned NumElems = ShufVT.getVectorNumElements();
5210     SmallVector<int, 16> ShuffleMask;
5211     bool IsUnary;
5212
5213     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5214       return SDValue();
5215
5216     int Elt = ShuffleMask[Index];
5217     if (Elt < 0)
5218       return DAG.getUNDEF(ShufVT.getVectorElementType());
5219
5220     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5221                                          : N->getOperand(1);
5222     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5223                                Depth+1);
5224   }
5225
5226   // Actual nodes that may contain scalar elements
5227   if (Opcode == ISD::BITCAST) {
5228     V = V.getOperand(0);
5229     EVT SrcVT = V.getValueType();
5230     unsigned NumElems = VT.getVectorNumElements();
5231
5232     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5233       return SDValue();
5234   }
5235
5236   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5237     return (Index == 0) ? V.getOperand(0)
5238                         : DAG.getUNDEF(VT.getVectorElementType());
5239
5240   if (V.getOpcode() == ISD::BUILD_VECTOR)
5241     return V.getOperand(Index);
5242
5243   return SDValue();
5244 }
5245
5246 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5247 /// shuffle operation which come from a consecutively from a zero. The
5248 /// search can start in two different directions, from left or right.
5249 /// We count undefs as zeros until PreferredNum is reached.
5250 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5251                                          unsigned NumElems, bool ZerosFromLeft,
5252                                          SelectionDAG &DAG,
5253                                          unsigned PreferredNum = -1U) {
5254   unsigned NumZeros = 0;
5255   for (unsigned i = 0; i != NumElems; ++i) {
5256     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5257     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5258     if (!Elt.getNode())
5259       break;
5260
5261     if (X86::isZeroNode(Elt))
5262       ++NumZeros;
5263     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5264       NumZeros = std::min(NumZeros + 1, PreferredNum);
5265     else
5266       break;
5267   }
5268
5269   return NumZeros;
5270 }
5271
5272 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5273 /// correspond consecutively to elements from one of the vector operands,
5274 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5275 static
5276 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5277                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5278                               unsigned NumElems, unsigned &OpNum) {
5279   bool SeenV1 = false;
5280   bool SeenV2 = false;
5281
5282   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5283     int Idx = SVOp->getMaskElt(i);
5284     // Ignore undef indicies
5285     if (Idx < 0)
5286       continue;
5287
5288     if (Idx < (int)NumElems)
5289       SeenV1 = true;
5290     else
5291       SeenV2 = true;
5292
5293     // Only accept consecutive elements from the same vector
5294     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5295       return false;
5296   }
5297
5298   OpNum = SeenV1 ? 0 : 1;
5299   return true;
5300 }
5301
5302 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5303 /// logical left shift of a vector.
5304 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5305                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5306   unsigned NumElems =
5307     SVOp->getSimpleValueType(0).getVectorNumElements();
5308   unsigned NumZeros = getNumOfConsecutiveZeros(
5309       SVOp, NumElems, false /* check zeros from right */, DAG,
5310       SVOp->getMaskElt(0));
5311   unsigned OpSrc;
5312
5313   if (!NumZeros)
5314     return false;
5315
5316   // Considering the elements in the mask that are not consecutive zeros,
5317   // check if they consecutively come from only one of the source vectors.
5318   //
5319   //               V1 = {X, A, B, C}     0
5320   //                         \  \  \    /
5321   //   vector_shuffle V1, V2 <1, 2, 3, X>
5322   //
5323   if (!isShuffleMaskConsecutive(SVOp,
5324             0,                   // Mask Start Index
5325             NumElems-NumZeros,   // Mask End Index(exclusive)
5326             NumZeros,            // Where to start looking in the src vector
5327             NumElems,            // Number of elements in vector
5328             OpSrc))              // Which source operand ?
5329     return false;
5330
5331   isLeft = false;
5332   ShAmt = NumZeros;
5333   ShVal = SVOp->getOperand(OpSrc);
5334   return true;
5335 }
5336
5337 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5338 /// logical left shift of a vector.
5339 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5340                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5341   unsigned NumElems =
5342     SVOp->getSimpleValueType(0).getVectorNumElements();
5343   unsigned NumZeros = getNumOfConsecutiveZeros(
5344       SVOp, NumElems, true /* check zeros from left */, DAG,
5345       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5346   unsigned OpSrc;
5347
5348   if (!NumZeros)
5349     return false;
5350
5351   // Considering the elements in the mask that are not consecutive zeros,
5352   // check if they consecutively come from only one of the source vectors.
5353   //
5354   //                           0    { A, B, X, X } = V2
5355   //                          / \    /  /
5356   //   vector_shuffle V1, V2 <X, X, 4, 5>
5357   //
5358   if (!isShuffleMaskConsecutive(SVOp,
5359             NumZeros,     // Mask Start Index
5360             NumElems,     // Mask End Index(exclusive)
5361             0,            // Where to start looking in the src vector
5362             NumElems,     // Number of elements in vector
5363             OpSrc))       // Which source operand ?
5364     return false;
5365
5366   isLeft = true;
5367   ShAmt = NumZeros;
5368   ShVal = SVOp->getOperand(OpSrc);
5369   return true;
5370 }
5371
5372 /// isVectorShift - Returns true if the shuffle can be implemented as a
5373 /// logical left or right shift of a vector.
5374 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5375                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5376   // Although the logic below support any bitwidth size, there are no
5377   // shift instructions which handle more than 128-bit vectors.
5378   if (!SVOp->getSimpleValueType(0).is128BitVector())
5379     return false;
5380
5381   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5382       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5383     return true;
5384
5385   return false;
5386 }
5387
5388 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5389 ///
5390 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5391                                        unsigned NumNonZero, unsigned NumZero,
5392                                        SelectionDAG &DAG,
5393                                        const X86Subtarget* Subtarget,
5394                                        const TargetLowering &TLI) {
5395   if (NumNonZero > 8)
5396     return SDValue();
5397
5398   SDLoc dl(Op);
5399   SDValue V;
5400   bool First = true;
5401   for (unsigned i = 0; i < 16; ++i) {
5402     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5403     if (ThisIsNonZero && First) {
5404       if (NumZero)
5405         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5406       else
5407         V = DAG.getUNDEF(MVT::v8i16);
5408       First = false;
5409     }
5410
5411     if ((i & 1) != 0) {
5412       SDValue ThisElt, LastElt;
5413       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5414       if (LastIsNonZero) {
5415         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5416                               MVT::i16, Op.getOperand(i-1));
5417       }
5418       if (ThisIsNonZero) {
5419         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5420         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5421                               ThisElt, DAG.getConstant(8, MVT::i8));
5422         if (LastIsNonZero)
5423           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5424       } else
5425         ThisElt = LastElt;
5426
5427       if (ThisElt.getNode())
5428         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5429                         DAG.getIntPtrConstant(i/2));
5430     }
5431   }
5432
5433   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5434 }
5435
5436 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5437 ///
5438 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5439                                      unsigned NumNonZero, unsigned NumZero,
5440                                      SelectionDAG &DAG,
5441                                      const X86Subtarget* Subtarget,
5442                                      const TargetLowering &TLI) {
5443   if (NumNonZero > 4)
5444     return SDValue();
5445
5446   SDLoc dl(Op);
5447   SDValue V;
5448   bool First = true;
5449   for (unsigned i = 0; i < 8; ++i) {
5450     bool isNonZero = (NonZeros & (1 << i)) != 0;
5451     if (isNonZero) {
5452       if (First) {
5453         if (NumZero)
5454           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5455         else
5456           V = DAG.getUNDEF(MVT::v8i16);
5457         First = false;
5458       }
5459       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5460                       MVT::v8i16, V, Op.getOperand(i),
5461                       DAG.getIntPtrConstant(i));
5462     }
5463   }
5464
5465   return V;
5466 }
5467
5468 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5469 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5470                                      unsigned NonZeros, unsigned NumNonZero,
5471                                      unsigned NumZero, SelectionDAG &DAG,
5472                                      const X86Subtarget *Subtarget,
5473                                      const TargetLowering &TLI) {
5474   // We know there's at least one non-zero element
5475   unsigned FirstNonZeroIdx = 0;
5476   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5477   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5478          X86::isZeroNode(FirstNonZero)) {
5479     ++FirstNonZeroIdx;
5480     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5481   }
5482
5483   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5484       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5485     return SDValue();
5486
5487   SDValue V = FirstNonZero.getOperand(0);
5488   MVT VVT = V.getSimpleValueType();
5489   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5490     return SDValue();
5491
5492   unsigned FirstNonZeroDst =
5493       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5494   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5495   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5496   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5497
5498   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5499     SDValue Elem = Op.getOperand(Idx);
5500     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5501       continue;
5502
5503     // TODO: What else can be here? Deal with it.
5504     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5505       return SDValue();
5506
5507     // TODO: Some optimizations are still possible here
5508     // ex: Getting one element from a vector, and the rest from another.
5509     if (Elem.getOperand(0) != V)
5510       return SDValue();
5511
5512     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5513     if (Dst == Idx)
5514       ++CorrectIdx;
5515     else if (IncorrectIdx == -1U) {
5516       IncorrectIdx = Idx;
5517       IncorrectDst = Dst;
5518     } else
5519       // There was already one element with an incorrect index.
5520       // We can't optimize this case to an insertps.
5521       return SDValue();
5522   }
5523
5524   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5525     SDLoc dl(Op);
5526     EVT VT = Op.getSimpleValueType();
5527     unsigned ElementMoveMask = 0;
5528     if (IncorrectIdx == -1U)
5529       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5530     else
5531       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5532
5533     SDValue InsertpsMask =
5534         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5535     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5536   }
5537
5538   return SDValue();
5539 }
5540
5541 /// getVShift - Return a vector logical shift node.
5542 ///
5543 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5544                          unsigned NumBits, SelectionDAG &DAG,
5545                          const TargetLowering &TLI, SDLoc dl) {
5546   assert(VT.is128BitVector() && "Unknown type for VShift");
5547   EVT ShVT = MVT::v2i64;
5548   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5549   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5550   return DAG.getNode(ISD::BITCAST, dl, VT,
5551                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5552                              DAG.getConstant(NumBits,
5553                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5554 }
5555
5556 static SDValue
5557 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5558
5559   // Check if the scalar load can be widened into a vector load. And if
5560   // the address is "base + cst" see if the cst can be "absorbed" into
5561   // the shuffle mask.
5562   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5563     SDValue Ptr = LD->getBasePtr();
5564     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5565       return SDValue();
5566     EVT PVT = LD->getValueType(0);
5567     if (PVT != MVT::i32 && PVT != MVT::f32)
5568       return SDValue();
5569
5570     int FI = -1;
5571     int64_t Offset = 0;
5572     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5573       FI = FINode->getIndex();
5574       Offset = 0;
5575     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5576                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5577       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5578       Offset = Ptr.getConstantOperandVal(1);
5579       Ptr = Ptr.getOperand(0);
5580     } else {
5581       return SDValue();
5582     }
5583
5584     // FIXME: 256-bit vector instructions don't require a strict alignment,
5585     // improve this code to support it better.
5586     unsigned RequiredAlign = VT.getSizeInBits()/8;
5587     SDValue Chain = LD->getChain();
5588     // Make sure the stack object alignment is at least 16 or 32.
5589     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5590     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5591       if (MFI->isFixedObjectIndex(FI)) {
5592         // Can't change the alignment. FIXME: It's possible to compute
5593         // the exact stack offset and reference FI + adjust offset instead.
5594         // If someone *really* cares about this. That's the way to implement it.
5595         return SDValue();
5596       } else {
5597         MFI->setObjectAlignment(FI, RequiredAlign);
5598       }
5599     }
5600
5601     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5602     // Ptr + (Offset & ~15).
5603     if (Offset < 0)
5604       return SDValue();
5605     if ((Offset % RequiredAlign) & 3)
5606       return SDValue();
5607     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5608     if (StartOffset)
5609       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5610                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5611
5612     int EltNo = (Offset - StartOffset) >> 2;
5613     unsigned NumElems = VT.getVectorNumElements();
5614
5615     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5616     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5617                              LD->getPointerInfo().getWithOffset(StartOffset),
5618                              false, false, false, 0);
5619
5620     SmallVector<int, 8> Mask;
5621     for (unsigned i = 0; i != NumElems; ++i)
5622       Mask.push_back(EltNo);
5623
5624     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5625   }
5626
5627   return SDValue();
5628 }
5629
5630 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5631 /// vector of type 'VT', see if the elements can be replaced by a single large
5632 /// load which has the same value as a build_vector whose operands are 'elts'.
5633 ///
5634 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5635 ///
5636 /// FIXME: we'd also like to handle the case where the last elements are zero
5637 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5638 /// There's even a handy isZeroNode for that purpose.
5639 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5640                                         SDLoc &DL, SelectionDAG &DAG,
5641                                         bool isAfterLegalize) {
5642   EVT EltVT = VT.getVectorElementType();
5643   unsigned NumElems = Elts.size();
5644
5645   LoadSDNode *LDBase = nullptr;
5646   unsigned LastLoadedElt = -1U;
5647
5648   // For each element in the initializer, see if we've found a load or an undef.
5649   // If we don't find an initial load element, or later load elements are
5650   // non-consecutive, bail out.
5651   for (unsigned i = 0; i < NumElems; ++i) {
5652     SDValue Elt = Elts[i];
5653
5654     if (!Elt.getNode() ||
5655         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5656       return SDValue();
5657     if (!LDBase) {
5658       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5659         return SDValue();
5660       LDBase = cast<LoadSDNode>(Elt.getNode());
5661       LastLoadedElt = i;
5662       continue;
5663     }
5664     if (Elt.getOpcode() == ISD::UNDEF)
5665       continue;
5666
5667     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5668     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5669       return SDValue();
5670     LastLoadedElt = i;
5671   }
5672
5673   // If we have found an entire vector of loads and undefs, then return a large
5674   // load of the entire vector width starting at the base pointer.  If we found
5675   // consecutive loads for the low half, generate a vzext_load node.
5676   if (LastLoadedElt == NumElems - 1) {
5677
5678     if (isAfterLegalize &&
5679         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5680       return SDValue();
5681
5682     SDValue NewLd = SDValue();
5683
5684     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5685       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5686                           LDBase->getPointerInfo(),
5687                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5688                           LDBase->isInvariant(), 0);
5689     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5690                         LDBase->getPointerInfo(),
5691                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5692                         LDBase->isInvariant(), LDBase->getAlignment());
5693
5694     if (LDBase->hasAnyUseOfValue(1)) {
5695       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5696                                      SDValue(LDBase, 1),
5697                                      SDValue(NewLd.getNode(), 1));
5698       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5699       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5700                              SDValue(NewLd.getNode(), 1));
5701     }
5702
5703     return NewLd;
5704   }
5705   if (NumElems == 4 && LastLoadedElt == 1 &&
5706       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5707     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5708     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5709     SDValue ResNode =
5710         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5711                                 LDBase->getPointerInfo(),
5712                                 LDBase->getAlignment(),
5713                                 false/*isVolatile*/, true/*ReadMem*/,
5714                                 false/*WriteMem*/);
5715
5716     // Make sure the newly-created LOAD is in the same position as LDBase in
5717     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5718     // update uses of LDBase's output chain to use the TokenFactor.
5719     if (LDBase->hasAnyUseOfValue(1)) {
5720       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5721                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5722       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5723       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5724                              SDValue(ResNode.getNode(), 1));
5725     }
5726
5727     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5728   }
5729   return SDValue();
5730 }
5731
5732 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5733 /// to generate a splat value for the following cases:
5734 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5735 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5736 /// a scalar load, or a constant.
5737 /// The VBROADCAST node is returned when a pattern is found,
5738 /// or SDValue() otherwise.
5739 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5740                                     SelectionDAG &DAG) {
5741   if (!Subtarget->hasFp256())
5742     return SDValue();
5743
5744   MVT VT = Op.getSimpleValueType();
5745   SDLoc dl(Op);
5746
5747   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5748          "Unsupported vector type for broadcast.");
5749
5750   SDValue Ld;
5751   bool ConstSplatVal;
5752
5753   switch (Op.getOpcode()) {
5754     default:
5755       // Unknown pattern found.
5756       return SDValue();
5757
5758     case ISD::BUILD_VECTOR: {
5759       // The BUILD_VECTOR node must be a splat.
5760       if (!isSplatVector(Op.getNode()))
5761         return SDValue();
5762
5763       Ld = Op.getOperand(0);
5764       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5765                      Ld.getOpcode() == ISD::ConstantFP);
5766
5767       // The suspected load node has several users. Make sure that all
5768       // of its users are from the BUILD_VECTOR node.
5769       // Constants may have multiple users.
5770       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5771         return SDValue();
5772       break;
5773     }
5774
5775     case ISD::VECTOR_SHUFFLE: {
5776       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5777
5778       // Shuffles must have a splat mask where the first element is
5779       // broadcasted.
5780       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5781         return SDValue();
5782
5783       SDValue Sc = Op.getOperand(0);
5784       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5785           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5786
5787         if (!Subtarget->hasInt256())
5788           return SDValue();
5789
5790         // Use the register form of the broadcast instruction available on AVX2.
5791         if (VT.getSizeInBits() >= 256)
5792           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5793         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5794       }
5795
5796       Ld = Sc.getOperand(0);
5797       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5798                        Ld.getOpcode() == ISD::ConstantFP);
5799
5800       // The scalar_to_vector node and the suspected
5801       // load node must have exactly one user.
5802       // Constants may have multiple users.
5803
5804       // AVX-512 has register version of the broadcast
5805       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5806         Ld.getValueType().getSizeInBits() >= 32;
5807       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5808           !hasRegVer))
5809         return SDValue();
5810       break;
5811     }
5812   }
5813
5814   bool IsGE256 = (VT.getSizeInBits() >= 256);
5815
5816   // Handle the broadcasting a single constant scalar from the constant pool
5817   // into a vector. On Sandybridge it is still better to load a constant vector
5818   // from the constant pool and not to broadcast it from a scalar.
5819   if (ConstSplatVal && Subtarget->hasInt256()) {
5820     EVT CVT = Ld.getValueType();
5821     assert(!CVT.isVector() && "Must not broadcast a vector type");
5822     unsigned ScalarSize = CVT.getSizeInBits();
5823
5824     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5825       const Constant *C = nullptr;
5826       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5827         C = CI->getConstantIntValue();
5828       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5829         C = CF->getConstantFPValue();
5830
5831       assert(C && "Invalid constant type");
5832
5833       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5834       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5835       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5836       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5837                        MachinePointerInfo::getConstantPool(),
5838                        false, false, false, Alignment);
5839
5840       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5841     }
5842   }
5843
5844   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5845   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5846
5847   // Handle AVX2 in-register broadcasts.
5848   if (!IsLoad && Subtarget->hasInt256() &&
5849       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5850     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5851
5852   // The scalar source must be a normal load.
5853   if (!IsLoad)
5854     return SDValue();
5855
5856   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5857     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5858
5859   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5860   // double since there is no vbroadcastsd xmm
5861   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5862     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5863       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5864   }
5865
5866   // Unsupported broadcast.
5867   return SDValue();
5868 }
5869
5870 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5871 /// underlying vector and index.
5872 ///
5873 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5874 /// index.
5875 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5876                                          SDValue ExtIdx) {
5877   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5878   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5879     return Idx;
5880
5881   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5882   // lowered this:
5883   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5884   // to:
5885   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5886   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5887   //                           undef)
5888   //                       Constant<0>)
5889   // In this case the vector is the extract_subvector expression and the index
5890   // is 2, as specified by the shuffle.
5891   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5892   SDValue ShuffleVec = SVOp->getOperand(0);
5893   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5894   assert(ShuffleVecVT.getVectorElementType() ==
5895          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5896
5897   int ShuffleIdx = SVOp->getMaskElt(Idx);
5898   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5899     ExtractedFromVec = ShuffleVec;
5900     return ShuffleIdx;
5901   }
5902   return Idx;
5903 }
5904
5905 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5906   MVT VT = Op.getSimpleValueType();
5907
5908   // Skip if insert_vec_elt is not supported.
5909   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5910   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5911     return SDValue();
5912
5913   SDLoc DL(Op);
5914   unsigned NumElems = Op.getNumOperands();
5915
5916   SDValue VecIn1;
5917   SDValue VecIn2;
5918   SmallVector<unsigned, 4> InsertIndices;
5919   SmallVector<int, 8> Mask(NumElems, -1);
5920
5921   for (unsigned i = 0; i != NumElems; ++i) {
5922     unsigned Opc = Op.getOperand(i).getOpcode();
5923
5924     if (Opc == ISD::UNDEF)
5925       continue;
5926
5927     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5928       // Quit if more than 1 elements need inserting.
5929       if (InsertIndices.size() > 1)
5930         return SDValue();
5931
5932       InsertIndices.push_back(i);
5933       continue;
5934     }
5935
5936     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5937     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5938     // Quit if non-constant index.
5939     if (!isa<ConstantSDNode>(ExtIdx))
5940       return SDValue();
5941     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5942
5943     // Quit if extracted from vector of different type.
5944     if (ExtractedFromVec.getValueType() != VT)
5945       return SDValue();
5946
5947     if (!VecIn1.getNode())
5948       VecIn1 = ExtractedFromVec;
5949     else if (VecIn1 != ExtractedFromVec) {
5950       if (!VecIn2.getNode())
5951         VecIn2 = ExtractedFromVec;
5952       else if (VecIn2 != ExtractedFromVec)
5953         // Quit if more than 2 vectors to shuffle
5954         return SDValue();
5955     }
5956
5957     if (ExtractedFromVec == VecIn1)
5958       Mask[i] = Idx;
5959     else if (ExtractedFromVec == VecIn2)
5960       Mask[i] = Idx + NumElems;
5961   }
5962
5963   if (!VecIn1.getNode())
5964     return SDValue();
5965
5966   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5967   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5968   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5969     unsigned Idx = InsertIndices[i];
5970     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5971                      DAG.getIntPtrConstant(Idx));
5972   }
5973
5974   return NV;
5975 }
5976
5977 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5978 SDValue
5979 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5980
5981   MVT VT = Op.getSimpleValueType();
5982   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5983          "Unexpected type in LowerBUILD_VECTORvXi1!");
5984
5985   SDLoc dl(Op);
5986   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5987     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5988     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5989     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5990   }
5991
5992   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5993     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5994     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5995     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5996   }
5997
5998   bool AllContants = true;
5999   uint64_t Immediate = 0;
6000   int NonConstIdx = -1;
6001   bool IsSplat = true;
6002   unsigned NumNonConsts = 0;
6003   unsigned NumConsts = 0;
6004   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6005     SDValue In = Op.getOperand(idx);
6006     if (In.getOpcode() == ISD::UNDEF)
6007       continue;
6008     if (!isa<ConstantSDNode>(In)) {
6009       AllContants = false;
6010       NonConstIdx = idx;
6011       NumNonConsts++;
6012     }
6013     else {
6014       NumConsts++;
6015       if (cast<ConstantSDNode>(In)->getZExtValue())
6016       Immediate |= (1ULL << idx);
6017     }
6018     if (In != Op.getOperand(0))
6019       IsSplat = false;
6020   }
6021
6022   if (AllContants) {
6023     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6024       DAG.getConstant(Immediate, MVT::i16));
6025     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6026                        DAG.getIntPtrConstant(0));
6027   }
6028
6029   if (NumNonConsts == 1 && NonConstIdx != 0) {
6030     SDValue DstVec;
6031     if (NumConsts) {
6032       SDValue VecAsImm = DAG.getConstant(Immediate,
6033                                          MVT::getIntegerVT(VT.getSizeInBits()));
6034       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6035     }
6036     else 
6037       DstVec = DAG.getUNDEF(VT);
6038     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6039                        Op.getOperand(NonConstIdx),
6040                        DAG.getIntPtrConstant(NonConstIdx));
6041   }
6042   if (!IsSplat && (NonConstIdx != 0))
6043     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6044   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6045   SDValue Select;
6046   if (IsSplat)
6047     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6048                           DAG.getConstant(-1, SelectVT),
6049                           DAG.getConstant(0, SelectVT));
6050   else
6051     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6052                          DAG.getConstant((Immediate | 1), SelectVT),
6053                          DAG.getConstant(Immediate, SelectVT));
6054   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6055 }
6056
6057 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6058                                           const X86Subtarget *Subtarget) {
6059   EVT VT = N->getValueType(0);
6060
6061   // Try to match a horizontal ADD or SUB.
6062   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) ||
6063       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget->hasAVX()) ||
6064       ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) ||
6065       ((VT == MVT::v8i32 || VT == MVT::v16i16) && Subtarget->hasAVX2())) {
6066     unsigned NumOperands = N->getNumOperands();
6067     unsigned Opcode = N->getOperand(0)->getOpcode();
6068     bool isCommutable = false;
6069     bool CanFold = false;
6070     switch (Opcode) {
6071     default : break;
6072     case ISD::ADD :
6073     case ISD::FADD :
6074       isCommutable = true;
6075       // FALL-THROUGH
6076     case ISD::SUB :
6077     case ISD::FSUB :
6078       CanFold = true;
6079     }
6080
6081     // Verify that operands have the same opcode; also, the opcode can only
6082     // be either of: ADD, FADD, SUB, FSUB.
6083     SDValue InVec0, InVec1;
6084     for (unsigned i = 0, e = NumOperands; i != e && CanFold; ++i) {
6085       SDValue Op = N->getOperand(i);
6086       CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6087
6088       if (!CanFold)
6089         break;
6090
6091       SDValue Op0 = Op.getOperand(0);
6092       SDValue Op1 = Op.getOperand(1);
6093
6094       // Try to match the following pattern:
6095       // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6096       CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6097           Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6098           Op0.getOperand(0) == Op1.getOperand(0) &&
6099           isa<ConstantSDNode>(Op0.getOperand(1)) &&
6100           isa<ConstantSDNode>(Op1.getOperand(1)));
6101       if (!CanFold)
6102         break;
6103
6104       unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6105       unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6106       unsigned ExpectedIndex = (i * 2) % NumOperands;
6107  
6108       if (i == 0)
6109         InVec0 = Op0.getOperand(0);
6110       else if (i * 2 == NumOperands)
6111         InVec1 = Op0.getOperand(0);
6112
6113       SDValue Expected = (i * 2 < NumOperands) ? InVec0 : InVec1;
6114       if (I0 == ExpectedIndex)
6115         CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6116       else if (isCommutable && I1 == ExpectedIndex) {
6117         // Try to see if we can match the following dag sequence:
6118         // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6119         CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6120       }
6121     }
6122
6123     if (CanFold) {
6124       unsigned NewOpcode;
6125       switch (Opcode) {
6126       default : llvm_unreachable("Unexpected opcode found!");
6127       case ISD::ADD : NewOpcode = X86ISD::HADD; break;
6128       case ISD::FADD : NewOpcode = X86ISD::FHADD; break;
6129       case ISD::SUB : NewOpcode = X86ISD::HSUB; break;
6130       case ISD::FSUB : NewOpcode = X86ISD::FHSUB; break;
6131       }
6132  
6133       return DAG.getNode(NewOpcode, SDLoc(N), VT, InVec0, InVec1);
6134     }
6135   }
6136
6137   return SDValue();
6138 }
6139
6140 SDValue
6141 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6142   SDLoc dl(Op);
6143
6144   MVT VT = Op.getSimpleValueType();
6145   MVT ExtVT = VT.getVectorElementType();
6146   unsigned NumElems = Op.getNumOperands();
6147
6148   // Generate vectors for predicate vectors.
6149   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6150     return LowerBUILD_VECTORvXi1(Op, DAG);
6151
6152   // Vectors containing all zeros can be matched by pxor and xorps later
6153   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6154     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6155     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6156     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6157       return Op;
6158
6159     return getZeroVector(VT, Subtarget, DAG, dl);
6160   }
6161
6162   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6163   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6164   // vpcmpeqd on 256-bit vectors.
6165   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6166     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6167       return Op;
6168
6169     if (!VT.is512BitVector())
6170       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6171   }
6172
6173   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6174   if (Broadcast.getNode())
6175     return Broadcast;
6176
6177   unsigned EVTBits = ExtVT.getSizeInBits();
6178
6179   unsigned NumZero  = 0;
6180   unsigned NumNonZero = 0;
6181   unsigned NonZeros = 0;
6182   bool IsAllConstants = true;
6183   SmallSet<SDValue, 8> Values;
6184   for (unsigned i = 0; i < NumElems; ++i) {
6185     SDValue Elt = Op.getOperand(i);
6186     if (Elt.getOpcode() == ISD::UNDEF)
6187       continue;
6188     Values.insert(Elt);
6189     if (Elt.getOpcode() != ISD::Constant &&
6190         Elt.getOpcode() != ISD::ConstantFP)
6191       IsAllConstants = false;
6192     if (X86::isZeroNode(Elt))
6193       NumZero++;
6194     else {
6195       NonZeros |= (1 << i);
6196       NumNonZero++;
6197     }
6198   }
6199
6200   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6201   if (NumNonZero == 0)
6202     return DAG.getUNDEF(VT);
6203
6204   // Special case for single non-zero, non-undef, element.
6205   if (NumNonZero == 1) {
6206     unsigned Idx = countTrailingZeros(NonZeros);
6207     SDValue Item = Op.getOperand(Idx);
6208
6209     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6210     // the value are obviously zero, truncate the value to i32 and do the
6211     // insertion that way.  Only do this if the value is non-constant or if the
6212     // value is a constant being inserted into element 0.  It is cheaper to do
6213     // a constant pool load than it is to do a movd + shuffle.
6214     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6215         (!IsAllConstants || Idx == 0)) {
6216       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6217         // Handle SSE only.
6218         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6219         EVT VecVT = MVT::v4i32;
6220         unsigned VecElts = 4;
6221
6222         // Truncate the value (which may itself be a constant) to i32, and
6223         // convert it to a vector with movd (S2V+shuffle to zero extend).
6224         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6225         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6226         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6227
6228         // Now we have our 32-bit value zero extended in the low element of
6229         // a vector.  If Idx != 0, swizzle it into place.
6230         if (Idx != 0) {
6231           SmallVector<int, 4> Mask;
6232           Mask.push_back(Idx);
6233           for (unsigned i = 1; i != VecElts; ++i)
6234             Mask.push_back(i);
6235           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6236                                       &Mask[0]);
6237         }
6238         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6239       }
6240     }
6241
6242     // If we have a constant or non-constant insertion into the low element of
6243     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6244     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6245     // depending on what the source datatype is.
6246     if (Idx == 0) {
6247       if (NumZero == 0)
6248         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6249
6250       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6251           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6252         if (VT.is256BitVector() || VT.is512BitVector()) {
6253           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6254           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6255                              Item, DAG.getIntPtrConstant(0));
6256         }
6257         assert(VT.is128BitVector() && "Expected an SSE value type!");
6258         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6259         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6260         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6261       }
6262
6263       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6264         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6265         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6266         if (VT.is256BitVector()) {
6267           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6268           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6269         } else {
6270           assert(VT.is128BitVector() && "Expected an SSE value type!");
6271           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6272         }
6273         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6274       }
6275     }
6276
6277     // Is it a vector logical left shift?
6278     if (NumElems == 2 && Idx == 1 &&
6279         X86::isZeroNode(Op.getOperand(0)) &&
6280         !X86::isZeroNode(Op.getOperand(1))) {
6281       unsigned NumBits = VT.getSizeInBits();
6282       return getVShift(true, VT,
6283                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6284                                    VT, Op.getOperand(1)),
6285                        NumBits/2, DAG, *this, dl);
6286     }
6287
6288     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6289       return SDValue();
6290
6291     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6292     // is a non-constant being inserted into an element other than the low one,
6293     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6294     // movd/movss) to move this into the low element, then shuffle it into
6295     // place.
6296     if (EVTBits == 32) {
6297       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6298
6299       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6300       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6301       SmallVector<int, 8> MaskVec;
6302       for (unsigned i = 0; i != NumElems; ++i)
6303         MaskVec.push_back(i == Idx ? 0 : 1);
6304       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6305     }
6306   }
6307
6308   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6309   if (Values.size() == 1) {
6310     if (EVTBits == 32) {
6311       // Instead of a shuffle like this:
6312       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6313       // Check if it's possible to issue this instead.
6314       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6315       unsigned Idx = countTrailingZeros(NonZeros);
6316       SDValue Item = Op.getOperand(Idx);
6317       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6318         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6319     }
6320     return SDValue();
6321   }
6322
6323   // A vector full of immediates; various special cases are already
6324   // handled, so this is best done with a single constant-pool load.
6325   if (IsAllConstants)
6326     return SDValue();
6327
6328   // For AVX-length vectors, build the individual 128-bit pieces and use
6329   // shuffles to put them in place.
6330   if (VT.is256BitVector() || VT.is512BitVector()) {
6331     SmallVector<SDValue, 64> V;
6332     for (unsigned i = 0; i != NumElems; ++i)
6333       V.push_back(Op.getOperand(i));
6334
6335     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6336
6337     // Build both the lower and upper subvector.
6338     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6339                                 makeArrayRef(&V[0], NumElems/2));
6340     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6341                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6342
6343     // Recreate the wider vector with the lower and upper part.
6344     if (VT.is256BitVector())
6345       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6346     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6347   }
6348
6349   // Let legalizer expand 2-wide build_vectors.
6350   if (EVTBits == 64) {
6351     if (NumNonZero == 1) {
6352       // One half is zero or undef.
6353       unsigned Idx = countTrailingZeros(NonZeros);
6354       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6355                                  Op.getOperand(Idx));
6356       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6357     }
6358     return SDValue();
6359   }
6360
6361   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6362   if (EVTBits == 8 && NumElems == 16) {
6363     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6364                                         Subtarget, *this);
6365     if (V.getNode()) return V;
6366   }
6367
6368   if (EVTBits == 16 && NumElems == 8) {
6369     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6370                                       Subtarget, *this);
6371     if (V.getNode()) return V;
6372   }
6373
6374   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6375   if (EVTBits == 32 && NumElems == 4) {
6376     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6377                                       NumZero, DAG, Subtarget, *this);
6378     if (V.getNode())
6379       return V;
6380   }
6381
6382   // If element VT is == 32 bits, turn it into a number of shuffles.
6383   SmallVector<SDValue, 8> V(NumElems);
6384   if (NumElems == 4 && NumZero > 0) {
6385     for (unsigned i = 0; i < 4; ++i) {
6386       bool isZero = !(NonZeros & (1 << i));
6387       if (isZero)
6388         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6389       else
6390         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6391     }
6392
6393     for (unsigned i = 0; i < 2; ++i) {
6394       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6395         default: break;
6396         case 0:
6397           V[i] = V[i*2];  // Must be a zero vector.
6398           break;
6399         case 1:
6400           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6401           break;
6402         case 2:
6403           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6404           break;
6405         case 3:
6406           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6407           break;
6408       }
6409     }
6410
6411     bool Reverse1 = (NonZeros & 0x3) == 2;
6412     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6413     int MaskVec[] = {
6414       Reverse1 ? 1 : 0,
6415       Reverse1 ? 0 : 1,
6416       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6417       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6418     };
6419     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6420   }
6421
6422   if (Values.size() > 1 && VT.is128BitVector()) {
6423     // Check for a build vector of consecutive loads.
6424     for (unsigned i = 0; i < NumElems; ++i)
6425       V[i] = Op.getOperand(i);
6426
6427     // Check for elements which are consecutive loads.
6428     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6429     if (LD.getNode())
6430       return LD;
6431
6432     // Check for a build vector from mostly shuffle plus few inserting.
6433     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6434     if (Sh.getNode())
6435       return Sh;
6436
6437     // For SSE 4.1, use insertps to put the high elements into the low element.
6438     if (getSubtarget()->hasSSE41()) {
6439       SDValue Result;
6440       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6441         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6442       else
6443         Result = DAG.getUNDEF(VT);
6444
6445       for (unsigned i = 1; i < NumElems; ++i) {
6446         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6447         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6448                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6449       }
6450       return Result;
6451     }
6452
6453     // Otherwise, expand into a number of unpckl*, start by extending each of
6454     // our (non-undef) elements to the full vector width with the element in the
6455     // bottom slot of the vector (which generates no code for SSE).
6456     for (unsigned i = 0; i < NumElems; ++i) {
6457       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6458         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6459       else
6460         V[i] = DAG.getUNDEF(VT);
6461     }
6462
6463     // Next, we iteratively mix elements, e.g. for v4f32:
6464     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6465     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6466     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6467     unsigned EltStride = NumElems >> 1;
6468     while (EltStride != 0) {
6469       for (unsigned i = 0; i < EltStride; ++i) {
6470         // If V[i+EltStride] is undef and this is the first round of mixing,
6471         // then it is safe to just drop this shuffle: V[i] is already in the
6472         // right place, the one element (since it's the first round) being
6473         // inserted as undef can be dropped.  This isn't safe for successive
6474         // rounds because they will permute elements within both vectors.
6475         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6476             EltStride == NumElems/2)
6477           continue;
6478
6479         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6480       }
6481       EltStride >>= 1;
6482     }
6483     return V[0];
6484   }
6485   return SDValue();
6486 }
6487
6488 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6489 // to create 256-bit vectors from two other 128-bit ones.
6490 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6491   SDLoc dl(Op);
6492   MVT ResVT = Op.getSimpleValueType();
6493
6494   assert((ResVT.is256BitVector() ||
6495           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6496
6497   SDValue V1 = Op.getOperand(0);
6498   SDValue V2 = Op.getOperand(1);
6499   unsigned NumElems = ResVT.getVectorNumElements();
6500   if(ResVT.is256BitVector())
6501     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6502
6503   if (Op.getNumOperands() == 4) {
6504     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6505                                 ResVT.getVectorNumElements()/2);
6506     SDValue V3 = Op.getOperand(2);
6507     SDValue V4 = Op.getOperand(3);
6508     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6509       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6510   }
6511   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6512 }
6513
6514 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6515   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6516   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6517          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6518           Op.getNumOperands() == 4)));
6519
6520   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6521   // from two other 128-bit ones.
6522
6523   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6524   return LowerAVXCONCAT_VECTORS(Op, DAG);
6525 }
6526
6527 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6528                         bool hasInt256, unsigned *MaskOut = nullptr) {
6529   MVT EltVT = VT.getVectorElementType();
6530
6531   // There is no blend with immediate in AVX-512.
6532   if (VT.is512BitVector())
6533     return false;
6534
6535   if (!hasSSE41 || EltVT == MVT::i8)
6536     return false;
6537   if (!hasInt256 && VT == MVT::v16i16)
6538     return false;
6539
6540   unsigned MaskValue = 0;
6541   unsigned NumElems = VT.getVectorNumElements();
6542   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6543   unsigned NumLanes = (NumElems - 1) / 8 + 1;
6544   unsigned NumElemsInLane = NumElems / NumLanes;
6545
6546   // Blend for v16i16 should be symetric for the both lanes.
6547   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6548
6549     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6550     int EltIdx = MaskVals[i];
6551
6552     if ((EltIdx < 0 || EltIdx == (int)i) &&
6553         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6554       continue;
6555
6556     if (((unsigned)EltIdx == (i + NumElems)) &&
6557         (SndLaneEltIdx < 0 ||
6558          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6559       MaskValue |= (1 << i);
6560     else
6561       return false;
6562   }
6563
6564   if (MaskOut)
6565     *MaskOut = MaskValue;
6566   return true;
6567 }
6568
6569 // Try to lower a shuffle node into a simple blend instruction.
6570 // This function assumes isBlendMask returns true for this
6571 // SuffleVectorSDNode
6572 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6573                                           unsigned MaskValue,
6574                                           const X86Subtarget *Subtarget,
6575                                           SelectionDAG &DAG) {
6576   MVT VT = SVOp->getSimpleValueType(0);
6577   MVT EltVT = VT.getVectorElementType();
6578   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6579                      Subtarget->hasInt256() && "Trying to lower a "
6580                                                "VECTOR_SHUFFLE to a Blend but "
6581                                                "with the wrong mask"));
6582   SDValue V1 = SVOp->getOperand(0);
6583   SDValue V2 = SVOp->getOperand(1);
6584   SDLoc dl(SVOp);
6585   unsigned NumElems = VT.getVectorNumElements();
6586
6587   // Convert i32 vectors to floating point if it is not AVX2.
6588   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6589   MVT BlendVT = VT;
6590   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6591     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6592                                NumElems);
6593     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6594     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6595   }
6596
6597   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6598                             DAG.getConstant(MaskValue, MVT::i32));
6599   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6600 }
6601
6602 /// In vector type \p VT, return true if the element at index \p InputIdx
6603 /// falls on a different 128-bit lane than \p OutputIdx.
6604 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6605                                      unsigned OutputIdx) {
6606   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6607   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6608 }
6609
6610 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6611 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6612 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6613 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6614 /// zero.
6615 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6616                          SelectionDAG &DAG) {
6617   MVT VT = V1.getSimpleValueType();
6618   assert(VT.is128BitVector() || VT.is256BitVector());
6619
6620   MVT EltVT = VT.getVectorElementType();
6621   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6622   unsigned NumElts = VT.getVectorNumElements();
6623
6624   SmallVector<SDValue, 32> PshufbMask;
6625   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6626     int InputIdx = MaskVals[OutputIdx];
6627     unsigned InputByteIdx;
6628
6629     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6630       InputByteIdx = 0x80;
6631     else {
6632       // Cross lane is not allowed.
6633       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6634         return SDValue();
6635       InputByteIdx = InputIdx * EltSizeInBytes;
6636       // Index is an byte offset within the 128-bit lane.
6637       InputByteIdx &= 0xf;
6638     }
6639
6640     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6641       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6642       if (InputByteIdx != 0x80)
6643         ++InputByteIdx;
6644     }
6645   }
6646
6647   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6648   if (ShufVT != VT)
6649     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6650   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6651                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6652 }
6653
6654 // v8i16 shuffles - Prefer shuffles in the following order:
6655 // 1. [all]   pshuflw, pshufhw, optional move
6656 // 2. [ssse3] 1 x pshufb
6657 // 3. [ssse3] 2 x pshufb + 1 x por
6658 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6659 static SDValue
6660 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6661                          SelectionDAG &DAG) {
6662   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6663   SDValue V1 = SVOp->getOperand(0);
6664   SDValue V2 = SVOp->getOperand(1);
6665   SDLoc dl(SVOp);
6666   SmallVector<int, 8> MaskVals;
6667
6668   // Determine if more than 1 of the words in each of the low and high quadwords
6669   // of the result come from the same quadword of one of the two inputs.  Undef
6670   // mask values count as coming from any quadword, for better codegen.
6671   //
6672   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6673   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6674   unsigned LoQuad[] = { 0, 0, 0, 0 };
6675   unsigned HiQuad[] = { 0, 0, 0, 0 };
6676   // Indices of quads used.
6677   std::bitset<4> InputQuads;
6678   for (unsigned i = 0; i < 8; ++i) {
6679     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6680     int EltIdx = SVOp->getMaskElt(i);
6681     MaskVals.push_back(EltIdx);
6682     if (EltIdx < 0) {
6683       ++Quad[0];
6684       ++Quad[1];
6685       ++Quad[2];
6686       ++Quad[3];
6687       continue;
6688     }
6689     ++Quad[EltIdx / 4];
6690     InputQuads.set(EltIdx / 4);
6691   }
6692
6693   int BestLoQuad = -1;
6694   unsigned MaxQuad = 1;
6695   for (unsigned i = 0; i < 4; ++i) {
6696     if (LoQuad[i] > MaxQuad) {
6697       BestLoQuad = i;
6698       MaxQuad = LoQuad[i];
6699     }
6700   }
6701
6702   int BestHiQuad = -1;
6703   MaxQuad = 1;
6704   for (unsigned i = 0; i < 4; ++i) {
6705     if (HiQuad[i] > MaxQuad) {
6706       BestHiQuad = i;
6707       MaxQuad = HiQuad[i];
6708     }
6709   }
6710
6711   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6712   // of the two input vectors, shuffle them into one input vector so only a
6713   // single pshufb instruction is necessary. If there are more than 2 input
6714   // quads, disable the next transformation since it does not help SSSE3.
6715   bool V1Used = InputQuads[0] || InputQuads[1];
6716   bool V2Used = InputQuads[2] || InputQuads[3];
6717   if (Subtarget->hasSSSE3()) {
6718     if (InputQuads.count() == 2 && V1Used && V2Used) {
6719       BestLoQuad = InputQuads[0] ? 0 : 1;
6720       BestHiQuad = InputQuads[2] ? 2 : 3;
6721     }
6722     if (InputQuads.count() > 2) {
6723       BestLoQuad = -1;
6724       BestHiQuad = -1;
6725     }
6726   }
6727
6728   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6729   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6730   // words from all 4 input quadwords.
6731   SDValue NewV;
6732   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6733     int MaskV[] = {
6734       BestLoQuad < 0 ? 0 : BestLoQuad,
6735       BestHiQuad < 0 ? 1 : BestHiQuad
6736     };
6737     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6738                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6739                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6740     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6741
6742     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6743     // source words for the shuffle, to aid later transformations.
6744     bool AllWordsInNewV = true;
6745     bool InOrder[2] = { true, true };
6746     for (unsigned i = 0; i != 8; ++i) {
6747       int idx = MaskVals[i];
6748       if (idx != (int)i)
6749         InOrder[i/4] = false;
6750       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6751         continue;
6752       AllWordsInNewV = false;
6753       break;
6754     }
6755
6756     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6757     if (AllWordsInNewV) {
6758       for (int i = 0; i != 8; ++i) {
6759         int idx = MaskVals[i];
6760         if (idx < 0)
6761           continue;
6762         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6763         if ((idx != i) && idx < 4)
6764           pshufhw = false;
6765         if ((idx != i) && idx > 3)
6766           pshuflw = false;
6767       }
6768       V1 = NewV;
6769       V2Used = false;
6770       BestLoQuad = 0;
6771       BestHiQuad = 1;
6772     }
6773
6774     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6775     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6776     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6777       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6778       unsigned TargetMask = 0;
6779       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6780                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6781       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6782       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6783                              getShufflePSHUFLWImmediate(SVOp);
6784       V1 = NewV.getOperand(0);
6785       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6786     }
6787   }
6788
6789   // Promote splats to a larger type which usually leads to more efficient code.
6790   // FIXME: Is this true if pshufb is available?
6791   if (SVOp->isSplat())
6792     return PromoteSplat(SVOp, DAG);
6793
6794   // If we have SSSE3, and all words of the result are from 1 input vector,
6795   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6796   // is present, fall back to case 4.
6797   if (Subtarget->hasSSSE3()) {
6798     SmallVector<SDValue,16> pshufbMask;
6799
6800     // If we have elements from both input vectors, set the high bit of the
6801     // shuffle mask element to zero out elements that come from V2 in the V1
6802     // mask, and elements that come from V1 in the V2 mask, so that the two
6803     // results can be OR'd together.
6804     bool TwoInputs = V1Used && V2Used;
6805     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6806     if (!TwoInputs)
6807       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6808
6809     // Calculate the shuffle mask for the second input, shuffle it, and
6810     // OR it with the first shuffled input.
6811     CommuteVectorShuffleMask(MaskVals, 8);
6812     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6813     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6814     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6815   }
6816
6817   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6818   // and update MaskVals with new element order.
6819   std::bitset<8> InOrder;
6820   if (BestLoQuad >= 0) {
6821     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6822     for (int i = 0; i != 4; ++i) {
6823       int idx = MaskVals[i];
6824       if (idx < 0) {
6825         InOrder.set(i);
6826       } else if ((idx / 4) == BestLoQuad) {
6827         MaskV[i] = idx & 3;
6828         InOrder.set(i);
6829       }
6830     }
6831     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6832                                 &MaskV[0]);
6833
6834     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6835       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6836       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6837                                   NewV.getOperand(0),
6838                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6839     }
6840   }
6841
6842   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6843   // and update MaskVals with the new element order.
6844   if (BestHiQuad >= 0) {
6845     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6846     for (unsigned i = 4; i != 8; ++i) {
6847       int idx = MaskVals[i];
6848       if (idx < 0) {
6849         InOrder.set(i);
6850       } else if ((idx / 4) == BestHiQuad) {
6851         MaskV[i] = (idx & 3) + 4;
6852         InOrder.set(i);
6853       }
6854     }
6855     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6856                                 &MaskV[0]);
6857
6858     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6859       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6860       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6861                                   NewV.getOperand(0),
6862                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6863     }
6864   }
6865
6866   // In case BestHi & BestLo were both -1, which means each quadword has a word
6867   // from each of the four input quadwords, calculate the InOrder bitvector now
6868   // before falling through to the insert/extract cleanup.
6869   if (BestLoQuad == -1 && BestHiQuad == -1) {
6870     NewV = V1;
6871     for (int i = 0; i != 8; ++i)
6872       if (MaskVals[i] < 0 || MaskVals[i] == i)
6873         InOrder.set(i);
6874   }
6875
6876   // The other elements are put in the right place using pextrw and pinsrw.
6877   for (unsigned i = 0; i != 8; ++i) {
6878     if (InOrder[i])
6879       continue;
6880     int EltIdx = MaskVals[i];
6881     if (EltIdx < 0)
6882       continue;
6883     SDValue ExtOp = (EltIdx < 8) ?
6884       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6885                   DAG.getIntPtrConstant(EltIdx)) :
6886       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6887                   DAG.getIntPtrConstant(EltIdx - 8));
6888     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6889                        DAG.getIntPtrConstant(i));
6890   }
6891   return NewV;
6892 }
6893
6894 /// \brief v16i16 shuffles
6895 ///
6896 /// FIXME: We only support generation of a single pshufb currently.  We can
6897 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6898 /// well (e.g 2 x pshufb + 1 x por).
6899 static SDValue
6900 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6901   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6902   SDValue V1 = SVOp->getOperand(0);
6903   SDValue V2 = SVOp->getOperand(1);
6904   SDLoc dl(SVOp);
6905
6906   if (V2.getOpcode() != ISD::UNDEF)
6907     return SDValue();
6908
6909   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6910   return getPSHUFB(MaskVals, V1, dl, DAG);
6911 }
6912
6913 // v16i8 shuffles - Prefer shuffles in the following order:
6914 // 1. [ssse3] 1 x pshufb
6915 // 2. [ssse3] 2 x pshufb + 1 x por
6916 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6917 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6918                                         const X86Subtarget* Subtarget,
6919                                         SelectionDAG &DAG) {
6920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6921   SDValue V1 = SVOp->getOperand(0);
6922   SDValue V2 = SVOp->getOperand(1);
6923   SDLoc dl(SVOp);
6924   ArrayRef<int> MaskVals = SVOp->getMask();
6925
6926   // Promote splats to a larger type which usually leads to more efficient code.
6927   // FIXME: Is this true if pshufb is available?
6928   if (SVOp->isSplat())
6929     return PromoteSplat(SVOp, DAG);
6930
6931   // If we have SSSE3, case 1 is generated when all result bytes come from
6932   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6933   // present, fall back to case 3.
6934
6935   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6936   if (Subtarget->hasSSSE3()) {
6937     SmallVector<SDValue,16> pshufbMask;
6938
6939     // If all result elements are from one input vector, then only translate
6940     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6941     //
6942     // Otherwise, we have elements from both input vectors, and must zero out
6943     // elements that come from V2 in the first mask, and V1 in the second mask
6944     // so that we can OR them together.
6945     for (unsigned i = 0; i != 16; ++i) {
6946       int EltIdx = MaskVals[i];
6947       if (EltIdx < 0 || EltIdx >= 16)
6948         EltIdx = 0x80;
6949       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6950     }
6951     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6952                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6953                                  MVT::v16i8, pshufbMask));
6954
6955     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6956     // the 2nd operand if it's undefined or zero.
6957     if (V2.getOpcode() == ISD::UNDEF ||
6958         ISD::isBuildVectorAllZeros(V2.getNode()))
6959       return V1;
6960
6961     // Calculate the shuffle mask for the second input, shuffle it, and
6962     // OR it with the first shuffled input.
6963     pshufbMask.clear();
6964     for (unsigned i = 0; i != 16; ++i) {
6965       int EltIdx = MaskVals[i];
6966       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6967       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6968     }
6969     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6970                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6971                                  MVT::v16i8, pshufbMask));
6972     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6973   }
6974
6975   // No SSSE3 - Calculate in place words and then fix all out of place words
6976   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6977   // the 16 different words that comprise the two doublequadword input vectors.
6978   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6979   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6980   SDValue NewV = V1;
6981   for (int i = 0; i != 8; ++i) {
6982     int Elt0 = MaskVals[i*2];
6983     int Elt1 = MaskVals[i*2+1];
6984
6985     // This word of the result is all undef, skip it.
6986     if (Elt0 < 0 && Elt1 < 0)
6987       continue;
6988
6989     // This word of the result is already in the correct place, skip it.
6990     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6991       continue;
6992
6993     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6994     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6995     SDValue InsElt;
6996
6997     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6998     // using a single extract together, load it and store it.
6999     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7000       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7001                            DAG.getIntPtrConstant(Elt1 / 2));
7002       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7003                         DAG.getIntPtrConstant(i));
7004       continue;
7005     }
7006
7007     // If Elt1 is defined, extract it from the appropriate source.  If the
7008     // source byte is not also odd, shift the extracted word left 8 bits
7009     // otherwise clear the bottom 8 bits if we need to do an or.
7010     if (Elt1 >= 0) {
7011       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7012                            DAG.getIntPtrConstant(Elt1 / 2));
7013       if ((Elt1 & 1) == 0)
7014         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7015                              DAG.getConstant(8,
7016                                   TLI.getShiftAmountTy(InsElt.getValueType())));
7017       else if (Elt0 >= 0)
7018         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7019                              DAG.getConstant(0xFF00, MVT::i16));
7020     }
7021     // If Elt0 is defined, extract it from the appropriate source.  If the
7022     // source byte is not also even, shift the extracted word right 8 bits. If
7023     // Elt1 was also defined, OR the extracted values together before
7024     // inserting them in the result.
7025     if (Elt0 >= 0) {
7026       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7027                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7028       if ((Elt0 & 1) != 0)
7029         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7030                               DAG.getConstant(8,
7031                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
7032       else if (Elt1 >= 0)
7033         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7034                              DAG.getConstant(0x00FF, MVT::i16));
7035       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7036                          : InsElt0;
7037     }
7038     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7039                        DAG.getIntPtrConstant(i));
7040   }
7041   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7042 }
7043
7044 // v32i8 shuffles - Translate to VPSHUFB if possible.
7045 static
7046 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7047                                  const X86Subtarget *Subtarget,
7048                                  SelectionDAG &DAG) {
7049   MVT VT = SVOp->getSimpleValueType(0);
7050   SDValue V1 = SVOp->getOperand(0);
7051   SDValue V2 = SVOp->getOperand(1);
7052   SDLoc dl(SVOp);
7053   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7054
7055   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7056   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7057   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7058
7059   // VPSHUFB may be generated if
7060   // (1) one of input vector is undefined or zeroinitializer.
7061   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7062   // And (2) the mask indexes don't cross the 128-bit lane.
7063   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7064       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7065     return SDValue();
7066
7067   if (V1IsAllZero && !V2IsAllZero) {
7068     CommuteVectorShuffleMask(MaskVals, 32);
7069     V1 = V2;
7070   }
7071   return getPSHUFB(MaskVals, V1, dl, DAG);
7072 }
7073
7074 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7075 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7076 /// done when every pair / quad of shuffle mask elements point to elements in
7077 /// the right sequence. e.g.
7078 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7079 static
7080 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7081                                  SelectionDAG &DAG) {
7082   MVT VT = SVOp->getSimpleValueType(0);
7083   SDLoc dl(SVOp);
7084   unsigned NumElems = VT.getVectorNumElements();
7085   MVT NewVT;
7086   unsigned Scale;
7087   switch (VT.SimpleTy) {
7088   default: llvm_unreachable("Unexpected!");
7089   case MVT::v2i64:
7090   case MVT::v2f64:
7091            return SDValue(SVOp, 0);
7092   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
7093   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
7094   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
7095   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
7096   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7097   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
7098   }
7099
7100   SmallVector<int, 8> MaskVec;
7101   for (unsigned i = 0; i != NumElems; i += Scale) {
7102     int StartIdx = -1;
7103     for (unsigned j = 0; j != Scale; ++j) {
7104       int EltIdx = SVOp->getMaskElt(i+j);
7105       if (EltIdx < 0)
7106         continue;
7107       if (StartIdx < 0)
7108         StartIdx = (EltIdx / Scale);
7109       if (EltIdx != (int)(StartIdx*Scale + j))
7110         return SDValue();
7111     }
7112     MaskVec.push_back(StartIdx);
7113   }
7114
7115   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7116   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7117   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7118 }
7119
7120 /// getVZextMovL - Return a zero-extending vector move low node.
7121 ///
7122 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7123                             SDValue SrcOp, SelectionDAG &DAG,
7124                             const X86Subtarget *Subtarget, SDLoc dl) {
7125   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7126     LoadSDNode *LD = nullptr;
7127     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7128       LD = dyn_cast<LoadSDNode>(SrcOp);
7129     if (!LD) {
7130       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7131       // instead.
7132       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7133       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7134           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7135           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7136           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7137         // PR2108
7138         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7139         return DAG.getNode(ISD::BITCAST, dl, VT,
7140                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7141                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7142                                                    OpVT,
7143                                                    SrcOp.getOperand(0)
7144                                                           .getOperand(0))));
7145       }
7146     }
7147   }
7148
7149   return DAG.getNode(ISD::BITCAST, dl, VT,
7150                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7151                                  DAG.getNode(ISD::BITCAST, dl,
7152                                              OpVT, SrcOp)));
7153 }
7154
7155 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7156 /// which could not be matched by any known target speficic shuffle
7157 static SDValue
7158 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7159
7160   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7161   if (NewOp.getNode())
7162     return NewOp;
7163
7164   MVT VT = SVOp->getSimpleValueType(0);
7165
7166   unsigned NumElems = VT.getVectorNumElements();
7167   unsigned NumLaneElems = NumElems / 2;
7168
7169   SDLoc dl(SVOp);
7170   MVT EltVT = VT.getVectorElementType();
7171   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7172   SDValue Output[2];
7173
7174   SmallVector<int, 16> Mask;
7175   for (unsigned l = 0; l < 2; ++l) {
7176     // Build a shuffle mask for the output, discovering on the fly which
7177     // input vectors to use as shuffle operands (recorded in InputUsed).
7178     // If building a suitable shuffle vector proves too hard, then bail
7179     // out with UseBuildVector set.
7180     bool UseBuildVector = false;
7181     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7182     unsigned LaneStart = l * NumLaneElems;
7183     for (unsigned i = 0; i != NumLaneElems; ++i) {
7184       // The mask element.  This indexes into the input.
7185       int Idx = SVOp->getMaskElt(i+LaneStart);
7186       if (Idx < 0) {
7187         // the mask element does not index into any input vector.
7188         Mask.push_back(-1);
7189         continue;
7190       }
7191
7192       // The input vector this mask element indexes into.
7193       int Input = Idx / NumLaneElems;
7194
7195       // Turn the index into an offset from the start of the input vector.
7196       Idx -= Input * NumLaneElems;
7197
7198       // Find or create a shuffle vector operand to hold this input.
7199       unsigned OpNo;
7200       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7201         if (InputUsed[OpNo] == Input)
7202           // This input vector is already an operand.
7203           break;
7204         if (InputUsed[OpNo] < 0) {
7205           // Create a new operand for this input vector.
7206           InputUsed[OpNo] = Input;
7207           break;
7208         }
7209       }
7210
7211       if (OpNo >= array_lengthof(InputUsed)) {
7212         // More than two input vectors used!  Give up on trying to create a
7213         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7214         UseBuildVector = true;
7215         break;
7216       }
7217
7218       // Add the mask index for the new shuffle vector.
7219       Mask.push_back(Idx + OpNo * NumLaneElems);
7220     }
7221
7222     if (UseBuildVector) {
7223       SmallVector<SDValue, 16> SVOps;
7224       for (unsigned i = 0; i != NumLaneElems; ++i) {
7225         // The mask element.  This indexes into the input.
7226         int Idx = SVOp->getMaskElt(i+LaneStart);
7227         if (Idx < 0) {
7228           SVOps.push_back(DAG.getUNDEF(EltVT));
7229           continue;
7230         }
7231
7232         // The input vector this mask element indexes into.
7233         int Input = Idx / NumElems;
7234
7235         // Turn the index into an offset from the start of the input vector.
7236         Idx -= Input * NumElems;
7237
7238         // Extract the vector element by hand.
7239         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7240                                     SVOp->getOperand(Input),
7241                                     DAG.getIntPtrConstant(Idx)));
7242       }
7243
7244       // Construct the output using a BUILD_VECTOR.
7245       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7246     } else if (InputUsed[0] < 0) {
7247       // No input vectors were used! The result is undefined.
7248       Output[l] = DAG.getUNDEF(NVT);
7249     } else {
7250       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7251                                         (InputUsed[0] % 2) * NumLaneElems,
7252                                         DAG, dl);
7253       // If only one input was used, use an undefined vector for the other.
7254       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7255         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7256                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7257       // At least one input vector was used. Create a new shuffle vector.
7258       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7259     }
7260
7261     Mask.clear();
7262   }
7263
7264   // Concatenate the result back
7265   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7266 }
7267
7268 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7269 /// 4 elements, and match them with several different shuffle types.
7270 static SDValue
7271 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7272   SDValue V1 = SVOp->getOperand(0);
7273   SDValue V2 = SVOp->getOperand(1);
7274   SDLoc dl(SVOp);
7275   MVT VT = SVOp->getSimpleValueType(0);
7276
7277   assert(VT.is128BitVector() && "Unsupported vector size");
7278
7279   std::pair<int, int> Locs[4];
7280   int Mask1[] = { -1, -1, -1, -1 };
7281   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7282
7283   unsigned NumHi = 0;
7284   unsigned NumLo = 0;
7285   for (unsigned i = 0; i != 4; ++i) {
7286     int Idx = PermMask[i];
7287     if (Idx < 0) {
7288       Locs[i] = std::make_pair(-1, -1);
7289     } else {
7290       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7291       if (Idx < 4) {
7292         Locs[i] = std::make_pair(0, NumLo);
7293         Mask1[NumLo] = Idx;
7294         NumLo++;
7295       } else {
7296         Locs[i] = std::make_pair(1, NumHi);
7297         if (2+NumHi < 4)
7298           Mask1[2+NumHi] = Idx;
7299         NumHi++;
7300       }
7301     }
7302   }
7303
7304   if (NumLo <= 2 && NumHi <= 2) {
7305     // If no more than two elements come from either vector. This can be
7306     // implemented with two shuffles. First shuffle gather the elements.
7307     // The second shuffle, which takes the first shuffle as both of its
7308     // vector operands, put the elements into the right order.
7309     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7310
7311     int Mask2[] = { -1, -1, -1, -1 };
7312
7313     for (unsigned i = 0; i != 4; ++i)
7314       if (Locs[i].first != -1) {
7315         unsigned Idx = (i < 2) ? 0 : 4;
7316         Idx += Locs[i].first * 2 + Locs[i].second;
7317         Mask2[i] = Idx;
7318       }
7319
7320     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7321   }
7322
7323   if (NumLo == 3 || NumHi == 3) {
7324     // Otherwise, we must have three elements from one vector, call it X, and
7325     // one element from the other, call it Y.  First, use a shufps to build an
7326     // intermediate vector with the one element from Y and the element from X
7327     // that will be in the same half in the final destination (the indexes don't
7328     // matter). Then, use a shufps to build the final vector, taking the half
7329     // containing the element from Y from the intermediate, and the other half
7330     // from X.
7331     if (NumHi == 3) {
7332       // Normalize it so the 3 elements come from V1.
7333       CommuteVectorShuffleMask(PermMask, 4);
7334       std::swap(V1, V2);
7335     }
7336
7337     // Find the element from V2.
7338     unsigned HiIndex;
7339     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7340       int Val = PermMask[HiIndex];
7341       if (Val < 0)
7342         continue;
7343       if (Val >= 4)
7344         break;
7345     }
7346
7347     Mask1[0] = PermMask[HiIndex];
7348     Mask1[1] = -1;
7349     Mask1[2] = PermMask[HiIndex^1];
7350     Mask1[3] = -1;
7351     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7352
7353     if (HiIndex >= 2) {
7354       Mask1[0] = PermMask[0];
7355       Mask1[1] = PermMask[1];
7356       Mask1[2] = HiIndex & 1 ? 6 : 4;
7357       Mask1[3] = HiIndex & 1 ? 4 : 6;
7358       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7359     }
7360
7361     Mask1[0] = HiIndex & 1 ? 2 : 0;
7362     Mask1[1] = HiIndex & 1 ? 0 : 2;
7363     Mask1[2] = PermMask[2];
7364     Mask1[3] = PermMask[3];
7365     if (Mask1[2] >= 0)
7366       Mask1[2] += 4;
7367     if (Mask1[3] >= 0)
7368       Mask1[3] += 4;
7369     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7370   }
7371
7372   // Break it into (shuffle shuffle_hi, shuffle_lo).
7373   int LoMask[] = { -1, -1, -1, -1 };
7374   int HiMask[] = { -1, -1, -1, -1 };
7375
7376   int *MaskPtr = LoMask;
7377   unsigned MaskIdx = 0;
7378   unsigned LoIdx = 0;
7379   unsigned HiIdx = 2;
7380   for (unsigned i = 0; i != 4; ++i) {
7381     if (i == 2) {
7382       MaskPtr = HiMask;
7383       MaskIdx = 1;
7384       LoIdx = 0;
7385       HiIdx = 2;
7386     }
7387     int Idx = PermMask[i];
7388     if (Idx < 0) {
7389       Locs[i] = std::make_pair(-1, -1);
7390     } else if (Idx < 4) {
7391       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7392       MaskPtr[LoIdx] = Idx;
7393       LoIdx++;
7394     } else {
7395       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7396       MaskPtr[HiIdx] = Idx;
7397       HiIdx++;
7398     }
7399   }
7400
7401   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7402   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7403   int MaskOps[] = { -1, -1, -1, -1 };
7404   for (unsigned i = 0; i != 4; ++i)
7405     if (Locs[i].first != -1)
7406       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7407   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7408 }
7409
7410 static bool MayFoldVectorLoad(SDValue V) {
7411   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7412     V = V.getOperand(0);
7413
7414   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7415     V = V.getOperand(0);
7416   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7417       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7418     // BUILD_VECTOR (load), undef
7419     V = V.getOperand(0);
7420
7421   return MayFoldLoad(V);
7422 }
7423
7424 static
7425 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7426   MVT VT = Op.getSimpleValueType();
7427
7428   // Canonizalize to v2f64.
7429   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7430   return DAG.getNode(ISD::BITCAST, dl, VT,
7431                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7432                                           V1, DAG));
7433 }
7434
7435 static
7436 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7437                         bool HasSSE2) {
7438   SDValue V1 = Op.getOperand(0);
7439   SDValue V2 = Op.getOperand(1);
7440   MVT VT = Op.getSimpleValueType();
7441
7442   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7443
7444   if (HasSSE2 && VT == MVT::v2f64)
7445     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7446
7447   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7448   return DAG.getNode(ISD::BITCAST, dl, VT,
7449                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7450                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7451                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7452 }
7453
7454 static
7455 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7456   SDValue V1 = Op.getOperand(0);
7457   SDValue V2 = Op.getOperand(1);
7458   MVT VT = Op.getSimpleValueType();
7459
7460   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7461          "unsupported shuffle type");
7462
7463   if (V2.getOpcode() == ISD::UNDEF)
7464     V2 = V1;
7465
7466   // v4i32 or v4f32
7467   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7468 }
7469
7470 static
7471 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7472   SDValue V1 = Op.getOperand(0);
7473   SDValue V2 = Op.getOperand(1);
7474   MVT VT = Op.getSimpleValueType();
7475   unsigned NumElems = VT.getVectorNumElements();
7476
7477   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7478   // operand of these instructions is only memory, so check if there's a
7479   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7480   // same masks.
7481   bool CanFoldLoad = false;
7482
7483   // Trivial case, when V2 comes from a load.
7484   if (MayFoldVectorLoad(V2))
7485     CanFoldLoad = true;
7486
7487   // When V1 is a load, it can be folded later into a store in isel, example:
7488   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7489   //    turns into:
7490   //  (MOVLPSmr addr:$src1, VR128:$src2)
7491   // So, recognize this potential and also use MOVLPS or MOVLPD
7492   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7493     CanFoldLoad = true;
7494
7495   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7496   if (CanFoldLoad) {
7497     if (HasSSE2 && NumElems == 2)
7498       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7499
7500     if (NumElems == 4)
7501       // If we don't care about the second element, proceed to use movss.
7502       if (SVOp->getMaskElt(1) != -1)
7503         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7504   }
7505
7506   // movl and movlp will both match v2i64, but v2i64 is never matched by
7507   // movl earlier because we make it strict to avoid messing with the movlp load
7508   // folding logic (see the code above getMOVLP call). Match it here then,
7509   // this is horrible, but will stay like this until we move all shuffle
7510   // matching to x86 specific nodes. Note that for the 1st condition all
7511   // types are matched with movsd.
7512   if (HasSSE2) {
7513     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7514     // as to remove this logic from here, as much as possible
7515     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7516       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7517     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7518   }
7519
7520   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7521
7522   // Invert the operand order and use SHUFPS to match it.
7523   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7524                               getShuffleSHUFImmediate(SVOp), DAG);
7525 }
7526
7527 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7528                                          SelectionDAG &DAG) {
7529   SDLoc dl(Load);
7530   MVT VT = Load->getSimpleValueType(0);
7531   MVT EVT = VT.getVectorElementType();
7532   SDValue Addr = Load->getOperand(1);
7533   SDValue NewAddr = DAG.getNode(
7534       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7535       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7536
7537   SDValue NewLoad =
7538       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7539                   DAG.getMachineFunction().getMachineMemOperand(
7540                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7541   return NewLoad;
7542 }
7543
7544 // It is only safe to call this function if isINSERTPSMask is true for
7545 // this shufflevector mask.
7546 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7547                            SelectionDAG &DAG) {
7548   // Generate an insertps instruction when inserting an f32 from memory onto a
7549   // v4f32 or when copying a member from one v4f32 to another.
7550   // We also use it for transferring i32 from one register to another,
7551   // since it simply copies the same bits.
7552   // If we're transferring an i32 from memory to a specific element in a
7553   // register, we output a generic DAG that will match the PINSRD
7554   // instruction.
7555   MVT VT = SVOp->getSimpleValueType(0);
7556   MVT EVT = VT.getVectorElementType();
7557   SDValue V1 = SVOp->getOperand(0);
7558   SDValue V2 = SVOp->getOperand(1);
7559   auto Mask = SVOp->getMask();
7560   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7561          "unsupported vector type for insertps/pinsrd");
7562
7563   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7564   auto FromV2Predicate = [](const int &i) { return i >= 4; };
7565   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7566
7567   SDValue From;
7568   SDValue To;
7569   unsigned DestIndex;
7570   if (FromV1 == 1) {
7571     From = V1;
7572     To = V2;
7573     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7574                 Mask.begin();
7575   } else {
7576     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7577            "More than one element from V1 and from V2, or no elements from one "
7578            "of the vectors. This case should not have returned true from "
7579            "isINSERTPSMask");
7580     From = V2;
7581     To = V1;
7582     DestIndex =
7583         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7584   }
7585
7586   if (MayFoldLoad(From)) {
7587     // Trivial case, when From comes from a load and is only used by the
7588     // shuffle. Make it use insertps from the vector that we need from that
7589     // load.
7590     SDValue NewLoad =
7591         NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7592     if (!NewLoad.getNode())
7593       return SDValue();
7594
7595     if (EVT == MVT::f32) {
7596       // Create this as a scalar to vector to match the instruction pattern.
7597       SDValue LoadScalarToVector =
7598           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7599       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7600       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7601                          InsertpsMask);
7602     } else { // EVT == MVT::i32
7603       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7604       // instruction, to match the PINSRD instruction, which loads an i32 to a
7605       // certain vector element.
7606       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7607                          DAG.getConstant(DestIndex, MVT::i32));
7608     }
7609   }
7610
7611   // Vector-element-to-vector
7612   unsigned SrcIndex = Mask[DestIndex] % 4;
7613   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7614   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7615 }
7616
7617 // Reduce a vector shuffle to zext.
7618 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7619                                     SelectionDAG &DAG) {
7620   // PMOVZX is only available from SSE41.
7621   if (!Subtarget->hasSSE41())
7622     return SDValue();
7623
7624   MVT VT = Op.getSimpleValueType();
7625
7626   // Only AVX2 support 256-bit vector integer extending.
7627   if (!Subtarget->hasInt256() && VT.is256BitVector())
7628     return SDValue();
7629
7630   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7631   SDLoc DL(Op);
7632   SDValue V1 = Op.getOperand(0);
7633   SDValue V2 = Op.getOperand(1);
7634   unsigned NumElems = VT.getVectorNumElements();
7635
7636   // Extending is an unary operation and the element type of the source vector
7637   // won't be equal to or larger than i64.
7638   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7639       VT.getVectorElementType() == MVT::i64)
7640     return SDValue();
7641
7642   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7643   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7644   while ((1U << Shift) < NumElems) {
7645     if (SVOp->getMaskElt(1U << Shift) == 1)
7646       break;
7647     Shift += 1;
7648     // The maximal ratio is 8, i.e. from i8 to i64.
7649     if (Shift > 3)
7650       return SDValue();
7651   }
7652
7653   // Check the shuffle mask.
7654   unsigned Mask = (1U << Shift) - 1;
7655   for (unsigned i = 0; i != NumElems; ++i) {
7656     int EltIdx = SVOp->getMaskElt(i);
7657     if ((i & Mask) != 0 && EltIdx != -1)
7658       return SDValue();
7659     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7660       return SDValue();
7661   }
7662
7663   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7664   MVT NeVT = MVT::getIntegerVT(NBits);
7665   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7666
7667   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7668     return SDValue();
7669
7670   // Simplify the operand as it's prepared to be fed into shuffle.
7671   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7672   if (V1.getOpcode() == ISD::BITCAST &&
7673       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7674       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7675       V1.getOperand(0).getOperand(0)
7676         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7677     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7678     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7679     ConstantSDNode *CIdx =
7680       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7681     // If it's foldable, i.e. normal load with single use, we will let code
7682     // selection to fold it. Otherwise, we will short the conversion sequence.
7683     if (CIdx && CIdx->getZExtValue() == 0 &&
7684         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7685       MVT FullVT = V.getSimpleValueType();
7686       MVT V1VT = V1.getSimpleValueType();
7687       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7688         // The "ext_vec_elt" node is wider than the result node.
7689         // In this case we should extract subvector from V.
7690         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7691         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7692         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7693                                         FullVT.getVectorNumElements()/Ratio);
7694         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7695                         DAG.getIntPtrConstant(0));
7696       }
7697       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7698     }
7699   }
7700
7701   return DAG.getNode(ISD::BITCAST, DL, VT,
7702                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7703 }
7704
7705 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7706                                       SelectionDAG &DAG) {
7707   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7708   MVT VT = Op.getSimpleValueType();
7709   SDLoc dl(Op);
7710   SDValue V1 = Op.getOperand(0);
7711   SDValue V2 = Op.getOperand(1);
7712
7713   if (isZeroShuffle(SVOp))
7714     return getZeroVector(VT, Subtarget, DAG, dl);
7715
7716   // Handle splat operations
7717   if (SVOp->isSplat()) {
7718     // Use vbroadcast whenever the splat comes from a foldable load
7719     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7720     if (Broadcast.getNode())
7721       return Broadcast;
7722   }
7723
7724   // Check integer expanding shuffles.
7725   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7726   if (NewOp.getNode())
7727     return NewOp;
7728
7729   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7730   // do it!
7731   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7732       VT == MVT::v32i8) {
7733     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7734     if (NewOp.getNode())
7735       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7736   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7737     // FIXME: Figure out a cleaner way to do this.
7738     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7739       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7740       if (NewOp.getNode()) {
7741         MVT NewVT = NewOp.getSimpleValueType();
7742         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7743                                NewVT, true, false))
7744           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7745                               dl);
7746       }
7747     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7748       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7749       if (NewOp.getNode()) {
7750         MVT NewVT = NewOp.getSimpleValueType();
7751         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7752           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7753                               dl);
7754       }
7755     }
7756   }
7757   return SDValue();
7758 }
7759
7760 SDValue
7761 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7762   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7763   SDValue V1 = Op.getOperand(0);
7764   SDValue V2 = Op.getOperand(1);
7765   MVT VT = Op.getSimpleValueType();
7766   SDLoc dl(Op);
7767   unsigned NumElems = VT.getVectorNumElements();
7768   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7769   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7770   bool V1IsSplat = false;
7771   bool V2IsSplat = false;
7772   bool HasSSE2 = Subtarget->hasSSE2();
7773   bool HasFp256    = Subtarget->hasFp256();
7774   bool HasInt256   = Subtarget->hasInt256();
7775   MachineFunction &MF = DAG.getMachineFunction();
7776   bool OptForSize = MF.getFunction()->getAttributes().
7777     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7778
7779   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7780
7781   if (V1IsUndef && V2IsUndef)
7782     return DAG.getUNDEF(VT);
7783
7784   // When we create a shuffle node we put the UNDEF node to second operand,
7785   // but in some cases the first operand may be transformed to UNDEF.
7786   // In this case we should just commute the node.
7787   if (V1IsUndef)
7788     return CommuteVectorShuffle(SVOp, DAG);
7789
7790   // Vector shuffle lowering takes 3 steps:
7791   //
7792   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7793   //    narrowing and commutation of operands should be handled.
7794   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7795   //    shuffle nodes.
7796   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7797   //    so the shuffle can be broken into other shuffles and the legalizer can
7798   //    try the lowering again.
7799   //
7800   // The general idea is that no vector_shuffle operation should be left to
7801   // be matched during isel, all of them must be converted to a target specific
7802   // node here.
7803
7804   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7805   // narrowing and commutation of operands should be handled. The actual code
7806   // doesn't include all of those, work in progress...
7807   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7808   if (NewOp.getNode())
7809     return NewOp;
7810
7811   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7812
7813   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7814   // unpckh_undef). Only use pshufd if speed is more important than size.
7815   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7816     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7817   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7818     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7819
7820   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7821       V2IsUndef && MayFoldVectorLoad(V1))
7822     return getMOVDDup(Op, dl, V1, DAG);
7823
7824   if (isMOVHLPS_v_undef_Mask(M, VT))
7825     return getMOVHighToLow(Op, dl, DAG);
7826
7827   // Use to match splats
7828   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7829       (VT == MVT::v2f64 || VT == MVT::v2i64))
7830     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7831
7832   if (isPSHUFDMask(M, VT)) {
7833     // The actual implementation will match the mask in the if above and then
7834     // during isel it can match several different instructions, not only pshufd
7835     // as its name says, sad but true, emulate the behavior for now...
7836     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7837       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7838
7839     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7840
7841     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7842       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7843
7844     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7845       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7846                                   DAG);
7847
7848     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7849                                 TargetMask, DAG);
7850   }
7851
7852   if (isPALIGNRMask(M, VT, Subtarget))
7853     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7854                                 getShufflePALIGNRImmediate(SVOp),
7855                                 DAG);
7856
7857   // Check if this can be converted into a logical shift.
7858   bool isLeft = false;
7859   unsigned ShAmt = 0;
7860   SDValue ShVal;
7861   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7862   if (isShift && ShVal.hasOneUse()) {
7863     // If the shifted value has multiple uses, it may be cheaper to use
7864     // v_set0 + movlhps or movhlps, etc.
7865     MVT EltVT = VT.getVectorElementType();
7866     ShAmt *= EltVT.getSizeInBits();
7867     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7868   }
7869
7870   if (isMOVLMask(M, VT)) {
7871     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7872       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7873     if (!isMOVLPMask(M, VT)) {
7874       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7875         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7876
7877       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7878         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7879     }
7880   }
7881
7882   // FIXME: fold these into legal mask.
7883   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7884     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7885
7886   if (isMOVHLPSMask(M, VT))
7887     return getMOVHighToLow(Op, dl, DAG);
7888
7889   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7890     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7891
7892   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7893     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7894
7895   if (isMOVLPMask(M, VT))
7896     return getMOVLP(Op, dl, DAG, HasSSE2);
7897
7898   if (ShouldXformToMOVHLPS(M, VT) ||
7899       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7900     return CommuteVectorShuffle(SVOp, DAG);
7901
7902   if (isShift) {
7903     // No better options. Use a vshldq / vsrldq.
7904     MVT EltVT = VT.getVectorElementType();
7905     ShAmt *= EltVT.getSizeInBits();
7906     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7907   }
7908
7909   bool Commuted = false;
7910   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7911   // 1,1,1,1 -> v8i16 though.
7912   V1IsSplat = isSplatVector(V1.getNode());
7913   V2IsSplat = isSplatVector(V2.getNode());
7914
7915   // Canonicalize the splat or undef, if present, to be on the RHS.
7916   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7917     CommuteVectorShuffleMask(M, NumElems);
7918     std::swap(V1, V2);
7919     std::swap(V1IsSplat, V2IsSplat);
7920     Commuted = true;
7921   }
7922
7923   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7924     // Shuffling low element of v1 into undef, just return v1.
7925     if (V2IsUndef)
7926       return V1;
7927     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7928     // the instruction selector will not match, so get a canonical MOVL with
7929     // swapped operands to undo the commute.
7930     return getMOVL(DAG, dl, VT, V2, V1);
7931   }
7932
7933   if (isUNPCKLMask(M, VT, HasInt256))
7934     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7935
7936   if (isUNPCKHMask(M, VT, HasInt256))
7937     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7938
7939   if (V2IsSplat) {
7940     // Normalize mask so all entries that point to V2 points to its first
7941     // element then try to match unpck{h|l} again. If match, return a
7942     // new vector_shuffle with the corrected mask.p
7943     SmallVector<int, 8> NewMask(M.begin(), M.end());
7944     NormalizeMask(NewMask, NumElems);
7945     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7946       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7947     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7948       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7949   }
7950
7951   if (Commuted) {
7952     // Commute is back and try unpck* again.
7953     // FIXME: this seems wrong.
7954     CommuteVectorShuffleMask(M, NumElems);
7955     std::swap(V1, V2);
7956     std::swap(V1IsSplat, V2IsSplat);
7957
7958     if (isUNPCKLMask(M, VT, HasInt256))
7959       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7960
7961     if (isUNPCKHMask(M, VT, HasInt256))
7962       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7963   }
7964
7965   // Normalize the node to match x86 shuffle ops if needed
7966   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7967     return CommuteVectorShuffle(SVOp, DAG);
7968
7969   // The checks below are all present in isShuffleMaskLegal, but they are
7970   // inlined here right now to enable us to directly emit target specific
7971   // nodes, and remove one by one until they don't return Op anymore.
7972
7973   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7974       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7975     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7976       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7977   }
7978
7979   if (isPSHUFHWMask(M, VT, HasInt256))
7980     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7981                                 getShufflePSHUFHWImmediate(SVOp),
7982                                 DAG);
7983
7984   if (isPSHUFLWMask(M, VT, HasInt256))
7985     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7986                                 getShufflePSHUFLWImmediate(SVOp),
7987                                 DAG);
7988
7989   if (isSHUFPMask(M, VT))
7990     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7991                                 getShuffleSHUFImmediate(SVOp), DAG);
7992
7993   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7994     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7995   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7996     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7997
7998   //===--------------------------------------------------------------------===//
7999   // Generate target specific nodes for 128 or 256-bit shuffles only
8000   // supported in the AVX instruction set.
8001   //
8002
8003   // Handle VMOVDDUPY permutations
8004   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8005     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8006
8007   // Handle VPERMILPS/D* permutations
8008   if (isVPERMILPMask(M, VT)) {
8009     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8010       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8011                                   getShuffleSHUFImmediate(SVOp), DAG);
8012     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8013                                 getShuffleSHUFImmediate(SVOp), DAG);
8014   }
8015
8016   unsigned Idx;
8017   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8018     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8019                               Idx*(NumElems/2), DAG, dl);
8020
8021   // Handle VPERM2F128/VPERM2I128 permutations
8022   if (isVPERM2X128Mask(M, VT, HasFp256))
8023     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8024                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8025
8026   unsigned MaskValue;
8027   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8028                   &MaskValue))
8029     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8030
8031   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8032     return getINSERTPS(SVOp, dl, DAG);
8033
8034   unsigned Imm8;
8035   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8036     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8037
8038   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8039       VT.is512BitVector()) {
8040     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8041     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8042     SmallVector<SDValue, 16> permclMask;
8043     for (unsigned i = 0; i != NumElems; ++i) {
8044       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8045     }
8046
8047     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8048     if (V2IsUndef)
8049       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8050       return DAG.getNode(X86ISD::VPERMV, dl, VT,
8051                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8052     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8053                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8054   }
8055
8056   //===--------------------------------------------------------------------===//
8057   // Since no target specific shuffle was selected for this generic one,
8058   // lower it into other known shuffles. FIXME: this isn't true yet, but
8059   // this is the plan.
8060   //
8061
8062   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8063   if (VT == MVT::v8i16) {
8064     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8065     if (NewOp.getNode())
8066       return NewOp;
8067   }
8068
8069   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8070     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8071     if (NewOp.getNode())
8072       return NewOp;
8073   }
8074
8075   if (VT == MVT::v16i8) {
8076     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8077     if (NewOp.getNode())
8078       return NewOp;
8079   }
8080
8081   if (VT == MVT::v32i8) {
8082     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8083     if (NewOp.getNode())
8084       return NewOp;
8085   }
8086
8087   // Handle all 128-bit wide vectors with 4 elements, and match them with
8088   // several different shuffle types.
8089   if (NumElems == 4 && VT.is128BitVector())
8090     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8091
8092   // Handle general 256-bit shuffles
8093   if (VT.is256BitVector())
8094     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8095
8096   return SDValue();
8097 }
8098
8099 // This function assumes its argument is a BUILD_VECTOR of constants or
8100 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8101 // true.
8102 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8103                                     unsigned &MaskValue) {
8104   MaskValue = 0;
8105   unsigned NumElems = BuildVector->getNumOperands();
8106   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8107   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8108   unsigned NumElemsInLane = NumElems / NumLanes;
8109
8110   // Blend for v16i16 should be symetric for the both lanes.
8111   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8112     SDValue EltCond = BuildVector->getOperand(i);
8113     SDValue SndLaneEltCond =
8114         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8115
8116     int Lane1Cond = -1, Lane2Cond = -1;
8117     if (isa<ConstantSDNode>(EltCond))
8118       Lane1Cond = !isZero(EltCond);
8119     if (isa<ConstantSDNode>(SndLaneEltCond))
8120       Lane2Cond = !isZero(SndLaneEltCond);
8121
8122     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8123       // Lane1Cond != 0, means we want the first argument.
8124       // Lane1Cond == 0, means we want the second argument.
8125       // The encoding of this argument is 0 for the first argument, 1
8126       // for the second. Therefore, invert the condition.
8127       MaskValue |= !Lane1Cond << i;
8128     else if (Lane1Cond < 0)
8129       MaskValue |= !Lane2Cond << i;
8130     else
8131       return false;
8132   }
8133   return true;
8134 }
8135
8136 // Try to lower a vselect node into a simple blend instruction.
8137 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8138                                    SelectionDAG &DAG) {
8139   SDValue Cond = Op.getOperand(0);
8140   SDValue LHS = Op.getOperand(1);
8141   SDValue RHS = Op.getOperand(2);
8142   SDLoc dl(Op);
8143   MVT VT = Op.getSimpleValueType();
8144   MVT EltVT = VT.getVectorElementType();
8145   unsigned NumElems = VT.getVectorNumElements();
8146
8147   // There is no blend with immediate in AVX-512.
8148   if (VT.is512BitVector())
8149     return SDValue();
8150
8151   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8152     return SDValue();
8153   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8154     return SDValue();
8155
8156   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8157     return SDValue();
8158
8159   // Check the mask for BLEND and build the value.
8160   unsigned MaskValue = 0;
8161   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8162     return SDValue();
8163
8164   // Convert i32 vectors to floating point if it is not AVX2.
8165   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8166   MVT BlendVT = VT;
8167   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8168     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8169                                NumElems);
8170     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8171     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8172   }
8173
8174   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8175                             DAG.getConstant(MaskValue, MVT::i32));
8176   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8177 }
8178
8179 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8180   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8181   if (BlendOp.getNode())
8182     return BlendOp;
8183
8184   // Some types for vselect were previously set to Expand, not Legal or
8185   // Custom. Return an empty SDValue so we fall-through to Expand, after
8186   // the Custom lowering phase.
8187   MVT VT = Op.getSimpleValueType();
8188   switch (VT.SimpleTy) {
8189   default:
8190     break;
8191   case MVT::v8i16:
8192   case MVT::v16i16:
8193     return SDValue();
8194   }
8195
8196   // We couldn't create a "Blend with immediate" node.
8197   // This node should still be legal, but we'll have to emit a blendv*
8198   // instruction.
8199   return Op;
8200 }
8201
8202 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8203   MVT VT = Op.getSimpleValueType();
8204   SDLoc dl(Op);
8205
8206   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8207     return SDValue();
8208
8209   if (VT.getSizeInBits() == 8) {
8210     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8211                                   Op.getOperand(0), Op.getOperand(1));
8212     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8213                                   DAG.getValueType(VT));
8214     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8215   }
8216
8217   if (VT.getSizeInBits() == 16) {
8218     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8219     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8220     if (Idx == 0)
8221       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8222                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8223                                      DAG.getNode(ISD::BITCAST, dl,
8224                                                  MVT::v4i32,
8225                                                  Op.getOperand(0)),
8226                                      Op.getOperand(1)));
8227     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8228                                   Op.getOperand(0), Op.getOperand(1));
8229     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8230                                   DAG.getValueType(VT));
8231     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8232   }
8233
8234   if (VT == MVT::f32) {
8235     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8236     // the result back to FR32 register. It's only worth matching if the
8237     // result has a single use which is a store or a bitcast to i32.  And in
8238     // the case of a store, it's not worth it if the index is a constant 0,
8239     // because a MOVSSmr can be used instead, which is smaller and faster.
8240     if (!Op.hasOneUse())
8241       return SDValue();
8242     SDNode *User = *Op.getNode()->use_begin();
8243     if ((User->getOpcode() != ISD::STORE ||
8244          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8245           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8246         (User->getOpcode() != ISD::BITCAST ||
8247          User->getValueType(0) != MVT::i32))
8248       return SDValue();
8249     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8250                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8251                                               Op.getOperand(0)),
8252                                               Op.getOperand(1));
8253     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8254   }
8255
8256   if (VT == MVT::i32 || VT == MVT::i64) {
8257     // ExtractPS/pextrq works with constant index.
8258     if (isa<ConstantSDNode>(Op.getOperand(1)))
8259       return Op;
8260   }
8261   return SDValue();
8262 }
8263
8264 /// Extract one bit from mask vector, like v16i1 or v8i1.
8265 /// AVX-512 feature.
8266 SDValue
8267 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8268   SDValue Vec = Op.getOperand(0);
8269   SDLoc dl(Vec);
8270   MVT VecVT = Vec.getSimpleValueType();
8271   SDValue Idx = Op.getOperand(1);
8272   MVT EltVT = Op.getSimpleValueType();
8273
8274   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8275
8276   // variable index can't be handled in mask registers,
8277   // extend vector to VR512
8278   if (!isa<ConstantSDNode>(Idx)) {
8279     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8280     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8281     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8282                               ExtVT.getVectorElementType(), Ext, Idx);
8283     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8284   }
8285
8286   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8287   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8288   unsigned MaxSift = rc->getSize()*8 - 1;
8289   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8290                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8291   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8292                     DAG.getConstant(MaxSift, MVT::i8));
8293   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8294                        DAG.getIntPtrConstant(0));
8295 }
8296
8297 SDValue
8298 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8299                                            SelectionDAG &DAG) const {
8300   SDLoc dl(Op);
8301   SDValue Vec = Op.getOperand(0);
8302   MVT VecVT = Vec.getSimpleValueType();
8303   SDValue Idx = Op.getOperand(1);
8304
8305   if (Op.getSimpleValueType() == MVT::i1)
8306     return ExtractBitFromMaskVector(Op, DAG);
8307
8308   if (!isa<ConstantSDNode>(Idx)) {
8309     if (VecVT.is512BitVector() ||
8310         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8311          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8312
8313       MVT MaskEltVT =
8314         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8315       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8316                                     MaskEltVT.getSizeInBits());
8317
8318       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8319       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8320                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8321                                 Idx, DAG.getConstant(0, getPointerTy()));
8322       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8323       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8324                         Perm, DAG.getConstant(0, getPointerTy()));
8325     }
8326     return SDValue();
8327   }
8328
8329   // If this is a 256-bit vector result, first extract the 128-bit vector and
8330   // then extract the element from the 128-bit vector.
8331   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8332
8333     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8334     // Get the 128-bit vector.
8335     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8336     MVT EltVT = VecVT.getVectorElementType();
8337
8338     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8339
8340     //if (IdxVal >= NumElems/2)
8341     //  IdxVal -= NumElems/2;
8342     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8343     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8344                        DAG.getConstant(IdxVal, MVT::i32));
8345   }
8346
8347   assert(VecVT.is128BitVector() && "Unexpected vector length");
8348
8349   if (Subtarget->hasSSE41()) {
8350     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8351     if (Res.getNode())
8352       return Res;
8353   }
8354
8355   MVT VT = Op.getSimpleValueType();
8356   // TODO: handle v16i8.
8357   if (VT.getSizeInBits() == 16) {
8358     SDValue Vec = Op.getOperand(0);
8359     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8360     if (Idx == 0)
8361       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8362                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8363                                      DAG.getNode(ISD::BITCAST, dl,
8364                                                  MVT::v4i32, Vec),
8365                                      Op.getOperand(1)));
8366     // Transform it so it match pextrw which produces a 32-bit result.
8367     MVT EltVT = MVT::i32;
8368     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8369                                   Op.getOperand(0), Op.getOperand(1));
8370     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8371                                   DAG.getValueType(VT));
8372     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8373   }
8374
8375   if (VT.getSizeInBits() == 32) {
8376     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8377     if (Idx == 0)
8378       return Op;
8379
8380     // SHUFPS the element to the lowest double word, then movss.
8381     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8382     MVT VVT = Op.getOperand(0).getSimpleValueType();
8383     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8384                                        DAG.getUNDEF(VVT), Mask);
8385     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8386                        DAG.getIntPtrConstant(0));
8387   }
8388
8389   if (VT.getSizeInBits() == 64) {
8390     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8391     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8392     //        to match extract_elt for f64.
8393     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8394     if (Idx == 0)
8395       return Op;
8396
8397     // UNPCKHPD the element to the lowest double word, then movsd.
8398     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8399     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8400     int Mask[2] = { 1, -1 };
8401     MVT VVT = Op.getOperand(0).getSimpleValueType();
8402     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8403                                        DAG.getUNDEF(VVT), Mask);
8404     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8405                        DAG.getIntPtrConstant(0));
8406   }
8407
8408   return SDValue();
8409 }
8410
8411 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8412   MVT VT = Op.getSimpleValueType();
8413   MVT EltVT = VT.getVectorElementType();
8414   SDLoc dl(Op);
8415
8416   SDValue N0 = Op.getOperand(0);
8417   SDValue N1 = Op.getOperand(1);
8418   SDValue N2 = Op.getOperand(2);
8419
8420   if (!VT.is128BitVector())
8421     return SDValue();
8422
8423   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8424       isa<ConstantSDNode>(N2)) {
8425     unsigned Opc;
8426     if (VT == MVT::v8i16)
8427       Opc = X86ISD::PINSRW;
8428     else if (VT == MVT::v16i8)
8429       Opc = X86ISD::PINSRB;
8430     else
8431       Opc = X86ISD::PINSRB;
8432
8433     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8434     // argument.
8435     if (N1.getValueType() != MVT::i32)
8436       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8437     if (N2.getValueType() != MVT::i32)
8438       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8439     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8440   }
8441
8442   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8443     // Bits [7:6] of the constant are the source select.  This will always be
8444     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8445     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8446     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8447     // Bits [5:4] of the constant are the destination select.  This is the
8448     //  value of the incoming immediate.
8449     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8450     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8451     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8452     // Create this as a scalar to vector..
8453     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8454     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8455   }
8456
8457   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8458     // PINSR* works with constant index.
8459     return Op;
8460   }
8461   return SDValue();
8462 }
8463
8464 /// Insert one bit to mask vector, like v16i1 or v8i1.
8465 /// AVX-512 feature.
8466 SDValue 
8467 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8468   SDLoc dl(Op);
8469   SDValue Vec = Op.getOperand(0);
8470   SDValue Elt = Op.getOperand(1);
8471   SDValue Idx = Op.getOperand(2);
8472   MVT VecVT = Vec.getSimpleValueType();
8473
8474   if (!isa<ConstantSDNode>(Idx)) {
8475     // Non constant index. Extend source and destination,
8476     // insert element and then truncate the result.
8477     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8478     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8479     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8480       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8481       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8482     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8483   }
8484
8485   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8486   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8487   if (Vec.getOpcode() == ISD::UNDEF)
8488     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8489                        DAG.getConstant(IdxVal, MVT::i8));
8490   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8491   unsigned MaxSift = rc->getSize()*8 - 1;
8492   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8493                     DAG.getConstant(MaxSift, MVT::i8));
8494   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8495                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8496   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8497 }
8498 SDValue
8499 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8500   MVT VT = Op.getSimpleValueType();
8501   MVT EltVT = VT.getVectorElementType();
8502   
8503   if (EltVT == MVT::i1)
8504     return InsertBitToMaskVector(Op, DAG);
8505
8506   SDLoc dl(Op);
8507   SDValue N0 = Op.getOperand(0);
8508   SDValue N1 = Op.getOperand(1);
8509   SDValue N2 = Op.getOperand(2);
8510
8511   // If this is a 256-bit vector result, first extract the 128-bit vector,
8512   // insert the element into the extracted half and then place it back.
8513   if (VT.is256BitVector() || VT.is512BitVector()) {
8514     if (!isa<ConstantSDNode>(N2))
8515       return SDValue();
8516
8517     // Get the desired 128-bit vector half.
8518     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8519     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8520
8521     // Insert the element into the desired half.
8522     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8523     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8524
8525     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8526                     DAG.getConstant(IdxIn128, MVT::i32));
8527
8528     // Insert the changed part back to the 256-bit vector
8529     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8530   }
8531
8532   if (Subtarget->hasSSE41())
8533     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8534
8535   if (EltVT == MVT::i8)
8536     return SDValue();
8537
8538   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8539     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8540     // as its second argument.
8541     if (N1.getValueType() != MVT::i32)
8542       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8543     if (N2.getValueType() != MVT::i32)
8544       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8545     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8546   }
8547   return SDValue();
8548 }
8549
8550 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8551   SDLoc dl(Op);
8552   MVT OpVT = Op.getSimpleValueType();
8553
8554   // If this is a 256-bit vector result, first insert into a 128-bit
8555   // vector and then insert into the 256-bit vector.
8556   if (!OpVT.is128BitVector()) {
8557     // Insert into a 128-bit vector.
8558     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8559     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8560                                  OpVT.getVectorNumElements() / SizeFactor);
8561
8562     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8563
8564     // Insert the 128-bit vector.
8565     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8566   }
8567
8568   if (OpVT == MVT::v1i64 &&
8569       Op.getOperand(0).getValueType() == MVT::i64)
8570     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8571
8572   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8573   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8574   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8575                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8576 }
8577
8578 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8579 // a simple subregister reference or explicit instructions to grab
8580 // upper bits of a vector.
8581 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8582                                       SelectionDAG &DAG) {
8583   SDLoc dl(Op);
8584   SDValue In =  Op.getOperand(0);
8585   SDValue Idx = Op.getOperand(1);
8586   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8587   MVT ResVT   = Op.getSimpleValueType();
8588   MVT InVT    = In.getSimpleValueType();
8589
8590   if (Subtarget->hasFp256()) {
8591     if (ResVT.is128BitVector() &&
8592         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8593         isa<ConstantSDNode>(Idx)) {
8594       return Extract128BitVector(In, IdxVal, DAG, dl);
8595     }
8596     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8597         isa<ConstantSDNode>(Idx)) {
8598       return Extract256BitVector(In, IdxVal, DAG, dl);
8599     }
8600   }
8601   return SDValue();
8602 }
8603
8604 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8605 // simple superregister reference or explicit instructions to insert
8606 // the upper bits of a vector.
8607 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8608                                      SelectionDAG &DAG) {
8609   if (Subtarget->hasFp256()) {
8610     SDLoc dl(Op.getNode());
8611     SDValue Vec = Op.getNode()->getOperand(0);
8612     SDValue SubVec = Op.getNode()->getOperand(1);
8613     SDValue Idx = Op.getNode()->getOperand(2);
8614
8615     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8616          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8617         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8618         isa<ConstantSDNode>(Idx)) {
8619       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8620       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8621     }
8622
8623     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8624         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8625         isa<ConstantSDNode>(Idx)) {
8626       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8627       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8628     }
8629   }
8630   return SDValue();
8631 }
8632
8633 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8634 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8635 // one of the above mentioned nodes. It has to be wrapped because otherwise
8636 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8637 // be used to form addressing mode. These wrapped nodes will be selected
8638 // into MOV32ri.
8639 SDValue
8640 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8641   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8642
8643   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8644   // global base reg.
8645   unsigned char OpFlag = 0;
8646   unsigned WrapperKind = X86ISD::Wrapper;
8647   CodeModel::Model M = getTargetMachine().getCodeModel();
8648
8649   if (Subtarget->isPICStyleRIPRel() &&
8650       (M == CodeModel::Small || M == CodeModel::Kernel))
8651     WrapperKind = X86ISD::WrapperRIP;
8652   else if (Subtarget->isPICStyleGOT())
8653     OpFlag = X86II::MO_GOTOFF;
8654   else if (Subtarget->isPICStyleStubPIC())
8655     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8656
8657   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8658                                              CP->getAlignment(),
8659                                              CP->getOffset(), OpFlag);
8660   SDLoc DL(CP);
8661   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8662   // With PIC, the address is actually $g + Offset.
8663   if (OpFlag) {
8664     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8665                          DAG.getNode(X86ISD::GlobalBaseReg,
8666                                      SDLoc(), getPointerTy()),
8667                          Result);
8668   }
8669
8670   return Result;
8671 }
8672
8673 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8674   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8675
8676   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8677   // global base reg.
8678   unsigned char OpFlag = 0;
8679   unsigned WrapperKind = X86ISD::Wrapper;
8680   CodeModel::Model M = getTargetMachine().getCodeModel();
8681
8682   if (Subtarget->isPICStyleRIPRel() &&
8683       (M == CodeModel::Small || M == CodeModel::Kernel))
8684     WrapperKind = X86ISD::WrapperRIP;
8685   else if (Subtarget->isPICStyleGOT())
8686     OpFlag = X86II::MO_GOTOFF;
8687   else if (Subtarget->isPICStyleStubPIC())
8688     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8689
8690   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8691                                           OpFlag);
8692   SDLoc DL(JT);
8693   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8694
8695   // With PIC, the address is actually $g + Offset.
8696   if (OpFlag)
8697     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8698                          DAG.getNode(X86ISD::GlobalBaseReg,
8699                                      SDLoc(), getPointerTy()),
8700                          Result);
8701
8702   return Result;
8703 }
8704
8705 SDValue
8706 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8707   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8708
8709   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8710   // global base reg.
8711   unsigned char OpFlag = 0;
8712   unsigned WrapperKind = X86ISD::Wrapper;
8713   CodeModel::Model M = getTargetMachine().getCodeModel();
8714
8715   if (Subtarget->isPICStyleRIPRel() &&
8716       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8717     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8718       OpFlag = X86II::MO_GOTPCREL;
8719     WrapperKind = X86ISD::WrapperRIP;
8720   } else if (Subtarget->isPICStyleGOT()) {
8721     OpFlag = X86II::MO_GOT;
8722   } else if (Subtarget->isPICStyleStubPIC()) {
8723     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8724   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8725     OpFlag = X86II::MO_DARWIN_NONLAZY;
8726   }
8727
8728   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8729
8730   SDLoc DL(Op);
8731   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8732
8733   // With PIC, the address is actually $g + Offset.
8734   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8735       !Subtarget->is64Bit()) {
8736     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8737                          DAG.getNode(X86ISD::GlobalBaseReg,
8738                                      SDLoc(), getPointerTy()),
8739                          Result);
8740   }
8741
8742   // For symbols that require a load from a stub to get the address, emit the
8743   // load.
8744   if (isGlobalStubReference(OpFlag))
8745     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8746                          MachinePointerInfo::getGOT(), false, false, false, 0);
8747
8748   return Result;
8749 }
8750
8751 SDValue
8752 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8753   // Create the TargetBlockAddressAddress node.
8754   unsigned char OpFlags =
8755     Subtarget->ClassifyBlockAddressReference();
8756   CodeModel::Model M = getTargetMachine().getCodeModel();
8757   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8758   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8759   SDLoc dl(Op);
8760   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8761                                              OpFlags);
8762
8763   if (Subtarget->isPICStyleRIPRel() &&
8764       (M == CodeModel::Small || M == CodeModel::Kernel))
8765     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8766   else
8767     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8768
8769   // With PIC, the address is actually $g + Offset.
8770   if (isGlobalRelativeToPICBase(OpFlags)) {
8771     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8772                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8773                          Result);
8774   }
8775
8776   return Result;
8777 }
8778
8779 SDValue
8780 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8781                                       int64_t Offset, SelectionDAG &DAG) const {
8782   // Create the TargetGlobalAddress node, folding in the constant
8783   // offset if it is legal.
8784   unsigned char OpFlags =
8785     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8786   CodeModel::Model M = getTargetMachine().getCodeModel();
8787   SDValue Result;
8788   if (OpFlags == X86II::MO_NO_FLAG &&
8789       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8790     // A direct static reference to a global.
8791     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8792     Offset = 0;
8793   } else {
8794     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8795   }
8796
8797   if (Subtarget->isPICStyleRIPRel() &&
8798       (M == CodeModel::Small || M == CodeModel::Kernel))
8799     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8800   else
8801     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8802
8803   // With PIC, the address is actually $g + Offset.
8804   if (isGlobalRelativeToPICBase(OpFlags)) {
8805     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8806                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8807                          Result);
8808   }
8809
8810   // For globals that require a load from a stub to get the address, emit the
8811   // load.
8812   if (isGlobalStubReference(OpFlags))
8813     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8814                          MachinePointerInfo::getGOT(), false, false, false, 0);
8815
8816   // If there was a non-zero offset that we didn't fold, create an explicit
8817   // addition for it.
8818   if (Offset != 0)
8819     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8820                          DAG.getConstant(Offset, getPointerTy()));
8821
8822   return Result;
8823 }
8824
8825 SDValue
8826 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8827   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8828   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8829   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8830 }
8831
8832 static SDValue
8833 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8834            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8835            unsigned char OperandFlags, bool LocalDynamic = false) {
8836   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8837   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8838   SDLoc dl(GA);
8839   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8840                                            GA->getValueType(0),
8841                                            GA->getOffset(),
8842                                            OperandFlags);
8843
8844   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8845                                            : X86ISD::TLSADDR;
8846
8847   if (InFlag) {
8848     SDValue Ops[] = { Chain,  TGA, *InFlag };
8849     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8850   } else {
8851     SDValue Ops[]  = { Chain, TGA };
8852     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8853   }
8854
8855   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8856   MFI->setAdjustsStack(true);
8857
8858   SDValue Flag = Chain.getValue(1);
8859   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8860 }
8861
8862 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8863 static SDValue
8864 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8865                                 const EVT PtrVT) {
8866   SDValue InFlag;
8867   SDLoc dl(GA);  // ? function entry point might be better
8868   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8869                                    DAG.getNode(X86ISD::GlobalBaseReg,
8870                                                SDLoc(), PtrVT), InFlag);
8871   InFlag = Chain.getValue(1);
8872
8873   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8874 }
8875
8876 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8877 static SDValue
8878 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8879                                 const EVT PtrVT) {
8880   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8881                     X86::RAX, X86II::MO_TLSGD);
8882 }
8883
8884 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8885                                            SelectionDAG &DAG,
8886                                            const EVT PtrVT,
8887                                            bool is64Bit) {
8888   SDLoc dl(GA);
8889
8890   // Get the start address of the TLS block for this module.
8891   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8892       .getInfo<X86MachineFunctionInfo>();
8893   MFI->incNumLocalDynamicTLSAccesses();
8894
8895   SDValue Base;
8896   if (is64Bit) {
8897     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8898                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8899   } else {
8900     SDValue InFlag;
8901     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8902         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8903     InFlag = Chain.getValue(1);
8904     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8905                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8906   }
8907
8908   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8909   // of Base.
8910
8911   // Build x@dtpoff.
8912   unsigned char OperandFlags = X86II::MO_DTPOFF;
8913   unsigned WrapperKind = X86ISD::Wrapper;
8914   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8915                                            GA->getValueType(0),
8916                                            GA->getOffset(), OperandFlags);
8917   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8918
8919   // Add x@dtpoff with the base.
8920   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8921 }
8922
8923 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8924 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8925                                    const EVT PtrVT, TLSModel::Model model,
8926                                    bool is64Bit, bool isPIC) {
8927   SDLoc dl(GA);
8928
8929   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8930   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8931                                                          is64Bit ? 257 : 256));
8932
8933   SDValue ThreadPointer =
8934       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8935                   MachinePointerInfo(Ptr), false, false, false, 0);
8936
8937   unsigned char OperandFlags = 0;
8938   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8939   // initialexec.
8940   unsigned WrapperKind = X86ISD::Wrapper;
8941   if (model == TLSModel::LocalExec) {
8942     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8943   } else if (model == TLSModel::InitialExec) {
8944     if (is64Bit) {
8945       OperandFlags = X86II::MO_GOTTPOFF;
8946       WrapperKind = X86ISD::WrapperRIP;
8947     } else {
8948       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8949     }
8950   } else {
8951     llvm_unreachable("Unexpected model");
8952   }
8953
8954   // emit "addl x@ntpoff,%eax" (local exec)
8955   // or "addl x@indntpoff,%eax" (initial exec)
8956   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8957   SDValue TGA =
8958       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8959                                  GA->getOffset(), OperandFlags);
8960   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8961
8962   if (model == TLSModel::InitialExec) {
8963     if (isPIC && !is64Bit) {
8964       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8965                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8966                            Offset);
8967     }
8968
8969     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8970                          MachinePointerInfo::getGOT(), false, false, false, 0);
8971   }
8972
8973   // The address of the thread local variable is the add of the thread
8974   // pointer with the offset of the variable.
8975   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8976 }
8977
8978 SDValue
8979 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8980
8981   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8982   const GlobalValue *GV = GA->getGlobal();
8983
8984   if (Subtarget->isTargetELF()) {
8985     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8986
8987     switch (model) {
8988       case TLSModel::GeneralDynamic:
8989         if (Subtarget->is64Bit())
8990           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8991         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8992       case TLSModel::LocalDynamic:
8993         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8994                                            Subtarget->is64Bit());
8995       case TLSModel::InitialExec:
8996       case TLSModel::LocalExec:
8997         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8998                                    Subtarget->is64Bit(),
8999                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
9000     }
9001     llvm_unreachable("Unknown TLS model.");
9002   }
9003
9004   if (Subtarget->isTargetDarwin()) {
9005     // Darwin only has one model of TLS.  Lower to that.
9006     unsigned char OpFlag = 0;
9007     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9008                            X86ISD::WrapperRIP : X86ISD::Wrapper;
9009
9010     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9011     // global base reg.
9012     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
9013                   !Subtarget->is64Bit();
9014     if (PIC32)
9015       OpFlag = X86II::MO_TLVP_PIC_BASE;
9016     else
9017       OpFlag = X86II::MO_TLVP;
9018     SDLoc DL(Op);
9019     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9020                                                 GA->getValueType(0),
9021                                                 GA->getOffset(), OpFlag);
9022     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9023
9024     // With PIC32, the address is actually $g + Offset.
9025     if (PIC32)
9026       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9027                            DAG.getNode(X86ISD::GlobalBaseReg,
9028                                        SDLoc(), getPointerTy()),
9029                            Offset);
9030
9031     // Lowering the machine isd will make sure everything is in the right
9032     // location.
9033     SDValue Chain = DAG.getEntryNode();
9034     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9035     SDValue Args[] = { Chain, Offset };
9036     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9037
9038     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9039     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9040     MFI->setAdjustsStack(true);
9041
9042     // And our return value (tls address) is in the standard call return value
9043     // location.
9044     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9045     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9046                               Chain.getValue(1));
9047   }
9048
9049   if (Subtarget->isTargetKnownWindowsMSVC() ||
9050       Subtarget->isTargetWindowsGNU()) {
9051     // Just use the implicit TLS architecture
9052     // Need to generate someting similar to:
9053     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9054     //                                  ; from TEB
9055     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
9056     //   mov     rcx, qword [rdx+rcx*8]
9057     //   mov     eax, .tls$:tlsvar
9058     //   [rax+rcx] contains the address
9059     // Windows 64bit: gs:0x58
9060     // Windows 32bit: fs:__tls_array
9061
9062     SDLoc dl(GA);
9063     SDValue Chain = DAG.getEntryNode();
9064
9065     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9066     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9067     // use its literal value of 0x2C.
9068     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9069                                         ? Type::getInt8PtrTy(*DAG.getContext(),
9070                                                              256)
9071                                         : Type::getInt32PtrTy(*DAG.getContext(),
9072                                                               257));
9073
9074     SDValue TlsArray =
9075         Subtarget->is64Bit()
9076             ? DAG.getIntPtrConstant(0x58)
9077             : (Subtarget->isTargetWindowsGNU()
9078                    ? DAG.getIntPtrConstant(0x2C)
9079                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9080
9081     SDValue ThreadPointer =
9082         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9083                     MachinePointerInfo(Ptr), false, false, false, 0);
9084
9085     // Load the _tls_index variable
9086     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9087     if (Subtarget->is64Bit())
9088       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9089                            IDX, MachinePointerInfo(), MVT::i32,
9090                            false, false, 0);
9091     else
9092       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9093                         false, false, false, 0);
9094
9095     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9096                                     getPointerTy());
9097     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9098
9099     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9100     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9101                       false, false, false, 0);
9102
9103     // Get the offset of start of .tls section
9104     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9105                                              GA->getValueType(0),
9106                                              GA->getOffset(), X86II::MO_SECREL);
9107     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9108
9109     // The address of the thread local variable is the add of the thread
9110     // pointer with the offset of the variable.
9111     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9112   }
9113
9114   llvm_unreachable("TLS not implemented for this target.");
9115 }
9116
9117 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9118 /// and take a 2 x i32 value to shift plus a shift amount.
9119 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9120   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9121   MVT VT = Op.getSimpleValueType();
9122   unsigned VTBits = VT.getSizeInBits();
9123   SDLoc dl(Op);
9124   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9125   SDValue ShOpLo = Op.getOperand(0);
9126   SDValue ShOpHi = Op.getOperand(1);
9127   SDValue ShAmt  = Op.getOperand(2);
9128   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9129   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9130   // during isel.
9131   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9132                                   DAG.getConstant(VTBits - 1, MVT::i8));
9133   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9134                                      DAG.getConstant(VTBits - 1, MVT::i8))
9135                        : DAG.getConstant(0, VT);
9136
9137   SDValue Tmp2, Tmp3;
9138   if (Op.getOpcode() == ISD::SHL_PARTS) {
9139     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9140     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9141   } else {
9142     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9143     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9144   }
9145
9146   // If the shift amount is larger or equal than the width of a part we can't
9147   // rely on the results of shld/shrd. Insert a test and select the appropriate
9148   // values for large shift amounts.
9149   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9150                                 DAG.getConstant(VTBits, MVT::i8));
9151   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9152                              AndNode, DAG.getConstant(0, MVT::i8));
9153
9154   SDValue Hi, Lo;
9155   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9156   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9157   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9158
9159   if (Op.getOpcode() == ISD::SHL_PARTS) {
9160     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9161     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9162   } else {
9163     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9164     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9165   }
9166
9167   SDValue Ops[2] = { Lo, Hi };
9168   return DAG.getMergeValues(Ops, dl);
9169 }
9170
9171 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9172                                            SelectionDAG &DAG) const {
9173   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9174
9175   if (SrcVT.isVector())
9176     return SDValue();
9177
9178   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9179          "Unknown SINT_TO_FP to lower!");
9180
9181   // These are really Legal; return the operand so the caller accepts it as
9182   // Legal.
9183   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9184     return Op;
9185   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9186       Subtarget->is64Bit()) {
9187     return Op;
9188   }
9189
9190   SDLoc dl(Op);
9191   unsigned Size = SrcVT.getSizeInBits()/8;
9192   MachineFunction &MF = DAG.getMachineFunction();
9193   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9194   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9195   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9196                                StackSlot,
9197                                MachinePointerInfo::getFixedStack(SSFI),
9198                                false, false, 0);
9199   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9200 }
9201
9202 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9203                                      SDValue StackSlot,
9204                                      SelectionDAG &DAG) const {
9205   // Build the FILD
9206   SDLoc DL(Op);
9207   SDVTList Tys;
9208   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9209   if (useSSE)
9210     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9211   else
9212     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9213
9214   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9215
9216   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9217   MachineMemOperand *MMO;
9218   if (FI) {
9219     int SSFI = FI->getIndex();
9220     MMO =
9221       DAG.getMachineFunction()
9222       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9223                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9224   } else {
9225     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9226     StackSlot = StackSlot.getOperand(1);
9227   }
9228   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9229   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9230                                            X86ISD::FILD, DL,
9231                                            Tys, Ops, SrcVT, MMO);
9232
9233   if (useSSE) {
9234     Chain = Result.getValue(1);
9235     SDValue InFlag = Result.getValue(2);
9236
9237     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9238     // shouldn't be necessary except that RFP cannot be live across
9239     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9240     MachineFunction &MF = DAG.getMachineFunction();
9241     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9242     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9243     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9244     Tys = DAG.getVTList(MVT::Other);
9245     SDValue Ops[] = {
9246       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9247     };
9248     MachineMemOperand *MMO =
9249       DAG.getMachineFunction()
9250       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9251                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9252
9253     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9254                                     Ops, Op.getValueType(), MMO);
9255     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9256                          MachinePointerInfo::getFixedStack(SSFI),
9257                          false, false, false, 0);
9258   }
9259
9260   return Result;
9261 }
9262
9263 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9264 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9265                                                SelectionDAG &DAG) const {
9266   // This algorithm is not obvious. Here it is what we're trying to output:
9267   /*
9268      movq       %rax,  %xmm0
9269      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9270      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9271      #ifdef __SSE3__
9272        haddpd   %xmm0, %xmm0
9273      #else
9274        pshufd   $0x4e, %xmm0, %xmm1
9275        addpd    %xmm1, %xmm0
9276      #endif
9277   */
9278
9279   SDLoc dl(Op);
9280   LLVMContext *Context = DAG.getContext();
9281
9282   // Build some magic constants.
9283   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9284   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9285   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9286
9287   SmallVector<Constant*,2> CV1;
9288   CV1.push_back(
9289     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9290                                       APInt(64, 0x4330000000000000ULL))));
9291   CV1.push_back(
9292     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9293                                       APInt(64, 0x4530000000000000ULL))));
9294   Constant *C1 = ConstantVector::get(CV1);
9295   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9296
9297   // Load the 64-bit value into an XMM register.
9298   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9299                             Op.getOperand(0));
9300   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9301                               MachinePointerInfo::getConstantPool(),
9302                               false, false, false, 16);
9303   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9304                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9305                               CLod0);
9306
9307   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9308                               MachinePointerInfo::getConstantPool(),
9309                               false, false, false, 16);
9310   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9311   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9312   SDValue Result;
9313
9314   if (Subtarget->hasSSE3()) {
9315     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9316     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9317   } else {
9318     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9319     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9320                                            S2F, 0x4E, DAG);
9321     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9322                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9323                          Sub);
9324   }
9325
9326   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9327                      DAG.getIntPtrConstant(0));
9328 }
9329
9330 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9331 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9332                                                SelectionDAG &DAG) const {
9333   SDLoc dl(Op);
9334   // FP constant to bias correct the final result.
9335   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9336                                    MVT::f64);
9337
9338   // Load the 32-bit value into an XMM register.
9339   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9340                              Op.getOperand(0));
9341
9342   // Zero out the upper parts of the register.
9343   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9344
9345   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9346                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9347                      DAG.getIntPtrConstant(0));
9348
9349   // Or the load with the bias.
9350   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9351                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9352                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9353                                                    MVT::v2f64, Load)),
9354                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9355                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9356                                                    MVT::v2f64, Bias)));
9357   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9358                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9359                    DAG.getIntPtrConstant(0));
9360
9361   // Subtract the bias.
9362   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9363
9364   // Handle final rounding.
9365   EVT DestVT = Op.getValueType();
9366
9367   if (DestVT.bitsLT(MVT::f64))
9368     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9369                        DAG.getIntPtrConstant(0));
9370   if (DestVT.bitsGT(MVT::f64))
9371     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9372
9373   // Handle final rounding.
9374   return Sub;
9375 }
9376
9377 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9378                                                SelectionDAG &DAG) const {
9379   SDValue N0 = Op.getOperand(0);
9380   MVT SVT = N0.getSimpleValueType();
9381   SDLoc dl(Op);
9382
9383   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9384           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9385          "Custom UINT_TO_FP is not supported!");
9386
9387   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9388   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9389                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9390 }
9391
9392 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9393                                            SelectionDAG &DAG) const {
9394   SDValue N0 = Op.getOperand(0);
9395   SDLoc dl(Op);
9396
9397   if (Op.getValueType().isVector())
9398     return lowerUINT_TO_FP_vec(Op, DAG);
9399
9400   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9401   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9402   // the optimization here.
9403   if (DAG.SignBitIsZero(N0))
9404     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9405
9406   MVT SrcVT = N0.getSimpleValueType();
9407   MVT DstVT = Op.getSimpleValueType();
9408   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9409     return LowerUINT_TO_FP_i64(Op, DAG);
9410   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9411     return LowerUINT_TO_FP_i32(Op, DAG);
9412   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9413     return SDValue();
9414
9415   // Make a 64-bit buffer, and use it to build an FILD.
9416   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9417   if (SrcVT == MVT::i32) {
9418     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9419     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9420                                      getPointerTy(), StackSlot, WordOff);
9421     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9422                                   StackSlot, MachinePointerInfo(),
9423                                   false, false, 0);
9424     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9425                                   OffsetSlot, MachinePointerInfo(),
9426                                   false, false, 0);
9427     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9428     return Fild;
9429   }
9430
9431   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9432   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9433                                StackSlot, MachinePointerInfo(),
9434                                false, false, 0);
9435   // For i64 source, we need to add the appropriate power of 2 if the input
9436   // was negative.  This is the same as the optimization in
9437   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9438   // we must be careful to do the computation in x87 extended precision, not
9439   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9440   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9441   MachineMemOperand *MMO =
9442     DAG.getMachineFunction()
9443     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9444                           MachineMemOperand::MOLoad, 8, 8);
9445
9446   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9447   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9448   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9449                                          MVT::i64, MMO);
9450
9451   APInt FF(32, 0x5F800000ULL);
9452
9453   // Check whether the sign bit is set.
9454   SDValue SignSet = DAG.getSetCC(dl,
9455                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9456                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9457                                  ISD::SETLT);
9458
9459   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9460   SDValue FudgePtr = DAG.getConstantPool(
9461                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9462                                          getPointerTy());
9463
9464   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9465   SDValue Zero = DAG.getIntPtrConstant(0);
9466   SDValue Four = DAG.getIntPtrConstant(4);
9467   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9468                                Zero, Four);
9469   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9470
9471   // Load the value out, extending it from f32 to f80.
9472   // FIXME: Avoid the extend by constructing the right constant pool?
9473   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9474                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9475                                  MVT::f32, false, false, 4);
9476   // Extend everything to 80 bits to force it to be done on x87.
9477   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9478   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9479 }
9480
9481 std::pair<SDValue,SDValue>
9482 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9483                                     bool IsSigned, bool IsReplace) const {
9484   SDLoc DL(Op);
9485
9486   EVT DstTy = Op.getValueType();
9487
9488   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9489     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9490     DstTy = MVT::i64;
9491   }
9492
9493   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9494          DstTy.getSimpleVT() >= MVT::i16 &&
9495          "Unknown FP_TO_INT to lower!");
9496
9497   // These are really Legal.
9498   if (DstTy == MVT::i32 &&
9499       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9500     return std::make_pair(SDValue(), SDValue());
9501   if (Subtarget->is64Bit() &&
9502       DstTy == MVT::i64 &&
9503       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9504     return std::make_pair(SDValue(), SDValue());
9505
9506   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9507   // stack slot, or into the FTOL runtime function.
9508   MachineFunction &MF = DAG.getMachineFunction();
9509   unsigned MemSize = DstTy.getSizeInBits()/8;
9510   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9511   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9512
9513   unsigned Opc;
9514   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9515     Opc = X86ISD::WIN_FTOL;
9516   else
9517     switch (DstTy.getSimpleVT().SimpleTy) {
9518     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9519     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9520     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9521     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9522     }
9523
9524   SDValue Chain = DAG.getEntryNode();
9525   SDValue Value = Op.getOperand(0);
9526   EVT TheVT = Op.getOperand(0).getValueType();
9527   // FIXME This causes a redundant load/store if the SSE-class value is already
9528   // in memory, such as if it is on the callstack.
9529   if (isScalarFPTypeInSSEReg(TheVT)) {
9530     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9531     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9532                          MachinePointerInfo::getFixedStack(SSFI),
9533                          false, false, 0);
9534     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9535     SDValue Ops[] = {
9536       Chain, StackSlot, DAG.getValueType(TheVT)
9537     };
9538
9539     MachineMemOperand *MMO =
9540       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9541                               MachineMemOperand::MOLoad, MemSize, MemSize);
9542     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9543     Chain = Value.getValue(1);
9544     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9545     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9546   }
9547
9548   MachineMemOperand *MMO =
9549     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9550                             MachineMemOperand::MOStore, MemSize, MemSize);
9551
9552   if (Opc != X86ISD::WIN_FTOL) {
9553     // Build the FP_TO_INT*_IN_MEM
9554     SDValue Ops[] = { Chain, Value, StackSlot };
9555     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9556                                            Ops, DstTy, MMO);
9557     return std::make_pair(FIST, StackSlot);
9558   } else {
9559     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9560       DAG.getVTList(MVT::Other, MVT::Glue),
9561       Chain, Value);
9562     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9563       MVT::i32, ftol.getValue(1));
9564     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9565       MVT::i32, eax.getValue(2));
9566     SDValue Ops[] = { eax, edx };
9567     SDValue pair = IsReplace
9568       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9569       : DAG.getMergeValues(Ops, DL);
9570     return std::make_pair(pair, SDValue());
9571   }
9572 }
9573
9574 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9575                               const X86Subtarget *Subtarget) {
9576   MVT VT = Op->getSimpleValueType(0);
9577   SDValue In = Op->getOperand(0);
9578   MVT InVT = In.getSimpleValueType();
9579   SDLoc dl(Op);
9580
9581   // Optimize vectors in AVX mode:
9582   //
9583   //   v8i16 -> v8i32
9584   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9585   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9586   //   Concat upper and lower parts.
9587   //
9588   //   v4i32 -> v4i64
9589   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9590   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9591   //   Concat upper and lower parts.
9592   //
9593
9594   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9595       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9596       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9597     return SDValue();
9598
9599   if (Subtarget->hasInt256())
9600     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9601
9602   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9603   SDValue Undef = DAG.getUNDEF(InVT);
9604   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9605   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9606   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9607
9608   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9609                              VT.getVectorNumElements()/2);
9610
9611   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9612   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9613
9614   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9615 }
9616
9617 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9618                                         SelectionDAG &DAG) {
9619   MVT VT = Op->getSimpleValueType(0);
9620   SDValue In = Op->getOperand(0);
9621   MVT InVT = In.getSimpleValueType();
9622   SDLoc DL(Op);
9623   unsigned int NumElts = VT.getVectorNumElements();
9624   if (NumElts != 8 && NumElts != 16)
9625     return SDValue();
9626
9627   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9628     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9629
9630   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9631   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9632   // Now we have only mask extension
9633   assert(InVT.getVectorElementType() == MVT::i1);
9634   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9635   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9636   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9637   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9638   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9639                            MachinePointerInfo::getConstantPool(),
9640                            false, false, false, Alignment);
9641
9642   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9643   if (VT.is512BitVector())
9644     return Brcst;
9645   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9646 }
9647
9648 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9649                                SelectionDAG &DAG) {
9650   if (Subtarget->hasFp256()) {
9651     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9652     if (Res.getNode())
9653       return Res;
9654   }
9655
9656   return SDValue();
9657 }
9658
9659 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9660                                 SelectionDAG &DAG) {
9661   SDLoc DL(Op);
9662   MVT VT = Op.getSimpleValueType();
9663   SDValue In = Op.getOperand(0);
9664   MVT SVT = In.getSimpleValueType();
9665
9666   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9667     return LowerZERO_EXTEND_AVX512(Op, DAG);
9668
9669   if (Subtarget->hasFp256()) {
9670     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9671     if (Res.getNode())
9672       return Res;
9673   }
9674
9675   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9676          VT.getVectorNumElements() != SVT.getVectorNumElements());
9677   return SDValue();
9678 }
9679
9680 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9681   SDLoc DL(Op);
9682   MVT VT = Op.getSimpleValueType();
9683   SDValue In = Op.getOperand(0);
9684   MVT InVT = In.getSimpleValueType();
9685
9686   if (VT == MVT::i1) {
9687     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9688            "Invalid scalar TRUNCATE operation");
9689     if (InVT == MVT::i32)
9690       return SDValue();
9691     if (InVT.getSizeInBits() == 64)
9692       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9693     else if (InVT.getSizeInBits() < 32)
9694       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9695     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9696   }
9697   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9698          "Invalid TRUNCATE operation");
9699
9700   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9701     if (VT.getVectorElementType().getSizeInBits() >=8)
9702       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9703
9704     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9705     unsigned NumElts = InVT.getVectorNumElements();
9706     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9707     if (InVT.getSizeInBits() < 512) {
9708       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9709       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9710       InVT = ExtVT;
9711     }
9712     
9713     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9714     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9715     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9716     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9717     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9718                            MachinePointerInfo::getConstantPool(),
9719                            false, false, false, Alignment);
9720     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9721     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9722     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9723   }
9724
9725   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9726     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9727     if (Subtarget->hasInt256()) {
9728       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9729       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9730       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9731                                 ShufMask);
9732       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9733                          DAG.getIntPtrConstant(0));
9734     }
9735
9736     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9737                                DAG.getIntPtrConstant(0));
9738     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9739                                DAG.getIntPtrConstant(2));
9740     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9741     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9742     static const int ShufMask[] = {0, 2, 4, 6};
9743     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9744   }
9745
9746   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9747     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9748     if (Subtarget->hasInt256()) {
9749       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9750
9751       SmallVector<SDValue,32> pshufbMask;
9752       for (unsigned i = 0; i < 2; ++i) {
9753         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9754         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9755         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9756         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9757         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9758         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9759         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9760         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9761         for (unsigned j = 0; j < 8; ++j)
9762           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9763       }
9764       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9765       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9766       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9767
9768       static const int ShufMask[] = {0,  2,  -1,  -1};
9769       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9770                                 &ShufMask[0]);
9771       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9772                        DAG.getIntPtrConstant(0));
9773       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9774     }
9775
9776     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9777                                DAG.getIntPtrConstant(0));
9778
9779     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9780                                DAG.getIntPtrConstant(4));
9781
9782     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9783     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9784
9785     // The PSHUFB mask:
9786     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9787                                    -1, -1, -1, -1, -1, -1, -1, -1};
9788
9789     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9790     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9791     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9792
9793     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9794     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9795
9796     // The MOVLHPS Mask:
9797     static const int ShufMask2[] = {0, 1, 4, 5};
9798     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9799     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9800   }
9801
9802   // Handle truncation of V256 to V128 using shuffles.
9803   if (!VT.is128BitVector() || !InVT.is256BitVector())
9804     return SDValue();
9805
9806   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9807
9808   unsigned NumElems = VT.getVectorNumElements();
9809   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9810
9811   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9812   // Prepare truncation shuffle mask
9813   for (unsigned i = 0; i != NumElems; ++i)
9814     MaskVec[i] = i * 2;
9815   SDValue V = DAG.getVectorShuffle(NVT, DL,
9816                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9817                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9818   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9819                      DAG.getIntPtrConstant(0));
9820 }
9821
9822 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9823                                            SelectionDAG &DAG) const {
9824   assert(!Op.getSimpleValueType().isVector());
9825
9826   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9827     /*IsSigned=*/ true, /*IsReplace=*/ false);
9828   SDValue FIST = Vals.first, StackSlot = Vals.second;
9829   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9830   if (!FIST.getNode()) return Op;
9831
9832   if (StackSlot.getNode())
9833     // Load the result.
9834     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9835                        FIST, StackSlot, MachinePointerInfo(),
9836                        false, false, false, 0);
9837
9838   // The node is the result.
9839   return FIST;
9840 }
9841
9842 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9843                                            SelectionDAG &DAG) const {
9844   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9845     /*IsSigned=*/ false, /*IsReplace=*/ false);
9846   SDValue FIST = Vals.first, StackSlot = Vals.second;
9847   assert(FIST.getNode() && "Unexpected failure");
9848
9849   if (StackSlot.getNode())
9850     // Load the result.
9851     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9852                        FIST, StackSlot, MachinePointerInfo(),
9853                        false, false, false, 0);
9854
9855   // The node is the result.
9856   return FIST;
9857 }
9858
9859 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9860   SDLoc DL(Op);
9861   MVT VT = Op.getSimpleValueType();
9862   SDValue In = Op.getOperand(0);
9863   MVT SVT = In.getSimpleValueType();
9864
9865   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9866
9867   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9868                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9869                                  In, DAG.getUNDEF(SVT)));
9870 }
9871
9872 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9873   LLVMContext *Context = DAG.getContext();
9874   SDLoc dl(Op);
9875   MVT VT = Op.getSimpleValueType();
9876   MVT EltVT = VT;
9877   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9878   if (VT.isVector()) {
9879     EltVT = VT.getVectorElementType();
9880     NumElts = VT.getVectorNumElements();
9881   }
9882   Constant *C;
9883   if (EltVT == MVT::f64)
9884     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9885                                           APInt(64, ~(1ULL << 63))));
9886   else
9887     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9888                                           APInt(32, ~(1U << 31))));
9889   C = ConstantVector::getSplat(NumElts, C);
9890   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9891   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9892   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9893   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9894                              MachinePointerInfo::getConstantPool(),
9895                              false, false, false, Alignment);
9896   if (VT.isVector()) {
9897     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9898     return DAG.getNode(ISD::BITCAST, dl, VT,
9899                        DAG.getNode(ISD::AND, dl, ANDVT,
9900                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9901                                                Op.getOperand(0)),
9902                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9903   }
9904   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9905 }
9906
9907 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9908   LLVMContext *Context = DAG.getContext();
9909   SDLoc dl(Op);
9910   MVT VT = Op.getSimpleValueType();
9911   MVT EltVT = VT;
9912   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9913   if (VT.isVector()) {
9914     EltVT = VT.getVectorElementType();
9915     NumElts = VT.getVectorNumElements();
9916   }
9917   Constant *C;
9918   if (EltVT == MVT::f64)
9919     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9920                                           APInt(64, 1ULL << 63)));
9921   else
9922     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9923                                           APInt(32, 1U << 31)));
9924   C = ConstantVector::getSplat(NumElts, C);
9925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9926   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9927   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9928   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9929                              MachinePointerInfo::getConstantPool(),
9930                              false, false, false, Alignment);
9931   if (VT.isVector()) {
9932     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9933     return DAG.getNode(ISD::BITCAST, dl, VT,
9934                        DAG.getNode(ISD::XOR, dl, XORVT,
9935                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9936                                                Op.getOperand(0)),
9937                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9938   }
9939
9940   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9941 }
9942
9943 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9945   LLVMContext *Context = DAG.getContext();
9946   SDValue Op0 = Op.getOperand(0);
9947   SDValue Op1 = Op.getOperand(1);
9948   SDLoc dl(Op);
9949   MVT VT = Op.getSimpleValueType();
9950   MVT SrcVT = Op1.getSimpleValueType();
9951
9952   // If second operand is smaller, extend it first.
9953   if (SrcVT.bitsLT(VT)) {
9954     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9955     SrcVT = VT;
9956   }
9957   // And if it is bigger, shrink it first.
9958   if (SrcVT.bitsGT(VT)) {
9959     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9960     SrcVT = VT;
9961   }
9962
9963   // At this point the operands and the result should have the same
9964   // type, and that won't be f80 since that is not custom lowered.
9965
9966   // First get the sign bit of second operand.
9967   SmallVector<Constant*,4> CV;
9968   if (SrcVT == MVT::f64) {
9969     const fltSemantics &Sem = APFloat::IEEEdouble;
9970     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9971     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9972   } else {
9973     const fltSemantics &Sem = APFloat::IEEEsingle;
9974     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9975     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9976     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9977     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9978   }
9979   Constant *C = ConstantVector::get(CV);
9980   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9981   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9982                               MachinePointerInfo::getConstantPool(),
9983                               false, false, false, 16);
9984   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9985
9986   // Shift sign bit right or left if the two operands have different types.
9987   if (SrcVT.bitsGT(VT)) {
9988     // Op0 is MVT::f32, Op1 is MVT::f64.
9989     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9990     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9991                           DAG.getConstant(32, MVT::i32));
9992     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9993     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9994                           DAG.getIntPtrConstant(0));
9995   }
9996
9997   // Clear first operand sign bit.
9998   CV.clear();
9999   if (VT == MVT::f64) {
10000     const fltSemantics &Sem = APFloat::IEEEdouble;
10001     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10002                                                    APInt(64, ~(1ULL << 63)))));
10003     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10004   } else {
10005     const fltSemantics &Sem = APFloat::IEEEsingle;
10006     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10007                                                    APInt(32, ~(1U << 31)))));
10008     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10009     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10010     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10011   }
10012   C = ConstantVector::get(CV);
10013   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10014   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10015                               MachinePointerInfo::getConstantPool(),
10016                               false, false, false, 16);
10017   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10018
10019   // Or the value with the sign bit.
10020   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10021 }
10022
10023 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10024   SDValue N0 = Op.getOperand(0);
10025   SDLoc dl(Op);
10026   MVT VT = Op.getSimpleValueType();
10027
10028   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10029   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10030                                   DAG.getConstant(1, VT));
10031   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10032 }
10033
10034 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10035 //
10036 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10037                                       SelectionDAG &DAG) {
10038   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10039
10040   if (!Subtarget->hasSSE41())
10041     return SDValue();
10042
10043   if (!Op->hasOneUse())
10044     return SDValue();
10045
10046   SDNode *N = Op.getNode();
10047   SDLoc DL(N);
10048
10049   SmallVector<SDValue, 8> Opnds;
10050   DenseMap<SDValue, unsigned> VecInMap;
10051   SmallVector<SDValue, 8> VecIns;
10052   EVT VT = MVT::Other;
10053
10054   // Recognize a special case where a vector is casted into wide integer to
10055   // test all 0s.
10056   Opnds.push_back(N->getOperand(0));
10057   Opnds.push_back(N->getOperand(1));
10058
10059   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10060     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10061     // BFS traverse all OR'd operands.
10062     if (I->getOpcode() == ISD::OR) {
10063       Opnds.push_back(I->getOperand(0));
10064       Opnds.push_back(I->getOperand(1));
10065       // Re-evaluate the number of nodes to be traversed.
10066       e += 2; // 2 more nodes (LHS and RHS) are pushed.
10067       continue;
10068     }
10069
10070     // Quit if a non-EXTRACT_VECTOR_ELT
10071     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10072       return SDValue();
10073
10074     // Quit if without a constant index.
10075     SDValue Idx = I->getOperand(1);
10076     if (!isa<ConstantSDNode>(Idx))
10077       return SDValue();
10078
10079     SDValue ExtractedFromVec = I->getOperand(0);
10080     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10081     if (M == VecInMap.end()) {
10082       VT = ExtractedFromVec.getValueType();
10083       // Quit if not 128/256-bit vector.
10084       if (!VT.is128BitVector() && !VT.is256BitVector())
10085         return SDValue();
10086       // Quit if not the same type.
10087       if (VecInMap.begin() != VecInMap.end() &&
10088           VT != VecInMap.begin()->first.getValueType())
10089         return SDValue();
10090       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10091       VecIns.push_back(ExtractedFromVec);
10092     }
10093     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10094   }
10095
10096   assert((VT.is128BitVector() || VT.is256BitVector()) &&
10097          "Not extracted from 128-/256-bit vector.");
10098
10099   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10100
10101   for (DenseMap<SDValue, unsigned>::const_iterator
10102         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10103     // Quit if not all elements are used.
10104     if (I->second != FullMask)
10105       return SDValue();
10106   }
10107
10108   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10109
10110   // Cast all vectors into TestVT for PTEST.
10111   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10112     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10113
10114   // If more than one full vectors are evaluated, OR them first before PTEST.
10115   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10116     // Each iteration will OR 2 nodes and append the result until there is only
10117     // 1 node left, i.e. the final OR'd value of all vectors.
10118     SDValue LHS = VecIns[Slot];
10119     SDValue RHS = VecIns[Slot + 1];
10120     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10121   }
10122
10123   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10124                      VecIns.back(), VecIns.back());
10125 }
10126
10127 /// \brief return true if \c Op has a use that doesn't just read flags.
10128 static bool hasNonFlagsUse(SDValue Op) {
10129   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10130        ++UI) {
10131     SDNode *User = *UI;
10132     unsigned UOpNo = UI.getOperandNo();
10133     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10134       // Look pass truncate.
10135       UOpNo = User->use_begin().getOperandNo();
10136       User = *User->use_begin();
10137     }
10138
10139     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10140         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10141       return true;
10142   }
10143   return false;
10144 }
10145
10146 /// Emit nodes that will be selected as "test Op0,Op0", or something
10147 /// equivalent.
10148 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10149                                     SelectionDAG &DAG) const {
10150   if (Op.getValueType() == MVT::i1)
10151     // KORTEST instruction should be selected
10152     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10153                        DAG.getConstant(0, Op.getValueType()));
10154
10155   // CF and OF aren't always set the way we want. Determine which
10156   // of these we need.
10157   bool NeedCF = false;
10158   bool NeedOF = false;
10159   switch (X86CC) {
10160   default: break;
10161   case X86::COND_A: case X86::COND_AE:
10162   case X86::COND_B: case X86::COND_BE:
10163     NeedCF = true;
10164     break;
10165   case X86::COND_G: case X86::COND_GE:
10166   case X86::COND_L: case X86::COND_LE:
10167   case X86::COND_O: case X86::COND_NO: {
10168     // Check if we really need to set the
10169     // Overflow flag. If NoSignedWrap is present
10170     // that is not actually needed.
10171     switch (Op->getOpcode()) {
10172     case ISD::ADD:
10173     case ISD::SUB:
10174     case ISD::MUL:
10175     case ISD::SHL: {
10176       const BinaryWithFlagsSDNode *BinNode =
10177           cast<BinaryWithFlagsSDNode>(Op.getNode());
10178       if (BinNode->hasNoSignedWrap())
10179         break;
10180     }
10181     default:
10182       NeedOF = true;
10183       break;
10184     }
10185     break;
10186   }
10187   }
10188   // See if we can use the EFLAGS value from the operand instead of
10189   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10190   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10191   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10192     // Emit a CMP with 0, which is the TEST pattern.
10193     //if (Op.getValueType() == MVT::i1)
10194     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10195     //                     DAG.getConstant(0, MVT::i1));
10196     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10197                        DAG.getConstant(0, Op.getValueType()));
10198   }
10199   unsigned Opcode = 0;
10200   unsigned NumOperands = 0;
10201
10202   // Truncate operations may prevent the merge of the SETCC instruction
10203   // and the arithmetic instruction before it. Attempt to truncate the operands
10204   // of the arithmetic instruction and use a reduced bit-width instruction.
10205   bool NeedTruncation = false;
10206   SDValue ArithOp = Op;
10207   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10208     SDValue Arith = Op->getOperand(0);
10209     // Both the trunc and the arithmetic op need to have one user each.
10210     if (Arith->hasOneUse())
10211       switch (Arith.getOpcode()) {
10212         default: break;
10213         case ISD::ADD:
10214         case ISD::SUB:
10215         case ISD::AND:
10216         case ISD::OR:
10217         case ISD::XOR: {
10218           NeedTruncation = true;
10219           ArithOp = Arith;
10220         }
10221       }
10222   }
10223
10224   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10225   // which may be the result of a CAST.  We use the variable 'Op', which is the
10226   // non-casted variable when we check for possible users.
10227   switch (ArithOp.getOpcode()) {
10228   case ISD::ADD:
10229     // Due to an isel shortcoming, be conservative if this add is likely to be
10230     // selected as part of a load-modify-store instruction. When the root node
10231     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10232     // uses of other nodes in the match, such as the ADD in this case. This
10233     // leads to the ADD being left around and reselected, with the result being
10234     // two adds in the output.  Alas, even if none our users are stores, that
10235     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10236     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10237     // climbing the DAG back to the root, and it doesn't seem to be worth the
10238     // effort.
10239     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10240          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10241       if (UI->getOpcode() != ISD::CopyToReg &&
10242           UI->getOpcode() != ISD::SETCC &&
10243           UI->getOpcode() != ISD::STORE)
10244         goto default_case;
10245
10246     if (ConstantSDNode *C =
10247         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10248       // An add of one will be selected as an INC.
10249       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10250         Opcode = X86ISD::INC;
10251         NumOperands = 1;
10252         break;
10253       }
10254
10255       // An add of negative one (subtract of one) will be selected as a DEC.
10256       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10257         Opcode = X86ISD::DEC;
10258         NumOperands = 1;
10259         break;
10260       }
10261     }
10262
10263     // Otherwise use a regular EFLAGS-setting add.
10264     Opcode = X86ISD::ADD;
10265     NumOperands = 2;
10266     break;
10267   case ISD::SHL:
10268   case ISD::SRL:
10269     // If we have a constant logical shift that's only used in a comparison
10270     // against zero turn it into an equivalent AND. This allows turning it into
10271     // a TEST instruction later.
10272     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10273         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10274       EVT VT = Op.getValueType();
10275       unsigned BitWidth = VT.getSizeInBits();
10276       unsigned ShAmt = Op->getConstantOperandVal(1);
10277       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10278         break;
10279       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10280                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10281                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10282       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10283         break;
10284       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10285                                 DAG.getConstant(Mask, VT));
10286       DAG.ReplaceAllUsesWith(Op, New);
10287       Op = New;
10288     }
10289     break;
10290
10291   case ISD::AND:
10292     // If the primary and result isn't used, don't bother using X86ISD::AND,
10293     // because a TEST instruction will be better.
10294     if (!hasNonFlagsUse(Op))
10295       break;
10296     // FALL THROUGH
10297   case ISD::SUB:
10298   case ISD::OR:
10299   case ISD::XOR:
10300     // Due to the ISEL shortcoming noted above, be conservative if this op is
10301     // likely to be selected as part of a load-modify-store instruction.
10302     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10303            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10304       if (UI->getOpcode() == ISD::STORE)
10305         goto default_case;
10306
10307     // Otherwise use a regular EFLAGS-setting instruction.
10308     switch (ArithOp.getOpcode()) {
10309     default: llvm_unreachable("unexpected operator!");
10310     case ISD::SUB: Opcode = X86ISD::SUB; break;
10311     case ISD::XOR: Opcode = X86ISD::XOR; break;
10312     case ISD::AND: Opcode = X86ISD::AND; break;
10313     case ISD::OR: {
10314       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10315         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10316         if (EFLAGS.getNode())
10317           return EFLAGS;
10318       }
10319       Opcode = X86ISD::OR;
10320       break;
10321     }
10322     }
10323
10324     NumOperands = 2;
10325     break;
10326   case X86ISD::ADD:
10327   case X86ISD::SUB:
10328   case X86ISD::INC:
10329   case X86ISD::DEC:
10330   case X86ISD::OR:
10331   case X86ISD::XOR:
10332   case X86ISD::AND:
10333     return SDValue(Op.getNode(), 1);
10334   default:
10335   default_case:
10336     break;
10337   }
10338
10339   // If we found that truncation is beneficial, perform the truncation and
10340   // update 'Op'.
10341   if (NeedTruncation) {
10342     EVT VT = Op.getValueType();
10343     SDValue WideVal = Op->getOperand(0);
10344     EVT WideVT = WideVal.getValueType();
10345     unsigned ConvertedOp = 0;
10346     // Use a target machine opcode to prevent further DAGCombine
10347     // optimizations that may separate the arithmetic operations
10348     // from the setcc node.
10349     switch (WideVal.getOpcode()) {
10350       default: break;
10351       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10352       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10353       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10354       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10355       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10356     }
10357
10358     if (ConvertedOp) {
10359       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10360       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10361         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10362         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10363         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10364       }
10365     }
10366   }
10367
10368   if (Opcode == 0)
10369     // Emit a CMP with 0, which is the TEST pattern.
10370     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10371                        DAG.getConstant(0, Op.getValueType()));
10372
10373   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10374   SmallVector<SDValue, 4> Ops;
10375   for (unsigned i = 0; i != NumOperands; ++i)
10376     Ops.push_back(Op.getOperand(i));
10377
10378   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10379   DAG.ReplaceAllUsesWith(Op, New);
10380   return SDValue(New.getNode(), 1);
10381 }
10382
10383 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
10384                              SelectionDAG &DAG) {
10385   MVT T = Op.getSimpleValueType();
10386   SDLoc DL(Op);
10387   unsigned Reg = 0;
10388   unsigned size = 0;
10389   switch(T.SimpleTy) {
10390   default: llvm_unreachable("Invalid value type!");
10391   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10392   case MVT::i16: Reg = X86::AX;  size = 2; break;
10393   case MVT::i32: Reg = X86::EAX; size = 4; break;
10394   case MVT::i64:
10395     assert(Subtarget->is64Bit() && "Node not type legal!");
10396     Reg = X86::RAX; size = 8;
10397     break;
10398   }
10399   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10400                                     Op.getOperand(2), SDValue());
10401   SDValue Ops[] = { cpIn.getValue(0),
10402                     Op.getOperand(1),
10403                     Op.getOperand(3),
10404                     DAG.getTargetConstant(size, MVT::i8),
10405                     cpIn.getValue(1) };
10406   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10407   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10408   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10409                                            Ops, T, MMO);
10410   SDValue cpOut =
10411     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10412   return cpOut;
10413 }
10414
10415
10416 /// Emit nodes that will be selected as "cmp Op0,Op1", or something equivalent
10417 /// and set X86CC to the needed condition code to make use of the
10418 /// comparison. This may not be the obvious equivalent to CC if the comparison
10419 /// can be achieved more efficiently using a different method.
10420 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, ISD::CondCode CC,
10421                                    SDLoc dl, SelectionDAG &DAG,
10422                                    unsigned &X86CC) const {
10423    // A cmpxchg instruction will actually perform the comparison
10424   if ((Op0.getOpcode() == ISD::ATOMIC_CMP_SWAP && Op0.getOperand(2) == Op1) ||
10425       (Op1.getOpcode() == ISD::ATOMIC_CMP_SWAP && Op1.getOperand(2) == Op0)) {
10426     SDValue CmpSwap;
10427     if (Op0.getOpcode() == ISD::ATOMIC_CMP_SWAP) {
10428       // x86's cmpxchg instruction performs the equivalent of "cmp desired,
10429       // loaded".
10430       CmpSwap = Op0;
10431       CC = getSetCCSwappedOperands(CC);
10432     } else
10433       CmpSwap = Op1;
10434
10435     // Lowering the CmpSwap node gives us a getCopyFromReg SDValue representing
10436     // the value loaded. I.e. the ATOMIC_CMP_SWAP
10437     X86CC = getSimpleX86IntCC(CC);
10438     SDValue EFLAGS = LowerCMP_SWAP(CmpSwap, Subtarget, DAG);
10439     DAG.ReplaceAllUsesOfValueWith(CmpSwap.getValue(0), EFLAGS);
10440
10441     // Glue on a copy from EFLAGS to be used in place of the required Cmp.
10442     EFLAGS = DAG.getCopyFromReg(EFLAGS.getValue(1), dl, X86::EFLAGS,
10443                                 MVT::i32, EFLAGS.getValue(2));
10444     DAG.ReplaceAllUsesOfValueWith(CmpSwap.getValue(1), EFLAGS.getValue(1));
10445
10446     return EFLAGS;
10447   }
10448
10449   bool IsFP = Op1.getSimpleValueType().isFloatingPoint();
10450   X86CC = TranslateX86CC(CC, IsFP, Op0, Op1, DAG);
10451   if (X86CC == X86::COND_INVALID)
10452     return SDValue();
10453
10454   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10455     if (C->getAPIntValue() == 0)
10456       return EmitTest(Op0, X86CC, dl, DAG);
10457
10458      if (Op0.getValueType() == MVT::i1)
10459        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10460   }
10461
10462   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10463        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10464     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10465     // This avoids subregister aliasing issues. Keep the smaller reference 
10466     // if we're optimizing for size, however, as that'll allow better folding 
10467     // of memory operations.
10468     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10469         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10470              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10471         !Subtarget->isAtom()) {
10472       unsigned ExtendOp =
10473           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10474       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10475       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10476     }
10477     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10478     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10479     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10480                               Op0, Op1);
10481     return SDValue(Sub.getNode(), 1);
10482   }
10483   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10484 }
10485
10486 /// Convert a comparison if required by the subtarget.
10487 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10488                                                  SelectionDAG &DAG) const {
10489   // If the subtarget does not support the FUCOMI instruction, floating-point
10490   // comparisons have to be converted.
10491   if (Subtarget->hasCMov() ||
10492       Cmp.getOpcode() != X86ISD::CMP ||
10493       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10494       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10495     return Cmp;
10496
10497   // The instruction selector will select an FUCOM instruction instead of
10498   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10499   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10500   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10501   SDLoc dl(Cmp);
10502   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10503   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10504   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10505                             DAG.getConstant(8, MVT::i8));
10506   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10507   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10508 }
10509
10510 static bool isAllOnes(SDValue V) {
10511   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10512   return C && C->isAllOnesValue();
10513 }
10514
10515 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10516 /// if it's possible.
10517 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10518                                      SDLoc dl, SelectionDAG &DAG) const {
10519   SDValue Op0 = And.getOperand(0);
10520   SDValue Op1 = And.getOperand(1);
10521   if (Op0.getOpcode() == ISD::TRUNCATE)
10522     Op0 = Op0.getOperand(0);
10523   if (Op1.getOpcode() == ISD::TRUNCATE)
10524     Op1 = Op1.getOperand(0);
10525
10526   SDValue LHS, RHS;
10527   if (Op1.getOpcode() == ISD::SHL)
10528     std::swap(Op0, Op1);
10529   if (Op0.getOpcode() == ISD::SHL) {
10530     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10531       if (And00C->getZExtValue() == 1) {
10532         // If we looked past a truncate, check that it's only truncating away
10533         // known zeros.
10534         unsigned BitWidth = Op0.getValueSizeInBits();
10535         unsigned AndBitWidth = And.getValueSizeInBits();
10536         if (BitWidth > AndBitWidth) {
10537           APInt Zeros, Ones;
10538           DAG.computeKnownBits(Op0, Zeros, Ones);
10539           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10540             return SDValue();
10541         }
10542         LHS = Op1;
10543         RHS = Op0.getOperand(1);
10544       }
10545   } else if (Op1.getOpcode() == ISD::Constant) {
10546     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10547     uint64_t AndRHSVal = AndRHS->getZExtValue();
10548     SDValue AndLHS = Op0;
10549
10550     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10551       LHS = AndLHS.getOperand(0);
10552       RHS = AndLHS.getOperand(1);
10553     }
10554
10555     // Use BT if the immediate can't be encoded in a TEST instruction.
10556     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10557       LHS = AndLHS;
10558       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10559     }
10560   }
10561
10562   if (LHS.getNode()) {
10563     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10564     // instruction.  Since the shift amount is in-range-or-undefined, we know
10565     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10566     // the encoding for the i16 version is larger than the i32 version.
10567     // Also promote i16 to i32 for performance / code size reason.
10568     if (LHS.getValueType() == MVT::i8 ||
10569         LHS.getValueType() == MVT::i16)
10570       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10571
10572     // If the operand types disagree, extend the shift amount to match.  Since
10573     // BT ignores high bits (like shifts) we can use anyextend.
10574     if (LHS.getValueType() != RHS.getValueType())
10575       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10576
10577     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10578     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10579     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10580                        DAG.getConstant(Cond, MVT::i8), BT);
10581   }
10582
10583   return SDValue();
10584 }
10585
10586 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10587 /// mask CMPs.
10588 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10589                               SDValue &Op1) {
10590   unsigned SSECC;
10591   bool Swap = false;
10592
10593   // SSE Condition code mapping:
10594   //  0 - EQ
10595   //  1 - LT
10596   //  2 - LE
10597   //  3 - UNORD
10598   //  4 - NEQ
10599   //  5 - NLT
10600   //  6 - NLE
10601   //  7 - ORD
10602   switch (SetCCOpcode) {
10603   default: llvm_unreachable("Unexpected SETCC condition");
10604   case ISD::SETOEQ:
10605   case ISD::SETEQ:  SSECC = 0; break;
10606   case ISD::SETOGT:
10607   case ISD::SETGT:  Swap = true; // Fallthrough
10608   case ISD::SETLT:
10609   case ISD::SETOLT: SSECC = 1; break;
10610   case ISD::SETOGE:
10611   case ISD::SETGE:  Swap = true; // Fallthrough
10612   case ISD::SETLE:
10613   case ISD::SETOLE: SSECC = 2; break;
10614   case ISD::SETUO:  SSECC = 3; break;
10615   case ISD::SETUNE:
10616   case ISD::SETNE:  SSECC = 4; break;
10617   case ISD::SETULE: Swap = true; // Fallthrough
10618   case ISD::SETUGE: SSECC = 5; break;
10619   case ISD::SETULT: Swap = true; // Fallthrough
10620   case ISD::SETUGT: SSECC = 6; break;
10621   case ISD::SETO:   SSECC = 7; break;
10622   case ISD::SETUEQ:
10623   case ISD::SETONE: SSECC = 8; break;
10624   }
10625   if (Swap)
10626     std::swap(Op0, Op1);
10627
10628   return SSECC;
10629 }
10630
10631 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10632 // ones, and then concatenate the result back.
10633 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10634   MVT VT = Op.getSimpleValueType();
10635
10636   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10637          "Unsupported value type for operation");
10638
10639   unsigned NumElems = VT.getVectorNumElements();
10640   SDLoc dl(Op);
10641   SDValue CC = Op.getOperand(2);
10642
10643   // Extract the LHS vectors
10644   SDValue LHS = Op.getOperand(0);
10645   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10646   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10647
10648   // Extract the RHS vectors
10649   SDValue RHS = Op.getOperand(1);
10650   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10651   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10652
10653   // Issue the operation on the smaller types and concatenate the result back
10654   MVT EltVT = VT.getVectorElementType();
10655   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10656   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10657                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10658                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10659 }
10660
10661 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10662                                      const X86Subtarget *Subtarget) {
10663   SDValue Op0 = Op.getOperand(0);
10664   SDValue Op1 = Op.getOperand(1);
10665   SDValue CC = Op.getOperand(2);
10666   MVT VT = Op.getSimpleValueType();
10667   SDLoc dl(Op);
10668
10669   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10670          Op.getValueType().getScalarType() == MVT::i1 &&
10671          "Cannot set masked compare for this operation");
10672
10673   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10674   unsigned  Opc = 0;
10675   bool Unsigned = false;
10676   bool Swap = false;
10677   unsigned SSECC;
10678   switch (SetCCOpcode) {
10679   default: llvm_unreachable("Unexpected SETCC condition");
10680   case ISD::SETNE:  SSECC = 4; break;
10681   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10682   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10683   case ISD::SETLT:  Swap = true; //fall-through
10684   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10685   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10686   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10687   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10688   case ISD::SETULE: Unsigned = true; //fall-through
10689   case ISD::SETLE:  SSECC = 2; break;
10690   }
10691
10692   if (Swap)
10693     std::swap(Op0, Op1);
10694   if (Opc)
10695     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10696   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10697   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10698                      DAG.getConstant(SSECC, MVT::i8));
10699 }
10700
10701 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10702 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10703 /// return an empty value.
10704 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10705 {
10706   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10707   if (!BV)
10708     return SDValue();
10709
10710   MVT VT = Op1.getSimpleValueType();
10711   MVT EVT = VT.getVectorElementType();
10712   unsigned n = VT.getVectorNumElements();
10713   SmallVector<SDValue, 8> ULTOp1;
10714
10715   for (unsigned i = 0; i < n; ++i) {
10716     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10717     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10718       return SDValue();
10719
10720     // Avoid underflow.
10721     APInt Val = Elt->getAPIntValue();
10722     if (Val == 0)
10723       return SDValue();
10724
10725     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10726   }
10727
10728   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10729 }
10730
10731 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10732                            SelectionDAG &DAG) {
10733   SDValue Op0 = Op.getOperand(0);
10734   SDValue Op1 = Op.getOperand(1);
10735   SDValue CC = Op.getOperand(2);
10736   MVT VT = Op.getSimpleValueType();
10737   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10738   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10739   SDLoc dl(Op);
10740
10741   if (isFP) {
10742 #ifndef NDEBUG
10743     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10744     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10745 #endif
10746
10747     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10748     unsigned Opc = X86ISD::CMPP;
10749     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10750       assert(VT.getVectorNumElements() <= 16);
10751       Opc = X86ISD::CMPM;
10752     }
10753     // In the two special cases we can't handle, emit two comparisons.
10754     if (SSECC == 8) {
10755       unsigned CC0, CC1;
10756       unsigned CombineOpc;
10757       if (SetCCOpcode == ISD::SETUEQ) {
10758         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10759       } else {
10760         assert(SetCCOpcode == ISD::SETONE);
10761         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10762       }
10763
10764       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10765                                  DAG.getConstant(CC0, MVT::i8));
10766       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10767                                  DAG.getConstant(CC1, MVT::i8));
10768       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10769     }
10770     // Handle all other FP comparisons here.
10771     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10772                        DAG.getConstant(SSECC, MVT::i8));
10773   }
10774
10775   // Break 256-bit integer vector compare into smaller ones.
10776   if (VT.is256BitVector() && !Subtarget->hasInt256())
10777     return Lower256IntVSETCC(Op, DAG);
10778
10779   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10780   EVT OpVT = Op1.getValueType();
10781   if (Subtarget->hasAVX512()) {
10782     if (Op1.getValueType().is512BitVector() ||
10783         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10784       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10785
10786     // In AVX-512 architecture setcc returns mask with i1 elements,
10787     // But there is no compare instruction for i8 and i16 elements.
10788     // We are not talking about 512-bit operands in this case, these
10789     // types are illegal.
10790     if (MaskResult &&
10791         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10792          OpVT.getVectorElementType().getSizeInBits() >= 8))
10793       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10794                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10795   }
10796
10797   // We are handling one of the integer comparisons here.  Since SSE only has
10798   // GT and EQ comparisons for integer, swapping operands and multiple
10799   // operations may be required for some comparisons.
10800   unsigned Opc;
10801   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10802   bool Subus = false;
10803
10804   switch (SetCCOpcode) {
10805   default: llvm_unreachable("Unexpected SETCC condition");
10806   case ISD::SETNE:  Invert = true;
10807   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10808   case ISD::SETLT:  Swap = true;
10809   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10810   case ISD::SETGE:  Swap = true;
10811   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10812                     Invert = true; break;
10813   case ISD::SETULT: Swap = true;
10814   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10815                     FlipSigns = true; break;
10816   case ISD::SETUGE: Swap = true;
10817   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10818                     FlipSigns = true; Invert = true; break;
10819   }
10820
10821   // Special case: Use min/max operations for SETULE/SETUGE
10822   MVT VET = VT.getVectorElementType();
10823   bool hasMinMax =
10824        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10825     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10826
10827   if (hasMinMax) {
10828     switch (SetCCOpcode) {
10829     default: break;
10830     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10831     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10832     }
10833
10834     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10835   }
10836
10837   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10838   if (!MinMax && hasSubus) {
10839     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10840     // Op0 u<= Op1:
10841     //   t = psubus Op0, Op1
10842     //   pcmpeq t, <0..0>
10843     switch (SetCCOpcode) {
10844     default: break;
10845     case ISD::SETULT: {
10846       // If the comparison is against a constant we can turn this into a
10847       // setule.  With psubus, setule does not require a swap.  This is
10848       // beneficial because the constant in the register is no longer
10849       // destructed as the destination so it can be hoisted out of a loop.
10850       // Only do this pre-AVX since vpcmp* is no longer destructive.
10851       if (Subtarget->hasAVX())
10852         break;
10853       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10854       if (ULEOp1.getNode()) {
10855         Op1 = ULEOp1;
10856         Subus = true; Invert = false; Swap = false;
10857       }
10858       break;
10859     }
10860     // Psubus is better than flip-sign because it requires no inversion.
10861     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10862     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10863     }
10864
10865     if (Subus) {
10866       Opc = X86ISD::SUBUS;
10867       FlipSigns = false;
10868     }
10869   }
10870
10871   if (Swap)
10872     std::swap(Op0, Op1);
10873
10874   // Check that the operation in question is available (most are plain SSE2,
10875   // but PCMPGTQ and PCMPEQQ have different requirements).
10876   if (VT == MVT::v2i64) {
10877     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10878       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10879
10880       // First cast everything to the right type.
10881       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10882       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10883
10884       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10885       // bits of the inputs before performing those operations. The lower
10886       // compare is always unsigned.
10887       SDValue SB;
10888       if (FlipSigns) {
10889         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10890       } else {
10891         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10892         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10893         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10894                          Sign, Zero, Sign, Zero);
10895       }
10896       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10897       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10898
10899       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10900       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10901       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10902
10903       // Create masks for only the low parts/high parts of the 64 bit integers.
10904       static const int MaskHi[] = { 1, 1, 3, 3 };
10905       static const int MaskLo[] = { 0, 0, 2, 2 };
10906       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10907       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10908       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10909
10910       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10911       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10912
10913       if (Invert)
10914         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10915
10916       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10917     }
10918
10919     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10920       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10921       // pcmpeqd + pshufd + pand.
10922       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10923
10924       // First cast everything to the right type.
10925       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10926       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10927
10928       // Do the compare.
10929       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10930
10931       // Make sure the lower and upper halves are both all-ones.
10932       static const int Mask[] = { 1, 0, 3, 2 };
10933       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10934       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10935
10936       if (Invert)
10937         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10938
10939       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10940     }
10941   }
10942
10943   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10944   // bits of the inputs before performing those operations.
10945   if (FlipSigns) {
10946     EVT EltVT = VT.getVectorElementType();
10947     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10948     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10949     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10950   }
10951
10952   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10953
10954   // If the logical-not of the result is required, perform that now.
10955   if (Invert)
10956     Result = DAG.getNOT(dl, Result, VT);
10957
10958   if (MinMax)
10959     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10960
10961   if (Subus)
10962     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10963                          getZeroVector(VT, Subtarget, DAG, dl));
10964
10965   return Result;
10966 }
10967
10968 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10969
10970   MVT VT = Op.getSimpleValueType();
10971
10972   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10973
10974   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10975          && "SetCC type must be 8-bit or 1-bit integer");
10976   SDValue Op0 = Op.getOperand(0);
10977   SDValue Op1 = Op.getOperand(1);
10978   SDLoc dl(Op);
10979   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10980
10981   // Optimize to BT if possible.
10982   // Lower (X & (1 << N)) == 0 to BT(X, N).
10983   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10984   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10985   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10986       Op1.getOpcode() == ISD::Constant &&
10987       cast<ConstantSDNode>(Op1)->isNullValue() &&
10988       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10989     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10990     if (NewSetCC.getNode())
10991       return NewSetCC;
10992   }
10993
10994   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10995   // these.
10996   if (Op1.getOpcode() == ISD::Constant &&
10997       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10998        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10999       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11000
11001     // If the input is a setcc, then reuse the input setcc or use a new one with
11002     // the inverted condition.
11003     if (Op0.getOpcode() == X86ISD::SETCC) {
11004       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
11005       bool Invert = (CC == ISD::SETNE) ^
11006         cast<ConstantSDNode>(Op1)->isNullValue();
11007       if (!Invert)
11008         return Op0;
11009
11010       CCode = X86::GetOppositeBranchCondition(CCode);
11011       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11012                                   DAG.getConstant(CCode, MVT::i8),
11013                                   Op0.getOperand(1));
11014       if (VT == MVT::i1)
11015         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11016       return SetCC;
11017     }
11018   }
11019   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11020       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11021       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11022
11023     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11024     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11025   }
11026
11027   unsigned X86CC;
11028   SDValue EFLAGS = EmitCmp(Op0, Op1, CC, dl, DAG, X86CC);
11029   if (!EFLAGS.getNode())
11030     return SDValue();
11031
11032   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11033   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11034                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11035   if (VT == MVT::i1)
11036     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11037   return SetCC;
11038 }
11039
11040 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11041 static bool isX86LogicalCmp(SDValue Op) {
11042   unsigned Opc = Op.getNode()->getOpcode();
11043   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11044       Opc == X86ISD::SAHF)
11045     return true;
11046   if (Op.getResNo() == 1 &&
11047       (Opc == X86ISD::ADD ||
11048        Opc == X86ISD::SUB ||
11049        Opc == X86ISD::ADC ||
11050        Opc == X86ISD::SBB ||
11051        Opc == X86ISD::SMUL ||
11052        Opc == X86ISD::UMUL ||
11053        Opc == X86ISD::INC ||
11054        Opc == X86ISD::DEC ||
11055        Opc == X86ISD::OR ||
11056        Opc == X86ISD::XOR ||
11057        Opc == X86ISD::AND))
11058     return true;
11059
11060   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11061     return true;
11062
11063   return false;
11064 }
11065
11066 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11067   if (V.getOpcode() != ISD::TRUNCATE)
11068     return false;
11069
11070   SDValue VOp0 = V.getOperand(0);
11071   unsigned InBits = VOp0.getValueSizeInBits();
11072   unsigned Bits = V.getValueSizeInBits();
11073   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11074 }
11075
11076 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11077   bool addTest = true;
11078   SDValue Cond  = Op.getOperand(0);
11079   SDValue Op1 = Op.getOperand(1);
11080   SDValue Op2 = Op.getOperand(2);
11081   SDLoc DL(Op);
11082   EVT VT = Op1.getValueType();
11083   SDValue CC;
11084
11085   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11086   // are available. Otherwise fp cmovs get lowered into a less efficient branch
11087   // sequence later on.
11088   if (Cond.getOpcode() == ISD::SETCC &&
11089       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11090        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11091       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11092     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11093     int SSECC = translateX86FSETCC(
11094         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11095
11096     if (SSECC != 8) {
11097       if (Subtarget->hasAVX512()) {
11098         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11099                                   DAG.getConstant(SSECC, MVT::i8));
11100         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11101       }
11102       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11103                                 DAG.getConstant(SSECC, MVT::i8));
11104       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11105       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11106       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11107     }
11108   }
11109
11110   if (Cond.getOpcode() == ISD::SETCC) {
11111     SDValue NewCond = LowerSETCC(Cond, DAG);
11112     if (NewCond.getNode())
11113       Cond = NewCond;
11114   }
11115
11116   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11117   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11118   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11119   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11120   if (Cond.getOpcode() == X86ISD::SETCC &&
11121       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11122       isZero(Cond.getOperand(1).getOperand(1))) {
11123     SDValue Cmp = Cond.getOperand(1);
11124
11125     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11126
11127     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11128         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11129       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11130
11131       SDValue CmpOp0 = Cmp.getOperand(0);
11132       // Apply further optimizations for special cases
11133       // (select (x != 0), -1, 0) -> neg & sbb
11134       // (select (x == 0), 0, -1) -> neg & sbb
11135       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11136         if (YC->isNullValue() &&
11137             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11138           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11139           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11140                                     DAG.getConstant(0, CmpOp0.getValueType()),
11141                                     CmpOp0);
11142           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11143                                     DAG.getConstant(X86::COND_B, MVT::i8),
11144                                     SDValue(Neg.getNode(), 1));
11145           return Res;
11146         }
11147
11148       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11149                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11150       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11151
11152       SDValue Res =   // Res = 0 or -1.
11153         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11154                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11155
11156       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11157         Res = DAG.getNOT(DL, Res, Res.getValueType());
11158
11159       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11160       if (!N2C || !N2C->isNullValue())
11161         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11162       return Res;
11163     }
11164   }
11165
11166   // Look past (and (setcc_carry (cmp ...)), 1).
11167   if (Cond.getOpcode() == ISD::AND &&
11168       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11169     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11170     if (C && C->getAPIntValue() == 1)
11171       Cond = Cond.getOperand(0);
11172   }
11173
11174   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11175   // setting operand in place of the X86ISD::SETCC.
11176   unsigned CondOpcode = Cond.getOpcode();
11177   if (CondOpcode == X86ISD::SETCC ||
11178       CondOpcode == X86ISD::SETCC_CARRY) {
11179     CC = Cond.getOperand(0);
11180
11181     SDValue Cmp = Cond.getOperand(1);
11182     unsigned Opc = Cmp.getOpcode();
11183     MVT VT = Op.getSimpleValueType();
11184
11185     bool IllegalFPCMov = false;
11186     if (VT.isFloatingPoint() && !VT.isVector() &&
11187         !isScalarFPTypeInSSEReg(VT))  // FPStack?
11188       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11189
11190     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11191         Opc == X86ISD::BT) { // FIXME
11192       Cond = Cmp;
11193       addTest = false;
11194     }
11195   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11196              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11197              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11198               Cond.getOperand(0).getValueType() != MVT::i8)) {
11199     SDValue LHS = Cond.getOperand(0);
11200     SDValue RHS = Cond.getOperand(1);
11201     unsigned X86Opcode;
11202     unsigned X86Cond;
11203     SDVTList VTs;
11204     switch (CondOpcode) {
11205     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11206     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11207     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11208     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11209     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11210     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11211     default: llvm_unreachable("unexpected overflowing operator");
11212     }
11213     if (CondOpcode == ISD::UMULO)
11214       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11215                           MVT::i32);
11216     else
11217       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11218
11219     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11220
11221     if (CondOpcode == ISD::UMULO)
11222       Cond = X86Op.getValue(2);
11223     else
11224       Cond = X86Op.getValue(1);
11225
11226     CC = DAG.getConstant(X86Cond, MVT::i8);
11227     addTest = false;
11228   }
11229
11230   if (addTest) {
11231     // Look pass the truncate if the high bits are known zero.
11232     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11233         Cond = Cond.getOperand(0);
11234
11235     // We know the result of AND is compared against zero. Try to match
11236     // it to BT.
11237     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11238       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11239       if (NewSetCC.getNode()) {
11240         CC = NewSetCC.getOperand(0);
11241         Cond = NewSetCC.getOperand(1);
11242         addTest = false;
11243       }
11244     }
11245   }
11246
11247   if (addTest) {
11248     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11249     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11250   }
11251
11252   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11253   // a <  b ?  0 : -1 -> RES = setcc_carry
11254   // a >= b ? -1 :  0 -> RES = setcc_carry
11255   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11256   if (Cond.getOpcode() == X86ISD::SUB) {
11257     Cond = ConvertCmpIfNecessary(Cond, DAG);
11258     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11259
11260     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11261         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11262       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11263                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11264       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11265         return DAG.getNOT(DL, Res, Res.getValueType());
11266       return Res;
11267     }
11268   }
11269
11270   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11271   // widen the cmov and push the truncate through. This avoids introducing a new
11272   // branch during isel and doesn't add any extensions.
11273   if (Op.getValueType() == MVT::i8 &&
11274       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11275     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11276     if (T1.getValueType() == T2.getValueType() &&
11277         // Blacklist CopyFromReg to avoid partial register stalls.
11278         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11279       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11280       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11281       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11282     }
11283   }
11284
11285   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11286   // condition is true.
11287   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11288   SDValue Ops[] = { Op2, Op1, CC, Cond };
11289   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11290 }
11291
11292 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11293   MVT VT = Op->getSimpleValueType(0);
11294   SDValue In = Op->getOperand(0);
11295   MVT InVT = In.getSimpleValueType();
11296   SDLoc dl(Op);
11297
11298   unsigned int NumElts = VT.getVectorNumElements();
11299   if (NumElts != 8 && NumElts != 16)
11300     return SDValue();
11301
11302   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11303     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11304
11305   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11306   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11307
11308   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11309   Constant *C = ConstantInt::get(*DAG.getContext(),
11310     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11311
11312   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11313   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11314   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11315                           MachinePointerInfo::getConstantPool(),
11316                           false, false, false, Alignment);
11317   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11318   if (VT.is512BitVector())
11319     return Brcst;
11320   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11321 }
11322
11323 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11324                                 SelectionDAG &DAG) {
11325   MVT VT = Op->getSimpleValueType(0);
11326   SDValue In = Op->getOperand(0);
11327   MVT InVT = In.getSimpleValueType();
11328   SDLoc dl(Op);
11329
11330   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11331     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11332
11333   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11334       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11335       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11336     return SDValue();
11337
11338   if (Subtarget->hasInt256())
11339     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11340
11341   // Optimize vectors in AVX mode
11342   // Sign extend  v8i16 to v8i32 and
11343   //              v4i32 to v4i64
11344   //
11345   // Divide input vector into two parts
11346   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11347   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11348   // concat the vectors to original VT
11349
11350   unsigned NumElems = InVT.getVectorNumElements();
11351   SDValue Undef = DAG.getUNDEF(InVT);
11352
11353   SmallVector<int,8> ShufMask1(NumElems, -1);
11354   for (unsigned i = 0; i != NumElems/2; ++i)
11355     ShufMask1[i] = i;
11356
11357   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11358
11359   SmallVector<int,8> ShufMask2(NumElems, -1);
11360   for (unsigned i = 0; i != NumElems/2; ++i)
11361     ShufMask2[i] = i + NumElems/2;
11362
11363   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11364
11365   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11366                                 VT.getVectorNumElements()/2);
11367
11368   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11369   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11370
11371   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11372 }
11373
11374 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11375 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11376 // from the AND / OR.
11377 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11378   Opc = Op.getOpcode();
11379   if (Opc != ISD::OR && Opc != ISD::AND)
11380     return false;
11381   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11382           Op.getOperand(0).hasOneUse() &&
11383           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11384           Op.getOperand(1).hasOneUse());
11385 }
11386
11387 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11388 // 1 and that the SETCC node has a single use.
11389 static bool isXor1OfSetCC(SDValue Op) {
11390   if (Op.getOpcode() != ISD::XOR)
11391     return false;
11392   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11393   if (N1C && N1C->getAPIntValue() == 1) {
11394     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11395       Op.getOperand(0).hasOneUse();
11396   }
11397   return false;
11398 }
11399
11400 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11401   bool addTest = true;
11402   SDValue Chain = Op.getOperand(0);
11403   SDValue Cond  = Op.getOperand(1);
11404   SDValue Dest  = Op.getOperand(2);
11405   SDLoc dl(Op);
11406   SDValue CC;
11407   bool Inverted = false;
11408
11409   if (Cond.getOpcode() == ISD::SETCC) {
11410     // Check for setcc([su]{add,sub,mul}o == 0).
11411     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11412         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11413         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11414         Cond.getOperand(0).getResNo() == 1 &&
11415         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11416          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11417          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11418          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11419          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11420          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11421       Inverted = true;
11422       Cond = Cond.getOperand(0);
11423     } else {
11424       SDValue NewCond = LowerSETCC(Cond, DAG);
11425       if (NewCond.getNode())
11426         Cond = NewCond;
11427     }
11428   }
11429 #if 0
11430   // FIXME: LowerXALUO doesn't handle these!!
11431   else if (Cond.getOpcode() == X86ISD::ADD  ||
11432            Cond.getOpcode() == X86ISD::SUB  ||
11433            Cond.getOpcode() == X86ISD::SMUL ||
11434            Cond.getOpcode() == X86ISD::UMUL)
11435     Cond = LowerXALUO(Cond, DAG);
11436 #endif
11437
11438   // Look pass (and (setcc_carry (cmp ...)), 1).
11439   if (Cond.getOpcode() == ISD::AND &&
11440       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11441     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11442     if (C && C->getAPIntValue() == 1)
11443       Cond = Cond.getOperand(0);
11444   }
11445
11446   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11447   // setting operand in place of the X86ISD::SETCC.
11448   unsigned CondOpcode = Cond.getOpcode();
11449   if (CondOpcode == X86ISD::SETCC ||
11450       CondOpcode == X86ISD::SETCC_CARRY) {
11451     CC = Cond.getOperand(0);
11452
11453     SDValue Cmp = Cond.getOperand(1);
11454     unsigned Opc = Cmp.getOpcode();
11455     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11456     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11457       Cond = Cmp;
11458       addTest = false;
11459     } else if (Opc == ISD::CopyFromReg &&
11460                Cmp->getOperand(0)->getOpcode() == ISD::CopyFromReg &&
11461                Cmp->getOperand(0)->getOperand(0)->getOpcode() ==
11462                    X86ISD::LCMPXCHG_DAG) {
11463       assert(cast<RegisterSDNode>(Cmp->getOperand(1))->getReg() == X86::EFLAGS);
11464       Chain = Cmp.getValue(1);
11465       Cond = Cmp;
11466       addTest = false;
11467     } else {
11468       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11469       default: break;
11470       case X86::COND_O:
11471       case X86::COND_B:
11472         // These can only come from an arithmetic instruction with overflow,
11473         // e.g. SADDO, UADDO.
11474         Cond = Cond.getNode()->getOperand(1);
11475         addTest = false;
11476         break;
11477       }
11478     }
11479   }
11480   CondOpcode = Cond.getOpcode();
11481   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11482       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11483       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11484        Cond.getOperand(0).getValueType() != MVT::i8)) {
11485     SDValue LHS = Cond.getOperand(0);
11486     SDValue RHS = Cond.getOperand(1);
11487     unsigned X86Opcode;
11488     unsigned X86Cond;
11489     SDVTList VTs;
11490     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11491     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11492     // X86ISD::INC).
11493     switch (CondOpcode) {
11494     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11495     case ISD::SADDO:
11496       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11497         if (C->isOne()) {
11498           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11499           break;
11500         }
11501       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11502     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11503     case ISD::SSUBO:
11504       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11505         if (C->isOne()) {
11506           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11507           break;
11508         }
11509       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11510     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11511     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11512     default: llvm_unreachable("unexpected overflowing operator");
11513     }
11514     if (Inverted)
11515       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11516     if (CondOpcode == ISD::UMULO)
11517       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11518                           MVT::i32);
11519     else
11520       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11521
11522     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11523
11524     if (CondOpcode == ISD::UMULO)
11525       Cond = X86Op.getValue(2);
11526     else
11527       Cond = X86Op.getValue(1);
11528
11529     CC = DAG.getConstant(X86Cond, MVT::i8);
11530     addTest = false;
11531   } else {
11532     unsigned CondOpc;
11533     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11534       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11535       if (CondOpc == ISD::OR) {
11536         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11537         // two branches instead of an explicit OR instruction with a
11538         // separate test.
11539         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11540             isX86LogicalCmp(Cmp)) {
11541           CC = Cond.getOperand(0).getOperand(0);
11542           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11543                               Chain, Dest, CC, Cmp);
11544           CC = Cond.getOperand(1).getOperand(0);
11545           Cond = Cmp;
11546           addTest = false;
11547         }
11548       } else { // ISD::AND
11549         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11550         // two branches instead of an explicit AND instruction with a
11551         // separate test. However, we only do this if this block doesn't
11552         // have a fall-through edge, because this requires an explicit
11553         // jmp when the condition is false.
11554         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11555             isX86LogicalCmp(Cmp) &&
11556             Op.getNode()->hasOneUse()) {
11557           X86::CondCode CCode =
11558             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11559           CCode = X86::GetOppositeBranchCondition(CCode);
11560           CC = DAG.getConstant(CCode, MVT::i8);
11561           SDNode *User = *Op.getNode()->use_begin();
11562           // Look for an unconditional branch following this conditional branch.
11563           // We need this because we need to reverse the successors in order
11564           // to implement FCMP_OEQ.
11565           if (User->getOpcode() == ISD::BR) {
11566             SDValue FalseBB = User->getOperand(1);
11567             SDNode *NewBR =
11568               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11569             assert(NewBR == User);
11570             (void)NewBR;
11571             Dest = FalseBB;
11572
11573             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11574                                 Chain, Dest, CC, Cmp);
11575             X86::CondCode CCode =
11576               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11577             CCode = X86::GetOppositeBranchCondition(CCode);
11578             CC = DAG.getConstant(CCode, MVT::i8);
11579             Cond = Cmp;
11580             addTest = false;
11581           }
11582         }
11583       }
11584     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11585       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11586       // It should be transformed during dag combiner except when the condition
11587       // is set by a arithmetics with overflow node.
11588       X86::CondCode CCode =
11589         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11590       CCode = X86::GetOppositeBranchCondition(CCode);
11591       CC = DAG.getConstant(CCode, MVT::i8);
11592       Cond = Cond.getOperand(0).getOperand(1);
11593       addTest = false;
11594     } else if (Cond.getOpcode() == ISD::SETCC &&
11595                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11596       // For FCMP_OEQ, we can emit
11597       // two branches instead of an explicit AND instruction with a
11598       // separate test. However, we only do this if this block doesn't
11599       // have a fall-through edge, because this requires an explicit
11600       // jmp when the condition is false.
11601       if (Op.getNode()->hasOneUse()) {
11602         SDNode *User = *Op.getNode()->use_begin();
11603         // Look for an unconditional branch following this conditional branch.
11604         // We need this because we need to reverse the successors in order
11605         // to implement FCMP_OEQ.
11606         if (User->getOpcode() == ISD::BR) {
11607           SDValue FalseBB = User->getOperand(1);
11608           SDNode *NewBR =
11609             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11610           assert(NewBR == User);
11611           (void)NewBR;
11612           Dest = FalseBB;
11613
11614           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11615                                     Cond.getOperand(0), Cond.getOperand(1));
11616           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11617           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11618           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11619                               Chain, Dest, CC, Cmp);
11620           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11621           Cond = Cmp;
11622           addTest = false;
11623         }
11624       }
11625     } else if (Cond.getOpcode() == ISD::SETCC &&
11626                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11627       // For FCMP_UNE, we can emit
11628       // two branches instead of an explicit AND instruction with a
11629       // separate test. However, we only do this if this block doesn't
11630       // have a fall-through edge, because this requires an explicit
11631       // jmp when the condition is false.
11632       if (Op.getNode()->hasOneUse()) {
11633         SDNode *User = *Op.getNode()->use_begin();
11634         // Look for an unconditional branch following this conditional branch.
11635         // We need this because we need to reverse the successors in order
11636         // to implement FCMP_UNE.
11637         if (User->getOpcode() == ISD::BR) {
11638           SDValue FalseBB = User->getOperand(1);
11639           SDNode *NewBR =
11640             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11641           assert(NewBR == User);
11642           (void)NewBR;
11643
11644           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11645                                     Cond.getOperand(0), Cond.getOperand(1));
11646           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11647           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11648           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11649                               Chain, Dest, CC, Cmp);
11650           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11651           Cond = Cmp;
11652           addTest = false;
11653           Dest = FalseBB;
11654         }
11655       }
11656     }
11657   }
11658
11659   if (addTest) {
11660     // Look pass the truncate if the high bits are known zero.
11661     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11662         Cond = Cond.getOperand(0);
11663
11664     // We know the result of AND is compared against zero. Try to match
11665     // it to BT.
11666     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11667       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11668       if (NewSetCC.getNode()) {
11669         CC = NewSetCC.getOperand(0);
11670         Cond = NewSetCC.getOperand(1);
11671         addTest = false;
11672       }
11673     }
11674   }
11675
11676   if (addTest) {
11677     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11678     CC = DAG.getConstant(X86Cond, MVT::i8);
11679     Cond = EmitTest(Cond, X86Cond, dl, DAG);
11680   }
11681   Cond = ConvertCmpIfNecessary(Cond, DAG);
11682   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11683                      Chain, Dest, CC, Cond);
11684 }
11685
11686 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11687 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11688 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11689 // that the guard pages used by the OS virtual memory manager are allocated in
11690 // correct sequence.
11691 SDValue
11692 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11693                                            SelectionDAG &DAG) const {
11694   MachineFunction &MF = DAG.getMachineFunction();
11695   bool SplitStack = MF.shouldSplitStack();
11696   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11697                SplitStack;
11698   SDLoc dl(Op);
11699
11700   if (!Lower) {
11701     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11702     SDNode* Node = Op.getNode();
11703
11704     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11705     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11706         " not tell us which reg is the stack pointer!");
11707     EVT VT = Node->getValueType(0);
11708     SDValue Tmp1 = SDValue(Node, 0);
11709     SDValue Tmp2 = SDValue(Node, 1);
11710     SDValue Tmp3 = Node->getOperand(2);
11711     SDValue Chain = Tmp1.getOperand(0);
11712
11713     // Chain the dynamic stack allocation so that it doesn't modify the stack
11714     // pointer when other instructions are using the stack.
11715     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11716         SDLoc(Node));
11717
11718     SDValue Size = Tmp2.getOperand(1);
11719     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11720     Chain = SP.getValue(1);
11721     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11722     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11723     unsigned StackAlign = TFI.getStackAlignment();
11724     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11725     if (Align > StackAlign)
11726       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11727           DAG.getConstant(-(uint64_t)Align, VT));
11728     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11729
11730     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11731         DAG.getIntPtrConstant(0, true), SDValue(),
11732         SDLoc(Node));
11733
11734     SDValue Ops[2] = { Tmp1, Tmp2 };
11735     return DAG.getMergeValues(Ops, dl);
11736   }
11737
11738   // Get the inputs.
11739   SDValue Chain = Op.getOperand(0);
11740   SDValue Size  = Op.getOperand(1);
11741   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11742   EVT VT = Op.getNode()->getValueType(0);
11743
11744   bool Is64Bit = Subtarget->is64Bit();
11745   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11746
11747   if (SplitStack) {
11748     MachineRegisterInfo &MRI = MF.getRegInfo();
11749
11750     if (Is64Bit) {
11751       // The 64 bit implementation of segmented stacks needs to clobber both r10
11752       // r11. This makes it impossible to use it along with nested parameters.
11753       const Function *F = MF.getFunction();
11754
11755       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11756            I != E; ++I)
11757         if (I->hasNestAttr())
11758           report_fatal_error("Cannot use segmented stacks with functions that "
11759                              "have nested arguments.");
11760     }
11761
11762     const TargetRegisterClass *AddrRegClass =
11763       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11764     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11765     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11766     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11767                                 DAG.getRegister(Vreg, SPTy));
11768     SDValue Ops1[2] = { Value, Chain };
11769     return DAG.getMergeValues(Ops1, dl);
11770   } else {
11771     SDValue Flag;
11772     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11773
11774     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11775     Flag = Chain.getValue(1);
11776     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11777
11778     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11779
11780     const X86RegisterInfo *RegInfo =
11781       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11782     unsigned SPReg = RegInfo->getStackRegister();
11783     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11784     Chain = SP.getValue(1);
11785
11786     if (Align) {
11787       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11788                        DAG.getConstant(-(uint64_t)Align, VT));
11789       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11790     }
11791
11792     SDValue Ops1[2] = { SP, Chain };
11793     return DAG.getMergeValues(Ops1, dl);
11794   }
11795 }
11796
11797 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11798   MachineFunction &MF = DAG.getMachineFunction();
11799   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11800
11801   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11802   SDLoc DL(Op);
11803
11804   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11805     // vastart just stores the address of the VarArgsFrameIndex slot into the
11806     // memory location argument.
11807     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11808                                    getPointerTy());
11809     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11810                         MachinePointerInfo(SV), false, false, 0);
11811   }
11812
11813   // __va_list_tag:
11814   //   gp_offset         (0 - 6 * 8)
11815   //   fp_offset         (48 - 48 + 8 * 16)
11816   //   overflow_arg_area (point to parameters coming in memory).
11817   //   reg_save_area
11818   SmallVector<SDValue, 8> MemOps;
11819   SDValue FIN = Op.getOperand(1);
11820   // Store gp_offset
11821   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11822                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11823                                                MVT::i32),
11824                                FIN, MachinePointerInfo(SV), false, false, 0);
11825   MemOps.push_back(Store);
11826
11827   // Store fp_offset
11828   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11829                     FIN, DAG.getIntPtrConstant(4));
11830   Store = DAG.getStore(Op.getOperand(0), DL,
11831                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11832                                        MVT::i32),
11833                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11834   MemOps.push_back(Store);
11835
11836   // Store ptr to overflow_arg_area
11837   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11838                     FIN, DAG.getIntPtrConstant(4));
11839   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11840                                     getPointerTy());
11841   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11842                        MachinePointerInfo(SV, 8),
11843                        false, false, 0);
11844   MemOps.push_back(Store);
11845
11846   // Store ptr to reg_save_area.
11847   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11848                     FIN, DAG.getIntPtrConstant(8));
11849   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11850                                     getPointerTy());
11851   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11852                        MachinePointerInfo(SV, 16), false, false, 0);
11853   MemOps.push_back(Store);
11854   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11855 }
11856
11857 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11858   assert(Subtarget->is64Bit() &&
11859          "LowerVAARG only handles 64-bit va_arg!");
11860   assert((Subtarget->isTargetLinux() ||
11861           Subtarget->isTargetDarwin()) &&
11862           "Unhandled target in LowerVAARG");
11863   assert(Op.getNode()->getNumOperands() == 4);
11864   SDValue Chain = Op.getOperand(0);
11865   SDValue SrcPtr = Op.getOperand(1);
11866   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11867   unsigned Align = Op.getConstantOperandVal(3);
11868   SDLoc dl(Op);
11869
11870   EVT ArgVT = Op.getNode()->getValueType(0);
11871   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11872   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11873   uint8_t ArgMode;
11874
11875   // Decide which area this value should be read from.
11876   // TODO: Implement the AMD64 ABI in its entirety. This simple
11877   // selection mechanism works only for the basic types.
11878   if (ArgVT == MVT::f80) {
11879     llvm_unreachable("va_arg for f80 not yet implemented");
11880   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11881     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11882   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11883     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11884   } else {
11885     llvm_unreachable("Unhandled argument type in LowerVAARG");
11886   }
11887
11888   if (ArgMode == 2) {
11889     // Sanity Check: Make sure using fp_offset makes sense.
11890     assert(!getTargetMachine().Options.UseSoftFloat &&
11891            !(DAG.getMachineFunction()
11892                 .getFunction()->getAttributes()
11893                 .hasAttribute(AttributeSet::FunctionIndex,
11894                               Attribute::NoImplicitFloat)) &&
11895            Subtarget->hasSSE1());
11896   }
11897
11898   // Insert VAARG_64 node into the DAG
11899   // VAARG_64 returns two values: Variable Argument Address, Chain
11900   SmallVector<SDValue, 11> InstOps;
11901   InstOps.push_back(Chain);
11902   InstOps.push_back(SrcPtr);
11903   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11904   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11905   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11906   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11907   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11908                                           VTs, InstOps, MVT::i64,
11909                                           MachinePointerInfo(SV),
11910                                           /*Align=*/0,
11911                                           /*Volatile=*/false,
11912                                           /*ReadMem=*/true,
11913                                           /*WriteMem=*/true);
11914   Chain = VAARG.getValue(1);
11915
11916   // Load the next argument and return it
11917   return DAG.getLoad(ArgVT, dl,
11918                      Chain,
11919                      VAARG,
11920                      MachinePointerInfo(),
11921                      false, false, false, 0);
11922 }
11923
11924 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11925                            SelectionDAG &DAG) {
11926   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11927   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11928   SDValue Chain = Op.getOperand(0);
11929   SDValue DstPtr = Op.getOperand(1);
11930   SDValue SrcPtr = Op.getOperand(2);
11931   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11932   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11933   SDLoc DL(Op);
11934
11935   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11936                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11937                        false,
11938                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11939 }
11940
11941 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11942 // amount is a constant. Takes immediate version of shift as input.
11943 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11944                                           SDValue SrcOp, uint64_t ShiftAmt,
11945                                           SelectionDAG &DAG) {
11946   MVT ElementType = VT.getVectorElementType();
11947
11948   // Fold this packed shift into its first operand if ShiftAmt is 0.
11949   if (ShiftAmt == 0)
11950     return SrcOp;
11951
11952   // Check for ShiftAmt >= element width
11953   if (ShiftAmt >= ElementType.getSizeInBits()) {
11954     if (Opc == X86ISD::VSRAI)
11955       ShiftAmt = ElementType.getSizeInBits() - 1;
11956     else
11957       return DAG.getConstant(0, VT);
11958   }
11959
11960   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11961          && "Unknown target vector shift-by-constant node");
11962
11963   // Fold this packed vector shift into a build vector if SrcOp is a
11964   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11965   if (VT == SrcOp.getSimpleValueType() &&
11966       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11967     SmallVector<SDValue, 8> Elts;
11968     unsigned NumElts = SrcOp->getNumOperands();
11969     ConstantSDNode *ND;
11970
11971     switch(Opc) {
11972     default: llvm_unreachable(nullptr);
11973     case X86ISD::VSHLI:
11974       for (unsigned i=0; i!=NumElts; ++i) {
11975         SDValue CurrentOp = SrcOp->getOperand(i);
11976         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11977           Elts.push_back(CurrentOp);
11978           continue;
11979         }
11980         ND = cast<ConstantSDNode>(CurrentOp);
11981         const APInt &C = ND->getAPIntValue();
11982         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11983       }
11984       break;
11985     case X86ISD::VSRLI:
11986       for (unsigned i=0; i!=NumElts; ++i) {
11987         SDValue CurrentOp = SrcOp->getOperand(i);
11988         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11989           Elts.push_back(CurrentOp);
11990           continue;
11991         }
11992         ND = cast<ConstantSDNode>(CurrentOp);
11993         const APInt &C = ND->getAPIntValue();
11994         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11995       }
11996       break;
11997     case X86ISD::VSRAI:
11998       for (unsigned i=0; i!=NumElts; ++i) {
11999         SDValue CurrentOp = SrcOp->getOperand(i);
12000         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12001           Elts.push_back(CurrentOp);
12002           continue;
12003         }
12004         ND = cast<ConstantSDNode>(CurrentOp);
12005         const APInt &C = ND->getAPIntValue();
12006         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
12007       }
12008       break;
12009     }
12010
12011     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
12012   }
12013
12014   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
12015 }
12016
12017 // getTargetVShiftNode - Handle vector element shifts where the shift amount
12018 // may or may not be a constant. Takes immediate version of shift as input.
12019 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
12020                                    SDValue SrcOp, SDValue ShAmt,
12021                                    SelectionDAG &DAG) {
12022   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
12023
12024   // Catch shift-by-constant.
12025   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12026     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12027                                       CShAmt->getZExtValue(), DAG);
12028
12029   // Change opcode to non-immediate version
12030   switch (Opc) {
12031     default: llvm_unreachable("Unknown target vector shift node");
12032     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12033     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12034     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12035   }
12036
12037   // Need to build a vector containing shift amount
12038   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12039   SDValue ShOps[4];
12040   ShOps[0] = ShAmt;
12041   ShOps[1] = DAG.getConstant(0, MVT::i32);
12042   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12043   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12044
12045   // The return type has to be a 128-bit type with the same element
12046   // type as the input type.
12047   MVT EltVT = VT.getVectorElementType();
12048   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12049
12050   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12051   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12052 }
12053
12054 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12055   SDLoc dl(Op);
12056   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12057   switch (IntNo) {
12058   default: return SDValue();    // Don't custom lower most intrinsics.
12059   // Comparison intrinsics.
12060   case Intrinsic::x86_sse_comieq_ss:
12061   case Intrinsic::x86_sse_comilt_ss:
12062   case Intrinsic::x86_sse_comile_ss:
12063   case Intrinsic::x86_sse_comigt_ss:
12064   case Intrinsic::x86_sse_comige_ss:
12065   case Intrinsic::x86_sse_comineq_ss:
12066   case Intrinsic::x86_sse_ucomieq_ss:
12067   case Intrinsic::x86_sse_ucomilt_ss:
12068   case Intrinsic::x86_sse_ucomile_ss:
12069   case Intrinsic::x86_sse_ucomigt_ss:
12070   case Intrinsic::x86_sse_ucomige_ss:
12071   case Intrinsic::x86_sse_ucomineq_ss:
12072   case Intrinsic::x86_sse2_comieq_sd:
12073   case Intrinsic::x86_sse2_comilt_sd:
12074   case Intrinsic::x86_sse2_comile_sd:
12075   case Intrinsic::x86_sse2_comigt_sd:
12076   case Intrinsic::x86_sse2_comige_sd:
12077   case Intrinsic::x86_sse2_comineq_sd:
12078   case Intrinsic::x86_sse2_ucomieq_sd:
12079   case Intrinsic::x86_sse2_ucomilt_sd:
12080   case Intrinsic::x86_sse2_ucomile_sd:
12081   case Intrinsic::x86_sse2_ucomigt_sd:
12082   case Intrinsic::x86_sse2_ucomige_sd:
12083   case Intrinsic::x86_sse2_ucomineq_sd: {
12084     unsigned Opc;
12085     ISD::CondCode CC;
12086     switch (IntNo) {
12087     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12088     case Intrinsic::x86_sse_comieq_ss:
12089     case Intrinsic::x86_sse2_comieq_sd:
12090       Opc = X86ISD::COMI;
12091       CC = ISD::SETEQ;
12092       break;
12093     case Intrinsic::x86_sse_comilt_ss:
12094     case Intrinsic::x86_sse2_comilt_sd:
12095       Opc = X86ISD::COMI;
12096       CC = ISD::SETLT;
12097       break;
12098     case Intrinsic::x86_sse_comile_ss:
12099     case Intrinsic::x86_sse2_comile_sd:
12100       Opc = X86ISD::COMI;
12101       CC = ISD::SETLE;
12102       break;
12103     case Intrinsic::x86_sse_comigt_ss:
12104     case Intrinsic::x86_sse2_comigt_sd:
12105       Opc = X86ISD::COMI;
12106       CC = ISD::SETGT;
12107       break;
12108     case Intrinsic::x86_sse_comige_ss:
12109     case Intrinsic::x86_sse2_comige_sd:
12110       Opc = X86ISD::COMI;
12111       CC = ISD::SETGE;
12112       break;
12113     case Intrinsic::x86_sse_comineq_ss:
12114     case Intrinsic::x86_sse2_comineq_sd:
12115       Opc = X86ISD::COMI;
12116       CC = ISD::SETNE;
12117       break;
12118     case Intrinsic::x86_sse_ucomieq_ss:
12119     case Intrinsic::x86_sse2_ucomieq_sd:
12120       Opc = X86ISD::UCOMI;
12121       CC = ISD::SETEQ;
12122       break;
12123     case Intrinsic::x86_sse_ucomilt_ss:
12124     case Intrinsic::x86_sse2_ucomilt_sd:
12125       Opc = X86ISD::UCOMI;
12126       CC = ISD::SETLT;
12127       break;
12128     case Intrinsic::x86_sse_ucomile_ss:
12129     case Intrinsic::x86_sse2_ucomile_sd:
12130       Opc = X86ISD::UCOMI;
12131       CC = ISD::SETLE;
12132       break;
12133     case Intrinsic::x86_sse_ucomigt_ss:
12134     case Intrinsic::x86_sse2_ucomigt_sd:
12135       Opc = X86ISD::UCOMI;
12136       CC = ISD::SETGT;
12137       break;
12138     case Intrinsic::x86_sse_ucomige_ss:
12139     case Intrinsic::x86_sse2_ucomige_sd:
12140       Opc = X86ISD::UCOMI;
12141       CC = ISD::SETGE;
12142       break;
12143     case Intrinsic::x86_sse_ucomineq_ss:
12144     case Intrinsic::x86_sse2_ucomineq_sd:
12145       Opc = X86ISD::UCOMI;
12146       CC = ISD::SETNE;
12147       break;
12148     }
12149
12150     SDValue LHS = Op.getOperand(1);
12151     SDValue RHS = Op.getOperand(2);
12152     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12153     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12154     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12155     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12156                                 DAG.getConstant(X86CC, MVT::i8), Cond);
12157     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12158   }
12159
12160   // Arithmetic intrinsics.
12161   case Intrinsic::x86_sse2_pmulu_dq:
12162   case Intrinsic::x86_avx2_pmulu_dq:
12163     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12164                        Op.getOperand(1), Op.getOperand(2));
12165
12166   case Intrinsic::x86_sse41_pmuldq:
12167   case Intrinsic::x86_avx2_pmul_dq:
12168     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12169                        Op.getOperand(1), Op.getOperand(2));
12170
12171   case Intrinsic::x86_sse2_pmulhu_w:
12172   case Intrinsic::x86_avx2_pmulhu_w:
12173     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12174                        Op.getOperand(1), Op.getOperand(2));
12175
12176   case Intrinsic::x86_sse2_pmulh_w:
12177   case Intrinsic::x86_avx2_pmulh_w:
12178     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12179                        Op.getOperand(1), Op.getOperand(2));
12180
12181   // SSE2/AVX2 sub with unsigned saturation intrinsics
12182   case Intrinsic::x86_sse2_psubus_b:
12183   case Intrinsic::x86_sse2_psubus_w:
12184   case Intrinsic::x86_avx2_psubus_b:
12185   case Intrinsic::x86_avx2_psubus_w:
12186     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12187                        Op.getOperand(1), Op.getOperand(2));
12188
12189   // SSE3/AVX horizontal add/sub intrinsics
12190   case Intrinsic::x86_sse3_hadd_ps:
12191   case Intrinsic::x86_sse3_hadd_pd:
12192   case Intrinsic::x86_avx_hadd_ps_256:
12193   case Intrinsic::x86_avx_hadd_pd_256:
12194   case Intrinsic::x86_sse3_hsub_ps:
12195   case Intrinsic::x86_sse3_hsub_pd:
12196   case Intrinsic::x86_avx_hsub_ps_256:
12197   case Intrinsic::x86_avx_hsub_pd_256:
12198   case Intrinsic::x86_ssse3_phadd_w_128:
12199   case Intrinsic::x86_ssse3_phadd_d_128:
12200   case Intrinsic::x86_avx2_phadd_w:
12201   case Intrinsic::x86_avx2_phadd_d:
12202   case Intrinsic::x86_ssse3_phsub_w_128:
12203   case Intrinsic::x86_ssse3_phsub_d_128:
12204   case Intrinsic::x86_avx2_phsub_w:
12205   case Intrinsic::x86_avx2_phsub_d: {
12206     unsigned Opcode;
12207     switch (IntNo) {
12208     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12209     case Intrinsic::x86_sse3_hadd_ps:
12210     case Intrinsic::x86_sse3_hadd_pd:
12211     case Intrinsic::x86_avx_hadd_ps_256:
12212     case Intrinsic::x86_avx_hadd_pd_256:
12213       Opcode = X86ISD::FHADD;
12214       break;
12215     case Intrinsic::x86_sse3_hsub_ps:
12216     case Intrinsic::x86_sse3_hsub_pd:
12217     case Intrinsic::x86_avx_hsub_ps_256:
12218     case Intrinsic::x86_avx_hsub_pd_256:
12219       Opcode = X86ISD::FHSUB;
12220       break;
12221     case Intrinsic::x86_ssse3_phadd_w_128:
12222     case Intrinsic::x86_ssse3_phadd_d_128:
12223     case Intrinsic::x86_avx2_phadd_w:
12224     case Intrinsic::x86_avx2_phadd_d:
12225       Opcode = X86ISD::HADD;
12226       break;
12227     case Intrinsic::x86_ssse3_phsub_w_128:
12228     case Intrinsic::x86_ssse3_phsub_d_128:
12229     case Intrinsic::x86_avx2_phsub_w:
12230     case Intrinsic::x86_avx2_phsub_d:
12231       Opcode = X86ISD::HSUB;
12232       break;
12233     }
12234     return DAG.getNode(Opcode, dl, Op.getValueType(),
12235                        Op.getOperand(1), Op.getOperand(2));
12236   }
12237
12238   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12239   case Intrinsic::x86_sse2_pmaxu_b:
12240   case Intrinsic::x86_sse41_pmaxuw:
12241   case Intrinsic::x86_sse41_pmaxud:
12242   case Intrinsic::x86_avx2_pmaxu_b:
12243   case Intrinsic::x86_avx2_pmaxu_w:
12244   case Intrinsic::x86_avx2_pmaxu_d:
12245   case Intrinsic::x86_sse2_pminu_b:
12246   case Intrinsic::x86_sse41_pminuw:
12247   case Intrinsic::x86_sse41_pminud:
12248   case Intrinsic::x86_avx2_pminu_b:
12249   case Intrinsic::x86_avx2_pminu_w:
12250   case Intrinsic::x86_avx2_pminu_d:
12251   case Intrinsic::x86_sse41_pmaxsb:
12252   case Intrinsic::x86_sse2_pmaxs_w:
12253   case Intrinsic::x86_sse41_pmaxsd:
12254   case Intrinsic::x86_avx2_pmaxs_b:
12255   case Intrinsic::x86_avx2_pmaxs_w:
12256   case Intrinsic::x86_avx2_pmaxs_d:
12257   case Intrinsic::x86_sse41_pminsb:
12258   case Intrinsic::x86_sse2_pmins_w:
12259   case Intrinsic::x86_sse41_pminsd:
12260   case Intrinsic::x86_avx2_pmins_b:
12261   case Intrinsic::x86_avx2_pmins_w:
12262   case Intrinsic::x86_avx2_pmins_d: {
12263     unsigned Opcode;
12264     switch (IntNo) {
12265     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12266     case Intrinsic::x86_sse2_pmaxu_b:
12267     case Intrinsic::x86_sse41_pmaxuw:
12268     case Intrinsic::x86_sse41_pmaxud:
12269     case Intrinsic::x86_avx2_pmaxu_b:
12270     case Intrinsic::x86_avx2_pmaxu_w:
12271     case Intrinsic::x86_avx2_pmaxu_d:
12272       Opcode = X86ISD::UMAX;
12273       break;
12274     case Intrinsic::x86_sse2_pminu_b:
12275     case Intrinsic::x86_sse41_pminuw:
12276     case Intrinsic::x86_sse41_pminud:
12277     case Intrinsic::x86_avx2_pminu_b:
12278     case Intrinsic::x86_avx2_pminu_w:
12279     case Intrinsic::x86_avx2_pminu_d:
12280       Opcode = X86ISD::UMIN;
12281       break;
12282     case Intrinsic::x86_sse41_pmaxsb:
12283     case Intrinsic::x86_sse2_pmaxs_w:
12284     case Intrinsic::x86_sse41_pmaxsd:
12285     case Intrinsic::x86_avx2_pmaxs_b:
12286     case Intrinsic::x86_avx2_pmaxs_w:
12287     case Intrinsic::x86_avx2_pmaxs_d:
12288       Opcode = X86ISD::SMAX;
12289       break;
12290     case Intrinsic::x86_sse41_pminsb:
12291     case Intrinsic::x86_sse2_pmins_w:
12292     case Intrinsic::x86_sse41_pminsd:
12293     case Intrinsic::x86_avx2_pmins_b:
12294     case Intrinsic::x86_avx2_pmins_w:
12295     case Intrinsic::x86_avx2_pmins_d:
12296       Opcode = X86ISD::SMIN;
12297       break;
12298     }
12299     return DAG.getNode(Opcode, dl, Op.getValueType(),
12300                        Op.getOperand(1), Op.getOperand(2));
12301   }
12302
12303   // SSE/SSE2/AVX floating point max/min intrinsics.
12304   case Intrinsic::x86_sse_max_ps:
12305   case Intrinsic::x86_sse2_max_pd:
12306   case Intrinsic::x86_avx_max_ps_256:
12307   case Intrinsic::x86_avx_max_pd_256:
12308   case Intrinsic::x86_sse_min_ps:
12309   case Intrinsic::x86_sse2_min_pd:
12310   case Intrinsic::x86_avx_min_ps_256:
12311   case Intrinsic::x86_avx_min_pd_256: {
12312     unsigned Opcode;
12313     switch (IntNo) {
12314     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12315     case Intrinsic::x86_sse_max_ps:
12316     case Intrinsic::x86_sse2_max_pd:
12317     case Intrinsic::x86_avx_max_ps_256:
12318     case Intrinsic::x86_avx_max_pd_256:
12319       Opcode = X86ISD::FMAX;
12320       break;
12321     case Intrinsic::x86_sse_min_ps:
12322     case Intrinsic::x86_sse2_min_pd:
12323     case Intrinsic::x86_avx_min_ps_256:
12324     case Intrinsic::x86_avx_min_pd_256:
12325       Opcode = X86ISD::FMIN;
12326       break;
12327     }
12328     return DAG.getNode(Opcode, dl, Op.getValueType(),
12329                        Op.getOperand(1), Op.getOperand(2));
12330   }
12331
12332   // AVX2 variable shift intrinsics
12333   case Intrinsic::x86_avx2_psllv_d:
12334   case Intrinsic::x86_avx2_psllv_q:
12335   case Intrinsic::x86_avx2_psllv_d_256:
12336   case Intrinsic::x86_avx2_psllv_q_256:
12337   case Intrinsic::x86_avx2_psrlv_d:
12338   case Intrinsic::x86_avx2_psrlv_q:
12339   case Intrinsic::x86_avx2_psrlv_d_256:
12340   case Intrinsic::x86_avx2_psrlv_q_256:
12341   case Intrinsic::x86_avx2_psrav_d:
12342   case Intrinsic::x86_avx2_psrav_d_256: {
12343     unsigned Opcode;
12344     switch (IntNo) {
12345     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12346     case Intrinsic::x86_avx2_psllv_d:
12347     case Intrinsic::x86_avx2_psllv_q:
12348     case Intrinsic::x86_avx2_psllv_d_256:
12349     case Intrinsic::x86_avx2_psllv_q_256:
12350       Opcode = ISD::SHL;
12351       break;
12352     case Intrinsic::x86_avx2_psrlv_d:
12353     case Intrinsic::x86_avx2_psrlv_q:
12354     case Intrinsic::x86_avx2_psrlv_d_256:
12355     case Intrinsic::x86_avx2_psrlv_q_256:
12356       Opcode = ISD::SRL;
12357       break;
12358     case Intrinsic::x86_avx2_psrav_d:
12359     case Intrinsic::x86_avx2_psrav_d_256:
12360       Opcode = ISD::SRA;
12361       break;
12362     }
12363     return DAG.getNode(Opcode, dl, Op.getValueType(),
12364                        Op.getOperand(1), Op.getOperand(2));
12365   }
12366
12367   case Intrinsic::x86_ssse3_pshuf_b_128:
12368   case Intrinsic::x86_avx2_pshuf_b:
12369     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12370                        Op.getOperand(1), Op.getOperand(2));
12371
12372   case Intrinsic::x86_ssse3_psign_b_128:
12373   case Intrinsic::x86_ssse3_psign_w_128:
12374   case Intrinsic::x86_ssse3_psign_d_128:
12375   case Intrinsic::x86_avx2_psign_b:
12376   case Intrinsic::x86_avx2_psign_w:
12377   case Intrinsic::x86_avx2_psign_d:
12378     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12379                        Op.getOperand(1), Op.getOperand(2));
12380
12381   case Intrinsic::x86_sse41_insertps:
12382     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12383                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12384
12385   case Intrinsic::x86_avx_vperm2f128_ps_256:
12386   case Intrinsic::x86_avx_vperm2f128_pd_256:
12387   case Intrinsic::x86_avx_vperm2f128_si_256:
12388   case Intrinsic::x86_avx2_vperm2i128:
12389     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12390                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12391
12392   case Intrinsic::x86_avx2_permd:
12393   case Intrinsic::x86_avx2_permps:
12394     // Operands intentionally swapped. Mask is last operand to intrinsic,
12395     // but second operand for node/instruction.
12396     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12397                        Op.getOperand(2), Op.getOperand(1));
12398
12399   case Intrinsic::x86_sse_sqrt_ps:
12400   case Intrinsic::x86_sse2_sqrt_pd:
12401   case Intrinsic::x86_avx_sqrt_ps_256:
12402   case Intrinsic::x86_avx_sqrt_pd_256:
12403     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12404
12405   // ptest and testp intrinsics. The intrinsic these come from are designed to
12406   // return an integer value, not just an instruction so lower it to the ptest
12407   // or testp pattern and a setcc for the result.
12408   case Intrinsic::x86_sse41_ptestz:
12409   case Intrinsic::x86_sse41_ptestc:
12410   case Intrinsic::x86_sse41_ptestnzc:
12411   case Intrinsic::x86_avx_ptestz_256:
12412   case Intrinsic::x86_avx_ptestc_256:
12413   case Intrinsic::x86_avx_ptestnzc_256:
12414   case Intrinsic::x86_avx_vtestz_ps:
12415   case Intrinsic::x86_avx_vtestc_ps:
12416   case Intrinsic::x86_avx_vtestnzc_ps:
12417   case Intrinsic::x86_avx_vtestz_pd:
12418   case Intrinsic::x86_avx_vtestc_pd:
12419   case Intrinsic::x86_avx_vtestnzc_pd:
12420   case Intrinsic::x86_avx_vtestz_ps_256:
12421   case Intrinsic::x86_avx_vtestc_ps_256:
12422   case Intrinsic::x86_avx_vtestnzc_ps_256:
12423   case Intrinsic::x86_avx_vtestz_pd_256:
12424   case Intrinsic::x86_avx_vtestc_pd_256:
12425   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12426     bool IsTestPacked = false;
12427     unsigned X86CC;
12428     switch (IntNo) {
12429     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12430     case Intrinsic::x86_avx_vtestz_ps:
12431     case Intrinsic::x86_avx_vtestz_pd:
12432     case Intrinsic::x86_avx_vtestz_ps_256:
12433     case Intrinsic::x86_avx_vtestz_pd_256:
12434       IsTestPacked = true; // Fallthrough
12435     case Intrinsic::x86_sse41_ptestz:
12436     case Intrinsic::x86_avx_ptestz_256:
12437       // ZF = 1
12438       X86CC = X86::COND_E;
12439       break;
12440     case Intrinsic::x86_avx_vtestc_ps:
12441     case Intrinsic::x86_avx_vtestc_pd:
12442     case Intrinsic::x86_avx_vtestc_ps_256:
12443     case Intrinsic::x86_avx_vtestc_pd_256:
12444       IsTestPacked = true; // Fallthrough
12445     case Intrinsic::x86_sse41_ptestc:
12446     case Intrinsic::x86_avx_ptestc_256:
12447       // CF = 1
12448       X86CC = X86::COND_B;
12449       break;
12450     case Intrinsic::x86_avx_vtestnzc_ps:
12451     case Intrinsic::x86_avx_vtestnzc_pd:
12452     case Intrinsic::x86_avx_vtestnzc_ps_256:
12453     case Intrinsic::x86_avx_vtestnzc_pd_256:
12454       IsTestPacked = true; // Fallthrough
12455     case Intrinsic::x86_sse41_ptestnzc:
12456     case Intrinsic::x86_avx_ptestnzc_256:
12457       // ZF and CF = 0
12458       X86CC = X86::COND_A;
12459       break;
12460     }
12461
12462     SDValue LHS = Op.getOperand(1);
12463     SDValue RHS = Op.getOperand(2);
12464     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12465     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12466     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12467     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12468     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12469   }
12470   case Intrinsic::x86_avx512_kortestz_w:
12471   case Intrinsic::x86_avx512_kortestc_w: {
12472     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12473     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12474     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12475     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12476     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12477     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12478     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12479   }
12480
12481   // SSE/AVX shift intrinsics
12482   case Intrinsic::x86_sse2_psll_w:
12483   case Intrinsic::x86_sse2_psll_d:
12484   case Intrinsic::x86_sse2_psll_q:
12485   case Intrinsic::x86_avx2_psll_w:
12486   case Intrinsic::x86_avx2_psll_d:
12487   case Intrinsic::x86_avx2_psll_q:
12488   case Intrinsic::x86_sse2_psrl_w:
12489   case Intrinsic::x86_sse2_psrl_d:
12490   case Intrinsic::x86_sse2_psrl_q:
12491   case Intrinsic::x86_avx2_psrl_w:
12492   case Intrinsic::x86_avx2_psrl_d:
12493   case Intrinsic::x86_avx2_psrl_q:
12494   case Intrinsic::x86_sse2_psra_w:
12495   case Intrinsic::x86_sse2_psra_d:
12496   case Intrinsic::x86_avx2_psra_w:
12497   case Intrinsic::x86_avx2_psra_d: {
12498     unsigned Opcode;
12499     switch (IntNo) {
12500     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12501     case Intrinsic::x86_sse2_psll_w:
12502     case Intrinsic::x86_sse2_psll_d:
12503     case Intrinsic::x86_sse2_psll_q:
12504     case Intrinsic::x86_avx2_psll_w:
12505     case Intrinsic::x86_avx2_psll_d:
12506     case Intrinsic::x86_avx2_psll_q:
12507       Opcode = X86ISD::VSHL;
12508       break;
12509     case Intrinsic::x86_sse2_psrl_w:
12510     case Intrinsic::x86_sse2_psrl_d:
12511     case Intrinsic::x86_sse2_psrl_q:
12512     case Intrinsic::x86_avx2_psrl_w:
12513     case Intrinsic::x86_avx2_psrl_d:
12514     case Intrinsic::x86_avx2_psrl_q:
12515       Opcode = X86ISD::VSRL;
12516       break;
12517     case Intrinsic::x86_sse2_psra_w:
12518     case Intrinsic::x86_sse2_psra_d:
12519     case Intrinsic::x86_avx2_psra_w:
12520     case Intrinsic::x86_avx2_psra_d:
12521       Opcode = X86ISD::VSRA;
12522       break;
12523     }
12524     return DAG.getNode(Opcode, dl, Op.getValueType(),
12525                        Op.getOperand(1), Op.getOperand(2));
12526   }
12527
12528   // SSE/AVX immediate shift intrinsics
12529   case Intrinsic::x86_sse2_pslli_w:
12530   case Intrinsic::x86_sse2_pslli_d:
12531   case Intrinsic::x86_sse2_pslli_q:
12532   case Intrinsic::x86_avx2_pslli_w:
12533   case Intrinsic::x86_avx2_pslli_d:
12534   case Intrinsic::x86_avx2_pslli_q:
12535   case Intrinsic::x86_sse2_psrli_w:
12536   case Intrinsic::x86_sse2_psrli_d:
12537   case Intrinsic::x86_sse2_psrli_q:
12538   case Intrinsic::x86_avx2_psrli_w:
12539   case Intrinsic::x86_avx2_psrli_d:
12540   case Intrinsic::x86_avx2_psrli_q:
12541   case Intrinsic::x86_sse2_psrai_w:
12542   case Intrinsic::x86_sse2_psrai_d:
12543   case Intrinsic::x86_avx2_psrai_w:
12544   case Intrinsic::x86_avx2_psrai_d: {
12545     unsigned Opcode;
12546     switch (IntNo) {
12547     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12548     case Intrinsic::x86_sse2_pslli_w:
12549     case Intrinsic::x86_sse2_pslli_d:
12550     case Intrinsic::x86_sse2_pslli_q:
12551     case Intrinsic::x86_avx2_pslli_w:
12552     case Intrinsic::x86_avx2_pslli_d:
12553     case Intrinsic::x86_avx2_pslli_q:
12554       Opcode = X86ISD::VSHLI;
12555       break;
12556     case Intrinsic::x86_sse2_psrli_w:
12557     case Intrinsic::x86_sse2_psrli_d:
12558     case Intrinsic::x86_sse2_psrli_q:
12559     case Intrinsic::x86_avx2_psrli_w:
12560     case Intrinsic::x86_avx2_psrli_d:
12561     case Intrinsic::x86_avx2_psrli_q:
12562       Opcode = X86ISD::VSRLI;
12563       break;
12564     case Intrinsic::x86_sse2_psrai_w:
12565     case Intrinsic::x86_sse2_psrai_d:
12566     case Intrinsic::x86_avx2_psrai_w:
12567     case Intrinsic::x86_avx2_psrai_d:
12568       Opcode = X86ISD::VSRAI;
12569       break;
12570     }
12571     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12572                                Op.getOperand(1), Op.getOperand(2), DAG);
12573   }
12574
12575   case Intrinsic::x86_sse42_pcmpistria128:
12576   case Intrinsic::x86_sse42_pcmpestria128:
12577   case Intrinsic::x86_sse42_pcmpistric128:
12578   case Intrinsic::x86_sse42_pcmpestric128:
12579   case Intrinsic::x86_sse42_pcmpistrio128:
12580   case Intrinsic::x86_sse42_pcmpestrio128:
12581   case Intrinsic::x86_sse42_pcmpistris128:
12582   case Intrinsic::x86_sse42_pcmpestris128:
12583   case Intrinsic::x86_sse42_pcmpistriz128:
12584   case Intrinsic::x86_sse42_pcmpestriz128: {
12585     unsigned Opcode;
12586     unsigned X86CC;
12587     switch (IntNo) {
12588     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12589     case Intrinsic::x86_sse42_pcmpistria128:
12590       Opcode = X86ISD::PCMPISTRI;
12591       X86CC = X86::COND_A;
12592       break;
12593     case Intrinsic::x86_sse42_pcmpestria128:
12594       Opcode = X86ISD::PCMPESTRI;
12595       X86CC = X86::COND_A;
12596       break;
12597     case Intrinsic::x86_sse42_pcmpistric128:
12598       Opcode = X86ISD::PCMPISTRI;
12599       X86CC = X86::COND_B;
12600       break;
12601     case Intrinsic::x86_sse42_pcmpestric128:
12602       Opcode = X86ISD::PCMPESTRI;
12603       X86CC = X86::COND_B;
12604       break;
12605     case Intrinsic::x86_sse42_pcmpistrio128:
12606       Opcode = X86ISD::PCMPISTRI;
12607       X86CC = X86::COND_O;
12608       break;
12609     case Intrinsic::x86_sse42_pcmpestrio128:
12610       Opcode = X86ISD::PCMPESTRI;
12611       X86CC = X86::COND_O;
12612       break;
12613     case Intrinsic::x86_sse42_pcmpistris128:
12614       Opcode = X86ISD::PCMPISTRI;
12615       X86CC = X86::COND_S;
12616       break;
12617     case Intrinsic::x86_sse42_pcmpestris128:
12618       Opcode = X86ISD::PCMPESTRI;
12619       X86CC = X86::COND_S;
12620       break;
12621     case Intrinsic::x86_sse42_pcmpistriz128:
12622       Opcode = X86ISD::PCMPISTRI;
12623       X86CC = X86::COND_E;
12624       break;
12625     case Intrinsic::x86_sse42_pcmpestriz128:
12626       Opcode = X86ISD::PCMPESTRI;
12627       X86CC = X86::COND_E;
12628       break;
12629     }
12630     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12631     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12632     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12633     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12634                                 DAG.getConstant(X86CC, MVT::i8),
12635                                 SDValue(PCMP.getNode(), 1));
12636     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12637   }
12638
12639   case Intrinsic::x86_sse42_pcmpistri128:
12640   case Intrinsic::x86_sse42_pcmpestri128: {
12641     unsigned Opcode;
12642     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12643       Opcode = X86ISD::PCMPISTRI;
12644     else
12645       Opcode = X86ISD::PCMPESTRI;
12646
12647     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12648     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12649     return DAG.getNode(Opcode, dl, VTs, NewOps);
12650   }
12651   case Intrinsic::x86_fma_vfmadd_ps:
12652   case Intrinsic::x86_fma_vfmadd_pd:
12653   case Intrinsic::x86_fma_vfmsub_ps:
12654   case Intrinsic::x86_fma_vfmsub_pd:
12655   case Intrinsic::x86_fma_vfnmadd_ps:
12656   case Intrinsic::x86_fma_vfnmadd_pd:
12657   case Intrinsic::x86_fma_vfnmsub_ps:
12658   case Intrinsic::x86_fma_vfnmsub_pd:
12659   case Intrinsic::x86_fma_vfmaddsub_ps:
12660   case Intrinsic::x86_fma_vfmaddsub_pd:
12661   case Intrinsic::x86_fma_vfmsubadd_ps:
12662   case Intrinsic::x86_fma_vfmsubadd_pd:
12663   case Intrinsic::x86_fma_vfmadd_ps_256:
12664   case Intrinsic::x86_fma_vfmadd_pd_256:
12665   case Intrinsic::x86_fma_vfmsub_ps_256:
12666   case Intrinsic::x86_fma_vfmsub_pd_256:
12667   case Intrinsic::x86_fma_vfnmadd_ps_256:
12668   case Intrinsic::x86_fma_vfnmadd_pd_256:
12669   case Intrinsic::x86_fma_vfnmsub_ps_256:
12670   case Intrinsic::x86_fma_vfnmsub_pd_256:
12671   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12672   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12673   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12674   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12675   case Intrinsic::x86_fma_vfmadd_ps_512:
12676   case Intrinsic::x86_fma_vfmadd_pd_512:
12677   case Intrinsic::x86_fma_vfmsub_ps_512:
12678   case Intrinsic::x86_fma_vfmsub_pd_512:
12679   case Intrinsic::x86_fma_vfnmadd_ps_512:
12680   case Intrinsic::x86_fma_vfnmadd_pd_512:
12681   case Intrinsic::x86_fma_vfnmsub_ps_512:
12682   case Intrinsic::x86_fma_vfnmsub_pd_512:
12683   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12684   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12685   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12686   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12687     unsigned Opc;
12688     switch (IntNo) {
12689     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12690     case Intrinsic::x86_fma_vfmadd_ps:
12691     case Intrinsic::x86_fma_vfmadd_pd:
12692     case Intrinsic::x86_fma_vfmadd_ps_256:
12693     case Intrinsic::x86_fma_vfmadd_pd_256:
12694     case Intrinsic::x86_fma_vfmadd_ps_512:
12695     case Intrinsic::x86_fma_vfmadd_pd_512:
12696       Opc = X86ISD::FMADD;
12697       break;
12698     case Intrinsic::x86_fma_vfmsub_ps:
12699     case Intrinsic::x86_fma_vfmsub_pd:
12700     case Intrinsic::x86_fma_vfmsub_ps_256:
12701     case Intrinsic::x86_fma_vfmsub_pd_256:
12702     case Intrinsic::x86_fma_vfmsub_ps_512:
12703     case Intrinsic::x86_fma_vfmsub_pd_512:
12704       Opc = X86ISD::FMSUB;
12705       break;
12706     case Intrinsic::x86_fma_vfnmadd_ps:
12707     case Intrinsic::x86_fma_vfnmadd_pd:
12708     case Intrinsic::x86_fma_vfnmadd_ps_256:
12709     case Intrinsic::x86_fma_vfnmadd_pd_256:
12710     case Intrinsic::x86_fma_vfnmadd_ps_512:
12711     case Intrinsic::x86_fma_vfnmadd_pd_512:
12712       Opc = X86ISD::FNMADD;
12713       break;
12714     case Intrinsic::x86_fma_vfnmsub_ps:
12715     case Intrinsic::x86_fma_vfnmsub_pd:
12716     case Intrinsic::x86_fma_vfnmsub_ps_256:
12717     case Intrinsic::x86_fma_vfnmsub_pd_256:
12718     case Intrinsic::x86_fma_vfnmsub_ps_512:
12719     case Intrinsic::x86_fma_vfnmsub_pd_512:
12720       Opc = X86ISD::FNMSUB;
12721       break;
12722     case Intrinsic::x86_fma_vfmaddsub_ps:
12723     case Intrinsic::x86_fma_vfmaddsub_pd:
12724     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12725     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12726     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12727     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12728       Opc = X86ISD::FMADDSUB;
12729       break;
12730     case Intrinsic::x86_fma_vfmsubadd_ps:
12731     case Intrinsic::x86_fma_vfmsubadd_pd:
12732     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12733     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12734     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12735     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12736       Opc = X86ISD::FMSUBADD;
12737       break;
12738     }
12739
12740     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12741                        Op.getOperand(2), Op.getOperand(3));
12742   }
12743   }
12744 }
12745
12746 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12747                               SDValue Src, SDValue Mask, SDValue Base,
12748                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12749                               const X86Subtarget * Subtarget) {
12750   SDLoc dl(Op);
12751   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12752   assert(C && "Invalid scale type");
12753   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12754   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12755                              Index.getSimpleValueType().getVectorNumElements());
12756   SDValue MaskInReg;
12757   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12758   if (MaskC)
12759     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12760   else
12761     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12762   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12763   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12764   SDValue Segment = DAG.getRegister(0, MVT::i32);
12765   if (Src.getOpcode() == ISD::UNDEF)
12766     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12767   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12768   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12769   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12770   return DAG.getMergeValues(RetOps, dl);
12771 }
12772
12773 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12774                                SDValue Src, SDValue Mask, SDValue Base,
12775                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12776   SDLoc dl(Op);
12777   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12778   assert(C && "Invalid scale type");
12779   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12780   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12781   SDValue Segment = DAG.getRegister(0, MVT::i32);
12782   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12783                              Index.getSimpleValueType().getVectorNumElements());
12784   SDValue MaskInReg;
12785   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12786   if (MaskC)
12787     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12788   else
12789     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12790   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12791   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12792   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12793   return SDValue(Res, 1);
12794 }
12795
12796 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12797                                SDValue Mask, SDValue Base, SDValue Index,
12798                                SDValue ScaleOp, SDValue Chain) {
12799   SDLoc dl(Op);
12800   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12801   assert(C && "Invalid scale type");
12802   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12803   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12804   SDValue Segment = DAG.getRegister(0, MVT::i32);
12805   EVT MaskVT =
12806     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12807   SDValue MaskInReg;
12808   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12809   if (MaskC)
12810     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12811   else
12812     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12813   //SDVTList VTs = DAG.getVTList(MVT::Other);
12814   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12815   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12816   return SDValue(Res, 0);
12817 }
12818
12819 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12820 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12821 // also used to custom lower READCYCLECOUNTER nodes.
12822 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12823                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12824                               SmallVectorImpl<SDValue> &Results) {
12825   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12826   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12827   SDValue LO, HI;
12828
12829   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12830   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12831   // and the EAX register is loaded with the low-order 32 bits.
12832   if (Subtarget->is64Bit()) {
12833     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12834     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12835                             LO.getValue(2));
12836   } else {
12837     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12838     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12839                             LO.getValue(2));
12840   }
12841   SDValue Chain = HI.getValue(1);
12842
12843   if (Opcode == X86ISD::RDTSCP_DAG) {
12844     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12845
12846     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12847     // the ECX register. Add 'ecx' explicitly to the chain.
12848     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12849                                      HI.getValue(2));
12850     // Explicitly store the content of ECX at the location passed in input
12851     // to the 'rdtscp' intrinsic.
12852     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12853                          MachinePointerInfo(), false, false, 0);
12854   }
12855
12856   if (Subtarget->is64Bit()) {
12857     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12858     // the EAX register is loaded with the low-order 32 bits.
12859     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12860                               DAG.getConstant(32, MVT::i8));
12861     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12862     Results.push_back(Chain);
12863     return;
12864   }
12865
12866   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12867   SDValue Ops[] = { LO, HI };
12868   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12869   Results.push_back(Pair);
12870   Results.push_back(Chain);
12871 }
12872
12873 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12874                                      SelectionDAG &DAG) {
12875   SmallVector<SDValue, 2> Results;
12876   SDLoc DL(Op);
12877   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12878                           Results);
12879   return DAG.getMergeValues(Results, DL);
12880 }
12881
12882 enum IntrinsicType {
12883   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12884 };
12885
12886 struct IntrinsicData {
12887   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12888     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12889   IntrinsicType Type;
12890   unsigned      Opc0;
12891   unsigned      Opc1;
12892 };
12893
12894 std::map < unsigned, IntrinsicData> IntrMap;
12895 static void InitIntinsicsMap() {
12896   static bool Initialized = false;
12897   if (Initialized) 
12898     return;
12899   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12900                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12901   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12902                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12903   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12904                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12905   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12906                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12907   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12908                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12909   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12910                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12911   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12912                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12913   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12914                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12915   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12916                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12917
12918   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12919                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12920   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12921                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12922   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12923                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12924   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12925                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12926   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12927                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12928   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12929                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12930   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
12931                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12932   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
12933                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12934    
12935   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
12936                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12937                                                         X86::VGATHERPF1QPSm)));
12938   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
12939                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12940                                                         X86::VGATHERPF1QPDm)));
12941   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
12942                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12943                                                         X86::VGATHERPF1DPDm)));
12944   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
12945                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12946                                                         X86::VGATHERPF1DPSm)));
12947   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
12948                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12949                                                         X86::VSCATTERPF1QPSm)));
12950   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
12951                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12952                                                         X86::VSCATTERPF1QPDm)));
12953   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
12954                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12955                                                         X86::VSCATTERPF1DPDm)));
12956   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
12957                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12958                                                         X86::VSCATTERPF1DPSm)));
12959   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12960                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12961   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12962                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12963   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12964                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12965   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12966                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12967   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12968                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12969   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12970                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12971   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12972                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
12973   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12974                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
12975   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12976                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
12977   Initialized = true;
12978 }
12979
12980 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12981                                       SelectionDAG &DAG) {
12982   InitIntinsicsMap();
12983   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12984   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12985   if (itr == IntrMap.end())
12986     return SDValue();
12987
12988   SDLoc dl(Op);
12989   IntrinsicData Intr = itr->second;
12990   switch(Intr.Type) {
12991   case RDSEED:
12992   case RDRAND: {
12993     // Emit the node with the right value type.
12994     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12995     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12996
12997     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12998     // Otherwise return the value from Rand, which is always 0, casted to i32.
12999     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
13000                       DAG.getConstant(1, Op->getValueType(1)),
13001                       DAG.getConstant(X86::COND_B, MVT::i32),
13002                       SDValue(Result.getNode(), 1) };
13003     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
13004                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
13005                                   Ops);
13006
13007     // Return { result, isValid, chain }.
13008     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
13009                        SDValue(Result.getNode(), 2));
13010   }
13011   case GATHER: {
13012   //gather(v1, mask, index, base, scale);
13013     SDValue Chain = Op.getOperand(0);
13014     SDValue Src   = Op.getOperand(2);
13015     SDValue Base  = Op.getOperand(3);
13016     SDValue Index = Op.getOperand(4);
13017     SDValue Mask  = Op.getOperand(5);
13018     SDValue Scale = Op.getOperand(6);
13019     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
13020                           Subtarget);
13021   }
13022   case SCATTER: {
13023   //scatter(base, mask, index, v1, scale);
13024     SDValue Chain = Op.getOperand(0);
13025     SDValue Base  = Op.getOperand(2);
13026     SDValue Mask  = Op.getOperand(3);
13027     SDValue Index = Op.getOperand(4);
13028     SDValue Src   = Op.getOperand(5);
13029     SDValue Scale = Op.getOperand(6);
13030     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13031   }
13032   case PREFETCH: {
13033     SDValue Hint = Op.getOperand(6);
13034     unsigned HintVal;
13035     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13036         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13037       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13038     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13039     SDValue Chain = Op.getOperand(0);
13040     SDValue Mask  = Op.getOperand(2);
13041     SDValue Index = Op.getOperand(3);
13042     SDValue Base  = Op.getOperand(4);
13043     SDValue Scale = Op.getOperand(5);
13044     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13045   }
13046   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13047   case RDTSC: {
13048     SmallVector<SDValue, 2> Results;
13049     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13050     return DAG.getMergeValues(Results, dl);
13051   }
13052   // XTEST intrinsics.
13053   case XTEST: {
13054     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13055     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13056     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13057                                 DAG.getConstant(X86::COND_NE, MVT::i8),
13058                                 InTrans);
13059     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13060     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13061                        Ret, SDValue(InTrans.getNode(), 1));
13062   }
13063   }
13064   llvm_unreachable("Unknown Intrinsic Type");
13065 }
13066
13067 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13068                                            SelectionDAG &DAG) const {
13069   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13070   MFI->setReturnAddressIsTaken(true);
13071
13072   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13073     return SDValue();
13074
13075   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13076   SDLoc dl(Op);
13077   EVT PtrVT = getPointerTy();
13078
13079   if (Depth > 0) {
13080     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13081     const X86RegisterInfo *RegInfo =
13082       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13083     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13084     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13085                        DAG.getNode(ISD::ADD, dl, PtrVT,
13086                                    FrameAddr, Offset),
13087                        MachinePointerInfo(), false, false, false, 0);
13088   }
13089
13090   // Just load the return address.
13091   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13092   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13093                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13094 }
13095
13096 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13097   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13098   MFI->setFrameAddressIsTaken(true);
13099
13100   EVT VT = Op.getValueType();
13101   SDLoc dl(Op);  // FIXME probably not meaningful
13102   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13103   const X86RegisterInfo *RegInfo =
13104     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13105   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13106   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13107           (FrameReg == X86::EBP && VT == MVT::i32)) &&
13108          "Invalid Frame Register!");
13109   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13110   while (Depth--)
13111     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13112                             MachinePointerInfo(),
13113                             false, false, false, 0);
13114   return FrameAddr;
13115 }
13116
13117 // FIXME? Maybe this could be a TableGen attribute on some registers and
13118 // this table could be generated automatically from RegInfo.
13119 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13120                                               EVT VT) const {
13121   unsigned Reg = StringSwitch<unsigned>(RegName)
13122                        .Case("esp", X86::ESP)
13123                        .Case("rsp", X86::RSP)
13124                        .Default(0);
13125   if (Reg)
13126     return Reg;
13127   report_fatal_error("Invalid register name global variable");
13128 }
13129
13130 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13131                                                      SelectionDAG &DAG) const {
13132   const X86RegisterInfo *RegInfo =
13133     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13134   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13135 }
13136
13137 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13138   SDValue Chain     = Op.getOperand(0);
13139   SDValue Offset    = Op.getOperand(1);
13140   SDValue Handler   = Op.getOperand(2);
13141   SDLoc dl      (Op);
13142
13143   EVT PtrVT = getPointerTy();
13144   const X86RegisterInfo *RegInfo =
13145     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13146   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13147   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13148           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13149          "Invalid Frame Register!");
13150   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13151   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13152
13153   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13154                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13155   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13156   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13157                        false, false, 0);
13158   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13159
13160   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13161                      DAG.getRegister(StoreAddrReg, PtrVT));
13162 }
13163
13164 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13165                                                SelectionDAG &DAG) const {
13166   SDLoc DL(Op);
13167   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13168                      DAG.getVTList(MVT::i32, MVT::Other),
13169                      Op.getOperand(0), Op.getOperand(1));
13170 }
13171
13172 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13173                                                 SelectionDAG &DAG) const {
13174   SDLoc DL(Op);
13175   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13176                      Op.getOperand(0), Op.getOperand(1));
13177 }
13178
13179 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13180   return Op.getOperand(0);
13181 }
13182
13183 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13184                                                 SelectionDAG &DAG) const {
13185   SDValue Root = Op.getOperand(0);
13186   SDValue Trmp = Op.getOperand(1); // trampoline
13187   SDValue FPtr = Op.getOperand(2); // nested function
13188   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13189   SDLoc dl (Op);
13190
13191   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13192   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13193
13194   if (Subtarget->is64Bit()) {
13195     SDValue OutChains[6];
13196
13197     // Large code-model.
13198     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
13199     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13200
13201     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13202     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13203
13204     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13205
13206     // Load the pointer to the nested function into R11.
13207     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13208     SDValue Addr = Trmp;
13209     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13210                                 Addr, MachinePointerInfo(TrmpAddr),
13211                                 false, false, 0);
13212
13213     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13214                        DAG.getConstant(2, MVT::i64));
13215     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13216                                 MachinePointerInfo(TrmpAddr, 2),
13217                                 false, false, 2);
13218
13219     // Load the 'nest' parameter value into R10.
13220     // R10 is specified in X86CallingConv.td
13221     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13222     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13223                        DAG.getConstant(10, MVT::i64));
13224     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13225                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13226                                 false, false, 0);
13227
13228     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13229                        DAG.getConstant(12, MVT::i64));
13230     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13231                                 MachinePointerInfo(TrmpAddr, 12),
13232                                 false, false, 2);
13233
13234     // Jump to the nested function.
13235     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13236     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13237                        DAG.getConstant(20, MVT::i64));
13238     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13239                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13240                                 false, false, 0);
13241
13242     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13243     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13244                        DAG.getConstant(22, MVT::i64));
13245     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13246                                 MachinePointerInfo(TrmpAddr, 22),
13247                                 false, false, 0);
13248
13249     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13250   } else {
13251     const Function *Func =
13252       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13253     CallingConv::ID CC = Func->getCallingConv();
13254     unsigned NestReg;
13255
13256     switch (CC) {
13257     default:
13258       llvm_unreachable("Unsupported calling convention");
13259     case CallingConv::C:
13260     case CallingConv::X86_StdCall: {
13261       // Pass 'nest' parameter in ECX.
13262       // Must be kept in sync with X86CallingConv.td
13263       NestReg = X86::ECX;
13264
13265       // Check that ECX wasn't needed by an 'inreg' parameter.
13266       FunctionType *FTy = Func->getFunctionType();
13267       const AttributeSet &Attrs = Func->getAttributes();
13268
13269       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13270         unsigned InRegCount = 0;
13271         unsigned Idx = 1;
13272
13273         for (FunctionType::param_iterator I = FTy->param_begin(),
13274              E = FTy->param_end(); I != E; ++I, ++Idx)
13275           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13276             // FIXME: should only count parameters that are lowered to integers.
13277             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13278
13279         if (InRegCount > 2) {
13280           report_fatal_error("Nest register in use - reduce number of inreg"
13281                              " parameters!");
13282         }
13283       }
13284       break;
13285     }
13286     case CallingConv::X86_FastCall:
13287     case CallingConv::X86_ThisCall:
13288     case CallingConv::Fast:
13289       // Pass 'nest' parameter in EAX.
13290       // Must be kept in sync with X86CallingConv.td
13291       NestReg = X86::EAX;
13292       break;
13293     }
13294
13295     SDValue OutChains[4];
13296     SDValue Addr, Disp;
13297
13298     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13299                        DAG.getConstant(10, MVT::i32));
13300     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13301
13302     // This is storing the opcode for MOV32ri.
13303     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13304     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13305     OutChains[0] = DAG.getStore(Root, dl,
13306                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13307                                 Trmp, MachinePointerInfo(TrmpAddr),
13308                                 false, false, 0);
13309
13310     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13311                        DAG.getConstant(1, MVT::i32));
13312     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13313                                 MachinePointerInfo(TrmpAddr, 1),
13314                                 false, false, 1);
13315
13316     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13317     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13318                        DAG.getConstant(5, MVT::i32));
13319     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13320                                 MachinePointerInfo(TrmpAddr, 5),
13321                                 false, false, 1);
13322
13323     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13324                        DAG.getConstant(6, MVT::i32));
13325     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13326                                 MachinePointerInfo(TrmpAddr, 6),
13327                                 false, false, 1);
13328
13329     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13330   }
13331 }
13332
13333 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13334                                             SelectionDAG &DAG) const {
13335   /*
13336    The rounding mode is in bits 11:10 of FPSR, and has the following
13337    settings:
13338      00 Round to nearest
13339      01 Round to -inf
13340      10 Round to +inf
13341      11 Round to 0
13342
13343   FLT_ROUNDS, on the other hand, expects the following:
13344     -1 Undefined
13345      0 Round to 0
13346      1 Round to nearest
13347      2 Round to +inf
13348      3 Round to -inf
13349
13350   To perform the conversion, we do:
13351     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13352   */
13353
13354   MachineFunction &MF = DAG.getMachineFunction();
13355   const TargetMachine &TM = MF.getTarget();
13356   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13357   unsigned StackAlignment = TFI.getStackAlignment();
13358   MVT VT = Op.getSimpleValueType();
13359   SDLoc DL(Op);
13360
13361   // Save FP Control Word to stack slot
13362   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13363   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13364
13365   MachineMemOperand *MMO =
13366    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13367                            MachineMemOperand::MOStore, 2, 2);
13368
13369   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13370   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13371                                           DAG.getVTList(MVT::Other),
13372                                           Ops, MVT::i16, MMO);
13373
13374   // Load FP Control Word from stack slot
13375   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13376                             MachinePointerInfo(), false, false, false, 0);
13377
13378   // Transform as necessary
13379   SDValue CWD1 =
13380     DAG.getNode(ISD::SRL, DL, MVT::i16,
13381                 DAG.getNode(ISD::AND, DL, MVT::i16,
13382                             CWD, DAG.getConstant(0x800, MVT::i16)),
13383                 DAG.getConstant(11, MVT::i8));
13384   SDValue CWD2 =
13385     DAG.getNode(ISD::SRL, DL, MVT::i16,
13386                 DAG.getNode(ISD::AND, DL, MVT::i16,
13387                             CWD, DAG.getConstant(0x400, MVT::i16)),
13388                 DAG.getConstant(9, MVT::i8));
13389
13390   SDValue RetVal =
13391     DAG.getNode(ISD::AND, DL, MVT::i16,
13392                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13393                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13394                             DAG.getConstant(1, MVT::i16)),
13395                 DAG.getConstant(3, MVT::i16));
13396
13397   return DAG.getNode((VT.getSizeInBits() < 16 ?
13398                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13399 }
13400
13401 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13402   MVT VT = Op.getSimpleValueType();
13403   EVT OpVT = VT;
13404   unsigned NumBits = VT.getSizeInBits();
13405   SDLoc dl(Op);
13406
13407   Op = Op.getOperand(0);
13408   if (VT == MVT::i8) {
13409     // Zero extend to i32 since there is not an i8 bsr.
13410     OpVT = MVT::i32;
13411     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13412   }
13413
13414   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13415   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13416   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13417
13418   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13419   SDValue Ops[] = {
13420     Op,
13421     DAG.getConstant(NumBits+NumBits-1, OpVT),
13422     DAG.getConstant(X86::COND_E, MVT::i8),
13423     Op.getValue(1)
13424   };
13425   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13426
13427   // Finally xor with NumBits-1.
13428   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13429
13430   if (VT == MVT::i8)
13431     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13432   return Op;
13433 }
13434
13435 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13436   MVT VT = Op.getSimpleValueType();
13437   EVT OpVT = VT;
13438   unsigned NumBits = VT.getSizeInBits();
13439   SDLoc dl(Op);
13440
13441   Op = Op.getOperand(0);
13442   if (VT == MVT::i8) {
13443     // Zero extend to i32 since there is not an i8 bsr.
13444     OpVT = MVT::i32;
13445     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13446   }
13447
13448   // Issue a bsr (scan bits in reverse).
13449   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13450   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13451
13452   // And xor with NumBits-1.
13453   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13454
13455   if (VT == MVT::i8)
13456     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13457   return Op;
13458 }
13459
13460 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13461   MVT VT = Op.getSimpleValueType();
13462   unsigned NumBits = VT.getSizeInBits();
13463   SDLoc dl(Op);
13464   Op = Op.getOperand(0);
13465
13466   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13467   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13468   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13469
13470   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13471   SDValue Ops[] = {
13472     Op,
13473     DAG.getConstant(NumBits, VT),
13474     DAG.getConstant(X86::COND_E, MVT::i8),
13475     Op.getValue(1)
13476   };
13477   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13478 }
13479
13480 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13481 // ones, and then concatenate the result back.
13482 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13483   MVT VT = Op.getSimpleValueType();
13484
13485   assert(VT.is256BitVector() && VT.isInteger() &&
13486          "Unsupported value type for operation");
13487
13488   unsigned NumElems = VT.getVectorNumElements();
13489   SDLoc dl(Op);
13490
13491   // Extract the LHS vectors
13492   SDValue LHS = Op.getOperand(0);
13493   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13494   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13495
13496   // Extract the RHS vectors
13497   SDValue RHS = Op.getOperand(1);
13498   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13499   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13500
13501   MVT EltVT = VT.getVectorElementType();
13502   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13503
13504   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13505                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13506                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13507 }
13508
13509 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13510   assert(Op.getSimpleValueType().is256BitVector() &&
13511          Op.getSimpleValueType().isInteger() &&
13512          "Only handle AVX 256-bit vector integer operation");
13513   return Lower256IntArith(Op, DAG);
13514 }
13515
13516 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13517   assert(Op.getSimpleValueType().is256BitVector() &&
13518          Op.getSimpleValueType().isInteger() &&
13519          "Only handle AVX 256-bit vector integer operation");
13520   return Lower256IntArith(Op, DAG);
13521 }
13522
13523 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13524                         SelectionDAG &DAG) {
13525   SDLoc dl(Op);
13526   MVT VT = Op.getSimpleValueType();
13527
13528   // Decompose 256-bit ops into smaller 128-bit ops.
13529   if (VT.is256BitVector() && !Subtarget->hasInt256())
13530     return Lower256IntArith(Op, DAG);
13531
13532   SDValue A = Op.getOperand(0);
13533   SDValue B = Op.getOperand(1);
13534
13535   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13536   if (VT == MVT::v4i32) {
13537     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13538            "Should not custom lower when pmuldq is available!");
13539
13540     // Extract the odd parts.
13541     static const int UnpackMask[] = { 1, -1, 3, -1 };
13542     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13543     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13544
13545     // Multiply the even parts.
13546     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13547     // Now multiply odd parts.
13548     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13549
13550     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13551     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13552
13553     // Merge the two vectors back together with a shuffle. This expands into 2
13554     // shuffles.
13555     static const int ShufMask[] = { 0, 4, 2, 6 };
13556     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13557   }
13558
13559   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13560          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13561
13562   //  Ahi = psrlqi(a, 32);
13563   //  Bhi = psrlqi(b, 32);
13564   //
13565   //  AloBlo = pmuludq(a, b);
13566   //  AloBhi = pmuludq(a, Bhi);
13567   //  AhiBlo = pmuludq(Ahi, b);
13568
13569   //  AloBhi = psllqi(AloBhi, 32);
13570   //  AhiBlo = psllqi(AhiBlo, 32);
13571   //  return AloBlo + AloBhi + AhiBlo;
13572
13573   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13574   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13575
13576   // Bit cast to 32-bit vectors for MULUDQ
13577   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13578                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13579   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13580   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13581   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13582   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13583
13584   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13585   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13586   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13587
13588   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13589   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13590
13591   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13592   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13593 }
13594
13595 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13596   assert(Subtarget->isTargetWin64() && "Unexpected target");
13597   EVT VT = Op.getValueType();
13598   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13599          "Unexpected return type for lowering");
13600
13601   RTLIB::Libcall LC;
13602   bool isSigned;
13603   switch (Op->getOpcode()) {
13604   default: llvm_unreachable("Unexpected request for libcall!");
13605   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13606   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13607   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13608   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13609   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13610   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13611   }
13612
13613   SDLoc dl(Op);
13614   SDValue InChain = DAG.getEntryNode();
13615
13616   TargetLowering::ArgListTy Args;
13617   TargetLowering::ArgListEntry Entry;
13618   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13619     EVT ArgVT = Op->getOperand(i).getValueType();
13620     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13621            "Unexpected argument type for lowering");
13622     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13623     Entry.Node = StackPtr;
13624     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13625                            false, false, 16);
13626     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13627     Entry.Ty = PointerType::get(ArgTy,0);
13628     Entry.isSExt = false;
13629     Entry.isZExt = false;
13630     Args.push_back(Entry);
13631   }
13632
13633   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13634                                          getPointerTy());
13635
13636   TargetLowering::CallLoweringInfo CLI(DAG);
13637   CLI.setDebugLoc(dl).setChain(InChain)
13638     .setCallee(getLibcallCallingConv(LC),
13639                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13640                Callee, &Args, 0)
13641     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13642
13643   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13644   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13645 }
13646
13647 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13648                              SelectionDAG &DAG) {
13649   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13650   EVT VT = Op0.getValueType();
13651   SDLoc dl(Op);
13652
13653   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13654          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13655
13656   // Get the high parts.
13657   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13658   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13659   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13660
13661   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13662   // ints.
13663   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13664   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13665   unsigned Opcode =
13666       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13667   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13668                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13669   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13670                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13671
13672   // Shuffle it back into the right order.
13673   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13674   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13675   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13676   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13677
13678   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13679   // unsigned multiply.
13680   if (IsSigned && !Subtarget->hasSSE41()) {
13681     SDValue ShAmt =
13682         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13683     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13684                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13685     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13686                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13687
13688     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13689     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13690   }
13691
13692   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13693 }
13694
13695 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13696                                          const X86Subtarget *Subtarget) {
13697   MVT VT = Op.getSimpleValueType();
13698   SDLoc dl(Op);
13699   SDValue R = Op.getOperand(0);
13700   SDValue Amt = Op.getOperand(1);
13701
13702   // Optimize shl/srl/sra with constant shift amount.
13703   if (isSplatVector(Amt.getNode())) {
13704     SDValue SclrAmt = Amt->getOperand(0);
13705     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13706       uint64_t ShiftAmt = C->getZExtValue();
13707
13708       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13709           (Subtarget->hasInt256() &&
13710            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13711           (Subtarget->hasAVX512() &&
13712            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13713         if (Op.getOpcode() == ISD::SHL)
13714           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13715                                             DAG);
13716         if (Op.getOpcode() == ISD::SRL)
13717           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13718                                             DAG);
13719         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13720           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13721                                             DAG);
13722       }
13723
13724       if (VT == MVT::v16i8) {
13725         if (Op.getOpcode() == ISD::SHL) {
13726           // Make a large shift.
13727           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13728                                                    MVT::v8i16, R, ShiftAmt,
13729                                                    DAG);
13730           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13731           // Zero out the rightmost bits.
13732           SmallVector<SDValue, 16> V(16,
13733                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13734                                                      MVT::i8));
13735           return DAG.getNode(ISD::AND, dl, VT, SHL,
13736                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13737         }
13738         if (Op.getOpcode() == ISD::SRL) {
13739           // Make a large shift.
13740           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13741                                                    MVT::v8i16, R, ShiftAmt,
13742                                                    DAG);
13743           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13744           // Zero out the leftmost bits.
13745           SmallVector<SDValue, 16> V(16,
13746                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13747                                                      MVT::i8));
13748           return DAG.getNode(ISD::AND, dl, VT, SRL,
13749                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13750         }
13751         if (Op.getOpcode() == ISD::SRA) {
13752           if (ShiftAmt == 7) {
13753             // R s>> 7  ===  R s< 0
13754             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13755             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13756           }
13757
13758           // R s>> a === ((R u>> a) ^ m) - m
13759           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13760           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13761                                                          MVT::i8));
13762           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13763           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13764           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13765           return Res;
13766         }
13767         llvm_unreachable("Unknown shift opcode.");
13768       }
13769
13770       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13771         if (Op.getOpcode() == ISD::SHL) {
13772           // Make a large shift.
13773           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13774                                                    MVT::v16i16, R, ShiftAmt,
13775                                                    DAG);
13776           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13777           // Zero out the rightmost bits.
13778           SmallVector<SDValue, 32> V(32,
13779                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13780                                                      MVT::i8));
13781           return DAG.getNode(ISD::AND, dl, VT, SHL,
13782                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13783         }
13784         if (Op.getOpcode() == ISD::SRL) {
13785           // Make a large shift.
13786           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13787                                                    MVT::v16i16, R, ShiftAmt,
13788                                                    DAG);
13789           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13790           // Zero out the leftmost bits.
13791           SmallVector<SDValue, 32> V(32,
13792                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13793                                                      MVT::i8));
13794           return DAG.getNode(ISD::AND, dl, VT, SRL,
13795                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13796         }
13797         if (Op.getOpcode() == ISD::SRA) {
13798           if (ShiftAmt == 7) {
13799             // R s>> 7  ===  R s< 0
13800             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13801             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13802           }
13803
13804           // R s>> a === ((R u>> a) ^ m) - m
13805           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13806           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13807                                                          MVT::i8));
13808           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13809           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13810           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13811           return Res;
13812         }
13813         llvm_unreachable("Unknown shift opcode.");
13814       }
13815     }
13816   }
13817
13818   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13819   if (!Subtarget->is64Bit() &&
13820       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13821       Amt.getOpcode() == ISD::BITCAST &&
13822       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13823     Amt = Amt.getOperand(0);
13824     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13825                      VT.getVectorNumElements();
13826     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13827     uint64_t ShiftAmt = 0;
13828     for (unsigned i = 0; i != Ratio; ++i) {
13829       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13830       if (!C)
13831         return SDValue();
13832       // 6 == Log2(64)
13833       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13834     }
13835     // Check remaining shift amounts.
13836     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13837       uint64_t ShAmt = 0;
13838       for (unsigned j = 0; j != Ratio; ++j) {
13839         ConstantSDNode *C =
13840           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13841         if (!C)
13842           return SDValue();
13843         // 6 == Log2(64)
13844         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13845       }
13846       if (ShAmt != ShiftAmt)
13847         return SDValue();
13848     }
13849     switch (Op.getOpcode()) {
13850     default:
13851       llvm_unreachable("Unknown shift opcode!");
13852     case ISD::SHL:
13853       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13854                                         DAG);
13855     case ISD::SRL:
13856       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13857                                         DAG);
13858     case ISD::SRA:
13859       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13860                                         DAG);
13861     }
13862   }
13863
13864   return SDValue();
13865 }
13866
13867 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13868                                         const X86Subtarget* Subtarget) {
13869   MVT VT = Op.getSimpleValueType();
13870   SDLoc dl(Op);
13871   SDValue R = Op.getOperand(0);
13872   SDValue Amt = Op.getOperand(1);
13873
13874   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13875       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13876       (Subtarget->hasInt256() &&
13877        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13878         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13879        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13880     SDValue BaseShAmt;
13881     EVT EltVT = VT.getVectorElementType();
13882
13883     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13884       unsigned NumElts = VT.getVectorNumElements();
13885       unsigned i, j;
13886       for (i = 0; i != NumElts; ++i) {
13887         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13888           continue;
13889         break;
13890       }
13891       for (j = i; j != NumElts; ++j) {
13892         SDValue Arg = Amt.getOperand(j);
13893         if (Arg.getOpcode() == ISD::UNDEF) continue;
13894         if (Arg != Amt.getOperand(i))
13895           break;
13896       }
13897       if (i != NumElts && j == NumElts)
13898         BaseShAmt = Amt.getOperand(i);
13899     } else {
13900       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13901         Amt = Amt.getOperand(0);
13902       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13903                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13904         SDValue InVec = Amt.getOperand(0);
13905         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13906           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13907           unsigned i = 0;
13908           for (; i != NumElts; ++i) {
13909             SDValue Arg = InVec.getOperand(i);
13910             if (Arg.getOpcode() == ISD::UNDEF) continue;
13911             BaseShAmt = Arg;
13912             break;
13913           }
13914         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13915            if (ConstantSDNode *C =
13916                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13917              unsigned SplatIdx =
13918                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13919              if (C->getZExtValue() == SplatIdx)
13920                BaseShAmt = InVec.getOperand(1);
13921            }
13922         }
13923         if (!BaseShAmt.getNode())
13924           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13925                                   DAG.getIntPtrConstant(0));
13926       }
13927     }
13928
13929     if (BaseShAmt.getNode()) {
13930       if (EltVT.bitsGT(MVT::i32))
13931         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13932       else if (EltVT.bitsLT(MVT::i32))
13933         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13934
13935       switch (Op.getOpcode()) {
13936       default:
13937         llvm_unreachable("Unknown shift opcode!");
13938       case ISD::SHL:
13939         switch (VT.SimpleTy) {
13940         default: return SDValue();
13941         case MVT::v2i64:
13942         case MVT::v4i32:
13943         case MVT::v8i16:
13944         case MVT::v4i64:
13945         case MVT::v8i32:
13946         case MVT::v16i16:
13947         case MVT::v16i32:
13948         case MVT::v8i64:
13949           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13950         }
13951       case ISD::SRA:
13952         switch (VT.SimpleTy) {
13953         default: return SDValue();
13954         case MVT::v4i32:
13955         case MVT::v8i16:
13956         case MVT::v8i32:
13957         case MVT::v16i16:
13958         case MVT::v16i32:
13959         case MVT::v8i64:
13960           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13961         }
13962       case ISD::SRL:
13963         switch (VT.SimpleTy) {
13964         default: return SDValue();
13965         case MVT::v2i64:
13966         case MVT::v4i32:
13967         case MVT::v8i16:
13968         case MVT::v4i64:
13969         case MVT::v8i32:
13970         case MVT::v16i16:
13971         case MVT::v16i32:
13972         case MVT::v8i64:
13973           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13974         }
13975       }
13976     }
13977   }
13978
13979   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13980   if (!Subtarget->is64Bit() &&
13981       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13982       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13983       Amt.getOpcode() == ISD::BITCAST &&
13984       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13985     Amt = Amt.getOperand(0);
13986     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13987                      VT.getVectorNumElements();
13988     std::vector<SDValue> Vals(Ratio);
13989     for (unsigned i = 0; i != Ratio; ++i)
13990       Vals[i] = Amt.getOperand(i);
13991     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13992       for (unsigned j = 0; j != Ratio; ++j)
13993         if (Vals[j] != Amt.getOperand(i + j))
13994           return SDValue();
13995     }
13996     switch (Op.getOpcode()) {
13997     default:
13998       llvm_unreachable("Unknown shift opcode!");
13999     case ISD::SHL:
14000       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
14001     case ISD::SRL:
14002       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
14003     case ISD::SRA:
14004       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
14005     }
14006   }
14007
14008   return SDValue();
14009 }
14010
14011 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
14012                           SelectionDAG &DAG) {
14013
14014   MVT VT = Op.getSimpleValueType();
14015   SDLoc dl(Op);
14016   SDValue R = Op.getOperand(0);
14017   SDValue Amt = Op.getOperand(1);
14018   SDValue V;
14019
14020   if (!Subtarget->hasSSE2())
14021     return SDValue();
14022
14023   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14024   if (V.getNode())
14025     return V;
14026
14027   V = LowerScalarVariableShift(Op, DAG, Subtarget);
14028   if (V.getNode())
14029       return V;
14030
14031   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14032     return Op;
14033   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14034   if (Subtarget->hasInt256()) {
14035     if (Op.getOpcode() == ISD::SRL &&
14036         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14037          VT == MVT::v4i64 || VT == MVT::v8i32))
14038       return Op;
14039     if (Op.getOpcode() == ISD::SHL &&
14040         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14041          VT == MVT::v4i64 || VT == MVT::v8i32))
14042       return Op;
14043     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14044       return Op;
14045   }
14046
14047   // If possible, lower this packed shift into a vector multiply instead of
14048   // expanding it into a sequence of scalar shifts.
14049   // Do this only if the vector shift count is a constant build_vector.
14050   if (Op.getOpcode() == ISD::SHL && 
14051       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14052        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14053       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14054     SmallVector<SDValue, 8> Elts;
14055     EVT SVT = VT.getScalarType();
14056     unsigned SVTBits = SVT.getSizeInBits();
14057     const APInt &One = APInt(SVTBits, 1);
14058     unsigned NumElems = VT.getVectorNumElements();
14059
14060     for (unsigned i=0; i !=NumElems; ++i) {
14061       SDValue Op = Amt->getOperand(i);
14062       if (Op->getOpcode() == ISD::UNDEF) {
14063         Elts.push_back(Op);
14064         continue;
14065       }
14066
14067       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14068       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14069       uint64_t ShAmt = C.getZExtValue();
14070       if (ShAmt >= SVTBits) {
14071         Elts.push_back(DAG.getUNDEF(SVT));
14072         continue;
14073       }
14074       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14075     }
14076     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14077     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14078   }
14079
14080   // Lower SHL with variable shift amount.
14081   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14082     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14083
14084     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14085     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14086     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14087     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14088   }
14089
14090   // If possible, lower this shift as a sequence of two shifts by
14091   // constant plus a MOVSS/MOVSD instead of scalarizing it.
14092   // Example:
14093   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14094   //
14095   // Could be rewritten as:
14096   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14097   //
14098   // The advantage is that the two shifts from the example would be
14099   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14100   // the vector shift into four scalar shifts plus four pairs of vector
14101   // insert/extract.
14102   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14103       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14104     unsigned TargetOpcode = X86ISD::MOVSS;
14105     bool CanBeSimplified;
14106     // The splat value for the first packed shift (the 'X' from the example).
14107     SDValue Amt1 = Amt->getOperand(0);
14108     // The splat value for the second packed shift (the 'Y' from the example).
14109     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14110                                         Amt->getOperand(2);
14111
14112     // See if it is possible to replace this node with a sequence of
14113     // two shifts followed by a MOVSS/MOVSD
14114     if (VT == MVT::v4i32) {
14115       // Check if it is legal to use a MOVSS.
14116       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14117                         Amt2 == Amt->getOperand(3);
14118       if (!CanBeSimplified) {
14119         // Otherwise, check if we can still simplify this node using a MOVSD.
14120         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14121                           Amt->getOperand(2) == Amt->getOperand(3);
14122         TargetOpcode = X86ISD::MOVSD;
14123         Amt2 = Amt->getOperand(2);
14124       }
14125     } else {
14126       // Do similar checks for the case where the machine value type
14127       // is MVT::v8i16.
14128       CanBeSimplified = Amt1 == Amt->getOperand(1);
14129       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14130         CanBeSimplified = Amt2 == Amt->getOperand(i);
14131
14132       if (!CanBeSimplified) {
14133         TargetOpcode = X86ISD::MOVSD;
14134         CanBeSimplified = true;
14135         Amt2 = Amt->getOperand(4);
14136         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14137           CanBeSimplified = Amt1 == Amt->getOperand(i);
14138         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14139           CanBeSimplified = Amt2 == Amt->getOperand(j);
14140       }
14141     }
14142     
14143     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14144         isa<ConstantSDNode>(Amt2)) {
14145       // Replace this node with two shifts followed by a MOVSS/MOVSD.
14146       EVT CastVT = MVT::v4i32;
14147       SDValue Splat1 = 
14148         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14149       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14150       SDValue Splat2 = 
14151         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14152       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14153       if (TargetOpcode == X86ISD::MOVSD)
14154         CastVT = MVT::v2i64;
14155       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14156       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14157       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14158                                             BitCast1, DAG);
14159       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14160     }
14161   }
14162
14163   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14164     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14165
14166     // a = a << 5;
14167     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14168     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14169
14170     // Turn 'a' into a mask suitable for VSELECT
14171     SDValue VSelM = DAG.getConstant(0x80, VT);
14172     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14173     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14174
14175     SDValue CM1 = DAG.getConstant(0x0f, VT);
14176     SDValue CM2 = DAG.getConstant(0x3f, VT);
14177
14178     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14179     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14180     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14181     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14182     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14183
14184     // a += a
14185     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14186     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14187     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14188
14189     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14190     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14191     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14192     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14193     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14194
14195     // a += a
14196     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14197     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14198     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14199
14200     // return VSELECT(r, r+r, a);
14201     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14202                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14203     return R;
14204   }
14205
14206   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14207   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14208   // solution better.
14209   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14210     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14211     unsigned ExtOpc =
14212         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14213     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14214     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14215     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14216                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14217     }
14218
14219   // Decompose 256-bit shifts into smaller 128-bit shifts.
14220   if (VT.is256BitVector()) {
14221     unsigned NumElems = VT.getVectorNumElements();
14222     MVT EltVT = VT.getVectorElementType();
14223     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14224
14225     // Extract the two vectors
14226     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14227     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14228
14229     // Recreate the shift amount vectors
14230     SDValue Amt1, Amt2;
14231     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14232       // Constant shift amount
14233       SmallVector<SDValue, 4> Amt1Csts;
14234       SmallVector<SDValue, 4> Amt2Csts;
14235       for (unsigned i = 0; i != NumElems/2; ++i)
14236         Amt1Csts.push_back(Amt->getOperand(i));
14237       for (unsigned i = NumElems/2; i != NumElems; ++i)
14238         Amt2Csts.push_back(Amt->getOperand(i));
14239
14240       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14241       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14242     } else {
14243       // Variable shift amount
14244       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14245       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14246     }
14247
14248     // Issue new vector shifts for the smaller types
14249     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14250     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14251
14252     // Concatenate the result back
14253     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14254   }
14255
14256   return SDValue();
14257 }
14258
14259 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14260   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14261   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14262   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14263   // has only one use.
14264   SDNode *N = Op.getNode();
14265   SDValue LHS = N->getOperand(0);
14266   SDValue RHS = N->getOperand(1);
14267   unsigned BaseOp = 0;
14268   unsigned Cond = 0;
14269   SDLoc DL(Op);
14270   switch (Op.getOpcode()) {
14271   default: llvm_unreachable("Unknown ovf instruction!");
14272   case ISD::SADDO:
14273     // A subtract of one will be selected as a INC. Note that INC doesn't
14274     // set CF, so we can't do this for UADDO.
14275     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14276       if (C->isOne()) {
14277         BaseOp = X86ISD::INC;
14278         Cond = X86::COND_O;
14279         break;
14280       }
14281     BaseOp = X86ISD::ADD;
14282     Cond = X86::COND_O;
14283     break;
14284   case ISD::UADDO:
14285     BaseOp = X86ISD::ADD;
14286     Cond = X86::COND_B;
14287     break;
14288   case ISD::SSUBO:
14289     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14290     // set CF, so we can't do this for USUBO.
14291     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14292       if (C->isOne()) {
14293         BaseOp = X86ISD::DEC;
14294         Cond = X86::COND_O;
14295         break;
14296       }
14297     BaseOp = X86ISD::SUB;
14298     Cond = X86::COND_O;
14299     break;
14300   case ISD::USUBO:
14301     BaseOp = X86ISD::SUB;
14302     Cond = X86::COND_B;
14303     break;
14304   case ISD::SMULO:
14305     BaseOp = X86ISD::SMUL;
14306     Cond = X86::COND_O;
14307     break;
14308   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14309     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14310                                  MVT::i32);
14311     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14312
14313     SDValue SetCC =
14314       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14315                   DAG.getConstant(X86::COND_O, MVT::i32),
14316                   SDValue(Sum.getNode(), 2));
14317
14318     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14319   }
14320   }
14321
14322   // Also sets EFLAGS.
14323   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14324   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14325
14326   SDValue SetCC =
14327     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14328                 DAG.getConstant(Cond, MVT::i32),
14329                 SDValue(Sum.getNode(), 1));
14330
14331   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14332 }
14333
14334 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14335                                                   SelectionDAG &DAG) const {
14336   SDLoc dl(Op);
14337   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14338   MVT VT = Op.getSimpleValueType();
14339
14340   if (!Subtarget->hasSSE2() || !VT.isVector())
14341     return SDValue();
14342
14343   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14344                       ExtraVT.getScalarType().getSizeInBits();
14345
14346   switch (VT.SimpleTy) {
14347     default: return SDValue();
14348     case MVT::v8i32:
14349     case MVT::v16i16:
14350       if (!Subtarget->hasFp256())
14351         return SDValue();
14352       if (!Subtarget->hasInt256()) {
14353         // needs to be split
14354         unsigned NumElems = VT.getVectorNumElements();
14355
14356         // Extract the LHS vectors
14357         SDValue LHS = Op.getOperand(0);
14358         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14359         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14360
14361         MVT EltVT = VT.getVectorElementType();
14362         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14363
14364         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14365         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14366         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14367                                    ExtraNumElems/2);
14368         SDValue Extra = DAG.getValueType(ExtraVT);
14369
14370         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14371         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14372
14373         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14374       }
14375       // fall through
14376     case MVT::v4i32:
14377     case MVT::v8i16: {
14378       SDValue Op0 = Op.getOperand(0);
14379       SDValue Op00 = Op0.getOperand(0);
14380       SDValue Tmp1;
14381       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14382       if (Op0.getOpcode() == ISD::BITCAST &&
14383           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14384         // (sext (vzext x)) -> (vsext x)
14385         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14386         if (Tmp1.getNode()) {
14387           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14388           // This folding is only valid when the in-reg type is a vector of i8,
14389           // i16, or i32.
14390           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14391               ExtraEltVT == MVT::i32) {
14392             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14393             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14394                    "This optimization is invalid without a VZEXT.");
14395             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14396           }
14397           Op0 = Tmp1;
14398         }
14399       }
14400
14401       // If the above didn't work, then just use Shift-Left + Shift-Right.
14402       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14403                                         DAG);
14404       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14405                                         DAG);
14406     }
14407   }
14408 }
14409
14410 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14411                                  SelectionDAG &DAG) {
14412   SDLoc dl(Op);
14413   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14414     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14415   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14416     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14417
14418   // The only fence that needs an instruction is a sequentially-consistent
14419   // cross-thread fence.
14420   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14421     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14422     // no-sse2). There isn't any reason to disable it if the target processor
14423     // supports it.
14424     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14425       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14426
14427     SDValue Chain = Op.getOperand(0);
14428     SDValue Zero = DAG.getConstant(0, MVT::i32);
14429     SDValue Ops[] = {
14430       DAG.getRegister(X86::ESP, MVT::i32), // Base
14431       DAG.getTargetConstant(1, MVT::i8),   // Scale
14432       DAG.getRegister(0, MVT::i32),        // Index
14433       DAG.getTargetConstant(0, MVT::i32),  // Disp
14434       DAG.getRegister(0, MVT::i32),        // Segment.
14435       Zero,
14436       Chain
14437     };
14438     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14439     return SDValue(Res, 0);
14440   }
14441
14442   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14443   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14444 }
14445
14446 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14447                             SelectionDAG &DAG) {
14448   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14449   MVT DstVT = Op.getSimpleValueType();
14450
14451   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14452     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14453     if (DstVT != MVT::f64)
14454       // This conversion needs to be expanded.
14455       return SDValue();
14456
14457     SDValue InVec = Op->getOperand(0);
14458     SDLoc dl(Op);
14459     unsigned NumElts = SrcVT.getVectorNumElements();
14460     EVT SVT = SrcVT.getVectorElementType();
14461
14462     // Widen the vector in input in the case of MVT::v2i32.
14463     // Example: from MVT::v2i32 to MVT::v4i32.
14464     SmallVector<SDValue, 16> Elts;
14465     for (unsigned i = 0, e = NumElts; i != e; ++i)
14466       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14467                                  DAG.getIntPtrConstant(i)));
14468
14469     // Explicitly mark the extra elements as Undef.
14470     SDValue Undef = DAG.getUNDEF(SVT);
14471     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14472       Elts.push_back(Undef);
14473
14474     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14475     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14476     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14477     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14478                        DAG.getIntPtrConstant(0));
14479   }
14480
14481   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14482          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14483   assert((DstVT == MVT::i64 ||
14484           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14485          "Unexpected custom BITCAST");
14486   // i64 <=> MMX conversions are Legal.
14487   if (SrcVT==MVT::i64 && DstVT.isVector())
14488     return Op;
14489   if (DstVT==MVT::i64 && SrcVT.isVector())
14490     return Op;
14491   // MMX <=> MMX conversions are Legal.
14492   if (SrcVT.isVector() && DstVT.isVector())
14493     return Op;
14494   // All other conversions need to be expanded.
14495   return SDValue();
14496 }
14497
14498 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14499   SDNode *Node = Op.getNode();
14500   SDLoc dl(Node);
14501   EVT T = Node->getValueType(0);
14502   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14503                               DAG.getConstant(0, T), Node->getOperand(2));
14504   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14505                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14506                        Node->getOperand(0),
14507                        Node->getOperand(1), negOp,
14508                        cast<AtomicSDNode>(Node)->getMemOperand(),
14509                        cast<AtomicSDNode>(Node)->getOrdering(),
14510                        cast<AtomicSDNode>(Node)->getSynchScope());
14511 }
14512
14513 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14514   SDNode *Node = Op.getNode();
14515   SDLoc dl(Node);
14516   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14517
14518   // Convert seq_cst store -> xchg
14519   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14520   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14521   //        (The only way to get a 16-byte store is cmpxchg16b)
14522   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14523   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14524       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14525     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14526                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14527                                  Node->getOperand(0),
14528                                  Node->getOperand(1), Node->getOperand(2),
14529                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14530                                  cast<AtomicSDNode>(Node)->getOrdering(),
14531                                  cast<AtomicSDNode>(Node)->getSynchScope());
14532     return Swap.getValue(1);
14533   }
14534   // Other atomic stores have a simple pattern.
14535   return Op;
14536 }
14537
14538 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14539   EVT VT = Op.getNode()->getSimpleValueType(0);
14540
14541   // Let legalize expand this if it isn't a legal type yet.
14542   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14543     return SDValue();
14544
14545   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14546
14547   unsigned Opc;
14548   bool ExtraOp = false;
14549   switch (Op.getOpcode()) {
14550   default: llvm_unreachable("Invalid code");
14551   case ISD::ADDC: Opc = X86ISD::ADD; break;
14552   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14553   case ISD::SUBC: Opc = X86ISD::SUB; break;
14554   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14555   }
14556
14557   if (!ExtraOp)
14558     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14559                        Op.getOperand(1));
14560   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14561                      Op.getOperand(1), Op.getOperand(2));
14562 }
14563
14564 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14565                             SelectionDAG &DAG) {
14566   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14567
14568   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14569   // which returns the values as { float, float } (in XMM0) or
14570   // { double, double } (which is returned in XMM0, XMM1).
14571   SDLoc dl(Op);
14572   SDValue Arg = Op.getOperand(0);
14573   EVT ArgVT = Arg.getValueType();
14574   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14575
14576   TargetLowering::ArgListTy Args;
14577   TargetLowering::ArgListEntry Entry;
14578
14579   Entry.Node = Arg;
14580   Entry.Ty = ArgTy;
14581   Entry.isSExt = false;
14582   Entry.isZExt = false;
14583   Args.push_back(Entry);
14584
14585   bool isF64 = ArgVT == MVT::f64;
14586   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14587   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14588   // the results are returned via SRet in memory.
14589   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14590   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14591   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14592
14593   Type *RetTy = isF64
14594     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14595     : (Type*)VectorType::get(ArgTy, 4);
14596
14597   TargetLowering::CallLoweringInfo CLI(DAG);
14598   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14599     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14600
14601   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14602
14603   if (isF64)
14604     // Returned in xmm0 and xmm1.
14605     return CallResult.first;
14606
14607   // Returned in bits 0:31 and 32:64 xmm0.
14608   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14609                                CallResult.first, DAG.getIntPtrConstant(0));
14610   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14611                                CallResult.first, DAG.getIntPtrConstant(1));
14612   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14613   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14614 }
14615
14616 /// LowerOperation - Provide custom lowering hooks for some operations.
14617 ///
14618 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14619   switch (Op.getOpcode()) {
14620   default: llvm_unreachable("Should not custom lower this!");
14621   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14622   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14623   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14624   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14625   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14626   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14627   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14628   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14629   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14630   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14631   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14632   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14633   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14634   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14635   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14636   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14637   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14638   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14639   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14640   case ISD::SHL_PARTS:
14641   case ISD::SRA_PARTS:
14642   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14643   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14644   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14645   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14646   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14647   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14648   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14649   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14650   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14651   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14652   case ISD::FABS:               return LowerFABS(Op, DAG);
14653   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14654   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14655   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14656   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14657   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14658   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14659   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14660   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14661   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14662   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14663   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14664   case ISD::INTRINSIC_VOID:
14665   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14666   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14667   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14668   case ISD::FRAME_TO_ARGS_OFFSET:
14669                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14670   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14671   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14672   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14673   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14674   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14675   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14676   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14677   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14678   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14679   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14680   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14681   case ISD::UMUL_LOHI:
14682   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14683   case ISD::SRA:
14684   case ISD::SRL:
14685   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14686   case ISD::SADDO:
14687   case ISD::UADDO:
14688   case ISD::SSUBO:
14689   case ISD::USUBO:
14690   case ISD::SMULO:
14691   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14692   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14693   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14694   case ISD::ADDC:
14695   case ISD::ADDE:
14696   case ISD::SUBC:
14697   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14698   case ISD::ADD:                return LowerADD(Op, DAG);
14699   case ISD::SUB:                return LowerSUB(Op, DAG);
14700   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14701   }
14702 }
14703
14704 static void ReplaceATOMIC_LOAD(SDNode *Node,
14705                                   SmallVectorImpl<SDValue> &Results,
14706                                   SelectionDAG &DAG) {
14707   SDLoc dl(Node);
14708   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14709
14710   // Convert wide load -> cmpxchg8b/cmpxchg16b
14711   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14712   //        (The only way to get a 16-byte load is cmpxchg16b)
14713   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14714   SDValue Zero = DAG.getConstant(0, VT);
14715   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14716                                Node->getOperand(0),
14717                                Node->getOperand(1), Zero, Zero,
14718                                cast<AtomicSDNode>(Node)->getMemOperand(),
14719                                cast<AtomicSDNode>(Node)->getOrdering(),
14720                                cast<AtomicSDNode>(Node)->getOrdering(),
14721                                cast<AtomicSDNode>(Node)->getSynchScope());
14722   Results.push_back(Swap.getValue(0));
14723   Results.push_back(Swap.getValue(1));
14724 }
14725
14726 static void
14727 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14728                         SelectionDAG &DAG, unsigned NewOp) {
14729   SDLoc dl(Node);
14730   assert (Node->getValueType(0) == MVT::i64 &&
14731           "Only know how to expand i64 atomics");
14732
14733   SDValue Chain = Node->getOperand(0);
14734   SDValue In1 = Node->getOperand(1);
14735   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14736                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14737   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14738                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14739   SDValue Ops[] = { Chain, In1, In2L, In2H };
14740   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14741   SDValue Result =
14742     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14743                             cast<MemSDNode>(Node)->getMemOperand());
14744   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14745   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14746   Results.push_back(Result.getValue(2));
14747 }
14748
14749 /// ReplaceNodeResults - Replace a node with an illegal result type
14750 /// with a new node built out of custom code.
14751 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14752                                            SmallVectorImpl<SDValue>&Results,
14753                                            SelectionDAG &DAG) const {
14754   SDLoc dl(N);
14755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14756   switch (N->getOpcode()) {
14757   default:
14758     llvm_unreachable("Do not know how to custom type legalize this operation!");
14759   case ISD::SIGN_EXTEND_INREG:
14760   case ISD::ADDC:
14761   case ISD::ADDE:
14762   case ISD::SUBC:
14763   case ISD::SUBE:
14764     // We don't want to expand or promote these.
14765     return;
14766   case ISD::SDIV:
14767   case ISD::UDIV:
14768   case ISD::SREM:
14769   case ISD::UREM:
14770   case ISD::SDIVREM:
14771   case ISD::UDIVREM: {
14772     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14773     Results.push_back(V);
14774     return;
14775   }
14776   case ISD::FP_TO_SINT:
14777   case ISD::FP_TO_UINT: {
14778     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14779
14780     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14781       return;
14782
14783     std::pair<SDValue,SDValue> Vals =
14784         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14785     SDValue FIST = Vals.first, StackSlot = Vals.second;
14786     if (FIST.getNode()) {
14787       EVT VT = N->getValueType(0);
14788       // Return a load from the stack slot.
14789       if (StackSlot.getNode())
14790         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14791                                       MachinePointerInfo(),
14792                                       false, false, false, 0));
14793       else
14794         Results.push_back(FIST);
14795     }
14796     return;
14797   }
14798   case ISD::UINT_TO_FP: {
14799     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14800     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14801         N->getValueType(0) != MVT::v2f32)
14802       return;
14803     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14804                                  N->getOperand(0));
14805     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14806                                      MVT::f64);
14807     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14808     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14809                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14810     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14811     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14812     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14813     return;
14814   }
14815   case ISD::FP_ROUND: {
14816     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14817         return;
14818     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14819     Results.push_back(V);
14820     return;
14821   }
14822   case ISD::INTRINSIC_W_CHAIN: {
14823     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14824     switch (IntNo) {
14825     default : llvm_unreachable("Do not know how to custom type "
14826                                "legalize this intrinsic operation!");
14827     case Intrinsic::x86_rdtsc:
14828       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14829                                      Results);
14830     case Intrinsic::x86_rdtscp:
14831       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14832                                      Results);
14833     }
14834   }
14835   case ISD::READCYCLECOUNTER: {
14836     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14837                                    Results);
14838   }
14839   case ISD::ATOMIC_CMP_SWAP: {
14840     EVT T = N->getValueType(0);
14841     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14842     bool Regs64bit = T == MVT::i128;
14843     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14844     SDValue cpInL, cpInH;
14845     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14846                         DAG.getConstant(0, HalfT));
14847     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14848                         DAG.getConstant(1, HalfT));
14849     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14850                              Regs64bit ? X86::RAX : X86::EAX,
14851                              cpInL, SDValue());
14852     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14853                              Regs64bit ? X86::RDX : X86::EDX,
14854                              cpInH, cpInL.getValue(1));
14855     SDValue swapInL, swapInH;
14856     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14857                           DAG.getConstant(0, HalfT));
14858     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14859                           DAG.getConstant(1, HalfT));
14860     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14861                                Regs64bit ? X86::RBX : X86::EBX,
14862                                swapInL, cpInH.getValue(1));
14863     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14864                                Regs64bit ? X86::RCX : X86::ECX,
14865                                swapInH, swapInL.getValue(1));
14866     SDValue Ops[] = { swapInH.getValue(0),
14867                       N->getOperand(1),
14868                       swapInH.getValue(1) };
14869     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14870     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14871     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14872                                   X86ISD::LCMPXCHG8_DAG;
14873     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14874     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14875                                         Regs64bit ? X86::RAX : X86::EAX,
14876                                         HalfT, Result.getValue(1));
14877     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14878                                         Regs64bit ? X86::RDX : X86::EDX,
14879                                         HalfT, cpOutL.getValue(2));
14880     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14881     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14882     Results.push_back(cpOutH.getValue(1));
14883     return;
14884   }
14885   case ISD::ATOMIC_LOAD_ADD:
14886   case ISD::ATOMIC_LOAD_AND:
14887   case ISD::ATOMIC_LOAD_NAND:
14888   case ISD::ATOMIC_LOAD_OR:
14889   case ISD::ATOMIC_LOAD_SUB:
14890   case ISD::ATOMIC_LOAD_XOR:
14891   case ISD::ATOMIC_LOAD_MAX:
14892   case ISD::ATOMIC_LOAD_MIN:
14893   case ISD::ATOMIC_LOAD_UMAX:
14894   case ISD::ATOMIC_LOAD_UMIN:
14895   case ISD::ATOMIC_SWAP: {
14896     unsigned Opc;
14897     switch (N->getOpcode()) {
14898     default: llvm_unreachable("Unexpected opcode");
14899     case ISD::ATOMIC_LOAD_ADD:
14900       Opc = X86ISD::ATOMADD64_DAG;
14901       break;
14902     case ISD::ATOMIC_LOAD_AND:
14903       Opc = X86ISD::ATOMAND64_DAG;
14904       break;
14905     case ISD::ATOMIC_LOAD_NAND:
14906       Opc = X86ISD::ATOMNAND64_DAG;
14907       break;
14908     case ISD::ATOMIC_LOAD_OR:
14909       Opc = X86ISD::ATOMOR64_DAG;
14910       break;
14911     case ISD::ATOMIC_LOAD_SUB:
14912       Opc = X86ISD::ATOMSUB64_DAG;
14913       break;
14914     case ISD::ATOMIC_LOAD_XOR:
14915       Opc = X86ISD::ATOMXOR64_DAG;
14916       break;
14917     case ISD::ATOMIC_LOAD_MAX:
14918       Opc = X86ISD::ATOMMAX64_DAG;
14919       break;
14920     case ISD::ATOMIC_LOAD_MIN:
14921       Opc = X86ISD::ATOMMIN64_DAG;
14922       break;
14923     case ISD::ATOMIC_LOAD_UMAX:
14924       Opc = X86ISD::ATOMUMAX64_DAG;
14925       break;
14926     case ISD::ATOMIC_LOAD_UMIN:
14927       Opc = X86ISD::ATOMUMIN64_DAG;
14928       break;
14929     case ISD::ATOMIC_SWAP:
14930       Opc = X86ISD::ATOMSWAP64_DAG;
14931       break;
14932     }
14933     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14934     return;
14935   }
14936   case ISD::ATOMIC_LOAD: {
14937     ReplaceATOMIC_LOAD(N, Results, DAG);
14938     return;
14939   }
14940   case ISD::BITCAST: {
14941     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14942     EVT DstVT = N->getValueType(0);
14943     EVT SrcVT = N->getOperand(0)->getValueType(0);
14944
14945     if (SrcVT != MVT::f64 ||
14946         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14947       return;
14948
14949     unsigned NumElts = DstVT.getVectorNumElements();
14950     EVT SVT = DstVT.getVectorElementType();
14951     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14952     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14953                                    MVT::v2f64, N->getOperand(0));
14954     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14955
14956     SmallVector<SDValue, 8> Elts;
14957     for (unsigned i = 0, e = NumElts; i != e; ++i)
14958       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14959                                    ToVecInt, DAG.getIntPtrConstant(i)));
14960
14961     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14962   }
14963   }
14964 }
14965
14966 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14967   switch (Opcode) {
14968   default: return nullptr;
14969   case X86ISD::BSF:                return "X86ISD::BSF";
14970   case X86ISD::BSR:                return "X86ISD::BSR";
14971   case X86ISD::SHLD:               return "X86ISD::SHLD";
14972   case X86ISD::SHRD:               return "X86ISD::SHRD";
14973   case X86ISD::FAND:               return "X86ISD::FAND";
14974   case X86ISD::FANDN:              return "X86ISD::FANDN";
14975   case X86ISD::FOR:                return "X86ISD::FOR";
14976   case X86ISD::FXOR:               return "X86ISD::FXOR";
14977   case X86ISD::FSRL:               return "X86ISD::FSRL";
14978   case X86ISD::FILD:               return "X86ISD::FILD";
14979   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14980   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14981   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14982   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14983   case X86ISD::FLD:                return "X86ISD::FLD";
14984   case X86ISD::FST:                return "X86ISD::FST";
14985   case X86ISD::CALL:               return "X86ISD::CALL";
14986   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14987   case X86ISD::BT:                 return "X86ISD::BT";
14988   case X86ISD::CMP:                return "X86ISD::CMP";
14989   case X86ISD::COMI:               return "X86ISD::COMI";
14990   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14991   case X86ISD::CMPM:               return "X86ISD::CMPM";
14992   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14993   case X86ISD::SETCC:              return "X86ISD::SETCC";
14994   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14995   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14996   case X86ISD::CMOV:               return "X86ISD::CMOV";
14997   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14998   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14999   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
15000   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
15001   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
15002   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
15003   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
15004   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
15005   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
15006   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
15007   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
15008   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
15009   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
15010   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
15011   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
15012   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
15013   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
15014   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
15015   case X86ISD::HADD:               return "X86ISD::HADD";
15016   case X86ISD::HSUB:               return "X86ISD::HSUB";
15017   case X86ISD::FHADD:              return "X86ISD::FHADD";
15018   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
15019   case X86ISD::UMAX:               return "X86ISD::UMAX";
15020   case X86ISD::UMIN:               return "X86ISD::UMIN";
15021   case X86ISD::SMAX:               return "X86ISD::SMAX";
15022   case X86ISD::SMIN:               return "X86ISD::SMIN";
15023   case X86ISD::FMAX:               return "X86ISD::FMAX";
15024   case X86ISD::FMIN:               return "X86ISD::FMIN";
15025   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
15026   case X86ISD::FMINC:              return "X86ISD::FMINC";
15027   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
15028   case X86ISD::FRCP:               return "X86ISD::FRCP";
15029   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
15030   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
15031   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
15032   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
15033   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
15034   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
15035   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
15036   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
15037   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
15038   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
15039   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
15040   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
15041   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
15042   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
15043   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
15044   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
15045   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
15046   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
15047   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
15048   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
15049   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
15050   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
15051   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
15052   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
15053   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
15054   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
15055   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
15056   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
15057   case X86ISD::VSHL:               return "X86ISD::VSHL";
15058   case X86ISD::VSRL:               return "X86ISD::VSRL";
15059   case X86ISD::VSRA:               return "X86ISD::VSRA";
15060   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
15061   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
15062   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
15063   case X86ISD::CMPP:               return "X86ISD::CMPP";
15064   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
15065   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
15066   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
15067   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
15068   case X86ISD::ADD:                return "X86ISD::ADD";
15069   case X86ISD::SUB:                return "X86ISD::SUB";
15070   case X86ISD::ADC:                return "X86ISD::ADC";
15071   case X86ISD::SBB:                return "X86ISD::SBB";
15072   case X86ISD::SMUL:               return "X86ISD::SMUL";
15073   case X86ISD::UMUL:               return "X86ISD::UMUL";
15074   case X86ISD::INC:                return "X86ISD::INC";
15075   case X86ISD::DEC:                return "X86ISD::DEC";
15076   case X86ISD::OR:                 return "X86ISD::OR";
15077   case X86ISD::XOR:                return "X86ISD::XOR";
15078   case X86ISD::AND:                return "X86ISD::AND";
15079   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
15080   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
15081   case X86ISD::PTEST:              return "X86ISD::PTEST";
15082   case X86ISD::TESTP:              return "X86ISD::TESTP";
15083   case X86ISD::TESTM:              return "X86ISD::TESTM";
15084   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
15085   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
15086   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
15087   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
15088   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
15089   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
15090   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
15091   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
15092   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
15093   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
15094   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
15095   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
15096   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
15097   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
15098   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
15099   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
15100   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
15101   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
15102   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
15103   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
15104   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
15105   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
15106   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
15107   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
15108   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
15109   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
15110   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
15111   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
15112   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
15113   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
15114   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15115   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
15116   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
15117   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
15118   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
15119   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
15120   case X86ISD::SAHF:               return "X86ISD::SAHF";
15121   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
15122   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
15123   case X86ISD::FMADD:              return "X86ISD::FMADD";
15124   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
15125   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
15126   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
15127   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
15128   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
15129   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
15130   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
15131   case X86ISD::XTEST:              return "X86ISD::XTEST";
15132   }
15133 }
15134
15135 // isLegalAddressingMode - Return true if the addressing mode represented
15136 // by AM is legal for this target, for a load/store of the specified type.
15137 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15138                                               Type *Ty) const {
15139   // X86 supports extremely general addressing modes.
15140   CodeModel::Model M = getTargetMachine().getCodeModel();
15141   Reloc::Model R = getTargetMachine().getRelocationModel();
15142
15143   // X86 allows a sign-extended 32-bit immediate field as a displacement.
15144   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15145     return false;
15146
15147   if (AM.BaseGV) {
15148     unsigned GVFlags =
15149       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15150
15151     // If a reference to this global requires an extra load, we can't fold it.
15152     if (isGlobalStubReference(GVFlags))
15153       return false;
15154
15155     // If BaseGV requires a register for the PIC base, we cannot also have a
15156     // BaseReg specified.
15157     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15158       return false;
15159
15160     // If lower 4G is not available, then we must use rip-relative addressing.
15161     if ((M != CodeModel::Small || R != Reloc::Static) &&
15162         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15163       return false;
15164   }
15165
15166   switch (AM.Scale) {
15167   case 0:
15168   case 1:
15169   case 2:
15170   case 4:
15171   case 8:
15172     // These scales always work.
15173     break;
15174   case 3:
15175   case 5:
15176   case 9:
15177     // These scales are formed with basereg+scalereg.  Only accept if there is
15178     // no basereg yet.
15179     if (AM.HasBaseReg)
15180       return false;
15181     break;
15182   default:  // Other stuff never works.
15183     return false;
15184   }
15185
15186   return true;
15187 }
15188
15189 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15190   unsigned Bits = Ty->getScalarSizeInBits();
15191
15192   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15193   // particularly cheaper than those without.
15194   if (Bits == 8)
15195     return false;
15196
15197   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15198   // variable shifts just as cheap as scalar ones.
15199   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15200     return false;
15201
15202   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15203   // fully general vector.
15204   return true;
15205 }
15206
15207 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15208   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15209     return false;
15210   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15211   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15212   return NumBits1 > NumBits2;
15213 }
15214
15215 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15216   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15217     return false;
15218
15219   if (!isTypeLegal(EVT::getEVT(Ty1)))
15220     return false;
15221
15222   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15223
15224   // Assuming the caller doesn't have a zeroext or signext return parameter,
15225   // truncation all the way down to i1 is valid.
15226   return true;
15227 }
15228
15229 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15230   return isInt<32>(Imm);
15231 }
15232
15233 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15234   // Can also use sub to handle negated immediates.
15235   return isInt<32>(Imm);
15236 }
15237
15238 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15239   if (!VT1.isInteger() || !VT2.isInteger())
15240     return false;
15241   unsigned NumBits1 = VT1.getSizeInBits();
15242   unsigned NumBits2 = VT2.getSizeInBits();
15243   return NumBits1 > NumBits2;
15244 }
15245
15246 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15247   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15248   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15249 }
15250
15251 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15252   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15253   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15254 }
15255
15256 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15257   EVT VT1 = Val.getValueType();
15258   if (isZExtFree(VT1, VT2))
15259     return true;
15260
15261   if (Val.getOpcode() != ISD::LOAD)
15262     return false;
15263
15264   if (!VT1.isSimple() || !VT1.isInteger() ||
15265       !VT2.isSimple() || !VT2.isInteger())
15266     return false;
15267
15268   switch (VT1.getSimpleVT().SimpleTy) {
15269   default: break;
15270   case MVT::i8:
15271   case MVT::i16:
15272   case MVT::i32:
15273     // X86 has 8, 16, and 32-bit zero-extending loads.
15274     return true;
15275   }
15276
15277   return false;
15278 }
15279
15280 bool
15281 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15282   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15283     return false;
15284
15285   VT = VT.getScalarType();
15286
15287   if (!VT.isSimple())
15288     return false;
15289
15290   switch (VT.getSimpleVT().SimpleTy) {
15291   case MVT::f32:
15292   case MVT::f64:
15293     return true;
15294   default:
15295     break;
15296   }
15297
15298   return false;
15299 }
15300
15301 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15302   // i16 instructions are longer (0x66 prefix) and potentially slower.
15303   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15304 }
15305
15306 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15307 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15308 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15309 /// are assumed to be legal.
15310 bool
15311 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15312                                       EVT VT) const {
15313   if (!VT.isSimple())
15314     return false;
15315
15316   MVT SVT = VT.getSimpleVT();
15317
15318   // Very little shuffling can be done for 64-bit vectors right now.
15319   if (VT.getSizeInBits() == 64)
15320     return false;
15321
15322   // If this is a single-input shuffle with no 128 bit lane crossings we can
15323   // lower it into pshufb.
15324   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15325       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15326     bool isLegal = true;
15327     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15328       if (M[I] >= (int)SVT.getVectorNumElements() ||
15329           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15330         isLegal = false;
15331         break;
15332       }
15333     }
15334     if (isLegal)
15335       return true;
15336   }
15337
15338   // FIXME: blends, shifts.
15339   return (SVT.getVectorNumElements() == 2 ||
15340           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15341           isMOVLMask(M, SVT) ||
15342           isSHUFPMask(M, SVT) ||
15343           isPSHUFDMask(M, SVT) ||
15344           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15345           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15346           isPALIGNRMask(M, SVT, Subtarget) ||
15347           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15348           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15349           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15350           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15351           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15352 }
15353
15354 bool
15355 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15356                                           EVT VT) const {
15357   if (!VT.isSimple())
15358     return false;
15359
15360   MVT SVT = VT.getSimpleVT();
15361   unsigned NumElts = SVT.getVectorNumElements();
15362   // FIXME: This collection of masks seems suspect.
15363   if (NumElts == 2)
15364     return true;
15365   if (NumElts == 4 && SVT.is128BitVector()) {
15366     return (isMOVLMask(Mask, SVT)  ||
15367             isCommutedMOVLMask(Mask, SVT, true) ||
15368             isSHUFPMask(Mask, SVT) ||
15369             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15370   }
15371   return false;
15372 }
15373
15374 //===----------------------------------------------------------------------===//
15375 //                           X86 Scheduler Hooks
15376 //===----------------------------------------------------------------------===//
15377
15378 /// Utility function to emit xbegin specifying the start of an RTM region.
15379 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15380                                      const TargetInstrInfo *TII) {
15381   DebugLoc DL = MI->getDebugLoc();
15382
15383   const BasicBlock *BB = MBB->getBasicBlock();
15384   MachineFunction::iterator I = MBB;
15385   ++I;
15386
15387   // For the v = xbegin(), we generate
15388   //
15389   // thisMBB:
15390   //  xbegin sinkMBB
15391   //
15392   // mainMBB:
15393   //  eax = -1
15394   //
15395   // sinkMBB:
15396   //  v = eax
15397
15398   MachineBasicBlock *thisMBB = MBB;
15399   MachineFunction *MF = MBB->getParent();
15400   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15401   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15402   MF->insert(I, mainMBB);
15403   MF->insert(I, sinkMBB);
15404
15405   // Transfer the remainder of BB and its successor edges to sinkMBB.
15406   sinkMBB->splice(sinkMBB->begin(), MBB,
15407                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15408   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15409
15410   // thisMBB:
15411   //  xbegin sinkMBB
15412   //  # fallthrough to mainMBB
15413   //  # abortion to sinkMBB
15414   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15415   thisMBB->addSuccessor(mainMBB);
15416   thisMBB->addSuccessor(sinkMBB);
15417
15418   // mainMBB:
15419   //  EAX = -1
15420   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15421   mainMBB->addSuccessor(sinkMBB);
15422
15423   // sinkMBB:
15424   // EAX is live into the sinkMBB
15425   sinkMBB->addLiveIn(X86::EAX);
15426   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15427           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15428     .addReg(X86::EAX);
15429
15430   MI->eraseFromParent();
15431   return sinkMBB;
15432 }
15433
15434 // Get CMPXCHG opcode for the specified data type.
15435 static unsigned getCmpXChgOpcode(EVT VT) {
15436   switch (VT.getSimpleVT().SimpleTy) {
15437   case MVT::i8:  return X86::LCMPXCHG8;
15438   case MVT::i16: return X86::LCMPXCHG16;
15439   case MVT::i32: return X86::LCMPXCHG32;
15440   case MVT::i64: return X86::LCMPXCHG64;
15441   default:
15442     break;
15443   }
15444   llvm_unreachable("Invalid operand size!");
15445 }
15446
15447 // Get LOAD opcode for the specified data type.
15448 static unsigned getLoadOpcode(EVT VT) {
15449   switch (VT.getSimpleVT().SimpleTy) {
15450   case MVT::i8:  return X86::MOV8rm;
15451   case MVT::i16: return X86::MOV16rm;
15452   case MVT::i32: return X86::MOV32rm;
15453   case MVT::i64: return X86::MOV64rm;
15454   default:
15455     break;
15456   }
15457   llvm_unreachable("Invalid operand size!");
15458 }
15459
15460 // Get opcode of the non-atomic one from the specified atomic instruction.
15461 static unsigned getNonAtomicOpcode(unsigned Opc) {
15462   switch (Opc) {
15463   case X86::ATOMAND8:  return X86::AND8rr;
15464   case X86::ATOMAND16: return X86::AND16rr;
15465   case X86::ATOMAND32: return X86::AND32rr;
15466   case X86::ATOMAND64: return X86::AND64rr;
15467   case X86::ATOMOR8:   return X86::OR8rr;
15468   case X86::ATOMOR16:  return X86::OR16rr;
15469   case X86::ATOMOR32:  return X86::OR32rr;
15470   case X86::ATOMOR64:  return X86::OR64rr;
15471   case X86::ATOMXOR8:  return X86::XOR8rr;
15472   case X86::ATOMXOR16: return X86::XOR16rr;
15473   case X86::ATOMXOR32: return X86::XOR32rr;
15474   case X86::ATOMXOR64: return X86::XOR64rr;
15475   }
15476   llvm_unreachable("Unhandled atomic-load-op opcode!");
15477 }
15478
15479 // Get opcode of the non-atomic one from the specified atomic instruction with
15480 // extra opcode.
15481 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15482                                                unsigned &ExtraOpc) {
15483   switch (Opc) {
15484   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15485   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15486   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15487   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15488   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15489   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15490   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15491   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15492   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15493   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15494   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15495   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15496   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15497   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15498   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15499   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15500   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15501   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15502   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15503   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15504   }
15505   llvm_unreachable("Unhandled atomic-load-op opcode!");
15506 }
15507
15508 // Get opcode of the non-atomic one from the specified atomic instruction for
15509 // 64-bit data type on 32-bit target.
15510 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15511   switch (Opc) {
15512   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15513   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15514   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15515   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15516   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15517   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15518   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15519   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15520   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15521   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15522   }
15523   llvm_unreachable("Unhandled atomic-load-op opcode!");
15524 }
15525
15526 // Get opcode of the non-atomic one from the specified atomic instruction for
15527 // 64-bit data type on 32-bit target with extra opcode.
15528 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15529                                                    unsigned &HiOpc,
15530                                                    unsigned &ExtraOpc) {
15531   switch (Opc) {
15532   case X86::ATOMNAND6432:
15533     ExtraOpc = X86::NOT32r;
15534     HiOpc = X86::AND32rr;
15535     return X86::AND32rr;
15536   }
15537   llvm_unreachable("Unhandled atomic-load-op opcode!");
15538 }
15539
15540 // Get pseudo CMOV opcode from the specified data type.
15541 static unsigned getPseudoCMOVOpc(EVT VT) {
15542   switch (VT.getSimpleVT().SimpleTy) {
15543   case MVT::i8:  return X86::CMOV_GR8;
15544   case MVT::i16: return X86::CMOV_GR16;
15545   case MVT::i32: return X86::CMOV_GR32;
15546   default:
15547     break;
15548   }
15549   llvm_unreachable("Unknown CMOV opcode!");
15550 }
15551
15552 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15553 // They will be translated into a spin-loop or compare-exchange loop from
15554 //
15555 //    ...
15556 //    dst = atomic-fetch-op MI.addr, MI.val
15557 //    ...
15558 //
15559 // to
15560 //
15561 //    ...
15562 //    t1 = LOAD MI.addr
15563 // loop:
15564 //    t4 = phi(t1, t3 / loop)
15565 //    t2 = OP MI.val, t4
15566 //    EAX = t4
15567 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15568 //    t3 = EAX
15569 //    JNE loop
15570 // sink:
15571 //    dst = t3
15572 //    ...
15573 MachineBasicBlock *
15574 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15575                                        MachineBasicBlock *MBB) const {
15576   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15577   DebugLoc DL = MI->getDebugLoc();
15578
15579   MachineFunction *MF = MBB->getParent();
15580   MachineRegisterInfo &MRI = MF->getRegInfo();
15581
15582   const BasicBlock *BB = MBB->getBasicBlock();
15583   MachineFunction::iterator I = MBB;
15584   ++I;
15585
15586   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15587          "Unexpected number of operands");
15588
15589   assert(MI->hasOneMemOperand() &&
15590          "Expected atomic-load-op to have one memoperand");
15591
15592   // Memory Reference
15593   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15594   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15595
15596   unsigned DstReg, SrcReg;
15597   unsigned MemOpndSlot;
15598
15599   unsigned CurOp = 0;
15600
15601   DstReg = MI->getOperand(CurOp++).getReg();
15602   MemOpndSlot = CurOp;
15603   CurOp += X86::AddrNumOperands;
15604   SrcReg = MI->getOperand(CurOp++).getReg();
15605
15606   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15607   MVT::SimpleValueType VT = *RC->vt_begin();
15608   unsigned t1 = MRI.createVirtualRegister(RC);
15609   unsigned t2 = MRI.createVirtualRegister(RC);
15610   unsigned t3 = MRI.createVirtualRegister(RC);
15611   unsigned t4 = MRI.createVirtualRegister(RC);
15612   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15613
15614   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15615   unsigned LOADOpc = getLoadOpcode(VT);
15616
15617   // For the atomic load-arith operator, we generate
15618   //
15619   //  thisMBB:
15620   //    t1 = LOAD [MI.addr]
15621   //  mainMBB:
15622   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15623   //    t1 = OP MI.val, EAX
15624   //    EAX = t4
15625   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15626   //    t3 = EAX
15627   //    JNE mainMBB
15628   //  sinkMBB:
15629   //    dst = t3
15630
15631   MachineBasicBlock *thisMBB = MBB;
15632   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15633   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15634   MF->insert(I, mainMBB);
15635   MF->insert(I, sinkMBB);
15636
15637   MachineInstrBuilder MIB;
15638
15639   // Transfer the remainder of BB and its successor edges to sinkMBB.
15640   sinkMBB->splice(sinkMBB->begin(), MBB,
15641                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15642   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15643
15644   // thisMBB:
15645   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15646   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15647     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15648     if (NewMO.isReg())
15649       NewMO.setIsKill(false);
15650     MIB.addOperand(NewMO);
15651   }
15652   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15653     unsigned flags = (*MMOI)->getFlags();
15654     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15655     MachineMemOperand *MMO =
15656       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15657                                (*MMOI)->getSize(),
15658                                (*MMOI)->getBaseAlignment(),
15659                                (*MMOI)->getTBAAInfo(),
15660                                (*MMOI)->getRanges());
15661     MIB.addMemOperand(MMO);
15662   }
15663
15664   thisMBB->addSuccessor(mainMBB);
15665
15666   // mainMBB:
15667   MachineBasicBlock *origMainMBB = mainMBB;
15668
15669   // Add a PHI.
15670   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15671                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15672
15673   unsigned Opc = MI->getOpcode();
15674   switch (Opc) {
15675   default:
15676     llvm_unreachable("Unhandled atomic-load-op opcode!");
15677   case X86::ATOMAND8:
15678   case X86::ATOMAND16:
15679   case X86::ATOMAND32:
15680   case X86::ATOMAND64:
15681   case X86::ATOMOR8:
15682   case X86::ATOMOR16:
15683   case X86::ATOMOR32:
15684   case X86::ATOMOR64:
15685   case X86::ATOMXOR8:
15686   case X86::ATOMXOR16:
15687   case X86::ATOMXOR32:
15688   case X86::ATOMXOR64: {
15689     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15690     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15691       .addReg(t4);
15692     break;
15693   }
15694   case X86::ATOMNAND8:
15695   case X86::ATOMNAND16:
15696   case X86::ATOMNAND32:
15697   case X86::ATOMNAND64: {
15698     unsigned Tmp = MRI.createVirtualRegister(RC);
15699     unsigned NOTOpc;
15700     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15701     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15702       .addReg(t4);
15703     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15704     break;
15705   }
15706   case X86::ATOMMAX8:
15707   case X86::ATOMMAX16:
15708   case X86::ATOMMAX32:
15709   case X86::ATOMMAX64:
15710   case X86::ATOMMIN8:
15711   case X86::ATOMMIN16:
15712   case X86::ATOMMIN32:
15713   case X86::ATOMMIN64:
15714   case X86::ATOMUMAX8:
15715   case X86::ATOMUMAX16:
15716   case X86::ATOMUMAX32:
15717   case X86::ATOMUMAX64:
15718   case X86::ATOMUMIN8:
15719   case X86::ATOMUMIN16:
15720   case X86::ATOMUMIN32:
15721   case X86::ATOMUMIN64: {
15722     unsigned CMPOpc;
15723     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15724
15725     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15726       .addReg(SrcReg)
15727       .addReg(t4);
15728
15729     if (Subtarget->hasCMov()) {
15730       if (VT != MVT::i8) {
15731         // Native support
15732         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15733           .addReg(SrcReg)
15734           .addReg(t4);
15735       } else {
15736         // Promote i8 to i32 to use CMOV32
15737         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15738         const TargetRegisterClass *RC32 =
15739           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15740         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15741         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15742         unsigned Tmp = MRI.createVirtualRegister(RC32);
15743
15744         unsigned Undef = MRI.createVirtualRegister(RC32);
15745         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15746
15747         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15748           .addReg(Undef)
15749           .addReg(SrcReg)
15750           .addImm(X86::sub_8bit);
15751         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15752           .addReg(Undef)
15753           .addReg(t4)
15754           .addImm(X86::sub_8bit);
15755
15756         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15757           .addReg(SrcReg32)
15758           .addReg(AccReg32);
15759
15760         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15761           .addReg(Tmp, 0, X86::sub_8bit);
15762       }
15763     } else {
15764       // Use pseudo select and lower them.
15765       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15766              "Invalid atomic-load-op transformation!");
15767       unsigned SelOpc = getPseudoCMOVOpc(VT);
15768       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15769       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15770       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15771               .addReg(SrcReg).addReg(t4)
15772               .addImm(CC);
15773       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15774       // Replace the original PHI node as mainMBB is changed after CMOV
15775       // lowering.
15776       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15777         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15778       Phi->eraseFromParent();
15779     }
15780     break;
15781   }
15782   }
15783
15784   // Copy PhyReg back from virtual register.
15785   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15786     .addReg(t4);
15787
15788   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15789   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15790     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15791     if (NewMO.isReg())
15792       NewMO.setIsKill(false);
15793     MIB.addOperand(NewMO);
15794   }
15795   MIB.addReg(t2);
15796   MIB.setMemRefs(MMOBegin, MMOEnd);
15797
15798   // Copy PhyReg back to virtual register.
15799   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15800     .addReg(PhyReg);
15801
15802   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15803
15804   mainMBB->addSuccessor(origMainMBB);
15805   mainMBB->addSuccessor(sinkMBB);
15806
15807   // sinkMBB:
15808   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15809           TII->get(TargetOpcode::COPY), DstReg)
15810     .addReg(t3);
15811
15812   MI->eraseFromParent();
15813   return sinkMBB;
15814 }
15815
15816 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15817 // instructions. They will be translated into a spin-loop or compare-exchange
15818 // loop from
15819 //
15820 //    ...
15821 //    dst = atomic-fetch-op MI.addr, MI.val
15822 //    ...
15823 //
15824 // to
15825 //
15826 //    ...
15827 //    t1L = LOAD [MI.addr + 0]
15828 //    t1H = LOAD [MI.addr + 4]
15829 // loop:
15830 //    t4L = phi(t1L, t3L / loop)
15831 //    t4H = phi(t1H, t3H / loop)
15832 //    t2L = OP MI.val.lo, t4L
15833 //    t2H = OP MI.val.hi, t4H
15834 //    EAX = t4L
15835 //    EDX = t4H
15836 //    EBX = t2L
15837 //    ECX = t2H
15838 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15839 //    t3L = EAX
15840 //    t3H = EDX
15841 //    JNE loop
15842 // sink:
15843 //    dstL = t3L
15844 //    dstH = t3H
15845 //    ...
15846 MachineBasicBlock *
15847 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15848                                            MachineBasicBlock *MBB) const {
15849   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15850   DebugLoc DL = MI->getDebugLoc();
15851
15852   MachineFunction *MF = MBB->getParent();
15853   MachineRegisterInfo &MRI = MF->getRegInfo();
15854
15855   const BasicBlock *BB = MBB->getBasicBlock();
15856   MachineFunction::iterator I = MBB;
15857   ++I;
15858
15859   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15860          "Unexpected number of operands");
15861
15862   assert(MI->hasOneMemOperand() &&
15863          "Expected atomic-load-op32 to have one memoperand");
15864
15865   // Memory Reference
15866   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15867   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15868
15869   unsigned DstLoReg, DstHiReg;
15870   unsigned SrcLoReg, SrcHiReg;
15871   unsigned MemOpndSlot;
15872
15873   unsigned CurOp = 0;
15874
15875   DstLoReg = MI->getOperand(CurOp++).getReg();
15876   DstHiReg = MI->getOperand(CurOp++).getReg();
15877   MemOpndSlot = CurOp;
15878   CurOp += X86::AddrNumOperands;
15879   SrcLoReg = MI->getOperand(CurOp++).getReg();
15880   SrcHiReg = MI->getOperand(CurOp++).getReg();
15881
15882   const TargetRegisterClass *RC = &X86::GR32RegClass;
15883   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15884
15885   unsigned t1L = MRI.createVirtualRegister(RC);
15886   unsigned t1H = MRI.createVirtualRegister(RC);
15887   unsigned t2L = MRI.createVirtualRegister(RC);
15888   unsigned t2H = MRI.createVirtualRegister(RC);
15889   unsigned t3L = MRI.createVirtualRegister(RC);
15890   unsigned t3H = MRI.createVirtualRegister(RC);
15891   unsigned t4L = MRI.createVirtualRegister(RC);
15892   unsigned t4H = MRI.createVirtualRegister(RC);
15893
15894   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15895   unsigned LOADOpc = X86::MOV32rm;
15896
15897   // For the atomic load-arith operator, we generate
15898   //
15899   //  thisMBB:
15900   //    t1L = LOAD [MI.addr + 0]
15901   //    t1H = LOAD [MI.addr + 4]
15902   //  mainMBB:
15903   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15904   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15905   //    t2L = OP MI.val.lo, t4L
15906   //    t2H = OP MI.val.hi, t4H
15907   //    EBX = t2L
15908   //    ECX = t2H
15909   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15910   //    t3L = EAX
15911   //    t3H = EDX
15912   //    JNE loop
15913   //  sinkMBB:
15914   //    dstL = t3L
15915   //    dstH = t3H
15916
15917   MachineBasicBlock *thisMBB = MBB;
15918   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15919   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15920   MF->insert(I, mainMBB);
15921   MF->insert(I, sinkMBB);
15922
15923   MachineInstrBuilder MIB;
15924
15925   // Transfer the remainder of BB and its successor edges to sinkMBB.
15926   sinkMBB->splice(sinkMBB->begin(), MBB,
15927                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15928   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15929
15930   // thisMBB:
15931   // Lo
15932   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15933   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15934     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15935     if (NewMO.isReg())
15936       NewMO.setIsKill(false);
15937     MIB.addOperand(NewMO);
15938   }
15939   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15940     unsigned flags = (*MMOI)->getFlags();
15941     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15942     MachineMemOperand *MMO =
15943       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15944                                (*MMOI)->getSize(),
15945                                (*MMOI)->getBaseAlignment(),
15946                                (*MMOI)->getTBAAInfo(),
15947                                (*MMOI)->getRanges());
15948     MIB.addMemOperand(MMO);
15949   };
15950   MachineInstr *LowMI = MIB;
15951
15952   // Hi
15953   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15954   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15955     if (i == X86::AddrDisp) {
15956       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15957     } else {
15958       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15959       if (NewMO.isReg())
15960         NewMO.setIsKill(false);
15961       MIB.addOperand(NewMO);
15962     }
15963   }
15964   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15965
15966   thisMBB->addSuccessor(mainMBB);
15967
15968   // mainMBB:
15969   MachineBasicBlock *origMainMBB = mainMBB;
15970
15971   // Add PHIs.
15972   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15973                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15974   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15975                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15976
15977   unsigned Opc = MI->getOpcode();
15978   switch (Opc) {
15979   default:
15980     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15981   case X86::ATOMAND6432:
15982   case X86::ATOMOR6432:
15983   case X86::ATOMXOR6432:
15984   case X86::ATOMADD6432:
15985   case X86::ATOMSUB6432: {
15986     unsigned HiOpc;
15987     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15988     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15989       .addReg(SrcLoReg);
15990     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15991       .addReg(SrcHiReg);
15992     break;
15993   }
15994   case X86::ATOMNAND6432: {
15995     unsigned HiOpc, NOTOpc;
15996     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15997     unsigned TmpL = MRI.createVirtualRegister(RC);
15998     unsigned TmpH = MRI.createVirtualRegister(RC);
15999     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16000       .addReg(t4L);
16001     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16002       .addReg(t4H);
16003     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16004     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16005     break;
16006   }
16007   case X86::ATOMMAX6432:
16008   case X86::ATOMMIN6432:
16009   case X86::ATOMUMAX6432:
16010   case X86::ATOMUMIN6432: {
16011     unsigned HiOpc;
16012     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16013     unsigned cL = MRI.createVirtualRegister(RC8);
16014     unsigned cH = MRI.createVirtualRegister(RC8);
16015     unsigned cL32 = MRI.createVirtualRegister(RC);
16016     unsigned cH32 = MRI.createVirtualRegister(RC);
16017     unsigned cc = MRI.createVirtualRegister(RC);
16018     // cl := cmp src_lo, lo
16019     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16020       .addReg(SrcLoReg).addReg(t4L);
16021     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16022     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16023     // ch := cmp src_hi, hi
16024     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16025       .addReg(SrcHiReg).addReg(t4H);
16026     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16027     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16028     // cc := if (src_hi == hi) ? cl : ch;
16029     if (Subtarget->hasCMov()) {
16030       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16031         .addReg(cH32).addReg(cL32);
16032     } else {
16033       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16034               .addReg(cH32).addReg(cL32)
16035               .addImm(X86::COND_E);
16036       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16037     }
16038     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16039     if (Subtarget->hasCMov()) {
16040       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16041         .addReg(SrcLoReg).addReg(t4L);
16042       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16043         .addReg(SrcHiReg).addReg(t4H);
16044     } else {
16045       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16046               .addReg(SrcLoReg).addReg(t4L)
16047               .addImm(X86::COND_NE);
16048       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16049       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16050       // 2nd CMOV lowering.
16051       mainMBB->addLiveIn(X86::EFLAGS);
16052       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16053               .addReg(SrcHiReg).addReg(t4H)
16054               .addImm(X86::COND_NE);
16055       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16056       // Replace the original PHI node as mainMBB is changed after CMOV
16057       // lowering.
16058       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16059         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16060       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16061         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16062       PhiL->eraseFromParent();
16063       PhiH->eraseFromParent();
16064     }
16065     break;
16066   }
16067   case X86::ATOMSWAP6432: {
16068     unsigned HiOpc;
16069     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16070     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16071     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16072     break;
16073   }
16074   }
16075
16076   // Copy EDX:EAX back from HiReg:LoReg
16077   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16078   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16079   // Copy ECX:EBX from t1H:t1L
16080   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16081   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16082
16083   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16084   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16085     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16086     if (NewMO.isReg())
16087       NewMO.setIsKill(false);
16088     MIB.addOperand(NewMO);
16089   }
16090   MIB.setMemRefs(MMOBegin, MMOEnd);
16091
16092   // Copy EDX:EAX back to t3H:t3L
16093   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16094   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16095
16096   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16097
16098   mainMBB->addSuccessor(origMainMBB);
16099   mainMBB->addSuccessor(sinkMBB);
16100
16101   // sinkMBB:
16102   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16103           TII->get(TargetOpcode::COPY), DstLoReg)
16104     .addReg(t3L);
16105   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16106           TII->get(TargetOpcode::COPY), DstHiReg)
16107     .addReg(t3H);
16108
16109   MI->eraseFromParent();
16110   return sinkMBB;
16111 }
16112
16113 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16114 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16115 // in the .td file.
16116 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16117                                        const TargetInstrInfo *TII) {
16118   unsigned Opc;
16119   switch (MI->getOpcode()) {
16120   default: llvm_unreachable("illegal opcode!");
16121   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16122   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16123   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16124   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16125   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16126   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16127   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16128   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16129   }
16130
16131   DebugLoc dl = MI->getDebugLoc();
16132   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16133
16134   unsigned NumArgs = MI->getNumOperands();
16135   for (unsigned i = 1; i < NumArgs; ++i) {
16136     MachineOperand &Op = MI->getOperand(i);
16137     if (!(Op.isReg() && Op.isImplicit()))
16138       MIB.addOperand(Op);
16139   }
16140   if (MI->hasOneMemOperand())
16141     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16142
16143   BuildMI(*BB, MI, dl,
16144     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16145     .addReg(X86::XMM0);
16146
16147   MI->eraseFromParent();
16148   return BB;
16149 }
16150
16151 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16152 // defs in an instruction pattern
16153 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16154                                        const TargetInstrInfo *TII) {
16155   unsigned Opc;
16156   switch (MI->getOpcode()) {
16157   default: llvm_unreachable("illegal opcode!");
16158   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16159   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16160   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16161   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16162   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16163   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16164   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16165   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16166   }
16167
16168   DebugLoc dl = MI->getDebugLoc();
16169   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16170
16171   unsigned NumArgs = MI->getNumOperands(); // remove the results
16172   for (unsigned i = 1; i < NumArgs; ++i) {
16173     MachineOperand &Op = MI->getOperand(i);
16174     if (!(Op.isReg() && Op.isImplicit()))
16175       MIB.addOperand(Op);
16176   }
16177   if (MI->hasOneMemOperand())
16178     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16179
16180   BuildMI(*BB, MI, dl,
16181     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16182     .addReg(X86::ECX);
16183
16184   MI->eraseFromParent();
16185   return BB;
16186 }
16187
16188 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16189                                        const TargetInstrInfo *TII,
16190                                        const X86Subtarget* Subtarget) {
16191   DebugLoc dl = MI->getDebugLoc();
16192
16193   // Address into RAX/EAX, other two args into ECX, EDX.
16194   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16195   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16196   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16197   for (int i = 0; i < X86::AddrNumOperands; ++i)
16198     MIB.addOperand(MI->getOperand(i));
16199
16200   unsigned ValOps = X86::AddrNumOperands;
16201   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16202     .addReg(MI->getOperand(ValOps).getReg());
16203   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16204     .addReg(MI->getOperand(ValOps+1).getReg());
16205
16206   // The instruction doesn't actually take any operands though.
16207   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16208
16209   MI->eraseFromParent(); // The pseudo is gone now.
16210   return BB;
16211 }
16212
16213 MachineBasicBlock *
16214 X86TargetLowering::EmitVAARG64WithCustomInserter(
16215                    MachineInstr *MI,
16216                    MachineBasicBlock *MBB) const {
16217   // Emit va_arg instruction on X86-64.
16218
16219   // Operands to this pseudo-instruction:
16220   // 0  ) Output        : destination address (reg)
16221   // 1-5) Input         : va_list address (addr, i64mem)
16222   // 6  ) ArgSize       : Size (in bytes) of vararg type
16223   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16224   // 8  ) Align         : Alignment of type
16225   // 9  ) EFLAGS (implicit-def)
16226
16227   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16228   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16229
16230   unsigned DestReg = MI->getOperand(0).getReg();
16231   MachineOperand &Base = MI->getOperand(1);
16232   MachineOperand &Scale = MI->getOperand(2);
16233   MachineOperand &Index = MI->getOperand(3);
16234   MachineOperand &Disp = MI->getOperand(4);
16235   MachineOperand &Segment = MI->getOperand(5);
16236   unsigned ArgSize = MI->getOperand(6).getImm();
16237   unsigned ArgMode = MI->getOperand(7).getImm();
16238   unsigned Align = MI->getOperand(8).getImm();
16239
16240   // Memory Reference
16241   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16242   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16243   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16244
16245   // Machine Information
16246   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16247   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16248   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16249   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16250   DebugLoc DL = MI->getDebugLoc();
16251
16252   // struct va_list {
16253   //   i32   gp_offset
16254   //   i32   fp_offset
16255   //   i64   overflow_area (address)
16256   //   i64   reg_save_area (address)
16257   // }
16258   // sizeof(va_list) = 24
16259   // alignment(va_list) = 8
16260
16261   unsigned TotalNumIntRegs = 6;
16262   unsigned TotalNumXMMRegs = 8;
16263   bool UseGPOffset = (ArgMode == 1);
16264   bool UseFPOffset = (ArgMode == 2);
16265   unsigned MaxOffset = TotalNumIntRegs * 8 +
16266                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16267
16268   /* Align ArgSize to a multiple of 8 */
16269   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16270   bool NeedsAlign = (Align > 8);
16271
16272   MachineBasicBlock *thisMBB = MBB;
16273   MachineBasicBlock *overflowMBB;
16274   MachineBasicBlock *offsetMBB;
16275   MachineBasicBlock *endMBB;
16276
16277   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16278   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16279   unsigned OffsetReg = 0;
16280
16281   if (!UseGPOffset && !UseFPOffset) {
16282     // If we only pull from the overflow region, we don't create a branch.
16283     // We don't need to alter control flow.
16284     OffsetDestReg = 0; // unused
16285     OverflowDestReg = DestReg;
16286
16287     offsetMBB = nullptr;
16288     overflowMBB = thisMBB;
16289     endMBB = thisMBB;
16290   } else {
16291     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16292     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16293     // If not, pull from overflow_area. (branch to overflowMBB)
16294     //
16295     //       thisMBB
16296     //         |     .
16297     //         |        .
16298     //     offsetMBB   overflowMBB
16299     //         |        .
16300     //         |     .
16301     //        endMBB
16302
16303     // Registers for the PHI in endMBB
16304     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16305     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16306
16307     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16308     MachineFunction *MF = MBB->getParent();
16309     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16310     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16311     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16312
16313     MachineFunction::iterator MBBIter = MBB;
16314     ++MBBIter;
16315
16316     // Insert the new basic blocks
16317     MF->insert(MBBIter, offsetMBB);
16318     MF->insert(MBBIter, overflowMBB);
16319     MF->insert(MBBIter, endMBB);
16320
16321     // Transfer the remainder of MBB and its successor edges to endMBB.
16322     endMBB->splice(endMBB->begin(), thisMBB,
16323                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16324     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16325
16326     // Make offsetMBB and overflowMBB successors of thisMBB
16327     thisMBB->addSuccessor(offsetMBB);
16328     thisMBB->addSuccessor(overflowMBB);
16329
16330     // endMBB is a successor of both offsetMBB and overflowMBB
16331     offsetMBB->addSuccessor(endMBB);
16332     overflowMBB->addSuccessor(endMBB);
16333
16334     // Load the offset value into a register
16335     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16336     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16337       .addOperand(Base)
16338       .addOperand(Scale)
16339       .addOperand(Index)
16340       .addDisp(Disp, UseFPOffset ? 4 : 0)
16341       .addOperand(Segment)
16342       .setMemRefs(MMOBegin, MMOEnd);
16343
16344     // Check if there is enough room left to pull this argument.
16345     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16346       .addReg(OffsetReg)
16347       .addImm(MaxOffset + 8 - ArgSizeA8);
16348
16349     // Branch to "overflowMBB" if offset >= max
16350     // Fall through to "offsetMBB" otherwise
16351     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16352       .addMBB(overflowMBB);
16353   }
16354
16355   // In offsetMBB, emit code to use the reg_save_area.
16356   if (offsetMBB) {
16357     assert(OffsetReg != 0);
16358
16359     // Read the reg_save_area address.
16360     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16361     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16362       .addOperand(Base)
16363       .addOperand(Scale)
16364       .addOperand(Index)
16365       .addDisp(Disp, 16)
16366       .addOperand(Segment)
16367       .setMemRefs(MMOBegin, MMOEnd);
16368
16369     // Zero-extend the offset
16370     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16371       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16372         .addImm(0)
16373         .addReg(OffsetReg)
16374         .addImm(X86::sub_32bit);
16375
16376     // Add the offset to the reg_save_area to get the final address.
16377     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16378       .addReg(OffsetReg64)
16379       .addReg(RegSaveReg);
16380
16381     // Compute the offset for the next argument
16382     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16383     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16384       .addReg(OffsetReg)
16385       .addImm(UseFPOffset ? 16 : 8);
16386
16387     // Store it back into the va_list.
16388     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16389       .addOperand(Base)
16390       .addOperand(Scale)
16391       .addOperand(Index)
16392       .addDisp(Disp, UseFPOffset ? 4 : 0)
16393       .addOperand(Segment)
16394       .addReg(NextOffsetReg)
16395       .setMemRefs(MMOBegin, MMOEnd);
16396
16397     // Jump to endMBB
16398     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16399       .addMBB(endMBB);
16400   }
16401
16402   //
16403   // Emit code to use overflow area
16404   //
16405
16406   // Load the overflow_area address into a register.
16407   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16408   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16409     .addOperand(Base)
16410     .addOperand(Scale)
16411     .addOperand(Index)
16412     .addDisp(Disp, 8)
16413     .addOperand(Segment)
16414     .setMemRefs(MMOBegin, MMOEnd);
16415
16416   // If we need to align it, do so. Otherwise, just copy the address
16417   // to OverflowDestReg.
16418   if (NeedsAlign) {
16419     // Align the overflow address
16420     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16421     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16422
16423     // aligned_addr = (addr + (align-1)) & ~(align-1)
16424     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16425       .addReg(OverflowAddrReg)
16426       .addImm(Align-1);
16427
16428     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16429       .addReg(TmpReg)
16430       .addImm(~(uint64_t)(Align-1));
16431   } else {
16432     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16433       .addReg(OverflowAddrReg);
16434   }
16435
16436   // Compute the next overflow address after this argument.
16437   // (the overflow address should be kept 8-byte aligned)
16438   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16439   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16440     .addReg(OverflowDestReg)
16441     .addImm(ArgSizeA8);
16442
16443   // Store the new overflow address.
16444   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16445     .addOperand(Base)
16446     .addOperand(Scale)
16447     .addOperand(Index)
16448     .addDisp(Disp, 8)
16449     .addOperand(Segment)
16450     .addReg(NextAddrReg)
16451     .setMemRefs(MMOBegin, MMOEnd);
16452
16453   // If we branched, emit the PHI to the front of endMBB.
16454   if (offsetMBB) {
16455     BuildMI(*endMBB, endMBB->begin(), DL,
16456             TII->get(X86::PHI), DestReg)
16457       .addReg(OffsetDestReg).addMBB(offsetMBB)
16458       .addReg(OverflowDestReg).addMBB(overflowMBB);
16459   }
16460
16461   // Erase the pseudo instruction
16462   MI->eraseFromParent();
16463
16464   return endMBB;
16465 }
16466
16467 MachineBasicBlock *
16468 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16469                                                  MachineInstr *MI,
16470                                                  MachineBasicBlock *MBB) const {
16471   // Emit code to save XMM registers to the stack. The ABI says that the
16472   // number of registers to save is given in %al, so it's theoretically
16473   // possible to do an indirect jump trick to avoid saving all of them,
16474   // however this code takes a simpler approach and just executes all
16475   // of the stores if %al is non-zero. It's less code, and it's probably
16476   // easier on the hardware branch predictor, and stores aren't all that
16477   // expensive anyway.
16478
16479   // Create the new basic blocks. One block contains all the XMM stores,
16480   // and one block is the final destination regardless of whether any
16481   // stores were performed.
16482   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16483   MachineFunction *F = MBB->getParent();
16484   MachineFunction::iterator MBBIter = MBB;
16485   ++MBBIter;
16486   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16487   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16488   F->insert(MBBIter, XMMSaveMBB);
16489   F->insert(MBBIter, EndMBB);
16490
16491   // Transfer the remainder of MBB and its successor edges to EndMBB.
16492   EndMBB->splice(EndMBB->begin(), MBB,
16493                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16494   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16495
16496   // The original block will now fall through to the XMM save block.
16497   MBB->addSuccessor(XMMSaveMBB);
16498   // The XMMSaveMBB will fall through to the end block.
16499   XMMSaveMBB->addSuccessor(EndMBB);
16500
16501   // Now add the instructions.
16502   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16503   DebugLoc DL = MI->getDebugLoc();
16504
16505   unsigned CountReg = MI->getOperand(0).getReg();
16506   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16507   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16508
16509   if (!Subtarget->isTargetWin64()) {
16510     // If %al is 0, branch around the XMM save block.
16511     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16512     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16513     MBB->addSuccessor(EndMBB);
16514   }
16515
16516   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16517   // that was just emitted, but clearly shouldn't be "saved".
16518   assert((MI->getNumOperands() <= 3 ||
16519           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16520           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16521          && "Expected last argument to be EFLAGS");
16522   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16523   // In the XMM save block, save all the XMM argument registers.
16524   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16525     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16526     MachineMemOperand *MMO =
16527       F->getMachineMemOperand(
16528           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16529         MachineMemOperand::MOStore,
16530         /*Size=*/16, /*Align=*/16);
16531     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16532       .addFrameIndex(RegSaveFrameIndex)
16533       .addImm(/*Scale=*/1)
16534       .addReg(/*IndexReg=*/0)
16535       .addImm(/*Disp=*/Offset)
16536       .addReg(/*Segment=*/0)
16537       .addReg(MI->getOperand(i).getReg())
16538       .addMemOperand(MMO);
16539   }
16540
16541   MI->eraseFromParent();   // The pseudo instruction is gone now.
16542
16543   return EndMBB;
16544 }
16545
16546 // The EFLAGS operand of SelectItr might be missing a kill marker
16547 // because there were multiple uses of EFLAGS, and ISel didn't know
16548 // which to mark. Figure out whether SelectItr should have had a
16549 // kill marker, and set it if it should. Returns the correct kill
16550 // marker value.
16551 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16552                                      MachineBasicBlock* BB,
16553                                      const TargetRegisterInfo* TRI) {
16554   // Scan forward through BB for a use/def of EFLAGS.
16555   MachineBasicBlock::iterator miI(std::next(SelectItr));
16556   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16557     const MachineInstr& mi = *miI;
16558     if (mi.readsRegister(X86::EFLAGS))
16559       return false;
16560     if (mi.definesRegister(X86::EFLAGS))
16561       break; // Should have kill-flag - update below.
16562   }
16563
16564   // If we hit the end of the block, check whether EFLAGS is live into a
16565   // successor.
16566   if (miI == BB->end()) {
16567     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16568                                           sEnd = BB->succ_end();
16569          sItr != sEnd; ++sItr) {
16570       MachineBasicBlock* succ = *sItr;
16571       if (succ->isLiveIn(X86::EFLAGS))
16572         return false;
16573     }
16574   }
16575
16576   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16577   // out. SelectMI should have a kill flag on EFLAGS.
16578   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16579   return true;
16580 }
16581
16582 MachineBasicBlock *
16583 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16584                                      MachineBasicBlock *BB) const {
16585   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16586   DebugLoc DL = MI->getDebugLoc();
16587
16588   // To "insert" a SELECT_CC instruction, we actually have to insert the
16589   // diamond control-flow pattern.  The incoming instruction knows the
16590   // destination vreg to set, the condition code register to branch on, the
16591   // true/false values to select between, and a branch opcode to use.
16592   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16593   MachineFunction::iterator It = BB;
16594   ++It;
16595
16596   //  thisMBB:
16597   //  ...
16598   //   TrueVal = ...
16599   //   cmpTY ccX, r1, r2
16600   //   bCC copy1MBB
16601   //   fallthrough --> copy0MBB
16602   MachineBasicBlock *thisMBB = BB;
16603   MachineFunction *F = BB->getParent();
16604   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16605   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16606   F->insert(It, copy0MBB);
16607   F->insert(It, sinkMBB);
16608
16609   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16610   // live into the sink and copy blocks.
16611   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16612   if (!MI->killsRegister(X86::EFLAGS) &&
16613       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16614     copy0MBB->addLiveIn(X86::EFLAGS);
16615     sinkMBB->addLiveIn(X86::EFLAGS);
16616   }
16617
16618   // Transfer the remainder of BB and its successor edges to sinkMBB.
16619   sinkMBB->splice(sinkMBB->begin(), BB,
16620                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16621   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16622
16623   // Add the true and fallthrough blocks as its successors.
16624   BB->addSuccessor(copy0MBB);
16625   BB->addSuccessor(sinkMBB);
16626
16627   // Create the conditional branch instruction.
16628   unsigned Opc =
16629     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16630   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16631
16632   //  copy0MBB:
16633   //   %FalseValue = ...
16634   //   # fallthrough to sinkMBB
16635   copy0MBB->addSuccessor(sinkMBB);
16636
16637   //  sinkMBB:
16638   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16639   //  ...
16640   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16641           TII->get(X86::PHI), MI->getOperand(0).getReg())
16642     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16643     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16644
16645   MI->eraseFromParent();   // The pseudo instruction is gone now.
16646   return sinkMBB;
16647 }
16648
16649 MachineBasicBlock *
16650 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16651                                         bool Is64Bit) const {
16652   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16653   DebugLoc DL = MI->getDebugLoc();
16654   MachineFunction *MF = BB->getParent();
16655   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16656
16657   assert(MF->shouldSplitStack());
16658
16659   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16660   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16661
16662   // BB:
16663   //  ... [Till the alloca]
16664   // If stacklet is not large enough, jump to mallocMBB
16665   //
16666   // bumpMBB:
16667   //  Allocate by subtracting from RSP
16668   //  Jump to continueMBB
16669   //
16670   // mallocMBB:
16671   //  Allocate by call to runtime
16672   //
16673   // continueMBB:
16674   //  ...
16675   //  [rest of original BB]
16676   //
16677
16678   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16679   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16680   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16681
16682   MachineRegisterInfo &MRI = MF->getRegInfo();
16683   const TargetRegisterClass *AddrRegClass =
16684     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16685
16686   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16687     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16688     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16689     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16690     sizeVReg = MI->getOperand(1).getReg(),
16691     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16692
16693   MachineFunction::iterator MBBIter = BB;
16694   ++MBBIter;
16695
16696   MF->insert(MBBIter, bumpMBB);
16697   MF->insert(MBBIter, mallocMBB);
16698   MF->insert(MBBIter, continueMBB);
16699
16700   continueMBB->splice(continueMBB->begin(), BB,
16701                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16702   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16703
16704   // Add code to the main basic block to check if the stack limit has been hit,
16705   // and if so, jump to mallocMBB otherwise to bumpMBB.
16706   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16707   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16708     .addReg(tmpSPVReg).addReg(sizeVReg);
16709   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16710     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16711     .addReg(SPLimitVReg);
16712   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16713
16714   // bumpMBB simply decreases the stack pointer, since we know the current
16715   // stacklet has enough space.
16716   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16717     .addReg(SPLimitVReg);
16718   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16719     .addReg(SPLimitVReg);
16720   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16721
16722   // Calls into a routine in libgcc to allocate more space from the heap.
16723   const uint32_t *RegMask =
16724     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16725   if (Is64Bit) {
16726     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16727       .addReg(sizeVReg);
16728     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16729       .addExternalSymbol("__morestack_allocate_stack_space")
16730       .addRegMask(RegMask)
16731       .addReg(X86::RDI, RegState::Implicit)
16732       .addReg(X86::RAX, RegState::ImplicitDefine);
16733   } else {
16734     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16735       .addImm(12);
16736     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16737     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16738       .addExternalSymbol("__morestack_allocate_stack_space")
16739       .addRegMask(RegMask)
16740       .addReg(X86::EAX, RegState::ImplicitDefine);
16741   }
16742
16743   if (!Is64Bit)
16744     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16745       .addImm(16);
16746
16747   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16748     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16749   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16750
16751   // Set up the CFG correctly.
16752   BB->addSuccessor(bumpMBB);
16753   BB->addSuccessor(mallocMBB);
16754   mallocMBB->addSuccessor(continueMBB);
16755   bumpMBB->addSuccessor(continueMBB);
16756
16757   // Take care of the PHI nodes.
16758   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16759           MI->getOperand(0).getReg())
16760     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16761     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16762
16763   // Delete the original pseudo instruction.
16764   MI->eraseFromParent();
16765
16766   // And we're done.
16767   return continueMBB;
16768 }
16769
16770 MachineBasicBlock *
16771 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16772                                           MachineBasicBlock *BB) const {
16773   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16774   DebugLoc DL = MI->getDebugLoc();
16775
16776   assert(!Subtarget->isTargetMacho());
16777
16778   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16779   // non-trivial part is impdef of ESP.
16780
16781   if (Subtarget->isTargetWin64()) {
16782     if (Subtarget->isTargetCygMing()) {
16783       // ___chkstk(Mingw64):
16784       // Clobbers R10, R11, RAX and EFLAGS.
16785       // Updates RSP.
16786       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16787         .addExternalSymbol("___chkstk")
16788         .addReg(X86::RAX, RegState::Implicit)
16789         .addReg(X86::RSP, RegState::Implicit)
16790         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16791         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16792         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16793     } else {
16794       // __chkstk(MSVCRT): does not update stack pointer.
16795       // Clobbers R10, R11 and EFLAGS.
16796       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16797         .addExternalSymbol("__chkstk")
16798         .addReg(X86::RAX, RegState::Implicit)
16799         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16800       // RAX has the offset to be subtracted from RSP.
16801       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16802         .addReg(X86::RSP)
16803         .addReg(X86::RAX);
16804     }
16805   } else {
16806     const char *StackProbeSymbol =
16807       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16808
16809     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16810       .addExternalSymbol(StackProbeSymbol)
16811       .addReg(X86::EAX, RegState::Implicit)
16812       .addReg(X86::ESP, RegState::Implicit)
16813       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16814       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16815       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16816   }
16817
16818   MI->eraseFromParent();   // The pseudo instruction is gone now.
16819   return BB;
16820 }
16821
16822 MachineBasicBlock *
16823 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16824                                       MachineBasicBlock *BB) const {
16825   // This is pretty easy.  We're taking the value that we received from
16826   // our load from the relocation, sticking it in either RDI (x86-64)
16827   // or EAX and doing an indirect call.  The return value will then
16828   // be in the normal return register.
16829   const X86InstrInfo *TII
16830     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16831   DebugLoc DL = MI->getDebugLoc();
16832   MachineFunction *F = BB->getParent();
16833
16834   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16835   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16836
16837   // Get a register mask for the lowered call.
16838   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16839   // proper register mask.
16840   const uint32_t *RegMask =
16841     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16842   if (Subtarget->is64Bit()) {
16843     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16844                                       TII->get(X86::MOV64rm), X86::RDI)
16845     .addReg(X86::RIP)
16846     .addImm(0).addReg(0)
16847     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16848                       MI->getOperand(3).getTargetFlags())
16849     .addReg(0);
16850     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16851     addDirectMem(MIB, X86::RDI);
16852     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16853   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16854     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16855                                       TII->get(X86::MOV32rm), X86::EAX)
16856     .addReg(0)
16857     .addImm(0).addReg(0)
16858     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16859                       MI->getOperand(3).getTargetFlags())
16860     .addReg(0);
16861     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16862     addDirectMem(MIB, X86::EAX);
16863     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16864   } else {
16865     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16866                                       TII->get(X86::MOV32rm), X86::EAX)
16867     .addReg(TII->getGlobalBaseReg(F))
16868     .addImm(0).addReg(0)
16869     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16870                       MI->getOperand(3).getTargetFlags())
16871     .addReg(0);
16872     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16873     addDirectMem(MIB, X86::EAX);
16874     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16875   }
16876
16877   MI->eraseFromParent(); // The pseudo instruction is gone now.
16878   return BB;
16879 }
16880
16881 MachineBasicBlock *
16882 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16883                                     MachineBasicBlock *MBB) const {
16884   DebugLoc DL = MI->getDebugLoc();
16885   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16886
16887   MachineFunction *MF = MBB->getParent();
16888   MachineRegisterInfo &MRI = MF->getRegInfo();
16889
16890   const BasicBlock *BB = MBB->getBasicBlock();
16891   MachineFunction::iterator I = MBB;
16892   ++I;
16893
16894   // Memory Reference
16895   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16896   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16897
16898   unsigned DstReg;
16899   unsigned MemOpndSlot = 0;
16900
16901   unsigned CurOp = 0;
16902
16903   DstReg = MI->getOperand(CurOp++).getReg();
16904   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16905   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16906   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16907   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16908
16909   MemOpndSlot = CurOp;
16910
16911   MVT PVT = getPointerTy();
16912   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16913          "Invalid Pointer Size!");
16914
16915   // For v = setjmp(buf), we generate
16916   //
16917   // thisMBB:
16918   //  buf[LabelOffset] = restoreMBB
16919   //  SjLjSetup restoreMBB
16920   //
16921   // mainMBB:
16922   //  v_main = 0
16923   //
16924   // sinkMBB:
16925   //  v = phi(main, restore)
16926   //
16927   // restoreMBB:
16928   //  v_restore = 1
16929
16930   MachineBasicBlock *thisMBB = MBB;
16931   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16932   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16933   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16934   MF->insert(I, mainMBB);
16935   MF->insert(I, sinkMBB);
16936   MF->push_back(restoreMBB);
16937
16938   MachineInstrBuilder MIB;
16939
16940   // Transfer the remainder of BB and its successor edges to sinkMBB.
16941   sinkMBB->splice(sinkMBB->begin(), MBB,
16942                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16943   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16944
16945   // thisMBB:
16946   unsigned PtrStoreOpc = 0;
16947   unsigned LabelReg = 0;
16948   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16949   Reloc::Model RM = getTargetMachine().getRelocationModel();
16950   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16951                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16952
16953   // Prepare IP either in reg or imm.
16954   if (!UseImmLabel) {
16955     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16956     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16957     LabelReg = MRI.createVirtualRegister(PtrRC);
16958     if (Subtarget->is64Bit()) {
16959       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16960               .addReg(X86::RIP)
16961               .addImm(0)
16962               .addReg(0)
16963               .addMBB(restoreMBB)
16964               .addReg(0);
16965     } else {
16966       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16967       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16968               .addReg(XII->getGlobalBaseReg(MF))
16969               .addImm(0)
16970               .addReg(0)
16971               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16972               .addReg(0);
16973     }
16974   } else
16975     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16976   // Store IP
16977   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16978   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16979     if (i == X86::AddrDisp)
16980       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16981     else
16982       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16983   }
16984   if (!UseImmLabel)
16985     MIB.addReg(LabelReg);
16986   else
16987     MIB.addMBB(restoreMBB);
16988   MIB.setMemRefs(MMOBegin, MMOEnd);
16989   // Setup
16990   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16991           .addMBB(restoreMBB);
16992
16993   const X86RegisterInfo *RegInfo =
16994     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16995   MIB.addRegMask(RegInfo->getNoPreservedMask());
16996   thisMBB->addSuccessor(mainMBB);
16997   thisMBB->addSuccessor(restoreMBB);
16998
16999   // mainMBB:
17000   //  EAX = 0
17001   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17002   mainMBB->addSuccessor(sinkMBB);
17003
17004   // sinkMBB:
17005   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17006           TII->get(X86::PHI), DstReg)
17007     .addReg(mainDstReg).addMBB(mainMBB)
17008     .addReg(restoreDstReg).addMBB(restoreMBB);
17009
17010   // restoreMBB:
17011   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17012   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17013   restoreMBB->addSuccessor(sinkMBB);
17014
17015   MI->eraseFromParent();
17016   return sinkMBB;
17017 }
17018
17019 MachineBasicBlock *
17020 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17021                                      MachineBasicBlock *MBB) const {
17022   DebugLoc DL = MI->getDebugLoc();
17023   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17024
17025   MachineFunction *MF = MBB->getParent();
17026   MachineRegisterInfo &MRI = MF->getRegInfo();
17027
17028   // Memory Reference
17029   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17030   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17031
17032   MVT PVT = getPointerTy();
17033   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17034          "Invalid Pointer Size!");
17035
17036   const TargetRegisterClass *RC =
17037     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17038   unsigned Tmp = MRI.createVirtualRegister(RC);
17039   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17040   const X86RegisterInfo *RegInfo =
17041     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
17042   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17043   unsigned SP = RegInfo->getStackRegister();
17044
17045   MachineInstrBuilder MIB;
17046
17047   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17048   const int64_t SPOffset = 2 * PVT.getStoreSize();
17049
17050   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17051   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17052
17053   // Reload FP
17054   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17055   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17056     MIB.addOperand(MI->getOperand(i));
17057   MIB.setMemRefs(MMOBegin, MMOEnd);
17058   // Reload IP
17059   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17060   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17061     if (i == X86::AddrDisp)
17062       MIB.addDisp(MI->getOperand(i), LabelOffset);
17063     else
17064       MIB.addOperand(MI->getOperand(i));
17065   }
17066   MIB.setMemRefs(MMOBegin, MMOEnd);
17067   // Reload SP
17068   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17069   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17070     if (i == X86::AddrDisp)
17071       MIB.addDisp(MI->getOperand(i), SPOffset);
17072     else
17073       MIB.addOperand(MI->getOperand(i));
17074   }
17075   MIB.setMemRefs(MMOBegin, MMOEnd);
17076   // Jump
17077   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17078
17079   MI->eraseFromParent();
17080   return MBB;
17081 }
17082
17083 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17084 // accumulator loops. Writing back to the accumulator allows the coalescer
17085 // to remove extra copies in the loop.   
17086 MachineBasicBlock *
17087 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17088                                  MachineBasicBlock *MBB) const {
17089   MachineOperand &AddendOp = MI->getOperand(3);
17090
17091   // Bail out early if the addend isn't a register - we can't switch these.
17092   if (!AddendOp.isReg())
17093     return MBB;
17094
17095   MachineFunction &MF = *MBB->getParent();
17096   MachineRegisterInfo &MRI = MF.getRegInfo();
17097
17098   // Check whether the addend is defined by a PHI:
17099   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17100   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17101   if (!AddendDef.isPHI())
17102     return MBB;
17103
17104   // Look for the following pattern:
17105   // loop:
17106   //   %addend = phi [%entry, 0], [%loop, %result]
17107   //   ...
17108   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17109
17110   // Replace with:
17111   //   loop:
17112   //   %addend = phi [%entry, 0], [%loop, %result]
17113   //   ...
17114   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17115
17116   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17117     assert(AddendDef.getOperand(i).isReg());
17118     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17119     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17120     if (&PHISrcInst == MI) {
17121       // Found a matching instruction.
17122       unsigned NewFMAOpc = 0;
17123       switch (MI->getOpcode()) {
17124         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17125         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17126         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17127         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17128         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17129         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17130         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17131         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17132         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17133         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17134         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17135         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17136         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17137         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17138         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17139         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17140         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17141         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17142         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17143         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17144         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17145         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17146         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17147         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17148         default: llvm_unreachable("Unrecognized FMA variant.");
17149       }
17150
17151       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17152       MachineInstrBuilder MIB =
17153         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17154         .addOperand(MI->getOperand(0))
17155         .addOperand(MI->getOperand(3))
17156         .addOperand(MI->getOperand(2))
17157         .addOperand(MI->getOperand(1));
17158       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17159       MI->eraseFromParent();
17160     }
17161   }
17162
17163   return MBB;
17164 }
17165
17166 MachineBasicBlock *
17167 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17168                                                MachineBasicBlock *BB) const {
17169   switch (MI->getOpcode()) {
17170   default: llvm_unreachable("Unexpected instr type to insert");
17171   case X86::TAILJMPd64:
17172   case X86::TAILJMPr64:
17173   case X86::TAILJMPm64:
17174     llvm_unreachable("TAILJMP64 would not be touched here.");
17175   case X86::TCRETURNdi64:
17176   case X86::TCRETURNri64:
17177   case X86::TCRETURNmi64:
17178     return BB;
17179   case X86::WIN_ALLOCA:
17180     return EmitLoweredWinAlloca(MI, BB);
17181   case X86::SEG_ALLOCA_32:
17182     return EmitLoweredSegAlloca(MI, BB, false);
17183   case X86::SEG_ALLOCA_64:
17184     return EmitLoweredSegAlloca(MI, BB, true);
17185   case X86::TLSCall_32:
17186   case X86::TLSCall_64:
17187     return EmitLoweredTLSCall(MI, BB);
17188   case X86::CMOV_GR8:
17189   case X86::CMOV_FR32:
17190   case X86::CMOV_FR64:
17191   case X86::CMOV_V4F32:
17192   case X86::CMOV_V2F64:
17193   case X86::CMOV_V2I64:
17194   case X86::CMOV_V8F32:
17195   case X86::CMOV_V4F64:
17196   case X86::CMOV_V4I64:
17197   case X86::CMOV_V16F32:
17198   case X86::CMOV_V8F64:
17199   case X86::CMOV_V8I64:
17200   case X86::CMOV_GR16:
17201   case X86::CMOV_GR32:
17202   case X86::CMOV_RFP32:
17203   case X86::CMOV_RFP64:
17204   case X86::CMOV_RFP80:
17205     return EmitLoweredSelect(MI, BB);
17206
17207   case X86::FP32_TO_INT16_IN_MEM:
17208   case X86::FP32_TO_INT32_IN_MEM:
17209   case X86::FP32_TO_INT64_IN_MEM:
17210   case X86::FP64_TO_INT16_IN_MEM:
17211   case X86::FP64_TO_INT32_IN_MEM:
17212   case X86::FP64_TO_INT64_IN_MEM:
17213   case X86::FP80_TO_INT16_IN_MEM:
17214   case X86::FP80_TO_INT32_IN_MEM:
17215   case X86::FP80_TO_INT64_IN_MEM: {
17216     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17217     DebugLoc DL = MI->getDebugLoc();
17218
17219     // Change the floating point control register to use "round towards zero"
17220     // mode when truncating to an integer value.
17221     MachineFunction *F = BB->getParent();
17222     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17223     addFrameReference(BuildMI(*BB, MI, DL,
17224                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17225
17226     // Load the old value of the high byte of the control word...
17227     unsigned OldCW =
17228       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17229     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17230                       CWFrameIdx);
17231
17232     // Set the high part to be round to zero...
17233     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17234       .addImm(0xC7F);
17235
17236     // Reload the modified control word now...
17237     addFrameReference(BuildMI(*BB, MI, DL,
17238                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17239
17240     // Restore the memory image of control word to original value
17241     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17242       .addReg(OldCW);
17243
17244     // Get the X86 opcode to use.
17245     unsigned Opc;
17246     switch (MI->getOpcode()) {
17247     default: llvm_unreachable("illegal opcode!");
17248     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17249     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17250     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17251     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17252     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17253     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17254     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17255     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17256     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17257     }
17258
17259     X86AddressMode AM;
17260     MachineOperand &Op = MI->getOperand(0);
17261     if (Op.isReg()) {
17262       AM.BaseType = X86AddressMode::RegBase;
17263       AM.Base.Reg = Op.getReg();
17264     } else {
17265       AM.BaseType = X86AddressMode::FrameIndexBase;
17266       AM.Base.FrameIndex = Op.getIndex();
17267     }
17268     Op = MI->getOperand(1);
17269     if (Op.isImm())
17270       AM.Scale = Op.getImm();
17271     Op = MI->getOperand(2);
17272     if (Op.isImm())
17273       AM.IndexReg = Op.getImm();
17274     Op = MI->getOperand(3);
17275     if (Op.isGlobal()) {
17276       AM.GV = Op.getGlobal();
17277     } else {
17278       AM.Disp = Op.getImm();
17279     }
17280     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17281                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17282
17283     // Reload the original control word now.
17284     addFrameReference(BuildMI(*BB, MI, DL,
17285                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17286
17287     MI->eraseFromParent();   // The pseudo instruction is gone now.
17288     return BB;
17289   }
17290     // String/text processing lowering.
17291   case X86::PCMPISTRM128REG:
17292   case X86::VPCMPISTRM128REG:
17293   case X86::PCMPISTRM128MEM:
17294   case X86::VPCMPISTRM128MEM:
17295   case X86::PCMPESTRM128REG:
17296   case X86::VPCMPESTRM128REG:
17297   case X86::PCMPESTRM128MEM:
17298   case X86::VPCMPESTRM128MEM:
17299     assert(Subtarget->hasSSE42() &&
17300            "Target must have SSE4.2 or AVX features enabled");
17301     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17302
17303   // String/text processing lowering.
17304   case X86::PCMPISTRIREG:
17305   case X86::VPCMPISTRIREG:
17306   case X86::PCMPISTRIMEM:
17307   case X86::VPCMPISTRIMEM:
17308   case X86::PCMPESTRIREG:
17309   case X86::VPCMPESTRIREG:
17310   case X86::PCMPESTRIMEM:
17311   case X86::VPCMPESTRIMEM:
17312     assert(Subtarget->hasSSE42() &&
17313            "Target must have SSE4.2 or AVX features enabled");
17314     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17315
17316   // Thread synchronization.
17317   case X86::MONITOR:
17318     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17319
17320   // xbegin
17321   case X86::XBEGIN:
17322     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17323
17324   // Atomic Lowering.
17325   case X86::ATOMAND8:
17326   case X86::ATOMAND16:
17327   case X86::ATOMAND32:
17328   case X86::ATOMAND64:
17329     // Fall through
17330   case X86::ATOMOR8:
17331   case X86::ATOMOR16:
17332   case X86::ATOMOR32:
17333   case X86::ATOMOR64:
17334     // Fall through
17335   case X86::ATOMXOR16:
17336   case X86::ATOMXOR8:
17337   case X86::ATOMXOR32:
17338   case X86::ATOMXOR64:
17339     // Fall through
17340   case X86::ATOMNAND8:
17341   case X86::ATOMNAND16:
17342   case X86::ATOMNAND32:
17343   case X86::ATOMNAND64:
17344     // Fall through
17345   case X86::ATOMMAX8:
17346   case X86::ATOMMAX16:
17347   case X86::ATOMMAX32:
17348   case X86::ATOMMAX64:
17349     // Fall through
17350   case X86::ATOMMIN8:
17351   case X86::ATOMMIN16:
17352   case X86::ATOMMIN32:
17353   case X86::ATOMMIN64:
17354     // Fall through
17355   case X86::ATOMUMAX8:
17356   case X86::ATOMUMAX16:
17357   case X86::ATOMUMAX32:
17358   case X86::ATOMUMAX64:
17359     // Fall through
17360   case X86::ATOMUMIN8:
17361   case X86::ATOMUMIN16:
17362   case X86::ATOMUMIN32:
17363   case X86::ATOMUMIN64:
17364     return EmitAtomicLoadArith(MI, BB);
17365
17366   // This group does 64-bit operations on a 32-bit host.
17367   case X86::ATOMAND6432:
17368   case X86::ATOMOR6432:
17369   case X86::ATOMXOR6432:
17370   case X86::ATOMNAND6432:
17371   case X86::ATOMADD6432:
17372   case X86::ATOMSUB6432:
17373   case X86::ATOMMAX6432:
17374   case X86::ATOMMIN6432:
17375   case X86::ATOMUMAX6432:
17376   case X86::ATOMUMIN6432:
17377   case X86::ATOMSWAP6432:
17378     return EmitAtomicLoadArith6432(MI, BB);
17379
17380   case X86::VASTART_SAVE_XMM_REGS:
17381     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17382
17383   case X86::VAARG_64:
17384     return EmitVAARG64WithCustomInserter(MI, BB);
17385
17386   case X86::EH_SjLj_SetJmp32:
17387   case X86::EH_SjLj_SetJmp64:
17388     return emitEHSjLjSetJmp(MI, BB);
17389
17390   case X86::EH_SjLj_LongJmp32:
17391   case X86::EH_SjLj_LongJmp64:
17392     return emitEHSjLjLongJmp(MI, BB);
17393
17394   case TargetOpcode::STACKMAP:
17395   case TargetOpcode::PATCHPOINT:
17396     return emitPatchPoint(MI, BB);
17397
17398   case X86::VFMADDPDr213r:
17399   case X86::VFMADDPSr213r:
17400   case X86::VFMADDSDr213r:
17401   case X86::VFMADDSSr213r:
17402   case X86::VFMSUBPDr213r:
17403   case X86::VFMSUBPSr213r:
17404   case X86::VFMSUBSDr213r:
17405   case X86::VFMSUBSSr213r:
17406   case X86::VFNMADDPDr213r:
17407   case X86::VFNMADDPSr213r:
17408   case X86::VFNMADDSDr213r:
17409   case X86::VFNMADDSSr213r:
17410   case X86::VFNMSUBPDr213r:
17411   case X86::VFNMSUBPSr213r:
17412   case X86::VFNMSUBSDr213r:
17413   case X86::VFNMSUBSSr213r:
17414   case X86::VFMADDPDr213rY:
17415   case X86::VFMADDPSr213rY:
17416   case X86::VFMSUBPDr213rY:
17417   case X86::VFMSUBPSr213rY:
17418   case X86::VFNMADDPDr213rY:
17419   case X86::VFNMADDPSr213rY:
17420   case X86::VFNMSUBPDr213rY:
17421   case X86::VFNMSUBPSr213rY:
17422     return emitFMA3Instr(MI, BB);
17423   }
17424 }
17425
17426 //===----------------------------------------------------------------------===//
17427 //                           X86 Optimization Hooks
17428 //===----------------------------------------------------------------------===//
17429
17430 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17431                                                       APInt &KnownZero,
17432                                                       APInt &KnownOne,
17433                                                       const SelectionDAG &DAG,
17434                                                       unsigned Depth) const {
17435   unsigned BitWidth = KnownZero.getBitWidth();
17436   unsigned Opc = Op.getOpcode();
17437   assert((Opc >= ISD::BUILTIN_OP_END ||
17438           Opc == ISD::INTRINSIC_WO_CHAIN ||
17439           Opc == ISD::INTRINSIC_W_CHAIN ||
17440           Opc == ISD::INTRINSIC_VOID) &&
17441          "Should use MaskedValueIsZero if you don't know whether Op"
17442          " is a target node!");
17443
17444   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17445   switch (Opc) {
17446   default: break;
17447   case X86ISD::ADD:
17448   case X86ISD::SUB:
17449   case X86ISD::ADC:
17450   case X86ISD::SBB:
17451   case X86ISD::SMUL:
17452   case X86ISD::UMUL:
17453   case X86ISD::INC:
17454   case X86ISD::DEC:
17455   case X86ISD::OR:
17456   case X86ISD::XOR:
17457   case X86ISD::AND:
17458     // These nodes' second result is a boolean.
17459     if (Op.getResNo() == 0)
17460       break;
17461     // Fallthrough
17462   case X86ISD::SETCC:
17463     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17464     break;
17465   case ISD::INTRINSIC_WO_CHAIN: {
17466     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17467     unsigned NumLoBits = 0;
17468     switch (IntId) {
17469     default: break;
17470     case Intrinsic::x86_sse_movmsk_ps:
17471     case Intrinsic::x86_avx_movmsk_ps_256:
17472     case Intrinsic::x86_sse2_movmsk_pd:
17473     case Intrinsic::x86_avx_movmsk_pd_256:
17474     case Intrinsic::x86_mmx_pmovmskb:
17475     case Intrinsic::x86_sse2_pmovmskb_128:
17476     case Intrinsic::x86_avx2_pmovmskb: {
17477       // High bits of movmskp{s|d}, pmovmskb are known zero.
17478       switch (IntId) {
17479         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17480         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17481         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17482         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17483         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17484         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17485         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17486         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17487       }
17488       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17489       break;
17490     }
17491     }
17492     break;
17493   }
17494   }
17495 }
17496
17497 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17498   SDValue Op,
17499   const SelectionDAG &,
17500   unsigned Depth) const {
17501   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17502   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17503     return Op.getValueType().getScalarType().getSizeInBits();
17504
17505   // Fallback case.
17506   return 1;
17507 }
17508
17509 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17510 /// node is a GlobalAddress + offset.
17511 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17512                                        const GlobalValue* &GA,
17513                                        int64_t &Offset) const {
17514   if (N->getOpcode() == X86ISD::Wrapper) {
17515     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17516       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17517       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17518       return true;
17519     }
17520   }
17521   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17522 }
17523
17524 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17525 /// same as extracting the high 128-bit part of 256-bit vector and then
17526 /// inserting the result into the low part of a new 256-bit vector
17527 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17528   EVT VT = SVOp->getValueType(0);
17529   unsigned NumElems = VT.getVectorNumElements();
17530
17531   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17532   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17533     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17534         SVOp->getMaskElt(j) >= 0)
17535       return false;
17536
17537   return true;
17538 }
17539
17540 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17541 /// same as extracting the low 128-bit part of 256-bit vector and then
17542 /// inserting the result into the high part of a new 256-bit vector
17543 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17544   EVT VT = SVOp->getValueType(0);
17545   unsigned NumElems = VT.getVectorNumElements();
17546
17547   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17548   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17549     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17550         SVOp->getMaskElt(j) >= 0)
17551       return false;
17552
17553   return true;
17554 }
17555
17556 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17557 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17558                                         TargetLowering::DAGCombinerInfo &DCI,
17559                                         const X86Subtarget* Subtarget) {
17560   SDLoc dl(N);
17561   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17562   SDValue V1 = SVOp->getOperand(0);
17563   SDValue V2 = SVOp->getOperand(1);
17564   EVT VT = SVOp->getValueType(0);
17565   unsigned NumElems = VT.getVectorNumElements();
17566
17567   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17568       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17569     //
17570     //                   0,0,0,...
17571     //                      |
17572     //    V      UNDEF    BUILD_VECTOR    UNDEF
17573     //     \      /           \           /
17574     //  CONCAT_VECTOR         CONCAT_VECTOR
17575     //         \                  /
17576     //          \                /
17577     //          RESULT: V + zero extended
17578     //
17579     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17580         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17581         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17582       return SDValue();
17583
17584     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17585       return SDValue();
17586
17587     // To match the shuffle mask, the first half of the mask should
17588     // be exactly the first vector, and all the rest a splat with the
17589     // first element of the second one.
17590     for (unsigned i = 0; i != NumElems/2; ++i)
17591       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17592           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17593         return SDValue();
17594
17595     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17596     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17597       if (Ld->hasNUsesOfValue(1, 0)) {
17598         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17599         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17600         SDValue ResNode =
17601           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17602                                   Ld->getMemoryVT(),
17603                                   Ld->getPointerInfo(),
17604                                   Ld->getAlignment(),
17605                                   false/*isVolatile*/, true/*ReadMem*/,
17606                                   false/*WriteMem*/);
17607
17608         // Make sure the newly-created LOAD is in the same position as Ld in
17609         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17610         // and update uses of Ld's output chain to use the TokenFactor.
17611         if (Ld->hasAnyUseOfValue(1)) {
17612           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17613                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17614           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17615           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17616                                  SDValue(ResNode.getNode(), 1));
17617         }
17618
17619         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17620       }
17621     }
17622
17623     // Emit a zeroed vector and insert the desired subvector on its
17624     // first half.
17625     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17626     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17627     return DCI.CombineTo(N, InsV);
17628   }
17629
17630   //===--------------------------------------------------------------------===//
17631   // Combine some shuffles into subvector extracts and inserts:
17632   //
17633
17634   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17635   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17636     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17637     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17638     return DCI.CombineTo(N, InsV);
17639   }
17640
17641   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17642   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17643     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17644     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17645     return DCI.CombineTo(N, InsV);
17646   }
17647
17648   return SDValue();
17649 }
17650
17651 /// PerformShuffleCombine - Performs several different shuffle combines.
17652 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17653                                      TargetLowering::DAGCombinerInfo &DCI,
17654                                      const X86Subtarget *Subtarget) {
17655   SDLoc dl(N);
17656   SDValue N0 = N->getOperand(0);
17657   SDValue N1 = N->getOperand(1);
17658   EVT VT = N->getValueType(0);
17659
17660   // Don't create instructions with illegal types after legalize types has run.
17661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17662   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17663     return SDValue();
17664
17665   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17666   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17667       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17668     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17669
17670   // During Type Legalization, when promoting illegal vector types,
17671   // the backend might introduce new shuffle dag nodes and bitcasts.
17672   //
17673   // This code performs the following transformation:
17674   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17675   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17676   //
17677   // We do this only if both the bitcast and the BINOP dag nodes have
17678   // one use. Also, perform this transformation only if the new binary
17679   // operation is legal. This is to avoid introducing dag nodes that
17680   // potentially need to be further expanded (or custom lowered) into a
17681   // less optimal sequence of dag nodes.
17682   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17683       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17684       N0.getOpcode() == ISD::BITCAST) {
17685     SDValue BC0 = N0.getOperand(0);
17686     EVT SVT = BC0.getValueType();
17687     unsigned Opcode = BC0.getOpcode();
17688     unsigned NumElts = VT.getVectorNumElements();
17689     
17690     if (BC0.hasOneUse() && SVT.isVector() &&
17691         SVT.getVectorNumElements() * 2 == NumElts &&
17692         TLI.isOperationLegal(Opcode, VT)) {
17693       bool CanFold = false;
17694       switch (Opcode) {
17695       default : break;
17696       case ISD::ADD :
17697       case ISD::FADD :
17698       case ISD::SUB :
17699       case ISD::FSUB :
17700       case ISD::MUL :
17701       case ISD::FMUL :
17702         CanFold = true;
17703       }
17704
17705       unsigned SVTNumElts = SVT.getVectorNumElements();
17706       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17707       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17708         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17709       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17710         CanFold = SVOp->getMaskElt(i) < 0;
17711
17712       if (CanFold) {
17713         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17714         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17715         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17716         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17717       }
17718     }
17719   }
17720
17721   // Only handle 128 wide vector from here on.
17722   if (!VT.is128BitVector())
17723     return SDValue();
17724
17725   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17726   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17727   // consecutive, non-overlapping, and in the right order.
17728   SmallVector<SDValue, 16> Elts;
17729   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17730     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17731
17732   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17733 }
17734
17735 /// PerformTruncateCombine - Converts truncate operation to
17736 /// a sequence of vector shuffle operations.
17737 /// It is possible when we truncate 256-bit vector to 128-bit vector
17738 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17739                                       TargetLowering::DAGCombinerInfo &DCI,
17740                                       const X86Subtarget *Subtarget)  {
17741   return SDValue();
17742 }
17743
17744 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17745 /// specific shuffle of a load can be folded into a single element load.
17746 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17747 /// shuffles have been customed lowered so we need to handle those here.
17748 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17749                                          TargetLowering::DAGCombinerInfo &DCI) {
17750   if (DCI.isBeforeLegalizeOps())
17751     return SDValue();
17752
17753   SDValue InVec = N->getOperand(0);
17754   SDValue EltNo = N->getOperand(1);
17755
17756   if (!isa<ConstantSDNode>(EltNo))
17757     return SDValue();
17758
17759   EVT VT = InVec.getValueType();
17760
17761   bool HasShuffleIntoBitcast = false;
17762   if (InVec.getOpcode() == ISD::BITCAST) {
17763     // Don't duplicate a load with other uses.
17764     if (!InVec.hasOneUse())
17765       return SDValue();
17766     EVT BCVT = InVec.getOperand(0).getValueType();
17767     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17768       return SDValue();
17769     InVec = InVec.getOperand(0);
17770     HasShuffleIntoBitcast = true;
17771   }
17772
17773   if (!isTargetShuffle(InVec.getOpcode()))
17774     return SDValue();
17775
17776   // Don't duplicate a load with other uses.
17777   if (!InVec.hasOneUse())
17778     return SDValue();
17779
17780   SmallVector<int, 16> ShuffleMask;
17781   bool UnaryShuffle;
17782   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17783                             UnaryShuffle))
17784     return SDValue();
17785
17786   // Select the input vector, guarding against out of range extract vector.
17787   unsigned NumElems = VT.getVectorNumElements();
17788   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17789   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17790   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17791                                          : InVec.getOperand(1);
17792
17793   // If inputs to shuffle are the same for both ops, then allow 2 uses
17794   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17795
17796   if (LdNode.getOpcode() == ISD::BITCAST) {
17797     // Don't duplicate a load with other uses.
17798     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17799       return SDValue();
17800
17801     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17802     LdNode = LdNode.getOperand(0);
17803   }
17804
17805   if (!ISD::isNormalLoad(LdNode.getNode()))
17806     return SDValue();
17807
17808   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17809
17810   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17811     return SDValue();
17812
17813   if (HasShuffleIntoBitcast) {
17814     // If there's a bitcast before the shuffle, check if the load type and
17815     // alignment is valid.
17816     unsigned Align = LN0->getAlignment();
17817     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17818     unsigned NewAlign = TLI.getDataLayout()->
17819       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17820
17821     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17822       return SDValue();
17823   }
17824
17825   // All checks match so transform back to vector_shuffle so that DAG combiner
17826   // can finish the job
17827   SDLoc dl(N);
17828
17829   // Create shuffle node taking into account the case that its a unary shuffle
17830   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17831   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17832                                  InVec.getOperand(0), Shuffle,
17833                                  &ShuffleMask[0]);
17834   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17835   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17836                      EltNo);
17837 }
17838
17839 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17840 /// generation and convert it from being a bunch of shuffles and extracts
17841 /// to a simple store and scalar loads to extract the elements.
17842 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17843                                          TargetLowering::DAGCombinerInfo &DCI) {
17844   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17845   if (NewOp.getNode())
17846     return NewOp;
17847
17848   SDValue InputVector = N->getOperand(0);
17849
17850   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17851   // from mmx to v2i32 has a single usage.
17852   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17853       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17854       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17855     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17856                        N->getValueType(0),
17857                        InputVector.getNode()->getOperand(0));
17858
17859   // Only operate on vectors of 4 elements, where the alternative shuffling
17860   // gets to be more expensive.
17861   if (InputVector.getValueType() != MVT::v4i32)
17862     return SDValue();
17863
17864   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17865   // single use which is a sign-extend or zero-extend, and all elements are
17866   // used.
17867   SmallVector<SDNode *, 4> Uses;
17868   unsigned ExtractedElements = 0;
17869   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17870        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17871     if (UI.getUse().getResNo() != InputVector.getResNo())
17872       return SDValue();
17873
17874     SDNode *Extract = *UI;
17875     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17876       return SDValue();
17877
17878     if (Extract->getValueType(0) != MVT::i32)
17879       return SDValue();
17880     if (!Extract->hasOneUse())
17881       return SDValue();
17882     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17883         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17884       return SDValue();
17885     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17886       return SDValue();
17887
17888     // Record which element was extracted.
17889     ExtractedElements |=
17890       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17891
17892     Uses.push_back(Extract);
17893   }
17894
17895   // If not all the elements were used, this may not be worthwhile.
17896   if (ExtractedElements != 15)
17897     return SDValue();
17898
17899   // Ok, we've now decided to do the transformation.
17900   SDLoc dl(InputVector);
17901
17902   // Store the value to a temporary stack slot.
17903   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17904   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17905                             MachinePointerInfo(), false, false, 0);
17906
17907   // Replace each use (extract) with a load of the appropriate element.
17908   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17909        UE = Uses.end(); UI != UE; ++UI) {
17910     SDNode *Extract = *UI;
17911
17912     // cOMpute the element's address.
17913     SDValue Idx = Extract->getOperand(1);
17914     unsigned EltSize =
17915         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17916     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17917     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17918     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17919
17920     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17921                                      StackPtr, OffsetVal);
17922
17923     // Load the scalar.
17924     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17925                                      ScalarAddr, MachinePointerInfo(),
17926                                      false, false, false, 0);
17927
17928     // Replace the exact with the load.
17929     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17930   }
17931
17932   // The replacement was made in place; don't return anything.
17933   return SDValue();
17934 }
17935
17936 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17937 static std::pair<unsigned, bool>
17938 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17939                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17940   if (!VT.isVector())
17941     return std::make_pair(0, false);
17942
17943   bool NeedSplit = false;
17944   switch (VT.getSimpleVT().SimpleTy) {
17945   default: return std::make_pair(0, false);
17946   case MVT::v32i8:
17947   case MVT::v16i16:
17948   case MVT::v8i32:
17949     if (!Subtarget->hasAVX2())
17950       NeedSplit = true;
17951     if (!Subtarget->hasAVX())
17952       return std::make_pair(0, false);
17953     break;
17954   case MVT::v16i8:
17955   case MVT::v8i16:
17956   case MVT::v4i32:
17957     if (!Subtarget->hasSSE2())
17958       return std::make_pair(0, false);
17959   }
17960
17961   // SSE2 has only a small subset of the operations.
17962   bool hasUnsigned = Subtarget->hasSSE41() ||
17963                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17964   bool hasSigned = Subtarget->hasSSE41() ||
17965                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17966
17967   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17968
17969   unsigned Opc = 0;
17970   // Check for x CC y ? x : y.
17971   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17972       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17973     switch (CC) {
17974     default: break;
17975     case ISD::SETULT:
17976     case ISD::SETULE:
17977       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17978     case ISD::SETUGT:
17979     case ISD::SETUGE:
17980       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17981     case ISD::SETLT:
17982     case ISD::SETLE:
17983       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17984     case ISD::SETGT:
17985     case ISD::SETGE:
17986       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17987     }
17988   // Check for x CC y ? y : x -- a min/max with reversed arms.
17989   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17990              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17991     switch (CC) {
17992     default: break;
17993     case ISD::SETULT:
17994     case ISD::SETULE:
17995       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17996     case ISD::SETUGT:
17997     case ISD::SETUGE:
17998       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17999     case ISD::SETLT:
18000     case ISD::SETLE:
18001       Opc = hasSigned ? X86ISD::SMAX : 0; break;
18002     case ISD::SETGT:
18003     case ISD::SETGE:
18004       Opc = hasSigned ? X86ISD::SMIN : 0; break;
18005     }
18006   }
18007
18008   return std::make_pair(Opc, NeedSplit);
18009 }
18010
18011 static SDValue
18012 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18013                                       const X86Subtarget *Subtarget) {
18014   SDLoc dl(N);
18015   SDValue Cond = N->getOperand(0);
18016   SDValue LHS = N->getOperand(1);
18017   SDValue RHS = N->getOperand(2);
18018
18019   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18020     SDValue CondSrc = Cond->getOperand(0);
18021     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18022       Cond = CondSrc->getOperand(0);
18023   }
18024
18025   MVT VT = N->getSimpleValueType(0);
18026   MVT EltVT = VT.getVectorElementType();
18027   unsigned NumElems = VT.getVectorNumElements();
18028   // There is no blend with immediate in AVX-512.
18029   if (VT.is512BitVector())
18030     return SDValue();
18031
18032   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18033     return SDValue();
18034   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18035     return SDValue();
18036
18037   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18038     return SDValue();
18039
18040   unsigned MaskValue = 0;
18041   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18042     return SDValue();
18043
18044   SmallVector<int, 8> ShuffleMask(NumElems, -1);
18045   for (unsigned i = 0; i < NumElems; ++i) {
18046     // Be sure we emit undef where we can.
18047     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18048       ShuffleMask[i] = -1;
18049     else
18050       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18051   }
18052
18053   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18054 }
18055
18056 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18057 /// nodes.
18058 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18059                                     TargetLowering::DAGCombinerInfo &DCI,
18060                                     const X86Subtarget *Subtarget) {
18061   SDLoc DL(N);
18062   SDValue Cond = N->getOperand(0);
18063   // Get the LHS/RHS of the select.
18064   SDValue LHS = N->getOperand(1);
18065   SDValue RHS = N->getOperand(2);
18066   EVT VT = LHS.getValueType();
18067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18068
18069   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18070   // instructions match the semantics of the common C idiom x<y?x:y but not
18071   // x<=y?x:y, because of how they handle negative zero (which can be
18072   // ignored in unsafe-math mode).
18073   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18074       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18075       (Subtarget->hasSSE2() ||
18076        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18077     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18078
18079     unsigned Opcode = 0;
18080     // Check for x CC y ? x : y.
18081     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18082         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18083       switch (CC) {
18084       default: break;
18085       case ISD::SETULT:
18086         // Converting this to a min would handle NaNs incorrectly, and swapping
18087         // the operands would cause it to handle comparisons between positive
18088         // and negative zero incorrectly.
18089         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18090           if (!DAG.getTarget().Options.UnsafeFPMath &&
18091               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18092             break;
18093           std::swap(LHS, RHS);
18094         }
18095         Opcode = X86ISD::FMIN;
18096         break;
18097       case ISD::SETOLE:
18098         // Converting this to a min would handle comparisons between positive
18099         // and negative zero incorrectly.
18100         if (!DAG.getTarget().Options.UnsafeFPMath &&
18101             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18102           break;
18103         Opcode = X86ISD::FMIN;
18104         break;
18105       case ISD::SETULE:
18106         // Converting this to a min would handle both negative zeros and NaNs
18107         // incorrectly, but we can swap the operands to fix both.
18108         std::swap(LHS, RHS);
18109       case ISD::SETOLT:
18110       case ISD::SETLT:
18111       case ISD::SETLE:
18112         Opcode = X86ISD::FMIN;
18113         break;
18114
18115       case ISD::SETOGE:
18116         // Converting this to a max would handle comparisons between positive
18117         // and negative zero incorrectly.
18118         if (!DAG.getTarget().Options.UnsafeFPMath &&
18119             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18120           break;
18121         Opcode = X86ISD::FMAX;
18122         break;
18123       case ISD::SETUGT:
18124         // Converting this to a max would handle NaNs incorrectly, and swapping
18125         // the operands would cause it to handle comparisons between positive
18126         // and negative zero incorrectly.
18127         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18128           if (!DAG.getTarget().Options.UnsafeFPMath &&
18129               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18130             break;
18131           std::swap(LHS, RHS);
18132         }
18133         Opcode = X86ISD::FMAX;
18134         break;
18135       case ISD::SETUGE:
18136         // Converting this to a max would handle both negative zeros and NaNs
18137         // incorrectly, but we can swap the operands to fix both.
18138         std::swap(LHS, RHS);
18139       case ISD::SETOGT:
18140       case ISD::SETGT:
18141       case ISD::SETGE:
18142         Opcode = X86ISD::FMAX;
18143         break;
18144       }
18145     // Check for x CC y ? y : x -- a min/max with reversed arms.
18146     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18147                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18148       switch (CC) {
18149       default: break;
18150       case ISD::SETOGE:
18151         // Converting this to a min would handle comparisons between positive
18152         // and negative zero incorrectly, and swapping the operands would
18153         // cause it to handle NaNs incorrectly.
18154         if (!DAG.getTarget().Options.UnsafeFPMath &&
18155             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18156           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18157             break;
18158           std::swap(LHS, RHS);
18159         }
18160         Opcode = X86ISD::FMIN;
18161         break;
18162       case ISD::SETUGT:
18163         // Converting this to a min would handle NaNs incorrectly.
18164         if (!DAG.getTarget().Options.UnsafeFPMath &&
18165             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18166           break;
18167         Opcode = X86ISD::FMIN;
18168         break;
18169       case ISD::SETUGE:
18170         // Converting this to a min would handle both negative zeros and NaNs
18171         // incorrectly, but we can swap the operands to fix both.
18172         std::swap(LHS, RHS);
18173       case ISD::SETOGT:
18174       case ISD::SETGT:
18175       case ISD::SETGE:
18176         Opcode = X86ISD::FMIN;
18177         break;
18178
18179       case ISD::SETULT:
18180         // Converting this to a max would handle NaNs incorrectly.
18181         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18182           break;
18183         Opcode = X86ISD::FMAX;
18184         break;
18185       case ISD::SETOLE:
18186         // Converting this to a max would handle comparisons between positive
18187         // and negative zero incorrectly, and swapping the operands would
18188         // cause it to handle NaNs incorrectly.
18189         if (!DAG.getTarget().Options.UnsafeFPMath &&
18190             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18191           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18192             break;
18193           std::swap(LHS, RHS);
18194         }
18195         Opcode = X86ISD::FMAX;
18196         break;
18197       case ISD::SETULE:
18198         // Converting this to a max would handle both negative zeros and NaNs
18199         // incorrectly, but we can swap the operands to fix both.
18200         std::swap(LHS, RHS);
18201       case ISD::SETOLT:
18202       case ISD::SETLT:
18203       case ISD::SETLE:
18204         Opcode = X86ISD::FMAX;
18205         break;
18206       }
18207     }
18208
18209     if (Opcode)
18210       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18211   }
18212
18213   EVT CondVT = Cond.getValueType();
18214   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18215       CondVT.getVectorElementType() == MVT::i1) {
18216     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18217     // lowering on AVX-512. In this case we convert it to
18218     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18219     // The same situation for all 128 and 256-bit vectors of i8 and i16
18220     EVT OpVT = LHS.getValueType();
18221     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18222         (OpVT.getVectorElementType() == MVT::i8 ||
18223          OpVT.getVectorElementType() == MVT::i16)) {
18224       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18225       DCI.AddToWorklist(Cond.getNode());
18226       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18227     }
18228   }
18229   // If this is a select between two integer constants, try to do some
18230   // optimizations.
18231   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18232     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18233       // Don't do this for crazy integer types.
18234       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18235         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18236         // so that TrueC (the true value) is larger than FalseC.
18237         bool NeedsCondInvert = false;
18238
18239         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18240             // Efficiently invertible.
18241             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
18242              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
18243               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18244           NeedsCondInvert = true;
18245           std::swap(TrueC, FalseC);
18246         }
18247
18248         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18249         if (FalseC->getAPIntValue() == 0 &&
18250             TrueC->getAPIntValue().isPowerOf2()) {
18251           if (NeedsCondInvert) // Invert the condition if needed.
18252             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18253                                DAG.getConstant(1, Cond.getValueType()));
18254
18255           // Zero extend the condition if needed.
18256           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18257
18258           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18259           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18260                              DAG.getConstant(ShAmt, MVT::i8));
18261         }
18262
18263         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18264         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18265           if (NeedsCondInvert) // Invert the condition if needed.
18266             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18267                                DAG.getConstant(1, Cond.getValueType()));
18268
18269           // Zero extend the condition if needed.
18270           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18271                              FalseC->getValueType(0), Cond);
18272           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18273                              SDValue(FalseC, 0));
18274         }
18275
18276         // Optimize cases that will turn into an LEA instruction.  This requires
18277         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18278         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18279           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18280           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18281
18282           bool isFastMultiplier = false;
18283           if (Diff < 10) {
18284             switch ((unsigned char)Diff) {
18285               default: break;
18286               case 1:  // result = add base, cond
18287               case 2:  // result = lea base(    , cond*2)
18288               case 3:  // result = lea base(cond, cond*2)
18289               case 4:  // result = lea base(    , cond*4)
18290               case 5:  // result = lea base(cond, cond*4)
18291               case 8:  // result = lea base(    , cond*8)
18292               case 9:  // result = lea base(cond, cond*8)
18293                 isFastMultiplier = true;
18294                 break;
18295             }
18296           }
18297
18298           if (isFastMultiplier) {
18299             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18300             if (NeedsCondInvert) // Invert the condition if needed.
18301               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18302                                  DAG.getConstant(1, Cond.getValueType()));
18303
18304             // Zero extend the condition if needed.
18305             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18306                                Cond);
18307             // Scale the condition by the difference.
18308             if (Diff != 1)
18309               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18310                                  DAG.getConstant(Diff, Cond.getValueType()));
18311
18312             // Add the base if non-zero.
18313             if (FalseC->getAPIntValue() != 0)
18314               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18315                                  SDValue(FalseC, 0));
18316             return Cond;
18317           }
18318         }
18319       }
18320   }
18321
18322   // Canonicalize max and min:
18323   // (x > y) ? x : y -> (x >= y) ? x : y
18324   // (x < y) ? x : y -> (x <= y) ? x : y
18325   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18326   // the need for an extra compare
18327   // against zero. e.g.
18328   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18329   // subl   %esi, %edi
18330   // testl  %edi, %edi
18331   // movl   $0, %eax
18332   // cmovgl %edi, %eax
18333   // =>
18334   // xorl   %eax, %eax
18335   // subl   %esi, $edi
18336   // cmovsl %eax, %edi
18337   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18338       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18339       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18340     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18341     switch (CC) {
18342     default: break;
18343     case ISD::SETLT:
18344     case ISD::SETGT: {
18345       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18346       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18347                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18348       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18349     }
18350     }
18351   }
18352
18353   // Early exit check
18354   if (!TLI.isTypeLegal(VT))
18355     return SDValue();
18356
18357   // Match VSELECTs into subs with unsigned saturation.
18358   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18359       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18360       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18361        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18362     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18363
18364     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18365     // left side invert the predicate to simplify logic below.
18366     SDValue Other;
18367     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18368       Other = RHS;
18369       CC = ISD::getSetCCInverse(CC, true);
18370     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18371       Other = LHS;
18372     }
18373
18374     if (Other.getNode() && Other->getNumOperands() == 2 &&
18375         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18376       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18377       SDValue CondRHS = Cond->getOperand(1);
18378
18379       // Look for a general sub with unsigned saturation first.
18380       // x >= y ? x-y : 0 --> subus x, y
18381       // x >  y ? x-y : 0 --> subus x, y
18382       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18383           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18384         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18385
18386       // If the RHS is a constant we have to reverse the const canonicalization.
18387       // x > C-1 ? x+-C : 0 --> subus x, C
18388       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18389           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18390         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18391         if (CondRHS.getConstantOperandVal(0) == -A-1)
18392           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18393                              DAG.getConstant(-A, VT));
18394       }
18395
18396       // Another special case: If C was a sign bit, the sub has been
18397       // canonicalized into a xor.
18398       // FIXME: Would it be better to use computeKnownBits to determine whether
18399       //        it's safe to decanonicalize the xor?
18400       // x s< 0 ? x^C : 0 --> subus x, C
18401       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18402           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18403           isSplatVector(OpRHS.getNode())) {
18404         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18405         if (A.isSignBit())
18406           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18407       }
18408     }
18409   }
18410
18411   // Try to match a min/max vector operation.
18412   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18413     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18414     unsigned Opc = ret.first;
18415     bool NeedSplit = ret.second;
18416
18417     if (Opc && NeedSplit) {
18418       unsigned NumElems = VT.getVectorNumElements();
18419       // Extract the LHS vectors
18420       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18421       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18422
18423       // Extract the RHS vectors
18424       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18425       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18426
18427       // Create min/max for each subvector
18428       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18429       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18430
18431       // Merge the result
18432       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18433     } else if (Opc)
18434       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18435   }
18436
18437   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18438   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18439       // Check if SETCC has already been promoted
18440       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18441       // Check that condition value type matches vselect operand type
18442       CondVT == VT) { 
18443
18444     assert(Cond.getValueType().isVector() &&
18445            "vector select expects a vector selector!");
18446
18447     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18448     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18449
18450     if (!TValIsAllOnes && !FValIsAllZeros) {
18451       // Try invert the condition if true value is not all 1s and false value
18452       // is not all 0s.
18453       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18454       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18455
18456       if (TValIsAllZeros || FValIsAllOnes) {
18457         SDValue CC = Cond.getOperand(2);
18458         ISD::CondCode NewCC =
18459           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18460                                Cond.getOperand(0).getValueType().isInteger());
18461         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18462         std::swap(LHS, RHS);
18463         TValIsAllOnes = FValIsAllOnes;
18464         FValIsAllZeros = TValIsAllZeros;
18465       }
18466     }
18467
18468     if (TValIsAllOnes || FValIsAllZeros) {
18469       SDValue Ret;
18470
18471       if (TValIsAllOnes && FValIsAllZeros)
18472         Ret = Cond;
18473       else if (TValIsAllOnes)
18474         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18475                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18476       else if (FValIsAllZeros)
18477         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18478                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18479
18480       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18481     }
18482   }
18483
18484   // Try to fold this VSELECT into a MOVSS/MOVSD
18485   if (N->getOpcode() == ISD::VSELECT &&
18486       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18487     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18488         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18489       bool CanFold = false;
18490       unsigned NumElems = Cond.getNumOperands();
18491       SDValue A = LHS;
18492       SDValue B = RHS;
18493       
18494       if (isZero(Cond.getOperand(0))) {
18495         CanFold = true;
18496
18497         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18498         // fold (vselect <0,-1> -> (movsd A, B)
18499         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18500           CanFold = isAllOnes(Cond.getOperand(i));
18501       } else if (isAllOnes(Cond.getOperand(0))) {
18502         CanFold = true;
18503         std::swap(A, B);
18504
18505         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18506         // fold (vselect <-1,0> -> (movsd B, A)
18507         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18508           CanFold = isZero(Cond.getOperand(i));
18509       }
18510
18511       if (CanFold) {
18512         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18513           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18514         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18515       }
18516
18517       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18518         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18519         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18520         //                             (v2i64 (bitcast B)))))
18521         //
18522         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18523         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18524         //                             (v2f64 (bitcast B)))))
18525         //
18526         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18527         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18528         //                             (v2i64 (bitcast A)))))
18529         //
18530         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18531         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18532         //                             (v2f64 (bitcast A)))))
18533
18534         CanFold = (isZero(Cond.getOperand(0)) &&
18535                    isZero(Cond.getOperand(1)) &&
18536                    isAllOnes(Cond.getOperand(2)) &&
18537                    isAllOnes(Cond.getOperand(3)));
18538
18539         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18540             isAllOnes(Cond.getOperand(1)) &&
18541             isZero(Cond.getOperand(2)) &&
18542             isZero(Cond.getOperand(3))) {
18543           CanFold = true;
18544           std::swap(LHS, RHS);
18545         }
18546
18547         if (CanFold) {
18548           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18549           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18550           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18551           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18552                                                 NewB, DAG);
18553           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18554         }
18555       }
18556     }
18557   }
18558
18559   // If we know that this node is legal then we know that it is going to be
18560   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18561   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18562   // to simplify previous instructions.
18563   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18564       !DCI.isBeforeLegalize() &&
18565       // We explicitly check against v8i16 and v16i16 because, although
18566       // they're marked as Custom, they might only be legal when Cond is a
18567       // build_vector of constants. This will be taken care in a later
18568       // condition.
18569       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18570        VT != MVT::v8i16)) {
18571     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18572
18573     // Don't optimize vector selects that map to mask-registers.
18574     if (BitWidth == 1)
18575       return SDValue();
18576
18577     // Check all uses of that condition operand to check whether it will be
18578     // consumed by non-BLEND instructions, which may depend on all bits are set
18579     // properly.
18580     for (SDNode::use_iterator I = Cond->use_begin(),
18581                               E = Cond->use_end(); I != E; ++I)
18582       if (I->getOpcode() != ISD::VSELECT)
18583         // TODO: Add other opcodes eventually lowered into BLEND.
18584         return SDValue();
18585
18586     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18587     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18588
18589     APInt KnownZero, KnownOne;
18590     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18591                                           DCI.isBeforeLegalizeOps());
18592     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18593         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18594       DCI.CommitTargetLoweringOpt(TLO);
18595   }
18596
18597   // We should generate an X86ISD::BLENDI from a vselect if its argument
18598   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18599   // constants. This specific pattern gets generated when we split a
18600   // selector for a 512 bit vector in a machine without AVX512 (but with
18601   // 256-bit vectors), during legalization:
18602   //
18603   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18604   //
18605   // Iff we find this pattern and the build_vectors are built from
18606   // constants, we translate the vselect into a shuffle_vector that we
18607   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18608   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18609     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18610     if (Shuffle.getNode())
18611       return Shuffle;
18612   }
18613
18614   return SDValue();
18615 }
18616
18617 // Check whether a boolean test is testing a boolean value generated by
18618 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18619 // code.
18620 //
18621 // Simplify the following patterns:
18622 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18623 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18624 // to (Op EFLAGS Cond)
18625 //
18626 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18627 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18628 // to (Op EFLAGS !Cond)
18629 //
18630 // where Op could be BRCOND or CMOV.
18631 //
18632 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18633   // Quit if not CMP and SUB with its value result used.
18634   if (Cmp.getOpcode() != X86ISD::CMP &&
18635       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18636       return SDValue();
18637
18638   // Quit if not used as a boolean value.
18639   if (CC != X86::COND_E && CC != X86::COND_NE)
18640     return SDValue();
18641
18642   // Check CMP operands. One of them should be 0 or 1 and the other should be
18643   // an SetCC or extended from it.
18644   SDValue Op1 = Cmp.getOperand(0);
18645   SDValue Op2 = Cmp.getOperand(1);
18646
18647   SDValue SetCC;
18648   const ConstantSDNode* C = nullptr;
18649   bool needOppositeCond = (CC == X86::COND_E);
18650   bool checkAgainstTrue = false; // Is it a comparison against 1?
18651
18652   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18653     SetCC = Op2;
18654   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18655     SetCC = Op1;
18656   else // Quit if all operands are not constants.
18657     return SDValue();
18658
18659   if (C->getZExtValue() == 1) {
18660     needOppositeCond = !needOppositeCond;
18661     checkAgainstTrue = true;
18662   } else if (C->getZExtValue() != 0)
18663     // Quit if the constant is neither 0 or 1.
18664     return SDValue();
18665
18666   bool truncatedToBoolWithAnd = false;
18667   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18668   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18669          SetCC.getOpcode() == ISD::TRUNCATE ||
18670          SetCC.getOpcode() == ISD::AND) {
18671     if (SetCC.getOpcode() == ISD::AND) {
18672       int OpIdx = -1;
18673       ConstantSDNode *CS;
18674       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18675           CS->getZExtValue() == 1)
18676         OpIdx = 1;
18677       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18678           CS->getZExtValue() == 1)
18679         OpIdx = 0;
18680       if (OpIdx == -1)
18681         break;
18682       SetCC = SetCC.getOperand(OpIdx);
18683       truncatedToBoolWithAnd = true;
18684     } else
18685       SetCC = SetCC.getOperand(0);
18686   }
18687
18688   switch (SetCC.getOpcode()) {
18689   case X86ISD::SETCC_CARRY:
18690     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18691     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18692     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18693     // truncated to i1 using 'and'.
18694     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18695       break;
18696     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18697            "Invalid use of SETCC_CARRY!");
18698     // FALL THROUGH
18699   case X86ISD::SETCC:
18700     // Set the condition code or opposite one if necessary.
18701     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18702     if (needOppositeCond)
18703       CC = X86::GetOppositeBranchCondition(CC);
18704     return SetCC.getOperand(1);
18705   case X86ISD::CMOV: {
18706     // Check whether false/true value has canonical one, i.e. 0 or 1.
18707     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18708     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18709     // Quit if true value is not a constant.
18710     if (!TVal)
18711       return SDValue();
18712     // Quit if false value is not a constant.
18713     if (!FVal) {
18714       SDValue Op = SetCC.getOperand(0);
18715       // Skip 'zext' or 'trunc' node.
18716       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18717           Op.getOpcode() == ISD::TRUNCATE)
18718         Op = Op.getOperand(0);
18719       // A special case for rdrand/rdseed, where 0 is set if false cond is
18720       // found.
18721       if ((Op.getOpcode() != X86ISD::RDRAND &&
18722            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18723         return SDValue();
18724     }
18725     // Quit if false value is not the constant 0 or 1.
18726     bool FValIsFalse = true;
18727     if (FVal && FVal->getZExtValue() != 0) {
18728       if (FVal->getZExtValue() != 1)
18729         return SDValue();
18730       // If FVal is 1, opposite cond is needed.
18731       needOppositeCond = !needOppositeCond;
18732       FValIsFalse = false;
18733     }
18734     // Quit if TVal is not the constant opposite of FVal.
18735     if (FValIsFalse && TVal->getZExtValue() != 1)
18736       return SDValue();
18737     if (!FValIsFalse && TVal->getZExtValue() != 0)
18738       return SDValue();
18739     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18740     if (needOppositeCond)
18741       CC = X86::GetOppositeBranchCondition(CC);
18742     return SetCC.getOperand(3);
18743   }
18744   }
18745
18746   return SDValue();
18747 }
18748
18749 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18750 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18751                                   TargetLowering::DAGCombinerInfo &DCI,
18752                                   const X86Subtarget *Subtarget) {
18753   SDLoc DL(N);
18754
18755   // If the flag operand isn't dead, don't touch this CMOV.
18756   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18757     return SDValue();
18758
18759   SDValue FalseOp = N->getOperand(0);
18760   SDValue TrueOp = N->getOperand(1);
18761   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18762   SDValue Cond = N->getOperand(3);
18763
18764   if (CC == X86::COND_E || CC == X86::COND_NE) {
18765     switch (Cond.getOpcode()) {
18766     default: break;
18767     case X86ISD::BSR:
18768     case X86ISD::BSF:
18769       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18770       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18771         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18772     }
18773   }
18774
18775   SDValue Flags;
18776
18777   Flags = checkBoolTestSetCCCombine(Cond, CC);
18778   if (Flags.getNode() &&
18779       // Extra check as FCMOV only supports a subset of X86 cond.
18780       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18781     SDValue Ops[] = { FalseOp, TrueOp,
18782                       DAG.getConstant(CC, MVT::i8), Flags };
18783     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18784   }
18785
18786   // If this is a select between two integer constants, try to do some
18787   // optimizations.  Note that the operands are ordered the opposite of SELECT
18788   // operands.
18789   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18790     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18791       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18792       // larger than FalseC (the false value).
18793       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18794         CC = X86::GetOppositeBranchCondition(CC);
18795         std::swap(TrueC, FalseC);
18796         std::swap(TrueOp, FalseOp);
18797       }
18798
18799       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18800       // This is efficient for any integer data type (including i8/i16) and
18801       // shift amount.
18802       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18803         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18804                            DAG.getConstant(CC, MVT::i8), Cond);
18805
18806         // Zero extend the condition if needed.
18807         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18808
18809         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18810         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18811                            DAG.getConstant(ShAmt, MVT::i8));
18812         if (N->getNumValues() == 2)  // Dead flag value?
18813           return DCI.CombineTo(N, Cond, SDValue());
18814         return Cond;
18815       }
18816
18817       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18818       // for any integer data type, including i8/i16.
18819       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18820         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18821                            DAG.getConstant(CC, MVT::i8), Cond);
18822
18823         // Zero extend the condition if needed.
18824         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18825                            FalseC->getValueType(0), Cond);
18826         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18827                            SDValue(FalseC, 0));
18828
18829         if (N->getNumValues() == 2)  // Dead flag value?
18830           return DCI.CombineTo(N, Cond, SDValue());
18831         return Cond;
18832       }
18833
18834       // Optimize cases that will turn into an LEA instruction.  This requires
18835       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18836       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18837         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18838         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18839
18840         bool isFastMultiplier = false;
18841         if (Diff < 10) {
18842           switch ((unsigned char)Diff) {
18843           default: break;
18844           case 1:  // result = add base, cond
18845           case 2:  // result = lea base(    , cond*2)
18846           case 3:  // result = lea base(cond, cond*2)
18847           case 4:  // result = lea base(    , cond*4)
18848           case 5:  // result = lea base(cond, cond*4)
18849           case 8:  // result = lea base(    , cond*8)
18850           case 9:  // result = lea base(cond, cond*8)
18851             isFastMultiplier = true;
18852             break;
18853           }
18854         }
18855
18856         if (isFastMultiplier) {
18857           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18858           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18859                              DAG.getConstant(CC, MVT::i8), Cond);
18860           // Zero extend the condition if needed.
18861           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18862                              Cond);
18863           // Scale the condition by the difference.
18864           if (Diff != 1)
18865             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18866                                DAG.getConstant(Diff, Cond.getValueType()));
18867
18868           // Add the base if non-zero.
18869           if (FalseC->getAPIntValue() != 0)
18870             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18871                                SDValue(FalseC, 0));
18872           if (N->getNumValues() == 2)  // Dead flag value?
18873             return DCI.CombineTo(N, Cond, SDValue());
18874           return Cond;
18875         }
18876       }
18877     }
18878   }
18879
18880   // Handle these cases:
18881   //   (select (x != c), e, c) -> select (x != c), e, x),
18882   //   (select (x == c), c, e) -> select (x == c), x, e)
18883   // where the c is an integer constant, and the "select" is the combination
18884   // of CMOV and CMP.
18885   //
18886   // The rationale for this change is that the conditional-move from a constant
18887   // needs two instructions, however, conditional-move from a register needs
18888   // only one instruction.
18889   //
18890   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18891   //  some instruction-combining opportunities. This opt needs to be
18892   //  postponed as late as possible.
18893   //
18894   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18895     // the DCI.xxxx conditions are provided to postpone the optimization as
18896     // late as possible.
18897
18898     ConstantSDNode *CmpAgainst = nullptr;
18899     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18900         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18901         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18902
18903       if (CC == X86::COND_NE &&
18904           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18905         CC = X86::GetOppositeBranchCondition(CC);
18906         std::swap(TrueOp, FalseOp);
18907       }
18908
18909       if (CC == X86::COND_E &&
18910           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18911         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18912                           DAG.getConstant(CC, MVT::i8), Cond };
18913         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18914       }
18915     }
18916   }
18917
18918   return SDValue();
18919 }
18920
18921 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18922                                                 const X86Subtarget *Subtarget) {
18923   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18924   switch (IntNo) {
18925   default: return SDValue();
18926   // SSE/AVX/AVX2 blend intrinsics.
18927   case Intrinsic::x86_avx2_pblendvb:
18928   case Intrinsic::x86_avx2_pblendw:
18929   case Intrinsic::x86_avx2_pblendd_128:
18930   case Intrinsic::x86_avx2_pblendd_256:
18931     // Don't try to simplify this intrinsic if we don't have AVX2.
18932     if (!Subtarget->hasAVX2())
18933       return SDValue();
18934     // FALL-THROUGH
18935   case Intrinsic::x86_avx_blend_pd_256:
18936   case Intrinsic::x86_avx_blend_ps_256:
18937   case Intrinsic::x86_avx_blendv_pd_256:
18938   case Intrinsic::x86_avx_blendv_ps_256:
18939     // Don't try to simplify this intrinsic if we don't have AVX.
18940     if (!Subtarget->hasAVX())
18941       return SDValue();
18942     // FALL-THROUGH
18943   case Intrinsic::x86_sse41_pblendw:
18944   case Intrinsic::x86_sse41_blendpd:
18945   case Intrinsic::x86_sse41_blendps:
18946   case Intrinsic::x86_sse41_blendvps:
18947   case Intrinsic::x86_sse41_blendvpd:
18948   case Intrinsic::x86_sse41_pblendvb: {
18949     SDValue Op0 = N->getOperand(1);
18950     SDValue Op1 = N->getOperand(2);
18951     SDValue Mask = N->getOperand(3);
18952
18953     // Don't try to simplify this intrinsic if we don't have SSE4.1.
18954     if (!Subtarget->hasSSE41())
18955       return SDValue();
18956
18957     // fold (blend A, A, Mask) -> A
18958     if (Op0 == Op1)
18959       return Op0;
18960     // fold (blend A, B, allZeros) -> A
18961     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18962       return Op0;
18963     // fold (blend A, B, allOnes) -> B
18964     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18965       return Op1;
18966     
18967     // Simplify the case where the mask is a constant i32 value.
18968     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18969       if (C->isNullValue())
18970         return Op0;
18971       if (C->isAllOnesValue())
18972         return Op1;
18973     }
18974   }
18975
18976   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18977   case Intrinsic::x86_sse2_psrai_w:
18978   case Intrinsic::x86_sse2_psrai_d:
18979   case Intrinsic::x86_avx2_psrai_w:
18980   case Intrinsic::x86_avx2_psrai_d:
18981   case Intrinsic::x86_sse2_psra_w:
18982   case Intrinsic::x86_sse2_psra_d:
18983   case Intrinsic::x86_avx2_psra_w:
18984   case Intrinsic::x86_avx2_psra_d: {
18985     SDValue Op0 = N->getOperand(1);
18986     SDValue Op1 = N->getOperand(2);
18987     EVT VT = Op0.getValueType();
18988     assert(VT.isVector() && "Expected a vector type!");
18989
18990     if (isa<BuildVectorSDNode>(Op1))
18991       Op1 = Op1.getOperand(0);
18992
18993     if (!isa<ConstantSDNode>(Op1))
18994       return SDValue();
18995
18996     EVT SVT = VT.getVectorElementType();
18997     unsigned SVTBits = SVT.getSizeInBits();
18998
18999     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19000     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19001     uint64_t ShAmt = C.getZExtValue();
19002
19003     // Don't try to convert this shift into a ISD::SRA if the shift
19004     // count is bigger than or equal to the element size.
19005     if (ShAmt >= SVTBits)
19006       return SDValue();
19007
19008     // Trivial case: if the shift count is zero, then fold this
19009     // into the first operand.
19010     if (ShAmt == 0)
19011       return Op0;
19012
19013     // Replace this packed shift intrinsic with a target independent
19014     // shift dag node.
19015     SDValue Splat = DAG.getConstant(C, VT);
19016     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19017   }
19018   }
19019 }
19020
19021 /// PerformMulCombine - Optimize a single multiply with constant into two
19022 /// in order to implement it with two cheaper instructions, e.g.
19023 /// LEA + SHL, LEA + LEA.
19024 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19025                                  TargetLowering::DAGCombinerInfo &DCI) {
19026   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19027     return SDValue();
19028
19029   EVT VT = N->getValueType(0);
19030   if (VT != MVT::i64)
19031     return SDValue();
19032
19033   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19034   if (!C)
19035     return SDValue();
19036   uint64_t MulAmt = C->getZExtValue();
19037   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19038     return SDValue();
19039
19040   uint64_t MulAmt1 = 0;
19041   uint64_t MulAmt2 = 0;
19042   if ((MulAmt % 9) == 0) {
19043     MulAmt1 = 9;
19044     MulAmt2 = MulAmt / 9;
19045   } else if ((MulAmt % 5) == 0) {
19046     MulAmt1 = 5;
19047     MulAmt2 = MulAmt / 5;
19048   } else if ((MulAmt % 3) == 0) {
19049     MulAmt1 = 3;
19050     MulAmt2 = MulAmt / 3;
19051   }
19052   if (MulAmt2 &&
19053       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19054     SDLoc DL(N);
19055
19056     if (isPowerOf2_64(MulAmt2) &&
19057         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19058       // If second multiplifer is pow2, issue it first. We want the multiply by
19059       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19060       // is an add.
19061       std::swap(MulAmt1, MulAmt2);
19062
19063     SDValue NewMul;
19064     if (isPowerOf2_64(MulAmt1))
19065       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19066                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19067     else
19068       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19069                            DAG.getConstant(MulAmt1, VT));
19070
19071     if (isPowerOf2_64(MulAmt2))
19072       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19073                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19074     else
19075       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19076                            DAG.getConstant(MulAmt2, VT));
19077
19078     // Do not add new nodes to DAG combiner worklist.
19079     DCI.CombineTo(N, NewMul, false);
19080   }
19081   return SDValue();
19082 }
19083
19084 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19085   SDValue N0 = N->getOperand(0);
19086   SDValue N1 = N->getOperand(1);
19087   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19088   EVT VT = N0.getValueType();
19089
19090   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19091   // since the result of setcc_c is all zero's or all ones.
19092   if (VT.isInteger() && !VT.isVector() &&
19093       N1C && N0.getOpcode() == ISD::AND &&
19094       N0.getOperand(1).getOpcode() == ISD::Constant) {
19095     SDValue N00 = N0.getOperand(0);
19096     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19097         ((N00.getOpcode() == ISD::ANY_EXTEND ||
19098           N00.getOpcode() == ISD::ZERO_EXTEND) &&
19099          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19100       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19101       APInt ShAmt = N1C->getAPIntValue();
19102       Mask = Mask.shl(ShAmt);
19103       if (Mask != 0)
19104         return DAG.getNode(ISD::AND, SDLoc(N), VT,
19105                            N00, DAG.getConstant(Mask, VT));
19106     }
19107   }
19108
19109   // Hardware support for vector shifts is sparse which makes us scalarize the
19110   // vector operations in many cases. Also, on sandybridge ADD is faster than
19111   // shl.
19112   // (shl V, 1) -> add V,V
19113   if (isSplatVector(N1.getNode())) {
19114     assert(N0.getValueType().isVector() && "Invalid vector shift type");
19115     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19116     // We shift all of the values by one. In many cases we do not have
19117     // hardware support for this operation. This is better expressed as an ADD
19118     // of two values.
19119     if (N1C && (1 == N1C->getZExtValue())) {
19120       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19121     }
19122   }
19123
19124   return SDValue();
19125 }
19126
19127 /// \brief Returns a vector of 0s if the node in input is a vector logical
19128 /// shift by a constant amount which is known to be bigger than or equal
19129 /// to the vector element size in bits.
19130 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19131                                       const X86Subtarget *Subtarget) {
19132   EVT VT = N->getValueType(0);
19133
19134   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19135       (!Subtarget->hasInt256() ||
19136        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19137     return SDValue();
19138
19139   SDValue Amt = N->getOperand(1);
19140   SDLoc DL(N);
19141   if (isSplatVector(Amt.getNode())) {
19142     SDValue SclrAmt = Amt->getOperand(0);
19143     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19144       APInt ShiftAmt = C->getAPIntValue();
19145       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19146
19147       // SSE2/AVX2 logical shifts always return a vector of 0s
19148       // if the shift amount is bigger than or equal to
19149       // the element size. The constant shift amount will be
19150       // encoded as a 8-bit immediate.
19151       if (ShiftAmt.trunc(8).uge(MaxAmount))
19152         return getZeroVector(VT, Subtarget, DAG, DL);
19153     }
19154   }
19155
19156   return SDValue();
19157 }
19158
19159 /// PerformShiftCombine - Combine shifts.
19160 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19161                                    TargetLowering::DAGCombinerInfo &DCI,
19162                                    const X86Subtarget *Subtarget) {
19163   if (N->getOpcode() == ISD::SHL) {
19164     SDValue V = PerformSHLCombine(N, DAG);
19165     if (V.getNode()) return V;
19166   }
19167
19168   if (N->getOpcode() != ISD::SRA) {
19169     // Try to fold this logical shift into a zero vector.
19170     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19171     if (V.getNode()) return V;
19172   }
19173
19174   return SDValue();
19175 }
19176
19177 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
19178 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19179 // and friends.  Likewise for OR -> CMPNEQSS.
19180 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19181                             TargetLowering::DAGCombinerInfo &DCI,
19182                             const X86Subtarget *Subtarget) {
19183   unsigned opcode;
19184
19185   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19186   // we're requiring SSE2 for both.
19187   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19188     SDValue N0 = N->getOperand(0);
19189     SDValue N1 = N->getOperand(1);
19190     SDValue CMP0 = N0->getOperand(1);
19191     SDValue CMP1 = N1->getOperand(1);
19192     SDLoc DL(N);
19193
19194     // The SETCCs should both refer to the same CMP.
19195     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19196       return SDValue();
19197
19198     SDValue CMP00 = CMP0->getOperand(0);
19199     SDValue CMP01 = CMP0->getOperand(1);
19200     EVT     VT    = CMP00.getValueType();
19201
19202     if (VT == MVT::f32 || VT == MVT::f64) {
19203       bool ExpectingFlags = false;
19204       // Check for any users that want flags:
19205       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19206            !ExpectingFlags && UI != UE; ++UI)
19207         switch (UI->getOpcode()) {
19208         default:
19209         case ISD::BR_CC:
19210         case ISD::BRCOND:
19211         case ISD::SELECT:
19212           ExpectingFlags = true;
19213           break;
19214         case ISD::CopyToReg:
19215         case ISD::SIGN_EXTEND:
19216         case ISD::ZERO_EXTEND:
19217         case ISD::ANY_EXTEND:
19218           break;
19219         }
19220
19221       if (!ExpectingFlags) {
19222         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19223         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19224
19225         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19226           X86::CondCode tmp = cc0;
19227           cc0 = cc1;
19228           cc1 = tmp;
19229         }
19230
19231         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
19232             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19233           // FIXME: need symbolic constants for these magic numbers.
19234           // See X86ATTInstPrinter.cpp:printSSECC().
19235           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19236           if (Subtarget->hasAVX512()) {
19237             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19238                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
19239             if (N->getValueType(0) != MVT::i1)
19240               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19241                                  FSetCC);
19242             return FSetCC;
19243           }
19244           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19245                                               CMP00.getValueType(), CMP00, CMP01,
19246                                               DAG.getConstant(x86cc, MVT::i8));
19247
19248           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19249           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19250
19251           if (is64BitFP && !Subtarget->is64Bit()) {
19252             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19253             // 64-bit integer, since that's not a legal type. Since
19254             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19255             // bits, but can do this little dance to extract the lowest 32 bits
19256             // and work with those going forward.
19257             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19258                                            OnesOrZeroesF);
19259             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19260                                            Vector64);
19261             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19262                                         Vector32, DAG.getIntPtrConstant(0));
19263             IntVT = MVT::i32;
19264           }
19265
19266           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19267           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19268                                       DAG.getConstant(1, IntVT));
19269           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19270           return OneBitOfTruth;
19271         }
19272       }
19273     }
19274   }
19275   return SDValue();
19276 }
19277
19278 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19279 /// so it can be folded inside ANDNP.
19280 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19281   EVT VT = N->getValueType(0);
19282
19283   // Match direct AllOnes for 128 and 256-bit vectors
19284   if (ISD::isBuildVectorAllOnes(N))
19285     return true;
19286
19287   // Look through a bit convert.
19288   if (N->getOpcode() == ISD::BITCAST)
19289     N = N->getOperand(0).getNode();
19290
19291   // Sometimes the operand may come from a insert_subvector building a 256-bit
19292   // allones vector
19293   if (VT.is256BitVector() &&
19294       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19295     SDValue V1 = N->getOperand(0);
19296     SDValue V2 = N->getOperand(1);
19297
19298     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19299         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19300         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19301         ISD::isBuildVectorAllOnes(V2.getNode()))
19302       return true;
19303   }
19304
19305   return false;
19306 }
19307
19308 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19309 // register. In most cases we actually compare or select YMM-sized registers
19310 // and mixing the two types creates horrible code. This method optimizes
19311 // some of the transition sequences.
19312 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19313                                  TargetLowering::DAGCombinerInfo &DCI,
19314                                  const X86Subtarget *Subtarget) {
19315   EVT VT = N->getValueType(0);
19316   if (!VT.is256BitVector())
19317     return SDValue();
19318
19319   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19320           N->getOpcode() == ISD::ZERO_EXTEND ||
19321           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19322
19323   SDValue Narrow = N->getOperand(0);
19324   EVT NarrowVT = Narrow->getValueType(0);
19325   if (!NarrowVT.is128BitVector())
19326     return SDValue();
19327
19328   if (Narrow->getOpcode() != ISD::XOR &&
19329       Narrow->getOpcode() != ISD::AND &&
19330       Narrow->getOpcode() != ISD::OR)
19331     return SDValue();
19332
19333   SDValue N0  = Narrow->getOperand(0);
19334   SDValue N1  = Narrow->getOperand(1);
19335   SDLoc DL(Narrow);
19336
19337   // The Left side has to be a trunc.
19338   if (N0.getOpcode() != ISD::TRUNCATE)
19339     return SDValue();
19340
19341   // The type of the truncated inputs.
19342   EVT WideVT = N0->getOperand(0)->getValueType(0);
19343   if (WideVT != VT)
19344     return SDValue();
19345
19346   // The right side has to be a 'trunc' or a constant vector.
19347   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19348   bool RHSConst = (isSplatVector(N1.getNode()) &&
19349                    isa<ConstantSDNode>(N1->getOperand(0)));
19350   if (!RHSTrunc && !RHSConst)
19351     return SDValue();
19352
19353   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19354
19355   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19356     return SDValue();
19357
19358   // Set N0 and N1 to hold the inputs to the new wide operation.
19359   N0 = N0->getOperand(0);
19360   if (RHSConst) {
19361     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19362                      N1->getOperand(0));
19363     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19364     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19365   } else if (RHSTrunc) {
19366     N1 = N1->getOperand(0);
19367   }
19368
19369   // Generate the wide operation.
19370   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19371   unsigned Opcode = N->getOpcode();
19372   switch (Opcode) {
19373   case ISD::ANY_EXTEND:
19374     return Op;
19375   case ISD::ZERO_EXTEND: {
19376     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19377     APInt Mask = APInt::getAllOnesValue(InBits);
19378     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19379     return DAG.getNode(ISD::AND, DL, VT,
19380                        Op, DAG.getConstant(Mask, VT));
19381   }
19382   case ISD::SIGN_EXTEND:
19383     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19384                        Op, DAG.getValueType(NarrowVT));
19385   default:
19386     llvm_unreachable("Unexpected opcode");
19387   }
19388 }
19389
19390 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19391                                  TargetLowering::DAGCombinerInfo &DCI,
19392                                  const X86Subtarget *Subtarget) {
19393   EVT VT = N->getValueType(0);
19394   if (DCI.isBeforeLegalizeOps())
19395     return SDValue();
19396
19397   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19398   if (R.getNode())
19399     return R;
19400
19401   // Create BEXTR instructions
19402   // BEXTR is ((X >> imm) & (2**size-1))
19403   if (VT == MVT::i32 || VT == MVT::i64) {
19404     SDValue N0 = N->getOperand(0);
19405     SDValue N1 = N->getOperand(1);
19406     SDLoc DL(N);
19407
19408     // Check for BEXTR.
19409     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19410         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19411       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19412       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19413       if (MaskNode && ShiftNode) {
19414         uint64_t Mask = MaskNode->getZExtValue();
19415         uint64_t Shift = ShiftNode->getZExtValue();
19416         if (isMask_64(Mask)) {
19417           uint64_t MaskSize = CountPopulation_64(Mask);
19418           if (Shift + MaskSize <= VT.getSizeInBits())
19419             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19420                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19421         }
19422       }
19423     } // BEXTR
19424
19425     return SDValue();
19426   }
19427
19428   // Want to form ANDNP nodes:
19429   // 1) In the hopes of then easily combining them with OR and AND nodes
19430   //    to form PBLEND/PSIGN.
19431   // 2) To match ANDN packed intrinsics
19432   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19433     return SDValue();
19434
19435   SDValue N0 = N->getOperand(0);
19436   SDValue N1 = N->getOperand(1);
19437   SDLoc DL(N);
19438
19439   // Check LHS for vnot
19440   if (N0.getOpcode() == ISD::XOR &&
19441       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19442       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19443     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19444
19445   // Check RHS for vnot
19446   if (N1.getOpcode() == ISD::XOR &&
19447       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19448       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19449     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19450
19451   return SDValue();
19452 }
19453
19454 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19455                                 TargetLowering::DAGCombinerInfo &DCI,
19456                                 const X86Subtarget *Subtarget) {
19457   if (DCI.isBeforeLegalizeOps())
19458     return SDValue();
19459
19460   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19461   if (R.getNode())
19462     return R;
19463
19464   SDValue N0 = N->getOperand(0);
19465   SDValue N1 = N->getOperand(1);
19466   EVT VT = N->getValueType(0);
19467
19468   // look for psign/blend
19469   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19470     if (!Subtarget->hasSSSE3() ||
19471         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19472       return SDValue();
19473
19474     // Canonicalize pandn to RHS
19475     if (N0.getOpcode() == X86ISD::ANDNP)
19476       std::swap(N0, N1);
19477     // or (and (m, y), (pandn m, x))
19478     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19479       SDValue Mask = N1.getOperand(0);
19480       SDValue X    = N1.getOperand(1);
19481       SDValue Y;
19482       if (N0.getOperand(0) == Mask)
19483         Y = N0.getOperand(1);
19484       if (N0.getOperand(1) == Mask)
19485         Y = N0.getOperand(0);
19486
19487       // Check to see if the mask appeared in both the AND and ANDNP and
19488       if (!Y.getNode())
19489         return SDValue();
19490
19491       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19492       // Look through mask bitcast.
19493       if (Mask.getOpcode() == ISD::BITCAST)
19494         Mask = Mask.getOperand(0);
19495       if (X.getOpcode() == ISD::BITCAST)
19496         X = X.getOperand(0);
19497       if (Y.getOpcode() == ISD::BITCAST)
19498         Y = Y.getOperand(0);
19499
19500       EVT MaskVT = Mask.getValueType();
19501
19502       // Validate that the Mask operand is a vector sra node.
19503       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19504       // there is no psrai.b
19505       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19506       unsigned SraAmt = ~0;
19507       if (Mask.getOpcode() == ISD::SRA) {
19508         SDValue Amt = Mask.getOperand(1);
19509         if (isSplatVector(Amt.getNode())) {
19510           SDValue SclrAmt = Amt->getOperand(0);
19511           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19512             SraAmt = C->getZExtValue();
19513         }
19514       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19515         SDValue SraC = Mask.getOperand(1);
19516         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19517       }
19518       if ((SraAmt + 1) != EltBits)
19519         return SDValue();
19520
19521       SDLoc DL(N);
19522
19523       // Now we know we at least have a plendvb with the mask val.  See if
19524       // we can form a psignb/w/d.
19525       // psign = x.type == y.type == mask.type && y = sub(0, x);
19526       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19527           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19528           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19529         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19530                "Unsupported VT for PSIGN");
19531         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19532         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19533       }
19534       // PBLENDVB only available on SSE 4.1
19535       if (!Subtarget->hasSSE41())
19536         return SDValue();
19537
19538       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19539
19540       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19541       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19542       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19543       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19544       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19545     }
19546   }
19547
19548   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19549     return SDValue();
19550
19551   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19552   MachineFunction &MF = DAG.getMachineFunction();
19553   bool OptForSize = MF.getFunction()->getAttributes().
19554     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19555
19556   // SHLD/SHRD instructions have lower register pressure, but on some
19557   // platforms they have higher latency than the equivalent
19558   // series of shifts/or that would otherwise be generated.
19559   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19560   // have higher latencies and we are not optimizing for size.
19561   if (!OptForSize && Subtarget->isSHLDSlow())
19562     return SDValue();
19563
19564   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19565     std::swap(N0, N1);
19566   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19567     return SDValue();
19568   if (!N0.hasOneUse() || !N1.hasOneUse())
19569     return SDValue();
19570
19571   SDValue ShAmt0 = N0.getOperand(1);
19572   if (ShAmt0.getValueType() != MVT::i8)
19573     return SDValue();
19574   SDValue ShAmt1 = N1.getOperand(1);
19575   if (ShAmt1.getValueType() != MVT::i8)
19576     return SDValue();
19577   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19578     ShAmt0 = ShAmt0.getOperand(0);
19579   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19580     ShAmt1 = ShAmt1.getOperand(0);
19581
19582   SDLoc DL(N);
19583   unsigned Opc = X86ISD::SHLD;
19584   SDValue Op0 = N0.getOperand(0);
19585   SDValue Op1 = N1.getOperand(0);
19586   if (ShAmt0.getOpcode() == ISD::SUB) {
19587     Opc = X86ISD::SHRD;
19588     std::swap(Op0, Op1);
19589     std::swap(ShAmt0, ShAmt1);
19590   }
19591
19592   unsigned Bits = VT.getSizeInBits();
19593   if (ShAmt1.getOpcode() == ISD::SUB) {
19594     SDValue Sum = ShAmt1.getOperand(0);
19595     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19596       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19597       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19598         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19599       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19600         return DAG.getNode(Opc, DL, VT,
19601                            Op0, Op1,
19602                            DAG.getNode(ISD::TRUNCATE, DL,
19603                                        MVT::i8, ShAmt0));
19604     }
19605   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19606     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19607     if (ShAmt0C &&
19608         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19609       return DAG.getNode(Opc, DL, VT,
19610                          N0.getOperand(0), N1.getOperand(0),
19611                          DAG.getNode(ISD::TRUNCATE, DL,
19612                                        MVT::i8, ShAmt0));
19613   }
19614
19615   return SDValue();
19616 }
19617
19618 // Generate NEG and CMOV for integer abs.
19619 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19620   EVT VT = N->getValueType(0);
19621
19622   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19623   // 8-bit integer abs to NEG and CMOV.
19624   if (VT.isInteger() && VT.getSizeInBits() == 8)
19625     return SDValue();
19626
19627   SDValue N0 = N->getOperand(0);
19628   SDValue N1 = N->getOperand(1);
19629   SDLoc DL(N);
19630
19631   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19632   // and change it to SUB and CMOV.
19633   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19634       N0.getOpcode() == ISD::ADD &&
19635       N0.getOperand(1) == N1 &&
19636       N1.getOpcode() == ISD::SRA &&
19637       N1.getOperand(0) == N0.getOperand(0))
19638     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19639       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19640         // Generate SUB & CMOV.
19641         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19642                                   DAG.getConstant(0, VT), N0.getOperand(0));
19643
19644         SDValue Ops[] = { N0.getOperand(0), Neg,
19645                           DAG.getConstant(X86::COND_GE, MVT::i8),
19646                           SDValue(Neg.getNode(), 1) };
19647         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19648       }
19649   return SDValue();
19650 }
19651
19652 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19653 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19654                                  TargetLowering::DAGCombinerInfo &DCI,
19655                                  const X86Subtarget *Subtarget) {
19656   if (DCI.isBeforeLegalizeOps())
19657     return SDValue();
19658
19659   if (Subtarget->hasCMov()) {
19660     SDValue RV = performIntegerAbsCombine(N, DAG);
19661     if (RV.getNode())
19662       return RV;
19663   }
19664
19665   return SDValue();
19666 }
19667
19668 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19669 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19670                                   TargetLowering::DAGCombinerInfo &DCI,
19671                                   const X86Subtarget *Subtarget) {
19672   LoadSDNode *Ld = cast<LoadSDNode>(N);
19673   EVT RegVT = Ld->getValueType(0);
19674   EVT MemVT = Ld->getMemoryVT();
19675   SDLoc dl(Ld);
19676   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19677   unsigned RegSz = RegVT.getSizeInBits();
19678
19679   // On Sandybridge unaligned 256bit loads are inefficient.
19680   ISD::LoadExtType Ext = Ld->getExtensionType();
19681   unsigned Alignment = Ld->getAlignment();
19682   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19683   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19684       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19685     unsigned NumElems = RegVT.getVectorNumElements();
19686     if (NumElems < 2)
19687       return SDValue();
19688
19689     SDValue Ptr = Ld->getBasePtr();
19690     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19691
19692     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19693                                   NumElems/2);
19694     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19695                                 Ld->getPointerInfo(), Ld->isVolatile(),
19696                                 Ld->isNonTemporal(), Ld->isInvariant(),
19697                                 Alignment);
19698     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19699     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19700                                 Ld->getPointerInfo(), Ld->isVolatile(),
19701                                 Ld->isNonTemporal(), Ld->isInvariant(),
19702                                 std::min(16U, Alignment));
19703     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19704                              Load1.getValue(1),
19705                              Load2.getValue(1));
19706
19707     SDValue NewVec = DAG.getUNDEF(RegVT);
19708     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19709     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19710     return DCI.CombineTo(N, NewVec, TF, true);
19711   }
19712
19713   // If this is a vector EXT Load then attempt to optimize it using a
19714   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19715   // expansion is still better than scalar code.
19716   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19717   // emit a shuffle and a arithmetic shift.
19718   // TODO: It is possible to support ZExt by zeroing the undef values
19719   // during the shuffle phase or after the shuffle.
19720   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19721       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19722     assert(MemVT != RegVT && "Cannot extend to the same type");
19723     assert(MemVT.isVector() && "Must load a vector from memory");
19724
19725     unsigned NumElems = RegVT.getVectorNumElements();
19726     unsigned MemSz = MemVT.getSizeInBits();
19727     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19728
19729     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19730       return SDValue();
19731
19732     // All sizes must be a power of two.
19733     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19734       return SDValue();
19735
19736     // Attempt to load the original value using scalar loads.
19737     // Find the largest scalar type that divides the total loaded size.
19738     MVT SclrLoadTy = MVT::i8;
19739     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19740          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19741       MVT Tp = (MVT::SimpleValueType)tp;
19742       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19743         SclrLoadTy = Tp;
19744       }
19745     }
19746
19747     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19748     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19749         (64 <= MemSz))
19750       SclrLoadTy = MVT::f64;
19751
19752     // Calculate the number of scalar loads that we need to perform
19753     // in order to load our vector from memory.
19754     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19755     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19756       return SDValue();
19757
19758     unsigned loadRegZize = RegSz;
19759     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19760       loadRegZize /= 2;
19761
19762     // Represent our vector as a sequence of elements which are the
19763     // largest scalar that we can load.
19764     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19765       loadRegZize/SclrLoadTy.getSizeInBits());
19766
19767     // Represent the data using the same element type that is stored in
19768     // memory. In practice, we ''widen'' MemVT.
19769     EVT WideVecVT =
19770           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19771                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19772
19773     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19774       "Invalid vector type");
19775
19776     // We can't shuffle using an illegal type.
19777     if (!TLI.isTypeLegal(WideVecVT))
19778       return SDValue();
19779
19780     SmallVector<SDValue, 8> Chains;
19781     SDValue Ptr = Ld->getBasePtr();
19782     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19783                                         TLI.getPointerTy());
19784     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19785
19786     for (unsigned i = 0; i < NumLoads; ++i) {
19787       // Perform a single load.
19788       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19789                                        Ptr, Ld->getPointerInfo(),
19790                                        Ld->isVolatile(), Ld->isNonTemporal(),
19791                                        Ld->isInvariant(), Ld->getAlignment());
19792       Chains.push_back(ScalarLoad.getValue(1));
19793       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19794       // another round of DAGCombining.
19795       if (i == 0)
19796         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19797       else
19798         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19799                           ScalarLoad, DAG.getIntPtrConstant(i));
19800
19801       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19802     }
19803
19804     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19805
19806     // Bitcast the loaded value to a vector of the original element type, in
19807     // the size of the target vector type.
19808     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19809     unsigned SizeRatio = RegSz/MemSz;
19810
19811     if (Ext == ISD::SEXTLOAD) {
19812       // If we have SSE4.1 we can directly emit a VSEXT node.
19813       if (Subtarget->hasSSE41()) {
19814         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19815         return DCI.CombineTo(N, Sext, TF, true);
19816       }
19817
19818       // Otherwise we'll shuffle the small elements in the high bits of the
19819       // larger type and perform an arithmetic shift. If the shift is not legal
19820       // it's better to scalarize.
19821       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19822         return SDValue();
19823
19824       // Redistribute the loaded elements into the different locations.
19825       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19826       for (unsigned i = 0; i != NumElems; ++i)
19827         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19828
19829       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19830                                            DAG.getUNDEF(WideVecVT),
19831                                            &ShuffleVec[0]);
19832
19833       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19834
19835       // Build the arithmetic shift.
19836       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19837                      MemVT.getVectorElementType().getSizeInBits();
19838       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19839                           DAG.getConstant(Amt, RegVT));
19840
19841       return DCI.CombineTo(N, Shuff, TF, true);
19842     }
19843
19844     // Redistribute the loaded elements into the different locations.
19845     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19846     for (unsigned i = 0; i != NumElems; ++i)
19847       ShuffleVec[i*SizeRatio] = i;
19848
19849     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19850                                          DAG.getUNDEF(WideVecVT),
19851                                          &ShuffleVec[0]);
19852
19853     // Bitcast to the requested type.
19854     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19855     // Replace the original load with the new sequence
19856     // and return the new chain.
19857     return DCI.CombineTo(N, Shuff, TF, true);
19858   }
19859
19860   return SDValue();
19861 }
19862
19863 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19864 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19865                                    const X86Subtarget *Subtarget) {
19866   StoreSDNode *St = cast<StoreSDNode>(N);
19867   EVT VT = St->getValue().getValueType();
19868   EVT StVT = St->getMemoryVT();
19869   SDLoc dl(St);
19870   SDValue StoredVal = St->getOperand(1);
19871   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19872
19873   // If we are saving a concatenation of two XMM registers, perform two stores.
19874   // On Sandy Bridge, 256-bit memory operations are executed by two
19875   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19876   // memory  operation.
19877   unsigned Alignment = St->getAlignment();
19878   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19879   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19880       StVT == VT && !IsAligned) {
19881     unsigned NumElems = VT.getVectorNumElements();
19882     if (NumElems < 2)
19883       return SDValue();
19884
19885     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19886     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19887
19888     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19889     SDValue Ptr0 = St->getBasePtr();
19890     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19891
19892     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19893                                 St->getPointerInfo(), St->isVolatile(),
19894                                 St->isNonTemporal(), Alignment);
19895     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19896                                 St->getPointerInfo(), St->isVolatile(),
19897                                 St->isNonTemporal(),
19898                                 std::min(16U, Alignment));
19899     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19900   }
19901
19902   // Optimize trunc store (of multiple scalars) to shuffle and store.
19903   // First, pack all of the elements in one place. Next, store to memory
19904   // in fewer chunks.
19905   if (St->isTruncatingStore() && VT.isVector()) {
19906     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19907     unsigned NumElems = VT.getVectorNumElements();
19908     assert(StVT != VT && "Cannot truncate to the same type");
19909     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19910     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19911
19912     // From, To sizes and ElemCount must be pow of two
19913     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19914     // We are going to use the original vector elt for storing.
19915     // Accumulated smaller vector elements must be a multiple of the store size.
19916     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19917
19918     unsigned SizeRatio  = FromSz / ToSz;
19919
19920     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19921
19922     // Create a type on which we perform the shuffle
19923     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19924             StVT.getScalarType(), NumElems*SizeRatio);
19925
19926     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19927
19928     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19929     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19930     for (unsigned i = 0; i != NumElems; ++i)
19931       ShuffleVec[i] = i * SizeRatio;
19932
19933     // Can't shuffle using an illegal type.
19934     if (!TLI.isTypeLegal(WideVecVT))
19935       return SDValue();
19936
19937     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19938                                          DAG.getUNDEF(WideVecVT),
19939                                          &ShuffleVec[0]);
19940     // At this point all of the data is stored at the bottom of the
19941     // register. We now need to save it to mem.
19942
19943     // Find the largest store unit
19944     MVT StoreType = MVT::i8;
19945     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19946          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19947       MVT Tp = (MVT::SimpleValueType)tp;
19948       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19949         StoreType = Tp;
19950     }
19951
19952     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19953     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19954         (64 <= NumElems * ToSz))
19955       StoreType = MVT::f64;
19956
19957     // Bitcast the original vector into a vector of store-size units
19958     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19959             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19960     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19961     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19962     SmallVector<SDValue, 8> Chains;
19963     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19964                                         TLI.getPointerTy());
19965     SDValue Ptr = St->getBasePtr();
19966
19967     // Perform one or more big stores into memory.
19968     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19969       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19970                                    StoreType, ShuffWide,
19971                                    DAG.getIntPtrConstant(i));
19972       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19973                                 St->getPointerInfo(), St->isVolatile(),
19974                                 St->isNonTemporal(), St->getAlignment());
19975       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19976       Chains.push_back(Ch);
19977     }
19978
19979     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19980   }
19981
19982   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19983   // the FP state in cases where an emms may be missing.
19984   // A preferable solution to the general problem is to figure out the right
19985   // places to insert EMMS.  This qualifies as a quick hack.
19986
19987   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19988   if (VT.getSizeInBits() != 64)
19989     return SDValue();
19990
19991   const Function *F = DAG.getMachineFunction().getFunction();
19992   bool NoImplicitFloatOps = F->getAttributes().
19993     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19994   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19995                      && Subtarget->hasSSE2();
19996   if ((VT.isVector() ||
19997        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19998       isa<LoadSDNode>(St->getValue()) &&
19999       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20000       St->getChain().hasOneUse() && !St->isVolatile()) {
20001     SDNode* LdVal = St->getValue().getNode();
20002     LoadSDNode *Ld = nullptr;
20003     int TokenFactorIndex = -1;
20004     SmallVector<SDValue, 8> Ops;
20005     SDNode* ChainVal = St->getChain().getNode();
20006     // Must be a store of a load.  We currently handle two cases:  the load
20007     // is a direct child, and it's under an intervening TokenFactor.  It is
20008     // possible to dig deeper under nested TokenFactors.
20009     if (ChainVal == LdVal)
20010       Ld = cast<LoadSDNode>(St->getChain());
20011     else if (St->getValue().hasOneUse() &&
20012              ChainVal->getOpcode() == ISD::TokenFactor) {
20013       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20014         if (ChainVal->getOperand(i).getNode() == LdVal) {
20015           TokenFactorIndex = i;
20016           Ld = cast<LoadSDNode>(St->getValue());
20017         } else
20018           Ops.push_back(ChainVal->getOperand(i));
20019       }
20020     }
20021
20022     if (!Ld || !ISD::isNormalLoad(Ld))
20023       return SDValue();
20024
20025     // If this is not the MMX case, i.e. we are just turning i64 load/store
20026     // into f64 load/store, avoid the transformation if there are multiple
20027     // uses of the loaded value.
20028     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20029       return SDValue();
20030
20031     SDLoc LdDL(Ld);
20032     SDLoc StDL(N);
20033     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20034     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20035     // pair instead.
20036     if (Subtarget->is64Bit() || F64IsLegal) {
20037       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20038       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20039                                   Ld->getPointerInfo(), Ld->isVolatile(),
20040                                   Ld->isNonTemporal(), Ld->isInvariant(),
20041                                   Ld->getAlignment());
20042       SDValue NewChain = NewLd.getValue(1);
20043       if (TokenFactorIndex != -1) {
20044         Ops.push_back(NewChain);
20045         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20046       }
20047       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20048                           St->getPointerInfo(),
20049                           St->isVolatile(), St->isNonTemporal(),
20050                           St->getAlignment());
20051     }
20052
20053     // Otherwise, lower to two pairs of 32-bit loads / stores.
20054     SDValue LoAddr = Ld->getBasePtr();
20055     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20056                                  DAG.getConstant(4, MVT::i32));
20057
20058     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20059                                Ld->getPointerInfo(),
20060                                Ld->isVolatile(), Ld->isNonTemporal(),
20061                                Ld->isInvariant(), Ld->getAlignment());
20062     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20063                                Ld->getPointerInfo().getWithOffset(4),
20064                                Ld->isVolatile(), Ld->isNonTemporal(),
20065                                Ld->isInvariant(),
20066                                MinAlign(Ld->getAlignment(), 4));
20067
20068     SDValue NewChain = LoLd.getValue(1);
20069     if (TokenFactorIndex != -1) {
20070       Ops.push_back(LoLd);
20071       Ops.push_back(HiLd);
20072       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20073     }
20074
20075     LoAddr = St->getBasePtr();
20076     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20077                          DAG.getConstant(4, MVT::i32));
20078
20079     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20080                                 St->getPointerInfo(),
20081                                 St->isVolatile(), St->isNonTemporal(),
20082                                 St->getAlignment());
20083     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20084                                 St->getPointerInfo().getWithOffset(4),
20085                                 St->isVolatile(),
20086                                 St->isNonTemporal(),
20087                                 MinAlign(St->getAlignment(), 4));
20088     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20089   }
20090   return SDValue();
20091 }
20092
20093 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20094 /// and return the operands for the horizontal operation in LHS and RHS.  A
20095 /// horizontal operation performs the binary operation on successive elements
20096 /// of its first operand, then on successive elements of its second operand,
20097 /// returning the resulting values in a vector.  For example, if
20098 ///   A = < float a0, float a1, float a2, float a3 >
20099 /// and
20100 ///   B = < float b0, float b1, float b2, float b3 >
20101 /// then the result of doing a horizontal operation on A and B is
20102 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20103 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20104 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20105 /// set to A, RHS to B, and the routine returns 'true'.
20106 /// Note that the binary operation should have the property that if one of the
20107 /// operands is UNDEF then the result is UNDEF.
20108 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20109   // Look for the following pattern: if
20110   //   A = < float a0, float a1, float a2, float a3 >
20111   //   B = < float b0, float b1, float b2, float b3 >
20112   // and
20113   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20114   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20115   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20116   // which is A horizontal-op B.
20117
20118   // At least one of the operands should be a vector shuffle.
20119   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20120       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20121     return false;
20122
20123   MVT VT = LHS.getSimpleValueType();
20124
20125   assert((VT.is128BitVector() || VT.is256BitVector()) &&
20126          "Unsupported vector type for horizontal add/sub");
20127
20128   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20129   // operate independently on 128-bit lanes.
20130   unsigned NumElts = VT.getVectorNumElements();
20131   unsigned NumLanes = VT.getSizeInBits()/128;
20132   unsigned NumLaneElts = NumElts / NumLanes;
20133   assert((NumLaneElts % 2 == 0) &&
20134          "Vector type should have an even number of elements in each lane");
20135   unsigned HalfLaneElts = NumLaneElts/2;
20136
20137   // View LHS in the form
20138   //   LHS = VECTOR_SHUFFLE A, B, LMask
20139   // If LHS is not a shuffle then pretend it is the shuffle
20140   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20141   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20142   // type VT.
20143   SDValue A, B;
20144   SmallVector<int, 16> LMask(NumElts);
20145   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20146     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20147       A = LHS.getOperand(0);
20148     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20149       B = LHS.getOperand(1);
20150     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20151     std::copy(Mask.begin(), Mask.end(), LMask.begin());
20152   } else {
20153     if (LHS.getOpcode() != ISD::UNDEF)
20154       A = LHS;
20155     for (unsigned i = 0; i != NumElts; ++i)
20156       LMask[i] = i;
20157   }
20158
20159   // Likewise, view RHS in the form
20160   //   RHS = VECTOR_SHUFFLE C, D, RMask
20161   SDValue C, D;
20162   SmallVector<int, 16> RMask(NumElts);
20163   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20164     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20165       C = RHS.getOperand(0);
20166     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20167       D = RHS.getOperand(1);
20168     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20169     std::copy(Mask.begin(), Mask.end(), RMask.begin());
20170   } else {
20171     if (RHS.getOpcode() != ISD::UNDEF)
20172       C = RHS;
20173     for (unsigned i = 0; i != NumElts; ++i)
20174       RMask[i] = i;
20175   }
20176
20177   // Check that the shuffles are both shuffling the same vectors.
20178   if (!(A == C && B == D) && !(A == D && B == C))
20179     return false;
20180
20181   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20182   if (!A.getNode() && !B.getNode())
20183     return false;
20184
20185   // If A and B occur in reverse order in RHS, then "swap" them (which means
20186   // rewriting the mask).
20187   if (A != C)
20188     CommuteVectorShuffleMask(RMask, NumElts);
20189
20190   // At this point LHS and RHS are equivalent to
20191   //   LHS = VECTOR_SHUFFLE A, B, LMask
20192   //   RHS = VECTOR_SHUFFLE A, B, RMask
20193   // Check that the masks correspond to performing a horizontal operation.
20194   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20195     for (unsigned i = 0; i != NumLaneElts; ++i) {
20196       int LIdx = LMask[i+l], RIdx = RMask[i+l];
20197
20198       // Ignore any UNDEF components.
20199       if (LIdx < 0 || RIdx < 0 ||
20200           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20201           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20202         continue;
20203
20204       // Check that successive elements are being operated on.  If not, this is
20205       // not a horizontal operation.
20206       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20207       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20208       if (!(LIdx == Index && RIdx == Index + 1) &&
20209           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20210         return false;
20211     }
20212   }
20213
20214   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20215   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20216   return true;
20217 }
20218
20219 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20220 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20221                                   const X86Subtarget *Subtarget) {
20222   EVT VT = N->getValueType(0);
20223   SDValue LHS = N->getOperand(0);
20224   SDValue RHS = N->getOperand(1);
20225
20226   // Try to synthesize horizontal adds from adds of shuffles.
20227   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20228        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20229       isHorizontalBinOp(LHS, RHS, true))
20230     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20231   return SDValue();
20232 }
20233
20234 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20235 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20236                                   const X86Subtarget *Subtarget) {
20237   EVT VT = N->getValueType(0);
20238   SDValue LHS = N->getOperand(0);
20239   SDValue RHS = N->getOperand(1);
20240
20241   // Try to synthesize horizontal subs from subs of shuffles.
20242   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20243        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20244       isHorizontalBinOp(LHS, RHS, false))
20245     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20246   return SDValue();
20247 }
20248
20249 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20250 /// X86ISD::FXOR nodes.
20251 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20252   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20253   // F[X]OR(0.0, x) -> x
20254   // F[X]OR(x, 0.0) -> x
20255   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20256     if (C->getValueAPF().isPosZero())
20257       return N->getOperand(1);
20258   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20259     if (C->getValueAPF().isPosZero())
20260       return N->getOperand(0);
20261   return SDValue();
20262 }
20263
20264 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20265 /// X86ISD::FMAX nodes.
20266 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20267   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20268
20269   // Only perform optimizations if UnsafeMath is used.
20270   if (!DAG.getTarget().Options.UnsafeFPMath)
20271     return SDValue();
20272
20273   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20274   // into FMINC and FMAXC, which are Commutative operations.
20275   unsigned NewOp = 0;
20276   switch (N->getOpcode()) {
20277     default: llvm_unreachable("unknown opcode");
20278     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20279     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20280   }
20281
20282   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20283                      N->getOperand(0), N->getOperand(1));
20284 }
20285
20286 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20287 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20288   // FAND(0.0, x) -> 0.0
20289   // FAND(x, 0.0) -> 0.0
20290   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20291     if (C->getValueAPF().isPosZero())
20292       return N->getOperand(0);
20293   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20294     if (C->getValueAPF().isPosZero())
20295       return N->getOperand(1);
20296   return SDValue();
20297 }
20298
20299 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20300 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20301   // FANDN(x, 0.0) -> 0.0
20302   // FANDN(0.0, x) -> x
20303   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20304     if (C->getValueAPF().isPosZero())
20305       return N->getOperand(1);
20306   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20307     if (C->getValueAPF().isPosZero())
20308       return N->getOperand(1);
20309   return SDValue();
20310 }
20311
20312 static SDValue PerformBTCombine(SDNode *N,
20313                                 SelectionDAG &DAG,
20314                                 TargetLowering::DAGCombinerInfo &DCI) {
20315   // BT ignores high bits in the bit index operand.
20316   SDValue Op1 = N->getOperand(1);
20317   if (Op1.hasOneUse()) {
20318     unsigned BitWidth = Op1.getValueSizeInBits();
20319     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20320     APInt KnownZero, KnownOne;
20321     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20322                                           !DCI.isBeforeLegalizeOps());
20323     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20324     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20325         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20326       DCI.CommitTargetLoweringOpt(TLO);
20327   }
20328   return SDValue();
20329 }
20330
20331 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20332   SDValue Op = N->getOperand(0);
20333   if (Op.getOpcode() == ISD::BITCAST)
20334     Op = Op.getOperand(0);
20335   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20336   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20337       VT.getVectorElementType().getSizeInBits() ==
20338       OpVT.getVectorElementType().getSizeInBits()) {
20339     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20340   }
20341   return SDValue();
20342 }
20343
20344 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20345                                                const X86Subtarget *Subtarget) {
20346   EVT VT = N->getValueType(0);
20347   if (!VT.isVector())
20348     return SDValue();
20349
20350   SDValue N0 = N->getOperand(0);
20351   SDValue N1 = N->getOperand(1);
20352   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20353   SDLoc dl(N);
20354
20355   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20356   // both SSE and AVX2 since there is no sign-extended shift right
20357   // operation on a vector with 64-bit elements.
20358   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20359   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20360   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20361       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20362     SDValue N00 = N0.getOperand(0);
20363
20364     // EXTLOAD has a better solution on AVX2,
20365     // it may be replaced with X86ISD::VSEXT node.
20366     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20367       if (!ISD::isNormalLoad(N00.getNode()))
20368         return SDValue();
20369
20370     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20371         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20372                                   N00, N1);
20373       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20374     }
20375   }
20376   return SDValue();
20377 }
20378
20379 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20380                                   TargetLowering::DAGCombinerInfo &DCI,
20381                                   const X86Subtarget *Subtarget) {
20382   if (!DCI.isBeforeLegalizeOps())
20383     return SDValue();
20384
20385   if (!Subtarget->hasFp256())
20386     return SDValue();
20387
20388   EVT VT = N->getValueType(0);
20389   if (VT.isVector() && VT.getSizeInBits() == 256) {
20390     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20391     if (R.getNode())
20392       return R;
20393   }
20394
20395   return SDValue();
20396 }
20397
20398 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20399                                  const X86Subtarget* Subtarget) {
20400   SDLoc dl(N);
20401   EVT VT = N->getValueType(0);
20402
20403   // Let legalize expand this if it isn't a legal type yet.
20404   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20405     return SDValue();
20406
20407   EVT ScalarVT = VT.getScalarType();
20408   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20409       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20410     return SDValue();
20411
20412   SDValue A = N->getOperand(0);
20413   SDValue B = N->getOperand(1);
20414   SDValue C = N->getOperand(2);
20415
20416   bool NegA = (A.getOpcode() == ISD::FNEG);
20417   bool NegB = (B.getOpcode() == ISD::FNEG);
20418   bool NegC = (C.getOpcode() == ISD::FNEG);
20419
20420   // Negative multiplication when NegA xor NegB
20421   bool NegMul = (NegA != NegB);
20422   if (NegA)
20423     A = A.getOperand(0);
20424   if (NegB)
20425     B = B.getOperand(0);
20426   if (NegC)
20427     C = C.getOperand(0);
20428
20429   unsigned Opcode;
20430   if (!NegMul)
20431     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20432   else
20433     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20434
20435   return DAG.getNode(Opcode, dl, VT, A, B, C);
20436 }
20437
20438 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20439                                   TargetLowering::DAGCombinerInfo &DCI,
20440                                   const X86Subtarget *Subtarget) {
20441   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20442   //           (and (i32 x86isd::setcc_carry), 1)
20443   // This eliminates the zext. This transformation is necessary because
20444   // ISD::SETCC is always legalized to i8.
20445   SDLoc dl(N);
20446   SDValue N0 = N->getOperand(0);
20447   EVT VT = N->getValueType(0);
20448
20449   if (N0.getOpcode() == ISD::AND &&
20450       N0.hasOneUse() &&
20451       N0.getOperand(0).hasOneUse()) {
20452     SDValue N00 = N0.getOperand(0);
20453     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20454       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20455       if (!C || C->getZExtValue() != 1)
20456         return SDValue();
20457       return DAG.getNode(ISD::AND, dl, VT,
20458                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20459                                      N00.getOperand(0), N00.getOperand(1)),
20460                          DAG.getConstant(1, VT));
20461     }
20462   }
20463
20464   if (N0.getOpcode() == ISD::TRUNCATE &&
20465       N0.hasOneUse() &&
20466       N0.getOperand(0).hasOneUse()) {
20467     SDValue N00 = N0.getOperand(0);
20468     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20469       return DAG.getNode(ISD::AND, dl, VT,
20470                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20471                                      N00.getOperand(0), N00.getOperand(1)),
20472                          DAG.getConstant(1, VT));
20473     }
20474   }
20475   if (VT.is256BitVector()) {
20476     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20477     if (R.getNode())
20478       return R;
20479   }
20480
20481   return SDValue();
20482 }
20483
20484 // Optimize x == -y --> x+y == 0
20485 //          x != -y --> x+y != 0
20486 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20487                                       const X86Subtarget* Subtarget) {
20488   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20489   SDValue LHS = N->getOperand(0);
20490   SDValue RHS = N->getOperand(1);
20491   EVT VT = N->getValueType(0);
20492   SDLoc DL(N);
20493
20494   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20495     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20496       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20497         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20498                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20499         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20500                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20501       }
20502   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20503     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20504       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20505         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20506                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20507         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20508                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20509       }
20510
20511   if (VT.getScalarType() == MVT::i1) {
20512     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20513       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20514     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20515     if (!IsSEXT0 && !IsVZero0)
20516       return SDValue();
20517     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20518       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20519     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20520
20521     if (!IsSEXT1 && !IsVZero1)
20522       return SDValue();
20523
20524     if (IsSEXT0 && IsVZero1) {
20525       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20526       if (CC == ISD::SETEQ)
20527         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20528       return LHS.getOperand(0);
20529     }
20530     if (IsSEXT1 && IsVZero0) {
20531       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20532       if (CC == ISD::SETEQ)
20533         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20534       return RHS.getOperand(0);
20535     }
20536   }
20537
20538   return SDValue();
20539 }
20540
20541 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20542                                       const X86Subtarget *Subtarget) {
20543   SDLoc dl(N);
20544   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20545   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20546          "X86insertps is only defined for v4x32");
20547
20548   SDValue Ld = N->getOperand(1);
20549   if (MayFoldLoad(Ld)) {
20550     // Extract the countS bits from the immediate so we can get the proper
20551     // address when narrowing the vector load to a specific element.
20552     // When the second source op is a memory address, interps doesn't use
20553     // countS and just gets an f32 from that address.
20554     unsigned DestIndex =
20555         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20556     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20557   } else
20558     return SDValue();
20559
20560   // Create this as a scalar to vector to match the instruction pattern.
20561   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20562   // countS bits are ignored when loading from memory on insertps, which
20563   // means we don't need to explicitly set them to 0.
20564   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20565                      LoadScalarToVector, N->getOperand(2));
20566 }
20567
20568 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20569 // as "sbb reg,reg", since it can be extended without zext and produces
20570 // an all-ones bit which is more useful than 0/1 in some cases.
20571 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20572                                MVT VT) {
20573   if (VT == MVT::i8)
20574     return DAG.getNode(ISD::AND, DL, VT,
20575                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20576                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20577                        DAG.getConstant(1, VT));
20578   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20579   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20580                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20581                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20582 }
20583
20584 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20585 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20586                                    TargetLowering::DAGCombinerInfo &DCI,
20587                                    const X86Subtarget *Subtarget) {
20588   SDLoc DL(N);
20589   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20590   SDValue EFLAGS = N->getOperand(1);
20591
20592   if (CC == X86::COND_A) {
20593     // Try to convert COND_A into COND_B in an attempt to facilitate
20594     // materializing "setb reg".
20595     //
20596     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20597     // cannot take an immediate as its first operand.
20598     //
20599     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20600         EFLAGS.getValueType().isInteger() &&
20601         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20602       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20603                                    EFLAGS.getNode()->getVTList(),
20604                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20605       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20606       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20607     }
20608   }
20609
20610   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20611   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20612   // cases.
20613   if (CC == X86::COND_B)
20614     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20615
20616   SDValue Flags;
20617
20618   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20619   if (Flags.getNode()) {
20620     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20621     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20622   }
20623
20624   return SDValue();
20625 }
20626
20627 // Optimize branch condition evaluation.
20628 //
20629 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20630                                     TargetLowering::DAGCombinerInfo &DCI,
20631                                     const X86Subtarget *Subtarget) {
20632   SDLoc DL(N);
20633   SDValue Chain = N->getOperand(0);
20634   SDValue Dest = N->getOperand(1);
20635   SDValue EFLAGS = N->getOperand(3);
20636   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20637
20638   SDValue Flags;
20639
20640   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20641   if (Flags.getNode()) {
20642     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20643     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20644                        Flags);
20645   }
20646
20647   return SDValue();
20648 }
20649
20650 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20651                                         const X86TargetLowering *XTLI) {
20652   SDValue Op0 = N->getOperand(0);
20653   EVT InVT = Op0->getValueType(0);
20654
20655   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20656   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20657     SDLoc dl(N);
20658     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20659     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20660     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20661   }
20662
20663   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20664   // a 32-bit target where SSE doesn't support i64->FP operations.
20665   if (Op0.getOpcode() == ISD::LOAD) {
20666     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20667     EVT VT = Ld->getValueType(0);
20668     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20669         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20670         !XTLI->getSubtarget()->is64Bit() &&
20671         VT == MVT::i64) {
20672       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20673                                           Ld->getChain(), Op0, DAG);
20674       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20675       return FILDChain;
20676     }
20677   }
20678   return SDValue();
20679 }
20680
20681 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20682 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20683                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20684   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20685   // the result is either zero or one (depending on the input carry bit).
20686   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20687   if (X86::isZeroNode(N->getOperand(0)) &&
20688       X86::isZeroNode(N->getOperand(1)) &&
20689       // We don't have a good way to replace an EFLAGS use, so only do this when
20690       // dead right now.
20691       SDValue(N, 1).use_empty()) {
20692     SDLoc DL(N);
20693     EVT VT = N->getValueType(0);
20694     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20695     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20696                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20697                                            DAG.getConstant(X86::COND_B,MVT::i8),
20698                                            N->getOperand(2)),
20699                                DAG.getConstant(1, VT));
20700     return DCI.CombineTo(N, Res1, CarryOut);
20701   }
20702
20703   return SDValue();
20704 }
20705
20706 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20707 //      (add Y, (setne X, 0)) -> sbb -1, Y
20708 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20709 //      (sub (setne X, 0), Y) -> adc -1, Y
20710 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20711   SDLoc DL(N);
20712
20713   // Look through ZExts.
20714   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20715   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20716     return SDValue();
20717
20718   SDValue SetCC = Ext.getOperand(0);
20719   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20720     return SDValue();
20721
20722   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20723   if (CC != X86::COND_E && CC != X86::COND_NE)
20724     return SDValue();
20725
20726   SDValue Cmp = SetCC.getOperand(1);
20727   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20728       !X86::isZeroNode(Cmp.getOperand(1)) ||
20729       !Cmp.getOperand(0).getValueType().isInteger())
20730     return SDValue();
20731
20732   SDValue CmpOp0 = Cmp.getOperand(0);
20733   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20734                                DAG.getConstant(1, CmpOp0.getValueType()));
20735
20736   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20737   if (CC == X86::COND_NE)
20738     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20739                        DL, OtherVal.getValueType(), OtherVal,
20740                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20741   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20742                      DL, OtherVal.getValueType(), OtherVal,
20743                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20744 }
20745
20746 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20747 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20748                                  const X86Subtarget *Subtarget) {
20749   EVT VT = N->getValueType(0);
20750   SDValue Op0 = N->getOperand(0);
20751   SDValue Op1 = N->getOperand(1);
20752
20753   // Try to synthesize horizontal adds from adds of shuffles.
20754   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20755        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20756       isHorizontalBinOp(Op0, Op1, true))
20757     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20758
20759   return OptimizeConditionalInDecrement(N, DAG);
20760 }
20761
20762 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20763                                  const X86Subtarget *Subtarget) {
20764   SDValue Op0 = N->getOperand(0);
20765   SDValue Op1 = N->getOperand(1);
20766
20767   // X86 can't encode an immediate LHS of a sub. See if we can push the
20768   // negation into a preceding instruction.
20769   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20770     // If the RHS of the sub is a XOR with one use and a constant, invert the
20771     // immediate. Then add one to the LHS of the sub so we can turn
20772     // X-Y -> X+~Y+1, saving one register.
20773     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20774         isa<ConstantSDNode>(Op1.getOperand(1))) {
20775       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20776       EVT VT = Op0.getValueType();
20777       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20778                                    Op1.getOperand(0),
20779                                    DAG.getConstant(~XorC, VT));
20780       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20781                          DAG.getConstant(C->getAPIntValue()+1, VT));
20782     }
20783   }
20784
20785   // Try to synthesize horizontal adds from adds of shuffles.
20786   EVT VT = N->getValueType(0);
20787   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20788        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20789       isHorizontalBinOp(Op0, Op1, true))
20790     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20791
20792   return OptimizeConditionalInDecrement(N, DAG);
20793 }
20794
20795 /// performVZEXTCombine - Performs build vector combines
20796 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20797                                         TargetLowering::DAGCombinerInfo &DCI,
20798                                         const X86Subtarget *Subtarget) {
20799   // (vzext (bitcast (vzext (x)) -> (vzext x)
20800   SDValue In = N->getOperand(0);
20801   while (In.getOpcode() == ISD::BITCAST)
20802     In = In.getOperand(0);
20803
20804   if (In.getOpcode() != X86ISD::VZEXT)
20805     return SDValue();
20806
20807   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20808                      In.getOperand(0));
20809 }
20810
20811 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20812                                              DAGCombinerInfo &DCI) const {
20813   SelectionDAG &DAG = DCI.DAG;
20814   switch (N->getOpcode()) {
20815   default: break;
20816   case ISD::EXTRACT_VECTOR_ELT:
20817     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20818   case ISD::VSELECT:
20819   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20820   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20821   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20822   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20823   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20824   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20825   case ISD::SHL:
20826   case ISD::SRA:
20827   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20828   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20829   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20830   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20831   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20832   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20833   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20834   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20835   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20836   case X86ISD::FXOR:
20837   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20838   case X86ISD::FMIN:
20839   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20840   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20841   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20842   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20843   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20844   case ISD::ANY_EXTEND:
20845   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20846   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20847   case ISD::SIGN_EXTEND_INREG:
20848     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20849   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20850   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20851   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20852   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20853   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20854   case X86ISD::SHUFP:       // Handle all target specific shuffles
20855   case X86ISD::PALIGNR:
20856   case X86ISD::UNPCKH:
20857   case X86ISD::UNPCKL:
20858   case X86ISD::MOVHLPS:
20859   case X86ISD::MOVLHPS:
20860   case X86ISD::PSHUFD:
20861   case X86ISD::PSHUFHW:
20862   case X86ISD::PSHUFLW:
20863   case X86ISD::MOVSS:
20864   case X86ISD::MOVSD:
20865   case X86ISD::VPERMILP:
20866   case X86ISD::VPERM2X128:
20867   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20868   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20869   case ISD::INTRINSIC_WO_CHAIN:
20870     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20871   case X86ISD::INSERTPS:
20872     return PerformINSERTPSCombine(N, DAG, Subtarget);
20873   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
20874   }
20875
20876   return SDValue();
20877 }
20878
20879 /// isTypeDesirableForOp - Return true if the target has native support for
20880 /// the specified value type and it is 'desirable' to use the type for the
20881 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20882 /// instruction encodings are longer and some i16 instructions are slow.
20883 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20884   if (!isTypeLegal(VT))
20885     return false;
20886   if (VT != MVT::i16)
20887     return true;
20888
20889   switch (Opc) {
20890   default:
20891     return true;
20892   case ISD::LOAD:
20893   case ISD::SIGN_EXTEND:
20894   case ISD::ZERO_EXTEND:
20895   case ISD::ANY_EXTEND:
20896   case ISD::SHL:
20897   case ISD::SRL:
20898   case ISD::SUB:
20899   case ISD::ADD:
20900   case ISD::MUL:
20901   case ISD::AND:
20902   case ISD::OR:
20903   case ISD::XOR:
20904     return false;
20905   }
20906 }
20907
20908 /// IsDesirableToPromoteOp - This method query the target whether it is
20909 /// beneficial for dag combiner to promote the specified node. If true, it
20910 /// should return the desired promotion type by reference.
20911 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20912   EVT VT = Op.getValueType();
20913   if (VT != MVT::i16)
20914     return false;
20915
20916   bool Promote = false;
20917   bool Commute = false;
20918   switch (Op.getOpcode()) {
20919   default: break;
20920   case ISD::LOAD: {
20921     LoadSDNode *LD = cast<LoadSDNode>(Op);
20922     // If the non-extending load has a single use and it's not live out, then it
20923     // might be folded.
20924     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20925                                                      Op.hasOneUse()*/) {
20926       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20927              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20928         // The only case where we'd want to promote LOAD (rather then it being
20929         // promoted as an operand is when it's only use is liveout.
20930         if (UI->getOpcode() != ISD::CopyToReg)
20931           return false;
20932       }
20933     }
20934     Promote = true;
20935     break;
20936   }
20937   case ISD::SIGN_EXTEND:
20938   case ISD::ZERO_EXTEND:
20939   case ISD::ANY_EXTEND:
20940     Promote = true;
20941     break;
20942   case ISD::SHL:
20943   case ISD::SRL: {
20944     SDValue N0 = Op.getOperand(0);
20945     // Look out for (store (shl (load), x)).
20946     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20947       return false;
20948     Promote = true;
20949     break;
20950   }
20951   case ISD::ADD:
20952   case ISD::MUL:
20953   case ISD::AND:
20954   case ISD::OR:
20955   case ISD::XOR:
20956     Commute = true;
20957     // fallthrough
20958   case ISD::SUB: {
20959     SDValue N0 = Op.getOperand(0);
20960     SDValue N1 = Op.getOperand(1);
20961     if (!Commute && MayFoldLoad(N1))
20962       return false;
20963     // Avoid disabling potential load folding opportunities.
20964     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20965       return false;
20966     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20967       return false;
20968     Promote = true;
20969   }
20970   }
20971
20972   PVT = MVT::i32;
20973   return Promote;
20974 }
20975
20976 //===----------------------------------------------------------------------===//
20977 //                           X86 Inline Assembly Support
20978 //===----------------------------------------------------------------------===//
20979
20980 namespace {
20981   // Helper to match a string separated by whitespace.
20982   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20983     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20984
20985     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20986       StringRef piece(*args[i]);
20987       if (!s.startswith(piece)) // Check if the piece matches.
20988         return false;
20989
20990       s = s.substr(piece.size());
20991       StringRef::size_type pos = s.find_first_not_of(" \t");
20992       if (pos == 0) // We matched a prefix.
20993         return false;
20994
20995       s = s.substr(pos);
20996     }
20997
20998     return s.empty();
20999   }
21000   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21001 }
21002
21003 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21004
21005   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21006     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21007         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21008         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21009
21010       if (AsmPieces.size() == 3)
21011         return true;
21012       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21013         return true;
21014     }
21015   }
21016   return false;
21017 }
21018
21019 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21020   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21021
21022   std::string AsmStr = IA->getAsmString();
21023
21024   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21025   if (!Ty || Ty->getBitWidth() % 16 != 0)
21026     return false;
21027
21028   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21029   SmallVector<StringRef, 4> AsmPieces;
21030   SplitString(AsmStr, AsmPieces, ";\n");
21031
21032   switch (AsmPieces.size()) {
21033   default: return false;
21034   case 1:
21035     // FIXME: this should verify that we are targeting a 486 or better.  If not,
21036     // we will turn this bswap into something that will be lowered to logical
21037     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
21038     // lower so don't worry about this.
21039     // bswap $0
21040     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21041         matchAsm(AsmPieces[0], "bswapl", "$0") ||
21042         matchAsm(AsmPieces[0], "bswapq", "$0") ||
21043         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21044         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21045         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21046       // No need to check constraints, nothing other than the equivalent of
21047       // "=r,0" would be valid here.
21048       return IntrinsicLowering::LowerToByteSwap(CI);
21049     }
21050
21051     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
21052     if (CI->getType()->isIntegerTy(16) &&
21053         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21054         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21055          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21056       AsmPieces.clear();
21057       const std::string &ConstraintsStr = IA->getConstraintString();
21058       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21059       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21060       if (clobbersFlagRegisters(AsmPieces))
21061         return IntrinsicLowering::LowerToByteSwap(CI);
21062     }
21063     break;
21064   case 3:
21065     if (CI->getType()->isIntegerTy(32) &&
21066         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21067         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21068         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21069         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21070       AsmPieces.clear();
21071       const std::string &ConstraintsStr = IA->getConstraintString();
21072       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21073       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21074       if (clobbersFlagRegisters(AsmPieces))
21075         return IntrinsicLowering::LowerToByteSwap(CI);
21076     }
21077
21078     if (CI->getType()->isIntegerTy(64)) {
21079       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21080       if (Constraints.size() >= 2 &&
21081           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21082           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21083         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
21084         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21085             matchAsm(AsmPieces[1], "bswap", "%edx") &&
21086             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21087           return IntrinsicLowering::LowerToByteSwap(CI);
21088       }
21089     }
21090     break;
21091   }
21092   return false;
21093 }
21094
21095 /// getConstraintType - Given a constraint letter, return the type of
21096 /// constraint it is for this target.
21097 X86TargetLowering::ConstraintType
21098 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21099   if (Constraint.size() == 1) {
21100     switch (Constraint[0]) {
21101     case 'R':
21102     case 'q':
21103     case 'Q':
21104     case 'f':
21105     case 't':
21106     case 'u':
21107     case 'y':
21108     case 'x':
21109     case 'Y':
21110     case 'l':
21111       return C_RegisterClass;
21112     case 'a':
21113     case 'b':
21114     case 'c':
21115     case 'd':
21116     case 'S':
21117     case 'D':
21118     case 'A':
21119       return C_Register;
21120     case 'I':
21121     case 'J':
21122     case 'K':
21123     case 'L':
21124     case 'M':
21125     case 'N':
21126     case 'G':
21127     case 'C':
21128     case 'e':
21129     case 'Z':
21130       return C_Other;
21131     default:
21132       break;
21133     }
21134   }
21135   return TargetLowering::getConstraintType(Constraint);
21136 }
21137
21138 /// Examine constraint type and operand type and determine a weight value.
21139 /// This object must already have been set up with the operand type
21140 /// and the current alternative constraint selected.
21141 TargetLowering::ConstraintWeight
21142   X86TargetLowering::getSingleConstraintMatchWeight(
21143     AsmOperandInfo &info, const char *constraint) const {
21144   ConstraintWeight weight = CW_Invalid;
21145   Value *CallOperandVal = info.CallOperandVal;
21146     // If we don't have a value, we can't do a match,
21147     // but allow it at the lowest weight.
21148   if (!CallOperandVal)
21149     return CW_Default;
21150   Type *type = CallOperandVal->getType();
21151   // Look at the constraint type.
21152   switch (*constraint) {
21153   default:
21154     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21155   case 'R':
21156   case 'q':
21157   case 'Q':
21158   case 'a':
21159   case 'b':
21160   case 'c':
21161   case 'd':
21162   case 'S':
21163   case 'D':
21164   case 'A':
21165     if (CallOperandVal->getType()->isIntegerTy())
21166       weight = CW_SpecificReg;
21167     break;
21168   case 'f':
21169   case 't':
21170   case 'u':
21171     if (type->isFloatingPointTy())
21172       weight = CW_SpecificReg;
21173     break;
21174   case 'y':
21175     if (type->isX86_MMXTy() && Subtarget->hasMMX())
21176       weight = CW_SpecificReg;
21177     break;
21178   case 'x':
21179   case 'Y':
21180     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21181         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21182       weight = CW_Register;
21183     break;
21184   case 'I':
21185     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21186       if (C->getZExtValue() <= 31)
21187         weight = CW_Constant;
21188     }
21189     break;
21190   case 'J':
21191     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21192       if (C->getZExtValue() <= 63)
21193         weight = CW_Constant;
21194     }
21195     break;
21196   case 'K':
21197     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21198       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21199         weight = CW_Constant;
21200     }
21201     break;
21202   case 'L':
21203     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21204       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21205         weight = CW_Constant;
21206     }
21207     break;
21208   case 'M':
21209     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21210       if (C->getZExtValue() <= 3)
21211         weight = CW_Constant;
21212     }
21213     break;
21214   case 'N':
21215     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21216       if (C->getZExtValue() <= 0xff)
21217         weight = CW_Constant;
21218     }
21219     break;
21220   case 'G':
21221   case 'C':
21222     if (dyn_cast<ConstantFP>(CallOperandVal)) {
21223       weight = CW_Constant;
21224     }
21225     break;
21226   case 'e':
21227     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21228       if ((C->getSExtValue() >= -0x80000000LL) &&
21229           (C->getSExtValue() <= 0x7fffffffLL))
21230         weight = CW_Constant;
21231     }
21232     break;
21233   case 'Z':
21234     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21235       if (C->getZExtValue() <= 0xffffffff)
21236         weight = CW_Constant;
21237     }
21238     break;
21239   }
21240   return weight;
21241 }
21242
21243 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21244 /// with another that has more specific requirements based on the type of the
21245 /// corresponding operand.
21246 const char *X86TargetLowering::
21247 LowerXConstraint(EVT ConstraintVT) const {
21248   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21249   // 'f' like normal targets.
21250   if (ConstraintVT.isFloatingPoint()) {
21251     if (Subtarget->hasSSE2())
21252       return "Y";
21253     if (Subtarget->hasSSE1())
21254       return "x";
21255   }
21256
21257   return TargetLowering::LowerXConstraint(ConstraintVT);
21258 }
21259
21260 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21261 /// vector.  If it is invalid, don't add anything to Ops.
21262 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21263                                                      std::string &Constraint,
21264                                                      std::vector<SDValue>&Ops,
21265                                                      SelectionDAG &DAG) const {
21266   SDValue Result;
21267
21268   // Only support length 1 constraints for now.
21269   if (Constraint.length() > 1) return;
21270
21271   char ConstraintLetter = Constraint[0];
21272   switch (ConstraintLetter) {
21273   default: break;
21274   case 'I':
21275     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21276       if (C->getZExtValue() <= 31) {
21277         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21278         break;
21279       }
21280     }
21281     return;
21282   case 'J':
21283     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21284       if (C->getZExtValue() <= 63) {
21285         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21286         break;
21287       }
21288     }
21289     return;
21290   case 'K':
21291     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21292       if (isInt<8>(C->getSExtValue())) {
21293         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21294         break;
21295       }
21296     }
21297     return;
21298   case 'N':
21299     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21300       if (C->getZExtValue() <= 255) {
21301         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21302         break;
21303       }
21304     }
21305     return;
21306   case 'e': {
21307     // 32-bit signed value
21308     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21309       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21310                                            C->getSExtValue())) {
21311         // Widen to 64 bits here to get it sign extended.
21312         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21313         break;
21314       }
21315     // FIXME gcc accepts some relocatable values here too, but only in certain
21316     // memory models; it's complicated.
21317     }
21318     return;
21319   }
21320   case 'Z': {
21321     // 32-bit unsigned value
21322     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21323       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21324                                            C->getZExtValue())) {
21325         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21326         break;
21327       }
21328     }
21329     // FIXME gcc accepts some relocatable values here too, but only in certain
21330     // memory models; it's complicated.
21331     return;
21332   }
21333   case 'i': {
21334     // Literal immediates are always ok.
21335     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21336       // Widen to 64 bits here to get it sign extended.
21337       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21338       break;
21339     }
21340
21341     // In any sort of PIC mode addresses need to be computed at runtime by
21342     // adding in a register or some sort of table lookup.  These can't
21343     // be used as immediates.
21344     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21345       return;
21346
21347     // If we are in non-pic codegen mode, we allow the address of a global (with
21348     // an optional displacement) to be used with 'i'.
21349     GlobalAddressSDNode *GA = nullptr;
21350     int64_t Offset = 0;
21351
21352     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21353     while (1) {
21354       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21355         Offset += GA->getOffset();
21356         break;
21357       } else if (Op.getOpcode() == ISD::ADD) {
21358         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21359           Offset += C->getZExtValue();
21360           Op = Op.getOperand(0);
21361           continue;
21362         }
21363       } else if (Op.getOpcode() == ISD::SUB) {
21364         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21365           Offset += -C->getZExtValue();
21366           Op = Op.getOperand(0);
21367           continue;
21368         }
21369       }
21370
21371       // Otherwise, this isn't something we can handle, reject it.
21372       return;
21373     }
21374
21375     const GlobalValue *GV = GA->getGlobal();
21376     // If we require an extra load to get this address, as in PIC mode, we
21377     // can't accept it.
21378     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21379                                                         getTargetMachine())))
21380       return;
21381
21382     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21383                                         GA->getValueType(0), Offset);
21384     break;
21385   }
21386   }
21387
21388   if (Result.getNode()) {
21389     Ops.push_back(Result);
21390     return;
21391   }
21392   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21393 }
21394
21395 std::pair<unsigned, const TargetRegisterClass*>
21396 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21397                                                 MVT VT) const {
21398   // First, see if this is a constraint that directly corresponds to an LLVM
21399   // register class.
21400   if (Constraint.size() == 1) {
21401     // GCC Constraint Letters
21402     switch (Constraint[0]) {
21403     default: break;
21404       // TODO: Slight differences here in allocation order and leaving
21405       // RIP in the class. Do they matter any more here than they do
21406       // in the normal allocation?
21407     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21408       if (Subtarget->is64Bit()) {
21409         if (VT == MVT::i32 || VT == MVT::f32)
21410           return std::make_pair(0U, &X86::GR32RegClass);
21411         if (VT == MVT::i16)
21412           return std::make_pair(0U, &X86::GR16RegClass);
21413         if (VT == MVT::i8 || VT == MVT::i1)
21414           return std::make_pair(0U, &X86::GR8RegClass);
21415         if (VT == MVT::i64 || VT == MVT::f64)
21416           return std::make_pair(0U, &X86::GR64RegClass);
21417         break;
21418       }
21419       // 32-bit fallthrough
21420     case 'Q':   // Q_REGS
21421       if (VT == MVT::i32 || VT == MVT::f32)
21422         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21423       if (VT == MVT::i16)
21424         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21425       if (VT == MVT::i8 || VT == MVT::i1)
21426         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21427       if (VT == MVT::i64)
21428         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21429       break;
21430     case 'r':   // GENERAL_REGS
21431     case 'l':   // INDEX_REGS
21432       if (VT == MVT::i8 || VT == MVT::i1)
21433         return std::make_pair(0U, &X86::GR8RegClass);
21434       if (VT == MVT::i16)
21435         return std::make_pair(0U, &X86::GR16RegClass);
21436       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21437         return std::make_pair(0U, &X86::GR32RegClass);
21438       return std::make_pair(0U, &X86::GR64RegClass);
21439     case 'R':   // LEGACY_REGS
21440       if (VT == MVT::i8 || VT == MVT::i1)
21441         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21442       if (VT == MVT::i16)
21443         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21444       if (VT == MVT::i32 || !Subtarget->is64Bit())
21445         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21446       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21447     case 'f':  // FP Stack registers.
21448       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21449       // value to the correct fpstack register class.
21450       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21451         return std::make_pair(0U, &X86::RFP32RegClass);
21452       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21453         return std::make_pair(0U, &X86::RFP64RegClass);
21454       return std::make_pair(0U, &X86::RFP80RegClass);
21455     case 'y':   // MMX_REGS if MMX allowed.
21456       if (!Subtarget->hasMMX()) break;
21457       return std::make_pair(0U, &X86::VR64RegClass);
21458     case 'Y':   // SSE_REGS if SSE2 allowed
21459       if (!Subtarget->hasSSE2()) break;
21460       // FALL THROUGH.
21461     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21462       if (!Subtarget->hasSSE1()) break;
21463
21464       switch (VT.SimpleTy) {
21465       default: break;
21466       // Scalar SSE types.
21467       case MVT::f32:
21468       case MVT::i32:
21469         return std::make_pair(0U, &X86::FR32RegClass);
21470       case MVT::f64:
21471       case MVT::i64:
21472         return std::make_pair(0U, &X86::FR64RegClass);
21473       // Vector types.
21474       case MVT::v16i8:
21475       case MVT::v8i16:
21476       case MVT::v4i32:
21477       case MVT::v2i64:
21478       case MVT::v4f32:
21479       case MVT::v2f64:
21480         return std::make_pair(0U, &X86::VR128RegClass);
21481       // AVX types.
21482       case MVT::v32i8:
21483       case MVT::v16i16:
21484       case MVT::v8i32:
21485       case MVT::v4i64:
21486       case MVT::v8f32:
21487       case MVT::v4f64:
21488         return std::make_pair(0U, &X86::VR256RegClass);
21489       case MVT::v8f64:
21490       case MVT::v16f32:
21491       case MVT::v16i32:
21492       case MVT::v8i64:
21493         return std::make_pair(0U, &X86::VR512RegClass);
21494       }
21495       break;
21496     }
21497   }
21498
21499   // Use the default implementation in TargetLowering to convert the register
21500   // constraint into a member of a register class.
21501   std::pair<unsigned, const TargetRegisterClass*> Res;
21502   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21503
21504   // Not found as a standard register?
21505   if (!Res.second) {
21506     // Map st(0) -> st(7) -> ST0
21507     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21508         tolower(Constraint[1]) == 's' &&
21509         tolower(Constraint[2]) == 't' &&
21510         Constraint[3] == '(' &&
21511         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21512         Constraint[5] == ')' &&
21513         Constraint[6] == '}') {
21514
21515       Res.first = X86::ST0+Constraint[4]-'0';
21516       Res.second = &X86::RFP80RegClass;
21517       return Res;
21518     }
21519
21520     // GCC allows "st(0)" to be called just plain "st".
21521     if (StringRef("{st}").equals_lower(Constraint)) {
21522       Res.first = X86::ST0;
21523       Res.second = &X86::RFP80RegClass;
21524       return Res;
21525     }
21526
21527     // flags -> EFLAGS
21528     if (StringRef("{flags}").equals_lower(Constraint)) {
21529       Res.first = X86::EFLAGS;
21530       Res.second = &X86::CCRRegClass;
21531       return Res;
21532     }
21533
21534     // 'A' means EAX + EDX.
21535     if (Constraint == "A") {
21536       Res.first = X86::EAX;
21537       Res.second = &X86::GR32_ADRegClass;
21538       return Res;
21539     }
21540     return Res;
21541   }
21542
21543   // Otherwise, check to see if this is a register class of the wrong value
21544   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21545   // turn into {ax},{dx}.
21546   if (Res.second->hasType(VT))
21547     return Res;   // Correct type already, nothing to do.
21548
21549   // All of the single-register GCC register classes map their values onto
21550   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21551   // really want an 8-bit or 32-bit register, map to the appropriate register
21552   // class and return the appropriate register.
21553   if (Res.second == &X86::GR16RegClass) {
21554     if (VT == MVT::i8 || VT == MVT::i1) {
21555       unsigned DestReg = 0;
21556       switch (Res.first) {
21557       default: break;
21558       case X86::AX: DestReg = X86::AL; break;
21559       case X86::DX: DestReg = X86::DL; break;
21560       case X86::CX: DestReg = X86::CL; break;
21561       case X86::BX: DestReg = X86::BL; break;
21562       }
21563       if (DestReg) {
21564         Res.first = DestReg;
21565         Res.second = &X86::GR8RegClass;
21566       }
21567     } else if (VT == MVT::i32 || VT == MVT::f32) {
21568       unsigned DestReg = 0;
21569       switch (Res.first) {
21570       default: break;
21571       case X86::AX: DestReg = X86::EAX; break;
21572       case X86::DX: DestReg = X86::EDX; break;
21573       case X86::CX: DestReg = X86::ECX; break;
21574       case X86::BX: DestReg = X86::EBX; break;
21575       case X86::SI: DestReg = X86::ESI; break;
21576       case X86::DI: DestReg = X86::EDI; break;
21577       case X86::BP: DestReg = X86::EBP; break;
21578       case X86::SP: DestReg = X86::ESP; break;
21579       }
21580       if (DestReg) {
21581         Res.first = DestReg;
21582         Res.second = &X86::GR32RegClass;
21583       }
21584     } else if (VT == MVT::i64 || VT == MVT::f64) {
21585       unsigned DestReg = 0;
21586       switch (Res.first) {
21587       default: break;
21588       case X86::AX: DestReg = X86::RAX; break;
21589       case X86::DX: DestReg = X86::RDX; break;
21590       case X86::CX: DestReg = X86::RCX; break;
21591       case X86::BX: DestReg = X86::RBX; break;
21592       case X86::SI: DestReg = X86::RSI; break;
21593       case X86::DI: DestReg = X86::RDI; break;
21594       case X86::BP: DestReg = X86::RBP; break;
21595       case X86::SP: DestReg = X86::RSP; break;
21596       }
21597       if (DestReg) {
21598         Res.first = DestReg;
21599         Res.second = &X86::GR64RegClass;
21600       }
21601     }
21602   } else if (Res.second == &X86::FR32RegClass ||
21603              Res.second == &X86::FR64RegClass ||
21604              Res.second == &X86::VR128RegClass ||
21605              Res.second == &X86::VR256RegClass ||
21606              Res.second == &X86::FR32XRegClass ||
21607              Res.second == &X86::FR64XRegClass ||
21608              Res.second == &X86::VR128XRegClass ||
21609              Res.second == &X86::VR256XRegClass ||
21610              Res.second == &X86::VR512RegClass) {
21611     // Handle references to XMM physical registers that got mapped into the
21612     // wrong class.  This can happen with constraints like {xmm0} where the
21613     // target independent register mapper will just pick the first match it can
21614     // find, ignoring the required type.
21615
21616     if (VT == MVT::f32 || VT == MVT::i32)
21617       Res.second = &X86::FR32RegClass;
21618     else if (VT == MVT::f64 || VT == MVT::i64)
21619       Res.second = &X86::FR64RegClass;
21620     else if (X86::VR128RegClass.hasType(VT))
21621       Res.second = &X86::VR128RegClass;
21622     else if (X86::VR256RegClass.hasType(VT))
21623       Res.second = &X86::VR256RegClass;
21624     else if (X86::VR512RegClass.hasType(VT))
21625       Res.second = &X86::VR512RegClass;
21626   }
21627
21628   return Res;
21629 }
21630
21631 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21632                                             Type *Ty) const {
21633   // Scaling factors are not free at all.
21634   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21635   // will take 2 allocations in the out of order engine instead of 1
21636   // for plain addressing mode, i.e. inst (reg1).
21637   // E.g.,
21638   // vaddps (%rsi,%drx), %ymm0, %ymm1
21639   // Requires two allocations (one for the load, one for the computation)
21640   // whereas:
21641   // vaddps (%rsi), %ymm0, %ymm1
21642   // Requires just 1 allocation, i.e., freeing allocations for other operations
21643   // and having less micro operations to execute.
21644   //
21645   // For some X86 architectures, this is even worse because for instance for
21646   // stores, the complex addressing mode forces the instruction to use the
21647   // "load" ports instead of the dedicated "store" port.
21648   // E.g., on Haswell:
21649   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21650   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21651   if (isLegalAddressingMode(AM, Ty))
21652     // Scale represents reg2 * scale, thus account for 1
21653     // as soon as we use a second register.
21654     return AM.Scale != 0;
21655   return -1;
21656 }
21657
21658 bool X86TargetLowering::isTargetFTOL() const {
21659   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
21660 }