[x86] Fix a miscompile in the new shuffle lowering found through the new
[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/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     // We support custom legalizing of sext and anyext loads for specific
1015     // memory vector types which we can load as a scalar (or sequence of
1016     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017     // loads these must work with a single scalar load.
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019     if (Subtarget->is64Bit()) {
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1022     }
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1034     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036
1037     if (Subtarget->is64Bit()) {
1038       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1039       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040     }
1041
1042     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044       MVT VT = (MVT::SimpleValueType)i;
1045
1046       // Do not attempt to promote non-128-bit vectors
1047       if (!VT.is128BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    VT, Promote);
1051       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1052       setOperationAction(ISD::OR,     VT, Promote);
1053       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1054       setOperationAction(ISD::XOR,    VT, Promote);
1055       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1056       setOperationAction(ISD::LOAD,   VT, Promote);
1057       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1058       setOperationAction(ISD::SELECT, VT, Promote);
1059       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060     }
1061
1062     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1063
1064     // Custom lower v2i64 and v2f64 selects.
1065     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1066     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1067     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1068     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1069
1070     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1072
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1075     // As there is no 64-bit GPR available, we need build a special custom
1076     // sequence to convert from v2i32 to v2f32.
1077     if (!Subtarget->is64Bit())
1078       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1079
1080     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1082
1083     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1084
1085     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1087     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1088   }
1089
1090   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1094     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1099     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1101
1102     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1105     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1106     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1107     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1110     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1111     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1112
1113     // FIXME: Do we need to handle scalar-to-vector here?
1114     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1115
1116     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1120     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1121     // There is no BLENDI for byte vectors. We don't need to custom lower
1122     // some vselects for now.
1123     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1124
1125     // SSE41 brings specific instructions for doing vector sign extend even in
1126     // cases where we don't have SRA.
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1130
1131     // i8 and i16 vectors are custom , because the source register and source
1132     // source memory operand types are not the same width.  f32 vectors are
1133     // custom since the immediate controlling the insert encodes additional
1134     // information.
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1139
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1144
1145     // FIXME: these should be Legal but thats only for the case where
1146     // the index is constant.  For now custom expand to deal with that.
1147     if (Subtarget->is64Bit()) {
1148       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1150     }
1151   }
1152
1153   if (Subtarget->hasSSE2()) {
1154     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1155     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1156
1157     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1158     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1159
1160     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1161     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1162
1163     // In the customized shift lowering, the legal cases in AVX2 will be
1164     // recognized.
1165     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1172   }
1173
1174   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1181
1182     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1184     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1185
1186     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1194     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1196     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1197     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1198
1199     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1207     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1209     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1210     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1211
1212     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213     // even though v8i16 is a legal type.
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1216     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1217
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1219     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1220     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1221
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1223     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1224
1225     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1226
1227     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1228     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1229
1230     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1231     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1232
1233     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1234     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1235
1236     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1239     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1240
1241     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1243     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1244
1245     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1248     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1249
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1252     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1255     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1258     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1261     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1262
1263     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1269       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1270     }
1271
1272     if (Subtarget->hasInt256()) {
1273       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1276       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1277
1278       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1281       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1282
1283       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1284       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1285       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1286       // Don't lower v32i8 because there is no 128-bit byte mul
1287
1288       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1290       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1291       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1292
1293       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1294       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1295     } else {
1296       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1299       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1300
1301       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1304       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1305
1306       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1309       // Don't lower v32i8 because there is no 128-bit byte mul
1310     }
1311
1312     // In the customized shift lowering, the legal cases in AVX2 will be
1313     // recognized.
1314     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1315     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1316
1317     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1318     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1319
1320     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1321
1322     // Custom lower several nodes for 256-bit types.
1323     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Extract subvector is special because the value type
1328       // (result) is 128-bit but the source is 256-bit wide.
1329       if (VT.is128BitVector())
1330         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1331
1332       // Do not attempt to custom lower other non-256-bit vectors
1333       if (!VT.is256BitVector())
1334         continue;
1335
1336       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1337       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1338       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1339       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1341       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1342       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1343     }
1344
1345     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347       MVT VT = (MVT::SimpleValueType)i;
1348
1349       // Do not attempt to promote non-256-bit vectors
1350       if (!VT.is256BitVector())
1351         continue;
1352
1353       setOperationAction(ISD::AND,    VT, Promote);
1354       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1355       setOperationAction(ISD::OR,     VT, Promote);
1356       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1357       setOperationAction(ISD::XOR,    VT, Promote);
1358       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1359       setOperationAction(ISD::LOAD,   VT, Promote);
1360       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1361       setOperationAction(ISD::SELECT, VT, Promote);
1362       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1363     }
1364   }
1365
1366   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1370     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1371
1372     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1373     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1374     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1375
1376     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1377     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1378     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1379     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1380     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1381     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1386     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1392     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1393     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1394
1395     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1399     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1400     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1401     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1402     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1403
1404     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1406     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1407     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1408     if (Subtarget->is64Bit()) {
1409       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1411       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1412       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1413     }
1414     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1422     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1423     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1424
1425     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460
1461     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1470     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1471
1472     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1473     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1474
1475     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1476     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1477
1478     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1480     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1482     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1483     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1484
1485     if (Subtarget->hasCDI()) {
1486       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1487       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1488     }
1489
1490     // Custom lower several nodes.
1491     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493       MVT VT = (MVT::SimpleValueType)i;
1494
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       // Extract subvector is special because the value type
1497       // (result) is 256/128-bit but the source is 512-bit wide.
1498       if (VT.is128BitVector() || VT.is256BitVector())
1499         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1500
1501       if (VT.getVectorElementType() == MVT::i1)
1502         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1503
1504       // Do not attempt to custom lower other non-512-bit vectors
1505       if (!VT.is512BitVector())
1506         continue;
1507
1508       if ( EltSize >= 32) {
1509         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1510         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1511         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1512         setOperationAction(ISD::VSELECT,             VT, Legal);
1513         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1514         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1515         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1516       }
1517     }
1518     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519       MVT VT = (MVT::SimpleValueType)i;
1520
1521       // Do not attempt to promote non-256-bit vectors
1522       if (!VT.is512BitVector())
1523         continue;
1524
1525       setOperationAction(ISD::SELECT, VT, Promote);
1526       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1527     }
1528   }// has  AVX-512
1529
1530   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1532     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1533   }
1534
1535   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536   // of this type with custom code.
1537   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1540                        Custom);
1541   }
1542
1543   // We want to custom lower some of our intrinsics.
1544   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547   if (!Subtarget->is64Bit())
1548     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1549
1550   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551   // handle type legalization for these operations here.
1552   //
1553   // FIXME: We really should do custom legalization for addition and
1554   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1555   // than generic legalization for 64-bit multiplication-with-overflow, though.
1556   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557     // Add/Sub/Mul with overflow operations are custom lowered.
1558     MVT VT = IntVTs[i];
1559     setOperationAction(ISD::SADDO, VT, Custom);
1560     setOperationAction(ISD::UADDO, VT, Custom);
1561     setOperationAction(ISD::SSUBO, VT, Custom);
1562     setOperationAction(ISD::USUBO, VT, Custom);
1563     setOperationAction(ISD::SMULO, VT, Custom);
1564     setOperationAction(ISD::UMULO, VT, Custom);
1565   }
1566
1567   // There are no 8-bit 3-address imul/mul instructions
1568   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1570
1571   if (!Subtarget->is64Bit()) {
1572     // These libcalls are not available in 32-bit.
1573     setLibcallName(RTLIB::SHL_I128, nullptr);
1574     setLibcallName(RTLIB::SRL_I128, nullptr);
1575     setLibcallName(RTLIB::SRA_I128, nullptr);
1576   }
1577
1578   // Combine sin / cos into one node or libcall if possible.
1579   if (Subtarget->hasSinCos()) {
1580     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582     if (Subtarget->isTargetDarwin()) {
1583       // For MacOSX, we don't want to the normal expansion of a libcall to
1584       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1585       // traffic.
1586       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1588     }
1589   }
1590
1591   if (Subtarget->isTargetWin64()) {
1592     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::SREM, MVT::i128, Custom);
1595     setOperationAction(ISD::UREM, MVT::i128, Custom);
1596     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1598   }
1599
1600   // We have target-specific dag combine patterns for the following nodes:
1601   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603   setTargetDAGCombine(ISD::VSELECT);
1604   setTargetDAGCombine(ISD::SELECT);
1605   setTargetDAGCombine(ISD::SHL);
1606   setTargetDAGCombine(ISD::SRA);
1607   setTargetDAGCombine(ISD::SRL);
1608   setTargetDAGCombine(ISD::OR);
1609   setTargetDAGCombine(ISD::AND);
1610   setTargetDAGCombine(ISD::ADD);
1611   setTargetDAGCombine(ISD::FADD);
1612   setTargetDAGCombine(ISD::FSUB);
1613   setTargetDAGCombine(ISD::FMA);
1614   setTargetDAGCombine(ISD::SUB);
1615   setTargetDAGCombine(ISD::LOAD);
1616   setTargetDAGCombine(ISD::STORE);
1617   setTargetDAGCombine(ISD::ZERO_EXTEND);
1618   setTargetDAGCombine(ISD::ANY_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND);
1620   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621   setTargetDAGCombine(ISD::TRUNCATE);
1622   setTargetDAGCombine(ISD::SINT_TO_FP);
1623   setTargetDAGCombine(ISD::SETCC);
1624   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625   setTargetDAGCombine(ISD::BUILD_VECTOR);
1626   if (Subtarget->is64Bit())
1627     setTargetDAGCombine(ISD::MUL);
1628   setTargetDAGCombine(ISD::XOR);
1629
1630   computeRegisterProperties();
1631
1632   // On Darwin, -Os means optimize for size without hurting performance,
1633   // do not reduce the limit.
1634   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   setPrefLoopAlignment(4); // 2^4 bytes.
1641
1642   // Predictable cmov don't hurt on atom because it's in-order.
1643   PredictableSelectIsExpensive = !Subtarget->isAtom();
1644
1645   setPrefFunctionAlignment(4); // 2^4 bytes.
1646 }
1647
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651          Subtarget->is64Bit();
1652 }
1653
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656   if (ExperimentalVectorWideningLegalization &&
1657       VT.getVectorNumElements() != 1 &&
1658       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659     return TypeWidenVector;
1660
1661   return TargetLoweringBase::getPreferredVectorAction(VT);
1662 }
1663
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1665   if (!VT.isVector())
1666     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1667
1668   if (Subtarget->hasAVX512())
1669     switch(VT.getVectorNumElements()) {
1670     case  8: return MVT::v8i1;
1671     case 16: return MVT::v16i1;
1672   }
1673
1674   return VT.changeVectorElementTypeToInteger();
1675 }
1676
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1680   if (MaxAlign == 16)
1681     return;
1682   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683     if (VTy->getBitWidth() == 128)
1684       MaxAlign = 16;
1685   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686     unsigned EltAlign = 0;
1687     getMaxByValAlign(ATy->getElementType(), EltAlign);
1688     if (EltAlign > MaxAlign)
1689       MaxAlign = EltAlign;
1690   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692       unsigned EltAlign = 0;
1693       getMaxByValAlign(STy->getElementType(i), EltAlign);
1694       if (EltAlign > MaxAlign)
1695         MaxAlign = EltAlign;
1696       if (MaxAlign == 16)
1697         break;
1698     }
1699   }
1700 }
1701
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707   if (Subtarget->is64Bit()) {
1708     // Max of 8 and alignment of type.
1709     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1710     if (TyAlign > 8)
1711       return TyAlign;
1712     return 8;
1713   }
1714
1715   unsigned Align = 4;
1716   if (Subtarget->hasSSE1())
1717     getMaxByValAlign(Ty, Align);
1718   return Align;
1719 }
1720
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1732 EVT
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734                                        unsigned DstAlign, unsigned SrcAlign,
1735                                        bool IsMemset, bool ZeroMemset,
1736                                        bool MemcpyStrSrc,
1737                                        MachineFunction &MF) const {
1738   const Function *F = MF.getFunction();
1739   if ((!IsMemset || ZeroMemset) &&
1740       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741                                        Attribute::NoImplicitFloat)) {
1742     if (Size >= 16 &&
1743         (Subtarget->isUnalignedMemAccessFast() ||
1744          ((DstAlign == 0 || DstAlign >= 16) &&
1745           (SrcAlign == 0 || SrcAlign >= 16)))) {
1746       if (Size >= 32) {
1747         if (Subtarget->hasInt256())
1748           return MVT::v8i32;
1749         if (Subtarget->hasFp256())
1750           return MVT::v8f32;
1751       }
1752       if (Subtarget->hasSSE2())
1753         return MVT::v4i32;
1754       if (Subtarget->hasSSE1())
1755         return MVT::v4f32;
1756     } else if (!MemcpyStrSrc && Size >= 8 &&
1757                !Subtarget->is64Bit() &&
1758                Subtarget->hasSSE2()) {
1759       // Do not use f64 to lower memcpy if source is string constant. It's
1760       // better to use i32 to avoid the loads.
1761       return MVT::f64;
1762     }
1763   }
1764   if (Subtarget->is64Bit() && Size >= 8)
1765     return MVT::i64;
1766   return MVT::i32;
1767 }
1768
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1770   if (VT == MVT::f32)
1771     return X86ScalarSSEf32;
1772   else if (VT == MVT::f64)
1773     return X86ScalarSSEf64;
1774   return true;
1775 }
1776
1777 bool
1778 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1779                                                   unsigned,
1780                                                   unsigned,
1781                                                   bool *Fast) const {
1782   if (Fast)
1783     *Fast = Subtarget->isUnalignedMemAccessFast();
1784   return true;
1785 }
1786
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function.  The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1792   // symbol.
1793   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794       Subtarget->isPICStyleGOT())
1795     return MachineJumpTableInfo::EK_Custom32;
1796
1797   // Otherwise, use the normal jump table encoding heuristics.
1798   return TargetLowering::getJumpTableEncoding();
1799 }
1800
1801 const MCExpr *
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803                                              const MachineBasicBlock *MBB,
1804                                              unsigned uid,MCContext &Ctx) const{
1805   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806          Subtarget->isPICStyleGOT());
1807   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1808   // entries.
1809   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1811 }
1812
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1814 /// jumptable.
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816                                                     SelectionDAG &DAG) const {
1817   if (!Subtarget->is64Bit())
1818     // This doesn't have SDLoc associated with it, but is not really the
1819     // same as a Register.
1820     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1821   return Table;
1822 }
1823
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1826 /// MCExpr.
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829                              MCContext &Ctx) const {
1830   // X86-64 uses RIP relative addressing based on the jump table label.
1831   if (Subtarget->isPICStyleRIPRel())
1832     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833
1834   // Otherwise, the reference is relative to the PIC base.
1835   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1836 }
1837
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841   const TargetRegisterClass *RRC = nullptr;
1842   uint8_t Cost = 1;
1843   switch (VT.SimpleTy) {
1844   default:
1845     return TargetLowering::findRepresentativeClass(VT);
1846   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847     RRC = Subtarget->is64Bit() ?
1848       (const TargetRegisterClass*)&X86::GR64RegClass :
1849       (const TargetRegisterClass*)&X86::GR32RegClass;
1850     break;
1851   case MVT::x86mmx:
1852     RRC = &X86::VR64RegClass;
1853     break;
1854   case MVT::f32: case MVT::f64:
1855   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856   case MVT::v4f32: case MVT::v2f64:
1857   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1858   case MVT::v4f64:
1859     RRC = &X86::VR128RegClass;
1860     break;
1861   }
1862   return std::make_pair(RRC, Cost);
1863 }
1864
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866                                                unsigned &Offset) const {
1867   if (!Subtarget->isTargetLinux())
1868     return false;
1869
1870   if (Subtarget->is64Bit()) {
1871     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1872     Offset = 0x28;
1873     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1874       AddressSpace = 256;
1875     else
1876       AddressSpace = 257;
1877   } else {
1878     // %gs:0x14 on i386
1879     Offset = 0x14;
1880     AddressSpace = 256;
1881   }
1882   return true;
1883 }
1884
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886                                             unsigned DestAS) const {
1887   assert(SrcAS != DestAS && "Expected different address spaces!");
1888
1889   return SrcAS < 256 && DestAS < 256;
1890 }
1891
1892 //===----------------------------------------------------------------------===//
1893 //               Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1895
1896 #include "X86GenCallingConv.inc"
1897
1898 bool
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900                                   MachineFunction &MF, bool isVarArg,
1901                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1902                         LLVMContext &Context) const {
1903   SmallVector<CCValAssign, 16> RVLocs;
1904   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1905   return CCInfo.CheckReturn(Outs, RetCC_X86);
1906 }
1907
1908 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1909   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1910   return ScratchRegs;
1911 }
1912
1913 SDValue
1914 X86TargetLowering::LowerReturn(SDValue Chain,
1915                                CallingConv::ID CallConv, bool isVarArg,
1916                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1917                                const SmallVectorImpl<SDValue> &OutVals,
1918                                SDLoc dl, SelectionDAG &DAG) const {
1919   MachineFunction &MF = DAG.getMachineFunction();
1920   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1921
1922   SmallVector<CCValAssign, 16> RVLocs;
1923   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1924   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1925
1926   SDValue Flag;
1927   SmallVector<SDValue, 6> RetOps;
1928   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1929   // Operand #1 = Bytes To Pop
1930   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1931                    MVT::i16));
1932
1933   // Copy the result values into the output registers.
1934   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1935     CCValAssign &VA = RVLocs[i];
1936     assert(VA.isRegLoc() && "Can only return in registers!");
1937     SDValue ValToCopy = OutVals[i];
1938     EVT ValVT = ValToCopy.getValueType();
1939
1940     // Promote values to the appropriate types
1941     if (VA.getLocInfo() == CCValAssign::SExt)
1942       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1943     else if (VA.getLocInfo() == CCValAssign::ZExt)
1944       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945     else if (VA.getLocInfo() == CCValAssign::AExt)
1946       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::BCvt)
1948       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1949
1950     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1951            "Unexpected FP-extend for return value.");  
1952
1953     // If this is x86-64, and we disabled SSE, we can't return FP values,
1954     // or SSE or MMX vectors.
1955     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1956          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1957           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1958       report_fatal_error("SSE register return with SSE disabled");
1959     }
1960     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1961     // llvm-gcc has never done it right and no one has noticed, so this
1962     // should be OK for now.
1963     if (ValVT == MVT::f64 &&
1964         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1965       report_fatal_error("SSE2 register return with SSE2 disabled");
1966
1967     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1968     // the RET instruction and handled by the FP Stackifier.
1969     if (VA.getLocReg() == X86::FP0 ||
1970         VA.getLocReg() == X86::FP1) {
1971       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1972       // change the value to the FP stack register class.
1973       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1974         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1975       RetOps.push_back(ValToCopy);
1976       // Don't emit a copytoreg.
1977       continue;
1978     }
1979
1980     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1981     // which is returned in RAX / RDX.
1982     if (Subtarget->is64Bit()) {
1983       if (ValVT == MVT::x86mmx) {
1984         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1985           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1986           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1987                                   ValToCopy);
1988           // If we don't have SSE2 available, convert to v4f32 so the generated
1989           // register is legal.
1990           if (!Subtarget->hasSSE2())
1991             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1992         }
1993       }
1994     }
1995
1996     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1997     Flag = Chain.getValue(1);
1998     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1999   }
2000
2001   // The x86-64 ABIs require that for returning structs by value we copy
2002   // the sret argument into %rax/%eax (depending on ABI) for the return.
2003   // Win32 requires us to put the sret argument to %eax as well.
2004   // We saved the argument into a virtual register in the entry block,
2005   // so now we copy the value out and into %rax/%eax.
2006   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2007       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2008     MachineFunction &MF = DAG.getMachineFunction();
2009     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2010     unsigned Reg = FuncInfo->getSRetReturnReg();
2011     assert(Reg &&
2012            "SRetReturnReg should have been set in LowerFormalArguments().");
2013     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2014
2015     unsigned RetValReg
2016         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2017           X86::RAX : X86::EAX;
2018     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2019     Flag = Chain.getValue(1);
2020
2021     // RAX/EAX now acts like a return value.
2022     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2023   }
2024
2025   RetOps[0] = Chain;  // Update chain.
2026
2027   // Add the flag if we have it.
2028   if (Flag.getNode())
2029     RetOps.push_back(Flag);
2030
2031   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2032 }
2033
2034 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2035   if (N->getNumValues() != 1)
2036     return false;
2037   if (!N->hasNUsesOfValue(1, 0))
2038     return false;
2039
2040   SDValue TCChain = Chain;
2041   SDNode *Copy = *N->use_begin();
2042   if (Copy->getOpcode() == ISD::CopyToReg) {
2043     // If the copy has a glue operand, we conservatively assume it isn't safe to
2044     // perform a tail call.
2045     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2046       return false;
2047     TCChain = Copy->getOperand(0);
2048   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2049     return false;
2050
2051   bool HasRet = false;
2052   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2053        UI != UE; ++UI) {
2054     if (UI->getOpcode() != X86ISD::RET_FLAG)
2055       return false;
2056     HasRet = true;
2057   }
2058
2059   if (!HasRet)
2060     return false;
2061
2062   Chain = TCChain;
2063   return true;
2064 }
2065
2066 MVT
2067 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2068                                             ISD::NodeType ExtendKind) const {
2069   MVT ReturnMVT;
2070   // TODO: Is this also valid on 32-bit?
2071   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2072     ReturnMVT = MVT::i8;
2073   else
2074     ReturnMVT = MVT::i32;
2075
2076   MVT MinVT = getRegisterType(ReturnMVT);
2077   return VT.bitsLT(MinVT) ? MinVT : VT;
2078 }
2079
2080 /// LowerCallResult - Lower the result values of a call into the
2081 /// appropriate copies out of appropriate physical registers.
2082 ///
2083 SDValue
2084 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2085                                    CallingConv::ID CallConv, bool isVarArg,
2086                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2087                                    SDLoc dl, SelectionDAG &DAG,
2088                                    SmallVectorImpl<SDValue> &InVals) const {
2089
2090   // Assign locations to each value returned by this call.
2091   SmallVector<CCValAssign, 16> RVLocs;
2092   bool Is64Bit = Subtarget->is64Bit();
2093   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2094                  *DAG.getContext());
2095   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2096
2097   // Copy all of the result registers out of their specified physreg.
2098   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2099     CCValAssign &VA = RVLocs[i];
2100     EVT CopyVT = VA.getValVT();
2101
2102     // If this is x86-64, and we disabled SSE, we can't return FP values
2103     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2104         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2105       report_fatal_error("SSE register return with SSE disabled");
2106     }
2107
2108     // If we prefer to use the value in xmm registers, copy it out as f80 and
2109     // use a truncate to move it from fp stack reg to xmm reg.
2110     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2111         isScalarFPTypeInSSEReg(VA.getValVT()))
2112       CopyVT = MVT::f80;
2113
2114     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2115                                CopyVT, InFlag).getValue(1);
2116     SDValue Val = Chain.getValue(0);
2117
2118     if (CopyVT != VA.getValVT())
2119       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2120                         // This truncation won't change the value.
2121                         DAG.getIntPtrConstant(1));
2122
2123     InFlag = Chain.getValue(2);
2124     InVals.push_back(Val);
2125   }
2126
2127   return Chain;
2128 }
2129
2130 //===----------------------------------------------------------------------===//
2131 //                C & StdCall & Fast Calling Convention implementation
2132 //===----------------------------------------------------------------------===//
2133 //  StdCall calling convention seems to be standard for many Windows' API
2134 //  routines and around. It differs from C calling convention just a little:
2135 //  callee should clean up the stack, not caller. Symbols should be also
2136 //  decorated in some fancy way :) It doesn't support any vector arguments.
2137 //  For info on fast calling convention see Fast Calling Convention (tail call)
2138 //  implementation LowerX86_32FastCCCallTo.
2139
2140 /// CallIsStructReturn - Determines whether a call uses struct return
2141 /// semantics.
2142 enum StructReturnType {
2143   NotStructReturn,
2144   RegStructReturn,
2145   StackStructReturn
2146 };
2147 static StructReturnType
2148 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2149   if (Outs.empty())
2150     return NotStructReturn;
2151
2152   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2153   if (!Flags.isSRet())
2154     return NotStructReturn;
2155   if (Flags.isInReg())
2156     return RegStructReturn;
2157   return StackStructReturn;
2158 }
2159
2160 /// ArgsAreStructReturn - Determines whether a function uses struct
2161 /// return semantics.
2162 static StructReturnType
2163 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2164   if (Ins.empty())
2165     return NotStructReturn;
2166
2167   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2168   if (!Flags.isSRet())
2169     return NotStructReturn;
2170   if (Flags.isInReg())
2171     return RegStructReturn;
2172   return StackStructReturn;
2173 }
2174
2175 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2176 /// by "Src" to address "Dst" with size and alignment information specified by
2177 /// the specific parameter attribute. The copy will be passed as a byval
2178 /// function parameter.
2179 static SDValue
2180 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2181                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2182                           SDLoc dl) {
2183   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2184
2185   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2186                        /*isVolatile*/false, /*AlwaysInline=*/true,
2187                        MachinePointerInfo(), MachinePointerInfo());
2188 }
2189
2190 /// IsTailCallConvention - Return true if the calling convention is one that
2191 /// supports tail call optimization.
2192 static bool IsTailCallConvention(CallingConv::ID CC) {
2193   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2194           CC == CallingConv::HiPE);
2195 }
2196
2197 /// \brief Return true if the calling convention is a C calling convention.
2198 static bool IsCCallConvention(CallingConv::ID CC) {
2199   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2200           CC == CallingConv::X86_64_SysV);
2201 }
2202
2203 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2204   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2205     return false;
2206
2207   CallSite CS(CI);
2208   CallingConv::ID CalleeCC = CS.getCallingConv();
2209   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2210     return false;
2211
2212   return true;
2213 }
2214
2215 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2216 /// a tailcall target by changing its ABI.
2217 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2218                                    bool GuaranteedTailCallOpt) {
2219   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2220 }
2221
2222 SDValue
2223 X86TargetLowering::LowerMemArgument(SDValue Chain,
2224                                     CallingConv::ID CallConv,
2225                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2226                                     SDLoc dl, SelectionDAG &DAG,
2227                                     const CCValAssign &VA,
2228                                     MachineFrameInfo *MFI,
2229                                     unsigned i) const {
2230   // Create the nodes corresponding to a load from this parameter slot.
2231   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2232   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2233       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2234   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2235   EVT ValVT;
2236
2237   // If value is passed by pointer we have address passed instead of the value
2238   // itself.
2239   if (VA.getLocInfo() == CCValAssign::Indirect)
2240     ValVT = VA.getLocVT();
2241   else
2242     ValVT = VA.getValVT();
2243
2244   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2245   // changed with more analysis.
2246   // In case of tail call optimization mark all arguments mutable. Since they
2247   // could be overwritten by lowering of arguments in case of a tail call.
2248   if (Flags.isByVal()) {
2249     unsigned Bytes = Flags.getByValSize();
2250     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2251     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2252     return DAG.getFrameIndex(FI, getPointerTy());
2253   } else {
2254     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2255                                     VA.getLocMemOffset(), isImmutable);
2256     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2257     return DAG.getLoad(ValVT, dl, Chain, FIN,
2258                        MachinePointerInfo::getFixedStack(FI),
2259                        false, false, false, 0);
2260   }
2261 }
2262
2263 SDValue
2264 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2265                                         CallingConv::ID CallConv,
2266                                         bool isVarArg,
2267                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2268                                         SDLoc dl,
2269                                         SelectionDAG &DAG,
2270                                         SmallVectorImpl<SDValue> &InVals)
2271                                           const {
2272   MachineFunction &MF = DAG.getMachineFunction();
2273   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2274
2275   const Function* Fn = MF.getFunction();
2276   if (Fn->hasExternalLinkage() &&
2277       Subtarget->isTargetCygMing() &&
2278       Fn->getName() == "main")
2279     FuncInfo->setForceFramePointer(true);
2280
2281   MachineFrameInfo *MFI = MF.getFrameInfo();
2282   bool Is64Bit = Subtarget->is64Bit();
2283   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2284
2285   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2286          "Var args not supported with calling convention fastcc, ghc or hipe");
2287
2288   // Assign locations to all of the incoming arguments.
2289   SmallVector<CCValAssign, 16> ArgLocs;
2290   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2291
2292   // Allocate shadow area for Win64
2293   if (IsWin64)
2294     CCInfo.AllocateStack(32, 8);
2295
2296   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2297
2298   unsigned LastVal = ~0U;
2299   SDValue ArgValue;
2300   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2301     CCValAssign &VA = ArgLocs[i];
2302     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2303     // places.
2304     assert(VA.getValNo() != LastVal &&
2305            "Don't support value assigned to multiple locs yet");
2306     (void)LastVal;
2307     LastVal = VA.getValNo();
2308
2309     if (VA.isRegLoc()) {
2310       EVT RegVT = VA.getLocVT();
2311       const TargetRegisterClass *RC;
2312       if (RegVT == MVT::i32)
2313         RC = &X86::GR32RegClass;
2314       else if (Is64Bit && RegVT == MVT::i64)
2315         RC = &X86::GR64RegClass;
2316       else if (RegVT == MVT::f32)
2317         RC = &X86::FR32RegClass;
2318       else if (RegVT == MVT::f64)
2319         RC = &X86::FR64RegClass;
2320       else if (RegVT.is512BitVector())
2321         RC = &X86::VR512RegClass;
2322       else if (RegVT.is256BitVector())
2323         RC = &X86::VR256RegClass;
2324       else if (RegVT.is128BitVector())
2325         RC = &X86::VR128RegClass;
2326       else if (RegVT == MVT::x86mmx)
2327         RC = &X86::VR64RegClass;
2328       else if (RegVT == MVT::i1)
2329         RC = &X86::VK1RegClass;
2330       else if (RegVT == MVT::v8i1)
2331         RC = &X86::VK8RegClass;
2332       else if (RegVT == MVT::v16i1)
2333         RC = &X86::VK16RegClass;
2334       else if (RegVT == MVT::v32i1)
2335         RC = &X86::VK32RegClass;
2336       else if (RegVT == MVT::v64i1)
2337         RC = &X86::VK64RegClass;
2338       else
2339         llvm_unreachable("Unknown argument type!");
2340
2341       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2342       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2343
2344       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2345       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2346       // right size.
2347       if (VA.getLocInfo() == CCValAssign::SExt)
2348         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2349                                DAG.getValueType(VA.getValVT()));
2350       else if (VA.getLocInfo() == CCValAssign::ZExt)
2351         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2352                                DAG.getValueType(VA.getValVT()));
2353       else if (VA.getLocInfo() == CCValAssign::BCvt)
2354         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2355
2356       if (VA.isExtInLoc()) {
2357         // Handle MMX values passed in XMM regs.
2358         if (RegVT.isVector())
2359           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2360         else
2361           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2362       }
2363     } else {
2364       assert(VA.isMemLoc());
2365       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2366     }
2367
2368     // If value is passed via pointer - do a load.
2369     if (VA.getLocInfo() == CCValAssign::Indirect)
2370       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2371                              MachinePointerInfo(), false, false, false, 0);
2372
2373     InVals.push_back(ArgValue);
2374   }
2375
2376   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2377     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2378       // The x86-64 ABIs require that for returning structs by value we copy
2379       // the sret argument into %rax/%eax (depending on ABI) for the return.
2380       // Win32 requires us to put the sret argument to %eax as well.
2381       // Save the argument into a virtual register so that we can access it
2382       // from the return points.
2383       if (Ins[i].Flags.isSRet()) {
2384         unsigned Reg = FuncInfo->getSRetReturnReg();
2385         if (!Reg) {
2386           MVT PtrTy = getPointerTy();
2387           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2388           FuncInfo->setSRetReturnReg(Reg);
2389         }
2390         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2391         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2392         break;
2393       }
2394     }
2395   }
2396
2397   unsigned StackSize = CCInfo.getNextStackOffset();
2398   // Align stack specially for tail calls.
2399   if (FuncIsMadeTailCallSafe(CallConv,
2400                              MF.getTarget().Options.GuaranteedTailCallOpt))
2401     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2402
2403   // If the function takes variable number of arguments, make a frame index for
2404   // the start of the first vararg value... for expansion of llvm.va_start.
2405   if (isVarArg) {
2406     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2407                     CallConv != CallingConv::X86_ThisCall)) {
2408       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2409     }
2410     if (Is64Bit) {
2411       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2412
2413       // FIXME: We should really autogenerate these arrays
2414       static const MCPhysReg GPR64ArgRegsWin64[] = {
2415         X86::RCX, X86::RDX, X86::R8,  X86::R9
2416       };
2417       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2418         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2419       };
2420       static const MCPhysReg XMMArgRegs64Bit[] = {
2421         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2422         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2423       };
2424       const MCPhysReg *GPR64ArgRegs;
2425       unsigned NumXMMRegs = 0;
2426
2427       if (IsWin64) {
2428         // The XMM registers which might contain var arg parameters are shadowed
2429         // in their paired GPR.  So we only need to save the GPR to their home
2430         // slots.
2431         TotalNumIntRegs = 4;
2432         GPR64ArgRegs = GPR64ArgRegsWin64;
2433       } else {
2434         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2435         GPR64ArgRegs = GPR64ArgRegs64Bit;
2436
2437         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2438                                                 TotalNumXMMRegs);
2439       }
2440       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2441                                                        TotalNumIntRegs);
2442
2443       bool NoImplicitFloatOps = Fn->getAttributes().
2444         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2445       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2446              "SSE register cannot be used when SSE is disabled!");
2447       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2448                NoImplicitFloatOps) &&
2449              "SSE register cannot be used when SSE is disabled!");
2450       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2451           !Subtarget->hasSSE1())
2452         // Kernel mode asks for SSE to be disabled, so don't push them
2453         // on the stack.
2454         TotalNumXMMRegs = 0;
2455
2456       if (IsWin64) {
2457         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2458         // Get to the caller-allocated home save location.  Add 8 to account
2459         // for the return address.
2460         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2461         FuncInfo->setRegSaveFrameIndex(
2462           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2463         // Fixup to set vararg frame on shadow area (4 x i64).
2464         if (NumIntRegs < 4)
2465           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2466       } else {
2467         // For X86-64, if there are vararg parameters that are passed via
2468         // registers, then we must store them to their spots on the stack so
2469         // they may be loaded by deferencing the result of va_next.
2470         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2471         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2472         FuncInfo->setRegSaveFrameIndex(
2473           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2474                                false));
2475       }
2476
2477       // Store the integer parameter registers.
2478       SmallVector<SDValue, 8> MemOps;
2479       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2480                                         getPointerTy());
2481       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2482       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2483         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2484                                   DAG.getIntPtrConstant(Offset));
2485         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2486                                      &X86::GR64RegClass);
2487         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2488         SDValue Store =
2489           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2490                        MachinePointerInfo::getFixedStack(
2491                          FuncInfo->getRegSaveFrameIndex(), Offset),
2492                        false, false, 0);
2493         MemOps.push_back(Store);
2494         Offset += 8;
2495       }
2496
2497       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2498         // Now store the XMM (fp + vector) parameter registers.
2499         SmallVector<SDValue, 11> SaveXMMOps;
2500         SaveXMMOps.push_back(Chain);
2501
2502         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2503         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2504         SaveXMMOps.push_back(ALVal);
2505
2506         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2507                                FuncInfo->getRegSaveFrameIndex()));
2508         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2509                                FuncInfo->getVarArgsFPOffset()));
2510
2511         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2512           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2513                                        &X86::VR128RegClass);
2514           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2515           SaveXMMOps.push_back(Val);
2516         }
2517         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2518                                      MVT::Other, SaveXMMOps));
2519       }
2520
2521       if (!MemOps.empty())
2522         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2523     }
2524   }
2525
2526   // Some CCs need callee pop.
2527   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2528                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2529     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2530   } else {
2531     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2532     // If this is an sret function, the return should pop the hidden pointer.
2533     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2534         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2535         argsAreStructReturn(Ins) == StackStructReturn)
2536       FuncInfo->setBytesToPopOnReturn(4);
2537   }
2538
2539   if (!Is64Bit) {
2540     // RegSaveFrameIndex is X86-64 only.
2541     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2542     if (CallConv == CallingConv::X86_FastCall ||
2543         CallConv == CallingConv::X86_ThisCall)
2544       // fastcc functions can't have varargs.
2545       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2546   }
2547
2548   FuncInfo->setArgumentStackSize(StackSize);
2549
2550   return Chain;
2551 }
2552
2553 SDValue
2554 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2555                                     SDValue StackPtr, SDValue Arg,
2556                                     SDLoc dl, SelectionDAG &DAG,
2557                                     const CCValAssign &VA,
2558                                     ISD::ArgFlagsTy Flags) const {
2559   unsigned LocMemOffset = VA.getLocMemOffset();
2560   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2561   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2562   if (Flags.isByVal())
2563     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2564
2565   return DAG.getStore(Chain, dl, Arg, PtrOff,
2566                       MachinePointerInfo::getStack(LocMemOffset),
2567                       false, false, 0);
2568 }
2569
2570 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2571 /// optimization is performed and it is required.
2572 SDValue
2573 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2574                                            SDValue &OutRetAddr, SDValue Chain,
2575                                            bool IsTailCall, bool Is64Bit,
2576                                            int FPDiff, SDLoc dl) const {
2577   // Adjust the Return address stack slot.
2578   EVT VT = getPointerTy();
2579   OutRetAddr = getReturnAddressFrameIndex(DAG);
2580
2581   // Load the "old" Return address.
2582   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2583                            false, false, false, 0);
2584   return SDValue(OutRetAddr.getNode(), 1);
2585 }
2586
2587 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2588 /// optimization is performed and it is required (FPDiff!=0).
2589 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2590                                         SDValue Chain, SDValue RetAddrFrIdx,
2591                                         EVT PtrVT, unsigned SlotSize,
2592                                         int FPDiff, SDLoc dl) {
2593   // Store the return address to the appropriate stack slot.
2594   if (!FPDiff) return Chain;
2595   // Calculate the new stack slot for the return address.
2596   int NewReturnAddrFI =
2597     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2598                                          false);
2599   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2600   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2601                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2602                        false, false, 0);
2603   return Chain;
2604 }
2605
2606 SDValue
2607 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2608                              SmallVectorImpl<SDValue> &InVals) const {
2609   SelectionDAG &DAG                     = CLI.DAG;
2610   SDLoc &dl                             = CLI.DL;
2611   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2612   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2613   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2614   SDValue Chain                         = CLI.Chain;
2615   SDValue Callee                        = CLI.Callee;
2616   CallingConv::ID CallConv              = CLI.CallConv;
2617   bool &isTailCall                      = CLI.IsTailCall;
2618   bool isVarArg                         = CLI.IsVarArg;
2619
2620   MachineFunction &MF = DAG.getMachineFunction();
2621   bool Is64Bit        = Subtarget->is64Bit();
2622   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2623   StructReturnType SR = callIsStructReturn(Outs);
2624   bool IsSibcall      = false;
2625
2626   if (MF.getTarget().Options.DisableTailCalls)
2627     isTailCall = false;
2628
2629   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2630   if (IsMustTail) {
2631     // Force this to be a tail call.  The verifier rules are enough to ensure
2632     // that we can lower this successfully without moving the return address
2633     // around.
2634     isTailCall = true;
2635   } else if (isTailCall) {
2636     // Check if it's really possible to do a tail call.
2637     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2638                     isVarArg, SR != NotStructReturn,
2639                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2640                     Outs, OutVals, Ins, DAG);
2641
2642     // Sibcalls are automatically detected tailcalls which do not require
2643     // ABI changes.
2644     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2645       IsSibcall = true;
2646
2647     if (isTailCall)
2648       ++NumTailCalls;
2649   }
2650
2651   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2652          "Var args not supported with calling convention fastcc, ghc or hipe");
2653
2654   // Analyze operands of the call, assigning locations to each operand.
2655   SmallVector<CCValAssign, 16> ArgLocs;
2656   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2657
2658   // Allocate shadow area for Win64
2659   if (IsWin64)
2660     CCInfo.AllocateStack(32, 8);
2661
2662   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2663
2664   // Get a count of how many bytes are to be pushed on the stack.
2665   unsigned NumBytes = CCInfo.getNextStackOffset();
2666   if (IsSibcall)
2667     // This is a sibcall. The memory operands are available in caller's
2668     // own caller's stack.
2669     NumBytes = 0;
2670   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2671            IsTailCallConvention(CallConv))
2672     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2673
2674   int FPDiff = 0;
2675   if (isTailCall && !IsSibcall && !IsMustTail) {
2676     // Lower arguments at fp - stackoffset + fpdiff.
2677     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2678     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2679
2680     FPDiff = NumBytesCallerPushed - NumBytes;
2681
2682     // Set the delta of movement of the returnaddr stackslot.
2683     // But only set if delta is greater than previous delta.
2684     if (FPDiff < X86Info->getTCReturnAddrDelta())
2685       X86Info->setTCReturnAddrDelta(FPDiff);
2686   }
2687
2688   unsigned NumBytesToPush = NumBytes;
2689   unsigned NumBytesToPop = NumBytes;
2690
2691   // If we have an inalloca argument, all stack space has already been allocated
2692   // for us and be right at the top of the stack.  We don't support multiple
2693   // arguments passed in memory when using inalloca.
2694   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2695     NumBytesToPush = 0;
2696     if (!ArgLocs.back().isMemLoc())
2697       report_fatal_error("cannot use inalloca attribute on a register "
2698                          "parameter");
2699     if (ArgLocs.back().getLocMemOffset() != 0)
2700       report_fatal_error("any parameter with the inalloca attribute must be "
2701                          "the only memory argument");
2702   }
2703
2704   if (!IsSibcall)
2705     Chain = DAG.getCALLSEQ_START(
2706         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2707
2708   SDValue RetAddrFrIdx;
2709   // Load return address for tail calls.
2710   if (isTailCall && FPDiff)
2711     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2712                                     Is64Bit, FPDiff, dl);
2713
2714   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2715   SmallVector<SDValue, 8> MemOpChains;
2716   SDValue StackPtr;
2717
2718   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2719   // of tail call optimization arguments are handle later.
2720   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2721       DAG.getSubtarget().getRegisterInfo());
2722   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2723     // Skip inalloca arguments, they have already been written.
2724     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2725     if (Flags.isInAlloca())
2726       continue;
2727
2728     CCValAssign &VA = ArgLocs[i];
2729     EVT RegVT = VA.getLocVT();
2730     SDValue Arg = OutVals[i];
2731     bool isByVal = Flags.isByVal();
2732
2733     // Promote the value if needed.
2734     switch (VA.getLocInfo()) {
2735     default: llvm_unreachable("Unknown loc info!");
2736     case CCValAssign::Full: break;
2737     case CCValAssign::SExt:
2738       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2739       break;
2740     case CCValAssign::ZExt:
2741       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2742       break;
2743     case CCValAssign::AExt:
2744       if (RegVT.is128BitVector()) {
2745         // Special case: passing MMX values in XMM registers.
2746         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2747         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2748         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2749       } else
2750         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2751       break;
2752     case CCValAssign::BCvt:
2753       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2754       break;
2755     case CCValAssign::Indirect: {
2756       // Store the argument.
2757       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2758       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2759       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2760                            MachinePointerInfo::getFixedStack(FI),
2761                            false, false, 0);
2762       Arg = SpillSlot;
2763       break;
2764     }
2765     }
2766
2767     if (VA.isRegLoc()) {
2768       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2769       if (isVarArg && IsWin64) {
2770         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2771         // shadow reg if callee is a varargs function.
2772         unsigned ShadowReg = 0;
2773         switch (VA.getLocReg()) {
2774         case X86::XMM0: ShadowReg = X86::RCX; break;
2775         case X86::XMM1: ShadowReg = X86::RDX; break;
2776         case X86::XMM2: ShadowReg = X86::R8; break;
2777         case X86::XMM3: ShadowReg = X86::R9; break;
2778         }
2779         if (ShadowReg)
2780           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2781       }
2782     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2783       assert(VA.isMemLoc());
2784       if (!StackPtr.getNode())
2785         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2786                                       getPointerTy());
2787       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2788                                              dl, DAG, VA, Flags));
2789     }
2790   }
2791
2792   if (!MemOpChains.empty())
2793     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2794
2795   if (Subtarget->isPICStyleGOT()) {
2796     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2797     // GOT pointer.
2798     if (!isTailCall) {
2799       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2800                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2801     } else {
2802       // If we are tail calling and generating PIC/GOT style code load the
2803       // address of the callee into ECX. The value in ecx is used as target of
2804       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2805       // for tail calls on PIC/GOT architectures. Normally we would just put the
2806       // address of GOT into ebx and then call target@PLT. But for tail calls
2807       // ebx would be restored (since ebx is callee saved) before jumping to the
2808       // target@PLT.
2809
2810       // Note: The actual moving to ECX is done further down.
2811       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2812       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2813           !G->getGlobal()->hasProtectedVisibility())
2814         Callee = LowerGlobalAddress(Callee, DAG);
2815       else if (isa<ExternalSymbolSDNode>(Callee))
2816         Callee = LowerExternalSymbol(Callee, DAG);
2817     }
2818   }
2819
2820   if (Is64Bit && isVarArg && !IsWin64) {
2821     // From AMD64 ABI document:
2822     // For calls that may call functions that use varargs or stdargs
2823     // (prototype-less calls or calls to functions containing ellipsis (...) in
2824     // the declaration) %al is used as hidden argument to specify the number
2825     // of SSE registers used. The contents of %al do not need to match exactly
2826     // the number of registers, but must be an ubound on the number of SSE
2827     // registers used and is in the range 0 - 8 inclusive.
2828
2829     // Count the number of XMM registers allocated.
2830     static const MCPhysReg XMMArgRegs[] = {
2831       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2832       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2833     };
2834     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2835     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2836            && "SSE registers cannot be used when SSE is disabled");
2837
2838     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2839                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2840   }
2841
2842   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2843   // don't need this because the eligibility check rejects calls that require
2844   // shuffling arguments passed in memory.
2845   if (!IsSibcall && isTailCall) {
2846     // Force all the incoming stack arguments to be loaded from the stack
2847     // before any new outgoing arguments are stored to the stack, because the
2848     // outgoing stack slots may alias the incoming argument stack slots, and
2849     // the alias isn't otherwise explicit. This is slightly more conservative
2850     // than necessary, because it means that each store effectively depends
2851     // on every argument instead of just those arguments it would clobber.
2852     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2853
2854     SmallVector<SDValue, 8> MemOpChains2;
2855     SDValue FIN;
2856     int FI = 0;
2857     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2858       CCValAssign &VA = ArgLocs[i];
2859       if (VA.isRegLoc())
2860         continue;
2861       assert(VA.isMemLoc());
2862       SDValue Arg = OutVals[i];
2863       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2864       // Skip inalloca arguments.  They don't require any work.
2865       if (Flags.isInAlloca())
2866         continue;
2867       // Create frame index.
2868       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2869       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2870       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2871       FIN = DAG.getFrameIndex(FI, getPointerTy());
2872
2873       if (Flags.isByVal()) {
2874         // Copy relative to framepointer.
2875         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2876         if (!StackPtr.getNode())
2877           StackPtr = DAG.getCopyFromReg(Chain, dl,
2878                                         RegInfo->getStackRegister(),
2879                                         getPointerTy());
2880         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2881
2882         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2883                                                          ArgChain,
2884                                                          Flags, DAG, dl));
2885       } else {
2886         // Store relative to framepointer.
2887         MemOpChains2.push_back(
2888           DAG.getStore(ArgChain, dl, Arg, FIN,
2889                        MachinePointerInfo::getFixedStack(FI),
2890                        false, false, 0));
2891       }
2892     }
2893
2894     if (!MemOpChains2.empty())
2895       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2896
2897     // Store the return address to the appropriate stack slot.
2898     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2899                                      getPointerTy(), RegInfo->getSlotSize(),
2900                                      FPDiff, dl);
2901   }
2902
2903   // Build a sequence of copy-to-reg nodes chained together with token chain
2904   // and flag operands which copy the outgoing args into registers.
2905   SDValue InFlag;
2906   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2907     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2908                              RegsToPass[i].second, InFlag);
2909     InFlag = Chain.getValue(1);
2910   }
2911
2912   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2913     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2914     // In the 64-bit large code model, we have to make all calls
2915     // through a register, since the call instruction's 32-bit
2916     // pc-relative offset may not be large enough to hold the whole
2917     // address.
2918   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2919     // If the callee is a GlobalAddress node (quite common, every direct call
2920     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2921     // it.
2922
2923     // We should use extra load for direct calls to dllimported functions in
2924     // non-JIT mode.
2925     const GlobalValue *GV = G->getGlobal();
2926     if (!GV->hasDLLImportStorageClass()) {
2927       unsigned char OpFlags = 0;
2928       bool ExtraLoad = false;
2929       unsigned WrapperKind = ISD::DELETED_NODE;
2930
2931       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2932       // external symbols most go through the PLT in PIC mode.  If the symbol
2933       // has hidden or protected visibility, or if it is static or local, then
2934       // we don't need to use the PLT - we can directly call it.
2935       if (Subtarget->isTargetELF() &&
2936           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2937           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2938         OpFlags = X86II::MO_PLT;
2939       } else if (Subtarget->isPICStyleStubAny() &&
2940                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2941                  (!Subtarget->getTargetTriple().isMacOSX() ||
2942                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2943         // PC-relative references to external symbols should go through $stub,
2944         // unless we're building with the leopard linker or later, which
2945         // automatically synthesizes these stubs.
2946         OpFlags = X86II::MO_DARWIN_STUB;
2947       } else if (Subtarget->isPICStyleRIPRel() &&
2948                  isa<Function>(GV) &&
2949                  cast<Function>(GV)->getAttributes().
2950                    hasAttribute(AttributeSet::FunctionIndex,
2951                                 Attribute::NonLazyBind)) {
2952         // If the function is marked as non-lazy, generate an indirect call
2953         // which loads from the GOT directly. This avoids runtime overhead
2954         // at the cost of eager binding (and one extra byte of encoding).
2955         OpFlags = X86II::MO_GOTPCREL;
2956         WrapperKind = X86ISD::WrapperRIP;
2957         ExtraLoad = true;
2958       }
2959
2960       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2961                                           G->getOffset(), OpFlags);
2962
2963       // Add a wrapper if needed.
2964       if (WrapperKind != ISD::DELETED_NODE)
2965         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2966       // Add extra indirection if needed.
2967       if (ExtraLoad)
2968         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2969                              MachinePointerInfo::getGOT(),
2970                              false, false, false, 0);
2971     }
2972   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2973     unsigned char OpFlags = 0;
2974
2975     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2976     // external symbols should go through the PLT.
2977     if (Subtarget->isTargetELF() &&
2978         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2979       OpFlags = X86II::MO_PLT;
2980     } else if (Subtarget->isPICStyleStubAny() &&
2981                (!Subtarget->getTargetTriple().isMacOSX() ||
2982                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2983       // PC-relative references to external symbols should go through $stub,
2984       // unless we're building with the leopard linker or later, which
2985       // automatically synthesizes these stubs.
2986       OpFlags = X86II::MO_DARWIN_STUB;
2987     }
2988
2989     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2990                                          OpFlags);
2991   }
2992
2993   // Returns a chain & a flag for retval copy to use.
2994   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2995   SmallVector<SDValue, 8> Ops;
2996
2997   if (!IsSibcall && isTailCall) {
2998     Chain = DAG.getCALLSEQ_END(Chain,
2999                                DAG.getIntPtrConstant(NumBytesToPop, true),
3000                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3001     InFlag = Chain.getValue(1);
3002   }
3003
3004   Ops.push_back(Chain);
3005   Ops.push_back(Callee);
3006
3007   if (isTailCall)
3008     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3009
3010   // Add argument registers to the end of the list so that they are known live
3011   // into the call.
3012   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3013     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3014                                   RegsToPass[i].second.getValueType()));
3015
3016   // Add a register mask operand representing the call-preserved registers.
3017   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3018   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3019   assert(Mask && "Missing call preserved mask for calling convention");
3020   Ops.push_back(DAG.getRegisterMask(Mask));
3021
3022   if (InFlag.getNode())
3023     Ops.push_back(InFlag);
3024
3025   if (isTailCall) {
3026     // We used to do:
3027     //// If this is the first return lowered for this function, add the regs
3028     //// to the liveout set for the function.
3029     // This isn't right, although it's probably harmless on x86; liveouts
3030     // should be computed from returns not tail calls.  Consider a void
3031     // function making a tail call to a function returning int.
3032     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3033   }
3034
3035   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3036   InFlag = Chain.getValue(1);
3037
3038   // Create the CALLSEQ_END node.
3039   unsigned NumBytesForCalleeToPop;
3040   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3041                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3042     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3043   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3044            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3045            SR == StackStructReturn)
3046     // If this is a call to a struct-return function, the callee
3047     // pops the hidden struct pointer, so we have to push it back.
3048     // This is common for Darwin/X86, Linux & Mingw32 targets.
3049     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3050     NumBytesForCalleeToPop = 4;
3051   else
3052     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3053
3054   // Returns a flag for retval copy to use.
3055   if (!IsSibcall) {
3056     Chain = DAG.getCALLSEQ_END(Chain,
3057                                DAG.getIntPtrConstant(NumBytesToPop, true),
3058                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3059                                                      true),
3060                                InFlag, dl);
3061     InFlag = Chain.getValue(1);
3062   }
3063
3064   // Handle result values, copying them out of physregs into vregs that we
3065   // return.
3066   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3067                          Ins, dl, DAG, InVals);
3068 }
3069
3070 //===----------------------------------------------------------------------===//
3071 //                Fast Calling Convention (tail call) implementation
3072 //===----------------------------------------------------------------------===//
3073
3074 //  Like std call, callee cleans arguments, convention except that ECX is
3075 //  reserved for storing the tail called function address. Only 2 registers are
3076 //  free for argument passing (inreg). Tail call optimization is performed
3077 //  provided:
3078 //                * tailcallopt is enabled
3079 //                * caller/callee are fastcc
3080 //  On X86_64 architecture with GOT-style position independent code only local
3081 //  (within module) calls are supported at the moment.
3082 //  To keep the stack aligned according to platform abi the function
3083 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3084 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3085 //  If a tail called function callee has more arguments than the caller the
3086 //  caller needs to make sure that there is room to move the RETADDR to. This is
3087 //  achieved by reserving an area the size of the argument delta right after the
3088 //  original RETADDR, but before the saved framepointer or the spilled registers
3089 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3090 //  stack layout:
3091 //    arg1
3092 //    arg2
3093 //    RETADDR
3094 //    [ new RETADDR
3095 //      move area ]
3096 //    (possible EBP)
3097 //    ESI
3098 //    EDI
3099 //    local1 ..
3100
3101 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3102 /// for a 16 byte align requirement.
3103 unsigned
3104 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3105                                                SelectionDAG& DAG) const {
3106   MachineFunction &MF = DAG.getMachineFunction();
3107   const TargetMachine &TM = MF.getTarget();
3108   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3109       TM.getSubtargetImpl()->getRegisterInfo());
3110   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3111   unsigned StackAlignment = TFI.getStackAlignment();
3112   uint64_t AlignMask = StackAlignment - 1;
3113   int64_t Offset = StackSize;
3114   unsigned SlotSize = RegInfo->getSlotSize();
3115   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3116     // Number smaller than 12 so just add the difference.
3117     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3118   } else {
3119     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3120     Offset = ((~AlignMask) & Offset) + StackAlignment +
3121       (StackAlignment-SlotSize);
3122   }
3123   return Offset;
3124 }
3125
3126 /// MatchingStackOffset - Return true if the given stack call argument is
3127 /// already available in the same position (relatively) of the caller's
3128 /// incoming argument stack.
3129 static
3130 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3131                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3132                          const X86InstrInfo *TII) {
3133   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3134   int FI = INT_MAX;
3135   if (Arg.getOpcode() == ISD::CopyFromReg) {
3136     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3137     if (!TargetRegisterInfo::isVirtualRegister(VR))
3138       return false;
3139     MachineInstr *Def = MRI->getVRegDef(VR);
3140     if (!Def)
3141       return false;
3142     if (!Flags.isByVal()) {
3143       if (!TII->isLoadFromStackSlot(Def, FI))
3144         return false;
3145     } else {
3146       unsigned Opcode = Def->getOpcode();
3147       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3148           Def->getOperand(1).isFI()) {
3149         FI = Def->getOperand(1).getIndex();
3150         Bytes = Flags.getByValSize();
3151       } else
3152         return false;
3153     }
3154   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3155     if (Flags.isByVal())
3156       // ByVal argument is passed in as a pointer but it's now being
3157       // dereferenced. e.g.
3158       // define @foo(%struct.X* %A) {
3159       //   tail call @bar(%struct.X* byval %A)
3160       // }
3161       return false;
3162     SDValue Ptr = Ld->getBasePtr();
3163     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3164     if (!FINode)
3165       return false;
3166     FI = FINode->getIndex();
3167   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3168     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3169     FI = FINode->getIndex();
3170     Bytes = Flags.getByValSize();
3171   } else
3172     return false;
3173
3174   assert(FI != INT_MAX);
3175   if (!MFI->isFixedObjectIndex(FI))
3176     return false;
3177   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3178 }
3179
3180 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3181 /// for tail call optimization. Targets which want to do tail call
3182 /// optimization should implement this function.
3183 bool
3184 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3185                                                      CallingConv::ID CalleeCC,
3186                                                      bool isVarArg,
3187                                                      bool isCalleeStructRet,
3188                                                      bool isCallerStructRet,
3189                                                      Type *RetTy,
3190                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3191                                     const SmallVectorImpl<SDValue> &OutVals,
3192                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3193                                                      SelectionDAG &DAG) const {
3194   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3195     return false;
3196
3197   // If -tailcallopt is specified, make fastcc functions tail-callable.
3198   const MachineFunction &MF = DAG.getMachineFunction();
3199   const Function *CallerF = MF.getFunction();
3200
3201   // If the function return type is x86_fp80 and the callee return type is not,
3202   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3203   // perform a tailcall optimization here.
3204   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3205     return false;
3206
3207   CallingConv::ID CallerCC = CallerF->getCallingConv();
3208   bool CCMatch = CallerCC == CalleeCC;
3209   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3210   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3211
3212   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3213     if (IsTailCallConvention(CalleeCC) && CCMatch)
3214       return true;
3215     return false;
3216   }
3217
3218   // Look for obvious safe cases to perform tail call optimization that do not
3219   // require ABI changes. This is what gcc calls sibcall.
3220
3221   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3222   // emit a special epilogue.
3223   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3224       DAG.getSubtarget().getRegisterInfo());
3225   if (RegInfo->needsStackRealignment(MF))
3226     return false;
3227
3228   // Also avoid sibcall optimization if either caller or callee uses struct
3229   // return semantics.
3230   if (isCalleeStructRet || isCallerStructRet)
3231     return false;
3232
3233   // An stdcall/thiscall caller is expected to clean up its arguments; the
3234   // callee isn't going to do that.
3235   // FIXME: this is more restrictive than needed. We could produce a tailcall
3236   // when the stack adjustment matches. For example, with a thiscall that takes
3237   // only one argument.
3238   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3239                    CallerCC == CallingConv::X86_ThisCall))
3240     return false;
3241
3242   // Do not sibcall optimize vararg calls unless all arguments are passed via
3243   // registers.
3244   if (isVarArg && !Outs.empty()) {
3245
3246     // Optimizing for varargs on Win64 is unlikely to be safe without
3247     // additional testing.
3248     if (IsCalleeWin64 || IsCallerWin64)
3249       return false;
3250
3251     SmallVector<CCValAssign, 16> ArgLocs;
3252     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3253                    *DAG.getContext());
3254
3255     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3256     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3257       if (!ArgLocs[i].isRegLoc())
3258         return false;
3259   }
3260
3261   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3262   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3263   // this into a sibcall.
3264   bool Unused = false;
3265   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3266     if (!Ins[i].Used) {
3267       Unused = true;
3268       break;
3269     }
3270   }
3271   if (Unused) {
3272     SmallVector<CCValAssign, 16> RVLocs;
3273     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3274                    *DAG.getContext());
3275     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3276     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3277       CCValAssign &VA = RVLocs[i];
3278       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3279         return false;
3280     }
3281   }
3282
3283   // If the calling conventions do not match, then we'd better make sure the
3284   // results are returned in the same way as what the caller expects.
3285   if (!CCMatch) {
3286     SmallVector<CCValAssign, 16> RVLocs1;
3287     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3288                     *DAG.getContext());
3289     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3290
3291     SmallVector<CCValAssign, 16> RVLocs2;
3292     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3293                     *DAG.getContext());
3294     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3295
3296     if (RVLocs1.size() != RVLocs2.size())
3297       return false;
3298     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3299       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3300         return false;
3301       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3302         return false;
3303       if (RVLocs1[i].isRegLoc()) {
3304         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3305           return false;
3306       } else {
3307         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3308           return false;
3309       }
3310     }
3311   }
3312
3313   // If the callee takes no arguments then go on to check the results of the
3314   // call.
3315   if (!Outs.empty()) {
3316     // Check if stack adjustment is needed. For now, do not do this if any
3317     // argument is passed on the stack.
3318     SmallVector<CCValAssign, 16> ArgLocs;
3319     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3320                    *DAG.getContext());
3321
3322     // Allocate shadow area for Win64
3323     if (IsCalleeWin64)
3324       CCInfo.AllocateStack(32, 8);
3325
3326     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3327     if (CCInfo.getNextStackOffset()) {
3328       MachineFunction &MF = DAG.getMachineFunction();
3329       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3330         return false;
3331
3332       // Check if the arguments are already laid out in the right way as
3333       // the caller's fixed stack objects.
3334       MachineFrameInfo *MFI = MF.getFrameInfo();
3335       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3336       const X86InstrInfo *TII =
3337           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3338       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3339         CCValAssign &VA = ArgLocs[i];
3340         SDValue Arg = OutVals[i];
3341         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3342         if (VA.getLocInfo() == CCValAssign::Indirect)
3343           return false;
3344         if (!VA.isRegLoc()) {
3345           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3346                                    MFI, MRI, TII))
3347             return false;
3348         }
3349       }
3350     }
3351
3352     // If the tailcall address may be in a register, then make sure it's
3353     // possible to register allocate for it. In 32-bit, the call address can
3354     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3355     // callee-saved registers are restored. These happen to be the same
3356     // registers used to pass 'inreg' arguments so watch out for those.
3357     if (!Subtarget->is64Bit() &&
3358         ((!isa<GlobalAddressSDNode>(Callee) &&
3359           !isa<ExternalSymbolSDNode>(Callee)) ||
3360          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3361       unsigned NumInRegs = 0;
3362       // In PIC we need an extra register to formulate the address computation
3363       // for the callee.
3364       unsigned MaxInRegs =
3365         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3366
3367       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3368         CCValAssign &VA = ArgLocs[i];
3369         if (!VA.isRegLoc())
3370           continue;
3371         unsigned Reg = VA.getLocReg();
3372         switch (Reg) {
3373         default: break;
3374         case X86::EAX: case X86::EDX: case X86::ECX:
3375           if (++NumInRegs == MaxInRegs)
3376             return false;
3377           break;
3378         }
3379       }
3380     }
3381   }
3382
3383   return true;
3384 }
3385
3386 FastISel *
3387 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3388                                   const TargetLibraryInfo *libInfo) const {
3389   return X86::createFastISel(funcInfo, libInfo);
3390 }
3391
3392 //===----------------------------------------------------------------------===//
3393 //                           Other Lowering Hooks
3394 //===----------------------------------------------------------------------===//
3395
3396 static bool MayFoldLoad(SDValue Op) {
3397   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3398 }
3399
3400 static bool MayFoldIntoStore(SDValue Op) {
3401   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3402 }
3403
3404 static bool isTargetShuffle(unsigned Opcode) {
3405   switch(Opcode) {
3406   default: return false;
3407   case X86ISD::PSHUFB:
3408   case X86ISD::PSHUFD:
3409   case X86ISD::PSHUFHW:
3410   case X86ISD::PSHUFLW:
3411   case X86ISD::SHUFP:
3412   case X86ISD::PALIGNR:
3413   case X86ISD::MOVLHPS:
3414   case X86ISD::MOVLHPD:
3415   case X86ISD::MOVHLPS:
3416   case X86ISD::MOVLPS:
3417   case X86ISD::MOVLPD:
3418   case X86ISD::MOVSHDUP:
3419   case X86ISD::MOVSLDUP:
3420   case X86ISD::MOVDDUP:
3421   case X86ISD::MOVSS:
3422   case X86ISD::MOVSD:
3423   case X86ISD::UNPCKL:
3424   case X86ISD::UNPCKH:
3425   case X86ISD::VPERMILP:
3426   case X86ISD::VPERM2X128:
3427   case X86ISD::VPERMI:
3428     return true;
3429   }
3430 }
3431
3432 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3433                                     SDValue V1, SelectionDAG &DAG) {
3434   switch(Opc) {
3435   default: llvm_unreachable("Unknown x86 shuffle node");
3436   case X86ISD::MOVSHDUP:
3437   case X86ISD::MOVSLDUP:
3438   case X86ISD::MOVDDUP:
3439     return DAG.getNode(Opc, dl, VT, V1);
3440   }
3441 }
3442
3443 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3444                                     SDValue V1, unsigned TargetMask,
3445                                     SelectionDAG &DAG) {
3446   switch(Opc) {
3447   default: llvm_unreachable("Unknown x86 shuffle node");
3448   case X86ISD::PSHUFD:
3449   case X86ISD::PSHUFHW:
3450   case X86ISD::PSHUFLW:
3451   case X86ISD::VPERMILP:
3452   case X86ISD::VPERMI:
3453     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3454   }
3455 }
3456
3457 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3458                                     SDValue V1, SDValue V2, unsigned TargetMask,
3459                                     SelectionDAG &DAG) {
3460   switch(Opc) {
3461   default: llvm_unreachable("Unknown x86 shuffle node");
3462   case X86ISD::PALIGNR:
3463   case X86ISD::VALIGN:
3464   case X86ISD::SHUFP:
3465   case X86ISD::VPERM2X128:
3466     return DAG.getNode(Opc, dl, VT, V1, V2,
3467                        DAG.getConstant(TargetMask, MVT::i8));
3468   }
3469 }
3470
3471 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3472                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3473   switch(Opc) {
3474   default: llvm_unreachable("Unknown x86 shuffle node");
3475   case X86ISD::MOVLHPS:
3476   case X86ISD::MOVLHPD:
3477   case X86ISD::MOVHLPS:
3478   case X86ISD::MOVLPS:
3479   case X86ISD::MOVLPD:
3480   case X86ISD::MOVSS:
3481   case X86ISD::MOVSD:
3482   case X86ISD::UNPCKL:
3483   case X86ISD::UNPCKH:
3484     return DAG.getNode(Opc, dl, VT, V1, V2);
3485   }
3486 }
3487
3488 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3489   MachineFunction &MF = DAG.getMachineFunction();
3490   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3491       DAG.getSubtarget().getRegisterInfo());
3492   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3493   int ReturnAddrIndex = FuncInfo->getRAIndex();
3494
3495   if (ReturnAddrIndex == 0) {
3496     // Set up a frame object for the return address.
3497     unsigned SlotSize = RegInfo->getSlotSize();
3498     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3499                                                            -(int64_t)SlotSize,
3500                                                            false);
3501     FuncInfo->setRAIndex(ReturnAddrIndex);
3502   }
3503
3504   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3505 }
3506
3507 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3508                                        bool hasSymbolicDisplacement) {
3509   // Offset should fit into 32 bit immediate field.
3510   if (!isInt<32>(Offset))
3511     return false;
3512
3513   // If we don't have a symbolic displacement - we don't have any extra
3514   // restrictions.
3515   if (!hasSymbolicDisplacement)
3516     return true;
3517
3518   // FIXME: Some tweaks might be needed for medium code model.
3519   if (M != CodeModel::Small && M != CodeModel::Kernel)
3520     return false;
3521
3522   // For small code model we assume that latest object is 16MB before end of 31
3523   // bits boundary. We may also accept pretty large negative constants knowing
3524   // that all objects are in the positive half of address space.
3525   if (M == CodeModel::Small && Offset < 16*1024*1024)
3526     return true;
3527
3528   // For kernel code model we know that all object resist in the negative half
3529   // of 32bits address space. We may not accept negative offsets, since they may
3530   // be just off and we may accept pretty large positive ones.
3531   if (M == CodeModel::Kernel && Offset > 0)
3532     return true;
3533
3534   return false;
3535 }
3536
3537 /// isCalleePop - Determines whether the callee is required to pop its
3538 /// own arguments. Callee pop is necessary to support tail calls.
3539 bool X86::isCalleePop(CallingConv::ID CallingConv,
3540                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3541   if (IsVarArg)
3542     return false;
3543
3544   switch (CallingConv) {
3545   default:
3546     return false;
3547   case CallingConv::X86_StdCall:
3548     return !is64Bit;
3549   case CallingConv::X86_FastCall:
3550     return !is64Bit;
3551   case CallingConv::X86_ThisCall:
3552     return !is64Bit;
3553   case CallingConv::Fast:
3554     return TailCallOpt;
3555   case CallingConv::GHC:
3556     return TailCallOpt;
3557   case CallingConv::HiPE:
3558     return TailCallOpt;
3559   }
3560 }
3561
3562 /// \brief Return true if the condition is an unsigned comparison operation.
3563 static bool isX86CCUnsigned(unsigned X86CC) {
3564   switch (X86CC) {
3565   default: llvm_unreachable("Invalid integer condition!");
3566   case X86::COND_E:     return true;
3567   case X86::COND_G:     return false;
3568   case X86::COND_GE:    return false;
3569   case X86::COND_L:     return false;
3570   case X86::COND_LE:    return false;
3571   case X86::COND_NE:    return true;
3572   case X86::COND_B:     return true;
3573   case X86::COND_A:     return true;
3574   case X86::COND_BE:    return true;
3575   case X86::COND_AE:    return true;
3576   }
3577   llvm_unreachable("covered switch fell through?!");
3578 }
3579
3580 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3581 /// specific condition code, returning the condition code and the LHS/RHS of the
3582 /// comparison to make.
3583 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3584                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3585   if (!isFP) {
3586     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3587       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3588         // X > -1   -> X == 0, jump !sign.
3589         RHS = DAG.getConstant(0, RHS.getValueType());
3590         return X86::COND_NS;
3591       }
3592       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3593         // X < 0   -> X == 0, jump on sign.
3594         return X86::COND_S;
3595       }
3596       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3597         // X < 1   -> X <= 0
3598         RHS = DAG.getConstant(0, RHS.getValueType());
3599         return X86::COND_LE;
3600       }
3601     }
3602
3603     switch (SetCCOpcode) {
3604     default: llvm_unreachable("Invalid integer condition!");
3605     case ISD::SETEQ:  return X86::COND_E;
3606     case ISD::SETGT:  return X86::COND_G;
3607     case ISD::SETGE:  return X86::COND_GE;
3608     case ISD::SETLT:  return X86::COND_L;
3609     case ISD::SETLE:  return X86::COND_LE;
3610     case ISD::SETNE:  return X86::COND_NE;
3611     case ISD::SETULT: return X86::COND_B;
3612     case ISD::SETUGT: return X86::COND_A;
3613     case ISD::SETULE: return X86::COND_BE;
3614     case ISD::SETUGE: return X86::COND_AE;
3615     }
3616   }
3617
3618   // First determine if it is required or is profitable to flip the operands.
3619
3620   // If LHS is a foldable load, but RHS is not, flip the condition.
3621   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3622       !ISD::isNON_EXTLoad(RHS.getNode())) {
3623     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3624     std::swap(LHS, RHS);
3625   }
3626
3627   switch (SetCCOpcode) {
3628   default: break;
3629   case ISD::SETOLT:
3630   case ISD::SETOLE:
3631   case ISD::SETUGT:
3632   case ISD::SETUGE:
3633     std::swap(LHS, RHS);
3634     break;
3635   }
3636
3637   // On a floating point condition, the flags are set as follows:
3638   // ZF  PF  CF   op
3639   //  0 | 0 | 0 | X > Y
3640   //  0 | 0 | 1 | X < Y
3641   //  1 | 0 | 0 | X == Y
3642   //  1 | 1 | 1 | unordered
3643   switch (SetCCOpcode) {
3644   default: llvm_unreachable("Condcode should be pre-legalized away");
3645   case ISD::SETUEQ:
3646   case ISD::SETEQ:   return X86::COND_E;
3647   case ISD::SETOLT:              // flipped
3648   case ISD::SETOGT:
3649   case ISD::SETGT:   return X86::COND_A;
3650   case ISD::SETOLE:              // flipped
3651   case ISD::SETOGE:
3652   case ISD::SETGE:   return X86::COND_AE;
3653   case ISD::SETUGT:              // flipped
3654   case ISD::SETULT:
3655   case ISD::SETLT:   return X86::COND_B;
3656   case ISD::SETUGE:              // flipped
3657   case ISD::SETULE:
3658   case ISD::SETLE:   return X86::COND_BE;
3659   case ISD::SETONE:
3660   case ISD::SETNE:   return X86::COND_NE;
3661   case ISD::SETUO:   return X86::COND_P;
3662   case ISD::SETO:    return X86::COND_NP;
3663   case ISD::SETOEQ:
3664   case ISD::SETUNE:  return X86::COND_INVALID;
3665   }
3666 }
3667
3668 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3669 /// code. Current x86 isa includes the following FP cmov instructions:
3670 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3671 static bool hasFPCMov(unsigned X86CC) {
3672   switch (X86CC) {
3673   default:
3674     return false;
3675   case X86::COND_B:
3676   case X86::COND_BE:
3677   case X86::COND_E:
3678   case X86::COND_P:
3679   case X86::COND_A:
3680   case X86::COND_AE:
3681   case X86::COND_NE:
3682   case X86::COND_NP:
3683     return true;
3684   }
3685 }
3686
3687 /// isFPImmLegal - Returns true if the target can instruction select the
3688 /// specified FP immediate natively. If false, the legalizer will
3689 /// materialize the FP immediate as a load from a constant pool.
3690 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3691   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3692     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3693       return true;
3694   }
3695   return false;
3696 }
3697
3698 /// \brief Returns true if it is beneficial to convert a load of a constant
3699 /// to just the constant itself.
3700 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3701                                                           Type *Ty) const {
3702   assert(Ty->isIntegerTy());
3703
3704   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3705   if (BitSize == 0 || BitSize > 64)
3706     return false;
3707   return true;
3708 }
3709
3710 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3711 /// the specified range (L, H].
3712 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3713   return (Val < 0) || (Val >= Low && Val < Hi);
3714 }
3715
3716 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3717 /// specified value.
3718 static bool isUndefOrEqual(int Val, int CmpVal) {
3719   return (Val < 0 || Val == CmpVal);
3720 }
3721
3722 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3723 /// from position Pos and ending in Pos+Size, falls within the specified
3724 /// sequential range (L, L+Pos]. or is undef.
3725 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3726                                        unsigned Pos, unsigned Size, int Low) {
3727   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3728     if (!isUndefOrEqual(Mask[i], Low))
3729       return false;
3730   return true;
3731 }
3732
3733 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3734 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3735 /// the second operand.
3736 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3737   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3738     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3739   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3740     return (Mask[0] < 2 && Mask[1] < 2);
3741   return false;
3742 }
3743
3744 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3745 /// is suitable for input to PSHUFHW.
3746 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3747   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3748     return false;
3749
3750   // Lower quadword copied in order or undef.
3751   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3752     return false;
3753
3754   // Upper quadword shuffled.
3755   for (unsigned i = 4; i != 8; ++i)
3756     if (!isUndefOrInRange(Mask[i], 4, 8))
3757       return false;
3758
3759   if (VT == MVT::v16i16) {
3760     // Lower quadword copied in order or undef.
3761     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3762       return false;
3763
3764     // Upper quadword shuffled.
3765     for (unsigned i = 12; i != 16; ++i)
3766       if (!isUndefOrInRange(Mask[i], 12, 16))
3767         return false;
3768   }
3769
3770   return true;
3771 }
3772
3773 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3774 /// is suitable for input to PSHUFLW.
3775 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3776   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3777     return false;
3778
3779   // Upper quadword copied in order.
3780   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3781     return false;
3782
3783   // Lower quadword shuffled.
3784   for (unsigned i = 0; i != 4; ++i)
3785     if (!isUndefOrInRange(Mask[i], 0, 4))
3786       return false;
3787
3788   if (VT == MVT::v16i16) {
3789     // Upper quadword copied in order.
3790     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3791       return false;
3792
3793     // Lower quadword shuffled.
3794     for (unsigned i = 8; i != 12; ++i)
3795       if (!isUndefOrInRange(Mask[i], 8, 12))
3796         return false;
3797   }
3798
3799   return true;
3800 }
3801
3802 /// \brief Return true if the mask specifies a shuffle of elements that is
3803 /// suitable for input to intralane (palignr) or interlane (valign) vector
3804 /// right-shift.
3805 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3806   unsigned NumElts = VT.getVectorNumElements();
3807   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3808   unsigned NumLaneElts = NumElts/NumLanes;
3809
3810   // Do not handle 64-bit element shuffles with palignr.
3811   if (NumLaneElts == 2)
3812     return false;
3813
3814   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3815     unsigned i;
3816     for (i = 0; i != NumLaneElts; ++i) {
3817       if (Mask[i+l] >= 0)
3818         break;
3819     }
3820
3821     // Lane is all undef, go to next lane
3822     if (i == NumLaneElts)
3823       continue;
3824
3825     int Start = Mask[i+l];
3826
3827     // Make sure its in this lane in one of the sources
3828     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3829         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3830       return false;
3831
3832     // If not lane 0, then we must match lane 0
3833     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3834       return false;
3835
3836     // Correct second source to be contiguous with first source
3837     if (Start >= (int)NumElts)
3838       Start -= NumElts - NumLaneElts;
3839
3840     // Make sure we're shifting in the right direction.
3841     if (Start <= (int)(i+l))
3842       return false;
3843
3844     Start -= i;
3845
3846     // Check the rest of the elements to see if they are consecutive.
3847     for (++i; i != NumLaneElts; ++i) {
3848       int Idx = Mask[i+l];
3849
3850       // Make sure its in this lane
3851       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3852           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3853         return false;
3854
3855       // If not lane 0, then we must match lane 0
3856       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3857         return false;
3858
3859       if (Idx >= (int)NumElts)
3860         Idx -= NumElts - NumLaneElts;
3861
3862       if (!isUndefOrEqual(Idx, Start+i))
3863         return false;
3864
3865     }
3866   }
3867
3868   return true;
3869 }
3870
3871 /// \brief Return true if the node specifies a shuffle of elements that is
3872 /// suitable for input to PALIGNR.
3873 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3874                           const X86Subtarget *Subtarget) {
3875   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3876       (VT.is256BitVector() && !Subtarget->hasInt256()))
3877     // FIXME: Add AVX512BW.
3878     return false;
3879
3880   return isAlignrMask(Mask, VT, false);
3881 }
3882
3883 /// \brief Return true if the node specifies a shuffle of elements that is
3884 /// suitable for input to VALIGN.
3885 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3886                           const X86Subtarget *Subtarget) {
3887   // FIXME: Add AVX512VL.
3888   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3889     return false;
3890   return isAlignrMask(Mask, VT, true);
3891 }
3892
3893 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3894 /// the two vector operands have swapped position.
3895 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3896                                      unsigned NumElems) {
3897   for (unsigned i = 0; i != NumElems; ++i) {
3898     int idx = Mask[i];
3899     if (idx < 0)
3900       continue;
3901     else if (idx < (int)NumElems)
3902       Mask[i] = idx + NumElems;
3903     else
3904       Mask[i] = idx - NumElems;
3905   }
3906 }
3907
3908 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3910 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3911 /// reverse of what x86 shuffles want.
3912 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3913
3914   unsigned NumElems = VT.getVectorNumElements();
3915   unsigned NumLanes = VT.getSizeInBits()/128;
3916   unsigned NumLaneElems = NumElems/NumLanes;
3917
3918   if (NumLaneElems != 2 && NumLaneElems != 4)
3919     return false;
3920
3921   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3922   bool symetricMaskRequired =
3923     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3924
3925   // VSHUFPSY divides the resulting vector into 4 chunks.
3926   // The sources are also splitted into 4 chunks, and each destination
3927   // chunk must come from a different source chunk.
3928   //
3929   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3930   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3931   //
3932   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3933   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3934   //
3935   // VSHUFPDY divides the resulting vector into 4 chunks.
3936   // The sources are also splitted into 4 chunks, and each destination
3937   // chunk must come from a different source chunk.
3938   //
3939   //  SRC1 =>      X3       X2       X1       X0
3940   //  SRC2 =>      Y3       Y2       Y1       Y0
3941   //
3942   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3943   //
3944   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3945   unsigned HalfLaneElems = NumLaneElems/2;
3946   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3947     for (unsigned i = 0; i != NumLaneElems; ++i) {
3948       int Idx = Mask[i+l];
3949       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3950       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3951         return false;
3952       // For VSHUFPSY, the mask of the second half must be the same as the
3953       // first but with the appropriate offsets. This works in the same way as
3954       // VPERMILPS works with masks.
3955       if (!symetricMaskRequired || Idx < 0)
3956         continue;
3957       if (MaskVal[i] < 0) {
3958         MaskVal[i] = Idx - l;
3959         continue;
3960       }
3961       if ((signed)(Idx - l) != MaskVal[i])
3962         return false;
3963     }
3964   }
3965
3966   return true;
3967 }
3968
3969 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3970 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3971 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3972   if (!VT.is128BitVector())
3973     return false;
3974
3975   unsigned NumElems = VT.getVectorNumElements();
3976
3977   if (NumElems != 4)
3978     return false;
3979
3980   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3981   return isUndefOrEqual(Mask[0], 6) &&
3982          isUndefOrEqual(Mask[1], 7) &&
3983          isUndefOrEqual(Mask[2], 2) &&
3984          isUndefOrEqual(Mask[3], 3);
3985 }
3986
3987 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3988 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3989 /// <2, 3, 2, 3>
3990 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3991   if (!VT.is128BitVector())
3992     return false;
3993
3994   unsigned NumElems = VT.getVectorNumElements();
3995
3996   if (NumElems != 4)
3997     return false;
3998
3999   return isUndefOrEqual(Mask[0], 2) &&
4000          isUndefOrEqual(Mask[1], 3) &&
4001          isUndefOrEqual(Mask[2], 2) &&
4002          isUndefOrEqual(Mask[3], 3);
4003 }
4004
4005 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4006 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4007 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4008   if (!VT.is128BitVector())
4009     return false;
4010
4011   unsigned NumElems = VT.getVectorNumElements();
4012
4013   if (NumElems != 2 && NumElems != 4)
4014     return false;
4015
4016   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4017     if (!isUndefOrEqual(Mask[i], i + NumElems))
4018       return false;
4019
4020   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4021     if (!isUndefOrEqual(Mask[i], i))
4022       return false;
4023
4024   return true;
4025 }
4026
4027 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4028 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4029 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4030   if (!VT.is128BitVector())
4031     return false;
4032
4033   unsigned NumElems = VT.getVectorNumElements();
4034
4035   if (NumElems != 2 && NumElems != 4)
4036     return false;
4037
4038   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4039     if (!isUndefOrEqual(Mask[i], i))
4040       return false;
4041
4042   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4043     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4044       return false;
4045
4046   return true;
4047 }
4048
4049 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4050 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4051 /// i. e: If all but one element come from the same vector.
4052 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4053   // TODO: Deal with AVX's VINSERTPS
4054   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4055     return false;
4056
4057   unsigned CorrectPosV1 = 0;
4058   unsigned CorrectPosV2 = 0;
4059   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4060     if (Mask[i] == -1) {
4061       ++CorrectPosV1;
4062       ++CorrectPosV2;
4063       continue;
4064     }
4065
4066     if (Mask[i] == i)
4067       ++CorrectPosV1;
4068     else if (Mask[i] == i + 4)
4069       ++CorrectPosV2;
4070   }
4071
4072   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4073     // We have 3 elements (undefs count as elements from any vector) from one
4074     // vector, and one from another.
4075     return true;
4076
4077   return false;
4078 }
4079
4080 //
4081 // Some special combinations that can be optimized.
4082 //
4083 static
4084 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4085                                SelectionDAG &DAG) {
4086   MVT VT = SVOp->getSimpleValueType(0);
4087   SDLoc dl(SVOp);
4088
4089   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4090     return SDValue();
4091
4092   ArrayRef<int> Mask = SVOp->getMask();
4093
4094   // These are the special masks that may be optimized.
4095   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4096   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4097   bool MatchEvenMask = true;
4098   bool MatchOddMask  = true;
4099   for (int i=0; i<8; ++i) {
4100     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4101       MatchEvenMask = false;
4102     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4103       MatchOddMask = false;
4104   }
4105
4106   if (!MatchEvenMask && !MatchOddMask)
4107     return SDValue();
4108
4109   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4110
4111   SDValue Op0 = SVOp->getOperand(0);
4112   SDValue Op1 = SVOp->getOperand(1);
4113
4114   if (MatchEvenMask) {
4115     // Shift the second operand right to 32 bits.
4116     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4117     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4118   } else {
4119     // Shift the first operand left to 32 bits.
4120     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4121     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4122   }
4123   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4124   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4125 }
4126
4127 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4128 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4129 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4130                          bool HasInt256, bool V2IsSplat = false) {
4131
4132   assert(VT.getSizeInBits() >= 128 &&
4133          "Unsupported vector type for unpckl");
4134
4135   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4136   unsigned NumLanes;
4137   unsigned NumOf256BitLanes;
4138   unsigned NumElts = VT.getVectorNumElements();
4139   if (VT.is256BitVector()) {
4140     if (NumElts != 4 && NumElts != 8 &&
4141         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4142     return false;
4143     NumLanes = 2;
4144     NumOf256BitLanes = 1;
4145   } else if (VT.is512BitVector()) {
4146     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4147            "Unsupported vector type for unpckh");
4148     NumLanes = 2;
4149     NumOf256BitLanes = 2;
4150   } else {
4151     NumLanes = 1;
4152     NumOf256BitLanes = 1;
4153   }
4154
4155   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4156   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4157
4158   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4159     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4160       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4161         int BitI  = Mask[l256*NumEltsInStride+l+i];
4162         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4163         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4164           return false;
4165         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4166           return false;
4167         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4168           return false;
4169       }
4170     }
4171   }
4172   return true;
4173 }
4174
4175 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4176 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4177 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4178                          bool HasInt256, bool V2IsSplat = false) {
4179   assert(VT.getSizeInBits() >= 128 &&
4180          "Unsupported vector type for unpckh");
4181
4182   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4183   unsigned NumLanes;
4184   unsigned NumOf256BitLanes;
4185   unsigned NumElts = VT.getVectorNumElements();
4186   if (VT.is256BitVector()) {
4187     if (NumElts != 4 && NumElts != 8 &&
4188         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4189     return false;
4190     NumLanes = 2;
4191     NumOf256BitLanes = 1;
4192   } else if (VT.is512BitVector()) {
4193     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4194            "Unsupported vector type for unpckh");
4195     NumLanes = 2;
4196     NumOf256BitLanes = 2;
4197   } else {
4198     NumLanes = 1;
4199     NumOf256BitLanes = 1;
4200   }
4201
4202   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4203   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4204
4205   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4206     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4207       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4208         int BitI  = Mask[l256*NumEltsInStride+l+i];
4209         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4210         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4211           return false;
4212         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4213           return false;
4214         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4215           return false;
4216       }
4217     }
4218   }
4219   return true;
4220 }
4221
4222 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4223 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4224 /// <0, 0, 1, 1>
4225 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4226   unsigned NumElts = VT.getVectorNumElements();
4227   bool Is256BitVec = VT.is256BitVector();
4228
4229   if (VT.is512BitVector())
4230     return false;
4231   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4232          "Unsupported vector type for unpckh");
4233
4234   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4235       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4236     return false;
4237
4238   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4239   // FIXME: Need a better way to get rid of this, there's no latency difference
4240   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4241   // the former later. We should also remove the "_undef" special mask.
4242   if (NumElts == 4 && Is256BitVec)
4243     return false;
4244
4245   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4246   // independently on 128-bit lanes.
4247   unsigned NumLanes = VT.getSizeInBits()/128;
4248   unsigned NumLaneElts = NumElts/NumLanes;
4249
4250   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4251     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4252       int BitI  = Mask[l+i];
4253       int BitI1 = Mask[l+i+1];
4254
4255       if (!isUndefOrEqual(BitI, j))
4256         return false;
4257       if (!isUndefOrEqual(BitI1, j))
4258         return false;
4259     }
4260   }
4261
4262   return true;
4263 }
4264
4265 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4266 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4267 /// <2, 2, 3, 3>
4268 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4269   unsigned NumElts = VT.getVectorNumElements();
4270
4271   if (VT.is512BitVector())
4272     return false;
4273
4274   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4275          "Unsupported vector type for unpckh");
4276
4277   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4278       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4279     return false;
4280
4281   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4282   // independently on 128-bit lanes.
4283   unsigned NumLanes = VT.getSizeInBits()/128;
4284   unsigned NumLaneElts = NumElts/NumLanes;
4285
4286   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4287     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4288       int BitI  = Mask[l+i];
4289       int BitI1 = Mask[l+i+1];
4290       if (!isUndefOrEqual(BitI, j))
4291         return false;
4292       if (!isUndefOrEqual(BitI1, j))
4293         return false;
4294     }
4295   }
4296   return true;
4297 }
4298
4299 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4300 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4301 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4302   if (!VT.is512BitVector())
4303     return false;
4304
4305   unsigned NumElts = VT.getVectorNumElements();
4306   unsigned HalfSize = NumElts/2;
4307   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4308     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4309       *Imm = 1;
4310       return true;
4311     }
4312   }
4313   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4314     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4315       *Imm = 0;
4316       return true;
4317     }
4318   }
4319   return false;
4320 }
4321
4322 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4323 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4324 /// MOVSD, and MOVD, i.e. setting the lowest element.
4325 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4326   if (VT.getVectorElementType().getSizeInBits() < 32)
4327     return false;
4328   if (!VT.is128BitVector())
4329     return false;
4330
4331   unsigned NumElts = VT.getVectorNumElements();
4332
4333   if (!isUndefOrEqual(Mask[0], NumElts))
4334     return false;
4335
4336   for (unsigned i = 1; i != NumElts; ++i)
4337     if (!isUndefOrEqual(Mask[i], i))
4338       return false;
4339
4340   return true;
4341 }
4342
4343 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4344 /// as permutations between 128-bit chunks or halves. As an example: this
4345 /// shuffle bellow:
4346 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4347 /// The first half comes from the second half of V1 and the second half from the
4348 /// the second half of V2.
4349 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4350   if (!HasFp256 || !VT.is256BitVector())
4351     return false;
4352
4353   // The shuffle result is divided into half A and half B. In total the two
4354   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4355   // B must come from C, D, E or F.
4356   unsigned HalfSize = VT.getVectorNumElements()/2;
4357   bool MatchA = false, MatchB = false;
4358
4359   // Check if A comes from one of C, D, E, F.
4360   for (unsigned Half = 0; Half != 4; ++Half) {
4361     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4362       MatchA = true;
4363       break;
4364     }
4365   }
4366
4367   // Check if B comes from one of C, D, E, F.
4368   for (unsigned Half = 0; Half != 4; ++Half) {
4369     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4370       MatchB = true;
4371       break;
4372     }
4373   }
4374
4375   return MatchA && MatchB;
4376 }
4377
4378 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4379 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4380 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4381   MVT VT = SVOp->getSimpleValueType(0);
4382
4383   unsigned HalfSize = VT.getVectorNumElements()/2;
4384
4385   unsigned FstHalf = 0, SndHalf = 0;
4386   for (unsigned i = 0; i < HalfSize; ++i) {
4387     if (SVOp->getMaskElt(i) > 0) {
4388       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4389       break;
4390     }
4391   }
4392   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4393     if (SVOp->getMaskElt(i) > 0) {
4394       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4395       break;
4396     }
4397   }
4398
4399   return (FstHalf | (SndHalf << 4));
4400 }
4401
4402 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4403 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4404   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4405   if (EltSize < 32)
4406     return false;
4407
4408   unsigned NumElts = VT.getVectorNumElements();
4409   Imm8 = 0;
4410   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4411     for (unsigned i = 0; i != NumElts; ++i) {
4412       if (Mask[i] < 0)
4413         continue;
4414       Imm8 |= Mask[i] << (i*2);
4415     }
4416     return true;
4417   }
4418
4419   unsigned LaneSize = 4;
4420   SmallVector<int, 4> MaskVal(LaneSize, -1);
4421
4422   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4423     for (unsigned i = 0; i != LaneSize; ++i) {
4424       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4425         return false;
4426       if (Mask[i+l] < 0)
4427         continue;
4428       if (MaskVal[i] < 0) {
4429         MaskVal[i] = Mask[i+l] - l;
4430         Imm8 |= MaskVal[i] << (i*2);
4431         continue;
4432       }
4433       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4434         return false;
4435     }
4436   }
4437   return true;
4438 }
4439
4440 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4441 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4442 /// Note that VPERMIL mask matching is different depending whether theunderlying
4443 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4444 /// to the same elements of the low, but to the higher half of the source.
4445 /// In VPERMILPD the two lanes could be shuffled independently of each other
4446 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4447 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4448   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4449   if (VT.getSizeInBits() < 256 || EltSize < 32)
4450     return false;
4451   bool symetricMaskRequired = (EltSize == 32);
4452   unsigned NumElts = VT.getVectorNumElements();
4453
4454   unsigned NumLanes = VT.getSizeInBits()/128;
4455   unsigned LaneSize = NumElts/NumLanes;
4456   // 2 or 4 elements in one lane
4457
4458   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4459   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4460     for (unsigned i = 0; i != LaneSize; ++i) {
4461       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4462         return false;
4463       if (symetricMaskRequired) {
4464         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4465           ExpectedMaskVal[i] = Mask[i+l] - l;
4466           continue;
4467         }
4468         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4469           return false;
4470       }
4471     }
4472   }
4473   return true;
4474 }
4475
4476 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4477 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4478 /// element of vector 2 and the other elements to come from vector 1 in order.
4479 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4480                                bool V2IsSplat = false, bool V2IsUndef = false) {
4481   if (!VT.is128BitVector())
4482     return false;
4483
4484   unsigned NumOps = VT.getVectorNumElements();
4485   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4486     return false;
4487
4488   if (!isUndefOrEqual(Mask[0], 0))
4489     return false;
4490
4491   for (unsigned i = 1; i != NumOps; ++i)
4492     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4493           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4494           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4495       return false;
4496
4497   return true;
4498 }
4499
4500 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4501 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4502 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4503 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4504                            const X86Subtarget *Subtarget) {
4505   if (!Subtarget->hasSSE3())
4506     return false;
4507
4508   unsigned NumElems = VT.getVectorNumElements();
4509
4510   if ((VT.is128BitVector() && NumElems != 4) ||
4511       (VT.is256BitVector() && NumElems != 8) ||
4512       (VT.is512BitVector() && NumElems != 16))
4513     return false;
4514
4515   // "i+1" is the value the indexed mask element must have
4516   for (unsigned i = 0; i != NumElems; i += 2)
4517     if (!isUndefOrEqual(Mask[i], i+1) ||
4518         !isUndefOrEqual(Mask[i+1], i+1))
4519       return false;
4520
4521   return true;
4522 }
4523
4524 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4525 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4526 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4527 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4528                            const X86Subtarget *Subtarget) {
4529   if (!Subtarget->hasSSE3())
4530     return false;
4531
4532   unsigned NumElems = VT.getVectorNumElements();
4533
4534   if ((VT.is128BitVector() && NumElems != 4) ||
4535       (VT.is256BitVector() && NumElems != 8) ||
4536       (VT.is512BitVector() && NumElems != 16))
4537     return false;
4538
4539   // "i" is the value the indexed mask element must have
4540   for (unsigned i = 0; i != NumElems; i += 2)
4541     if (!isUndefOrEqual(Mask[i], i) ||
4542         !isUndefOrEqual(Mask[i+1], i))
4543       return false;
4544
4545   return true;
4546 }
4547
4548 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4549 /// specifies a shuffle of elements that is suitable for input to 256-bit
4550 /// version of MOVDDUP.
4551 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4552   if (!HasFp256 || !VT.is256BitVector())
4553     return false;
4554
4555   unsigned NumElts = VT.getVectorNumElements();
4556   if (NumElts != 4)
4557     return false;
4558
4559   for (unsigned i = 0; i != NumElts/2; ++i)
4560     if (!isUndefOrEqual(Mask[i], 0))
4561       return false;
4562   for (unsigned i = NumElts/2; i != NumElts; ++i)
4563     if (!isUndefOrEqual(Mask[i], NumElts/2))
4564       return false;
4565   return true;
4566 }
4567
4568 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4569 /// specifies a shuffle of elements that is suitable for input to 128-bit
4570 /// version of MOVDDUP.
4571 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4572   if (!VT.is128BitVector())
4573     return false;
4574
4575   unsigned e = VT.getVectorNumElements() / 2;
4576   for (unsigned i = 0; i != e; ++i)
4577     if (!isUndefOrEqual(Mask[i], i))
4578       return false;
4579   for (unsigned i = 0; i != e; ++i)
4580     if (!isUndefOrEqual(Mask[e+i], i))
4581       return false;
4582   return true;
4583 }
4584
4585 /// isVEXTRACTIndex - Return true if the specified
4586 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4587 /// suitable for instruction that extract 128 or 256 bit vectors
4588 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4589   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4590   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4591     return false;
4592
4593   // The index should be aligned on a vecWidth-bit boundary.
4594   uint64_t Index =
4595     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4596
4597   MVT VT = N->getSimpleValueType(0);
4598   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4599   bool Result = (Index * ElSize) % vecWidth == 0;
4600
4601   return Result;
4602 }
4603
4604 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4605 /// operand specifies a subvector insert that is suitable for input to
4606 /// insertion of 128 or 256-bit subvectors
4607 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4608   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4609   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4610     return false;
4611   // The index should be aligned on a vecWidth-bit boundary.
4612   uint64_t Index =
4613     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4614
4615   MVT VT = N->getSimpleValueType(0);
4616   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4617   bool Result = (Index * ElSize) % vecWidth == 0;
4618
4619   return Result;
4620 }
4621
4622 bool X86::isVINSERT128Index(SDNode *N) {
4623   return isVINSERTIndex(N, 128);
4624 }
4625
4626 bool X86::isVINSERT256Index(SDNode *N) {
4627   return isVINSERTIndex(N, 256);
4628 }
4629
4630 bool X86::isVEXTRACT128Index(SDNode *N) {
4631   return isVEXTRACTIndex(N, 128);
4632 }
4633
4634 bool X86::isVEXTRACT256Index(SDNode *N) {
4635   return isVEXTRACTIndex(N, 256);
4636 }
4637
4638 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4639 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4640 /// Handles 128-bit and 256-bit.
4641 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4642   MVT VT = N->getSimpleValueType(0);
4643
4644   assert((VT.getSizeInBits() >= 128) &&
4645          "Unsupported vector type for PSHUF/SHUFP");
4646
4647   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4648   // independently on 128-bit lanes.
4649   unsigned NumElts = VT.getVectorNumElements();
4650   unsigned NumLanes = VT.getSizeInBits()/128;
4651   unsigned NumLaneElts = NumElts/NumLanes;
4652
4653   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4654          "Only supports 2, 4 or 8 elements per lane");
4655
4656   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4657   unsigned Mask = 0;
4658   for (unsigned i = 0; i != NumElts; ++i) {
4659     int Elt = N->getMaskElt(i);
4660     if (Elt < 0) continue;
4661     Elt &= NumLaneElts - 1;
4662     unsigned ShAmt = (i << Shift) % 8;
4663     Mask |= Elt << ShAmt;
4664   }
4665
4666   return Mask;
4667 }
4668
4669 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4670 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4671 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4672   MVT VT = N->getSimpleValueType(0);
4673
4674   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4675          "Unsupported vector type for PSHUFHW");
4676
4677   unsigned NumElts = VT.getVectorNumElements();
4678
4679   unsigned Mask = 0;
4680   for (unsigned l = 0; l != NumElts; l += 8) {
4681     // 8 nodes per lane, but we only care about the last 4.
4682     for (unsigned i = 0; i < 4; ++i) {
4683       int Elt = N->getMaskElt(l+i+4);
4684       if (Elt < 0) continue;
4685       Elt &= 0x3; // only 2-bits.
4686       Mask |= Elt << (i * 2);
4687     }
4688   }
4689
4690   return Mask;
4691 }
4692
4693 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4694 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4695 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4696   MVT VT = N->getSimpleValueType(0);
4697
4698   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4699          "Unsupported vector type for PSHUFHW");
4700
4701   unsigned NumElts = VT.getVectorNumElements();
4702
4703   unsigned Mask = 0;
4704   for (unsigned l = 0; l != NumElts; l += 8) {
4705     // 8 nodes per lane, but we only care about the first 4.
4706     for (unsigned i = 0; i < 4; ++i) {
4707       int Elt = N->getMaskElt(l+i);
4708       if (Elt < 0) continue;
4709       Elt &= 0x3; // only 2-bits
4710       Mask |= Elt << (i * 2);
4711     }
4712   }
4713
4714   return Mask;
4715 }
4716
4717 /// \brief Return the appropriate immediate to shuffle the specified
4718 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4719 /// VALIGN (if Interlane is true) instructions.
4720 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4721                                            bool InterLane) {
4722   MVT VT = SVOp->getSimpleValueType(0);
4723   unsigned EltSize = InterLane ? 1 :
4724     VT.getVectorElementType().getSizeInBits() >> 3;
4725
4726   unsigned NumElts = VT.getVectorNumElements();
4727   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4728   unsigned NumLaneElts = NumElts/NumLanes;
4729
4730   int Val = 0;
4731   unsigned i;
4732   for (i = 0; i != NumElts; ++i) {
4733     Val = SVOp->getMaskElt(i);
4734     if (Val >= 0)
4735       break;
4736   }
4737   if (Val >= (int)NumElts)
4738     Val -= NumElts - NumLaneElts;
4739
4740   assert(Val - i > 0 && "PALIGNR imm should be positive");
4741   return (Val - i) * EltSize;
4742 }
4743
4744 /// \brief Return the appropriate immediate to shuffle the specified
4745 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4746 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4747   return getShuffleAlignrImmediate(SVOp, false);
4748 }
4749
4750 /// \brief Return the appropriate immediate to shuffle the specified
4751 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4752 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4753   return getShuffleAlignrImmediate(SVOp, true);
4754 }
4755
4756
4757 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4758   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4759   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4760     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4761
4762   uint64_t Index =
4763     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4764
4765   MVT VecVT = N->getOperand(0).getSimpleValueType();
4766   MVT ElVT = VecVT.getVectorElementType();
4767
4768   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4769   return Index / NumElemsPerChunk;
4770 }
4771
4772 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4773   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4774   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4775     llvm_unreachable("Illegal insert subvector for VINSERT");
4776
4777   uint64_t Index =
4778     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4779
4780   MVT VecVT = N->getSimpleValueType(0);
4781   MVT ElVT = VecVT.getVectorElementType();
4782
4783   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4784   return Index / NumElemsPerChunk;
4785 }
4786
4787 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4788 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4789 /// and VINSERTI128 instructions.
4790 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4791   return getExtractVEXTRACTImmediate(N, 128);
4792 }
4793
4794 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4795 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4796 /// and VINSERTI64x4 instructions.
4797 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4798   return getExtractVEXTRACTImmediate(N, 256);
4799 }
4800
4801 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4802 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4803 /// and VINSERTI128 instructions.
4804 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4805   return getInsertVINSERTImmediate(N, 128);
4806 }
4807
4808 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4809 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4810 /// and VINSERTI64x4 instructions.
4811 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4812   return getInsertVINSERTImmediate(N, 256);
4813 }
4814
4815 /// isZero - Returns true if Elt is a constant integer zero
4816 static bool isZero(SDValue V) {
4817   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4818   return C && C->isNullValue();
4819 }
4820
4821 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4822 /// constant +0.0.
4823 bool X86::isZeroNode(SDValue Elt) {
4824   if (isZero(Elt))
4825     return true;
4826   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4827     return CFP->getValueAPF().isPosZero();
4828   return false;
4829 }
4830
4831 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4832 /// match movhlps. The lower half elements should come from upper half of
4833 /// V1 (and in order), and the upper half elements should come from the upper
4834 /// half of V2 (and in order).
4835 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4836   if (!VT.is128BitVector())
4837     return false;
4838   if (VT.getVectorNumElements() != 4)
4839     return false;
4840   for (unsigned i = 0, e = 2; i != e; ++i)
4841     if (!isUndefOrEqual(Mask[i], i+2))
4842       return false;
4843   for (unsigned i = 2; i != 4; ++i)
4844     if (!isUndefOrEqual(Mask[i], i+4))
4845       return false;
4846   return true;
4847 }
4848
4849 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4850 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4851 /// required.
4852 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4853   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4854     return false;
4855   N = N->getOperand(0).getNode();
4856   if (!ISD::isNON_EXTLoad(N))
4857     return false;
4858   if (LD)
4859     *LD = cast<LoadSDNode>(N);
4860   return true;
4861 }
4862
4863 // Test whether the given value is a vector value which will be legalized
4864 // into a load.
4865 static bool WillBeConstantPoolLoad(SDNode *N) {
4866   if (N->getOpcode() != ISD::BUILD_VECTOR)
4867     return false;
4868
4869   // Check for any non-constant elements.
4870   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4871     switch (N->getOperand(i).getNode()->getOpcode()) {
4872     case ISD::UNDEF:
4873     case ISD::ConstantFP:
4874     case ISD::Constant:
4875       break;
4876     default:
4877       return false;
4878     }
4879
4880   // Vectors of all-zeros and all-ones are materialized with special
4881   // instructions rather than being loaded.
4882   return !ISD::isBuildVectorAllZeros(N) &&
4883          !ISD::isBuildVectorAllOnes(N);
4884 }
4885
4886 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4887 /// match movlp{s|d}. The lower half elements should come from lower half of
4888 /// V1 (and in order), and the upper half elements should come from the upper
4889 /// half of V2 (and in order). And since V1 will become the source of the
4890 /// MOVLP, it must be either a vector load or a scalar load to vector.
4891 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4892                                ArrayRef<int> Mask, MVT VT) {
4893   if (!VT.is128BitVector())
4894     return false;
4895
4896   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4897     return false;
4898   // Is V2 is a vector load, don't do this transformation. We will try to use
4899   // load folding shufps op.
4900   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4901     return false;
4902
4903   unsigned NumElems = VT.getVectorNumElements();
4904
4905   if (NumElems != 2 && NumElems != 4)
4906     return false;
4907   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4908     if (!isUndefOrEqual(Mask[i], i))
4909       return false;
4910   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4911     if (!isUndefOrEqual(Mask[i], i+NumElems))
4912       return false;
4913   return true;
4914 }
4915
4916 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4917 /// to an zero vector.
4918 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4919 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4920   SDValue V1 = N->getOperand(0);
4921   SDValue V2 = N->getOperand(1);
4922   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4923   for (unsigned i = 0; i != NumElems; ++i) {
4924     int Idx = N->getMaskElt(i);
4925     if (Idx >= (int)NumElems) {
4926       unsigned Opc = V2.getOpcode();
4927       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4928         continue;
4929       if (Opc != ISD::BUILD_VECTOR ||
4930           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4931         return false;
4932     } else if (Idx >= 0) {
4933       unsigned Opc = V1.getOpcode();
4934       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4935         continue;
4936       if (Opc != ISD::BUILD_VECTOR ||
4937           !X86::isZeroNode(V1.getOperand(Idx)))
4938         return false;
4939     }
4940   }
4941   return true;
4942 }
4943
4944 /// getZeroVector - Returns a vector of specified type with all zero elements.
4945 ///
4946 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4947                              SelectionDAG &DAG, SDLoc dl) {
4948   assert(VT.isVector() && "Expected a vector type");
4949
4950   // Always build SSE zero vectors as <4 x i32> bitcasted
4951   // to their dest type. This ensures they get CSE'd.
4952   SDValue Vec;
4953   if (VT.is128BitVector()) {  // SSE
4954     if (Subtarget->hasSSE2()) {  // SSE2
4955       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4956       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4957     } else { // SSE1
4958       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4959       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4960     }
4961   } else if (VT.is256BitVector()) { // AVX
4962     if (Subtarget->hasInt256()) { // AVX2
4963       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4964       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4965       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4966     } else {
4967       // 256-bit logic and arithmetic instructions in AVX are all
4968       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4969       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4970       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4971       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4972     }
4973   } else if (VT.is512BitVector()) { // AVX-512
4974       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4975       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4976                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4977       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4978   } else if (VT.getScalarType() == MVT::i1) {
4979     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4980     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4981     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4982     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4983   } else
4984     llvm_unreachable("Unexpected vector type");
4985
4986   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4987 }
4988
4989 /// getOnesVector - Returns a vector of specified type with all bits set.
4990 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4991 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4992 /// Then bitcast to their original type, ensuring they get CSE'd.
4993 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4994                              SDLoc dl) {
4995   assert(VT.isVector() && "Expected a vector type");
4996
4997   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4998   SDValue Vec;
4999   if (VT.is256BitVector()) {
5000     if (HasInt256) { // AVX2
5001       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5002       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5003     } else { // AVX
5004       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5005       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5006     }
5007   } else if (VT.is128BitVector()) {
5008     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5009   } else
5010     llvm_unreachable("Unexpected vector type");
5011
5012   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5013 }
5014
5015 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5016 /// that point to V2 points to its first element.
5017 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5018   for (unsigned i = 0; i != NumElems; ++i) {
5019     if (Mask[i] > (int)NumElems) {
5020       Mask[i] = NumElems;
5021     }
5022   }
5023 }
5024
5025 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5026 /// operation of specified width.
5027 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5028                        SDValue V2) {
5029   unsigned NumElems = VT.getVectorNumElements();
5030   SmallVector<int, 8> Mask;
5031   Mask.push_back(NumElems);
5032   for (unsigned i = 1; i != NumElems; ++i)
5033     Mask.push_back(i);
5034   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5035 }
5036
5037 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5038 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5039                           SDValue V2) {
5040   unsigned NumElems = VT.getVectorNumElements();
5041   SmallVector<int, 8> Mask;
5042   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5043     Mask.push_back(i);
5044     Mask.push_back(i + NumElems);
5045   }
5046   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5047 }
5048
5049 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5050 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5051                           SDValue V2) {
5052   unsigned NumElems = VT.getVectorNumElements();
5053   SmallVector<int, 8> Mask;
5054   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5055     Mask.push_back(i + Half);
5056     Mask.push_back(i + NumElems + Half);
5057   }
5058   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5059 }
5060
5061 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5062 // a generic shuffle instruction because the target has no such instructions.
5063 // Generate shuffles which repeat i16 and i8 several times until they can be
5064 // represented by v4f32 and then be manipulated by target suported shuffles.
5065 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5066   MVT VT = V.getSimpleValueType();
5067   int NumElems = VT.getVectorNumElements();
5068   SDLoc dl(V);
5069
5070   while (NumElems > 4) {
5071     if (EltNo < NumElems/2) {
5072       V = getUnpackl(DAG, dl, VT, V, V);
5073     } else {
5074       V = getUnpackh(DAG, dl, VT, V, V);
5075       EltNo -= NumElems/2;
5076     }
5077     NumElems >>= 1;
5078   }
5079   return V;
5080 }
5081
5082 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5083 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5084   MVT VT = V.getSimpleValueType();
5085   SDLoc dl(V);
5086
5087   if (VT.is128BitVector()) {
5088     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5089     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5090     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5091                              &SplatMask[0]);
5092   } else if (VT.is256BitVector()) {
5093     // To use VPERMILPS to splat scalars, the second half of indicies must
5094     // refer to the higher part, which is a duplication of the lower one,
5095     // because VPERMILPS can only handle in-lane permutations.
5096     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5097                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5098
5099     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5100     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5101                              &SplatMask[0]);
5102   } else
5103     llvm_unreachable("Vector size not supported");
5104
5105   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5106 }
5107
5108 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5109 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5110   MVT SrcVT = SV->getSimpleValueType(0);
5111   SDValue V1 = SV->getOperand(0);
5112   SDLoc dl(SV);
5113
5114   int EltNo = SV->getSplatIndex();
5115   int NumElems = SrcVT.getVectorNumElements();
5116   bool Is256BitVec = SrcVT.is256BitVector();
5117
5118   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5119          "Unknown how to promote splat for type");
5120
5121   // Extract the 128-bit part containing the splat element and update
5122   // the splat element index when it refers to the higher register.
5123   if (Is256BitVec) {
5124     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5125     if (EltNo >= NumElems/2)
5126       EltNo -= NumElems/2;
5127   }
5128
5129   // All i16 and i8 vector types can't be used directly by a generic shuffle
5130   // instruction because the target has no such instruction. Generate shuffles
5131   // which repeat i16 and i8 several times until they fit in i32, and then can
5132   // be manipulated by target suported shuffles.
5133   MVT EltVT = SrcVT.getVectorElementType();
5134   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5135     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5136
5137   // Recreate the 256-bit vector and place the same 128-bit vector
5138   // into the low and high part. This is necessary because we want
5139   // to use VPERM* to shuffle the vectors
5140   if (Is256BitVec) {
5141     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5142   }
5143
5144   return getLegalSplat(DAG, V1, EltNo);
5145 }
5146
5147 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5148 /// vector of zero or undef vector.  This produces a shuffle where the low
5149 /// element of V2 is swizzled into the zero/undef vector, landing at element
5150 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5151 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5152                                            bool IsZero,
5153                                            const X86Subtarget *Subtarget,
5154                                            SelectionDAG &DAG) {
5155   MVT VT = V2.getSimpleValueType();
5156   SDValue V1 = IsZero
5157     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5158   unsigned NumElems = VT.getVectorNumElements();
5159   SmallVector<int, 16> MaskVec;
5160   for (unsigned i = 0; i != NumElems; ++i)
5161     // If this is the insertion idx, put the low elt of V2 here.
5162     MaskVec.push_back(i == Idx ? NumElems : i);
5163   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5164 }
5165
5166 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5167 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5168 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5169 /// shuffles which use a single input multiple times, and in those cases it will
5170 /// adjust the mask to only have indices within that single input.
5171 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5172                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5173   unsigned NumElems = VT.getVectorNumElements();
5174   SDValue ImmN;
5175
5176   IsUnary = false;
5177   bool IsFakeUnary = false;
5178   switch(N->getOpcode()) {
5179   case X86ISD::SHUFP:
5180     ImmN = N->getOperand(N->getNumOperands()-1);
5181     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5182     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5183     break;
5184   case X86ISD::UNPCKH:
5185     DecodeUNPCKHMask(VT, Mask);
5186     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5187     break;
5188   case X86ISD::UNPCKL:
5189     DecodeUNPCKLMask(VT, Mask);
5190     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5191     break;
5192   case X86ISD::MOVHLPS:
5193     DecodeMOVHLPSMask(NumElems, Mask);
5194     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5195     break;
5196   case X86ISD::MOVLHPS:
5197     DecodeMOVLHPSMask(NumElems, Mask);
5198     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5199     break;
5200   case X86ISD::PALIGNR:
5201     ImmN = N->getOperand(N->getNumOperands()-1);
5202     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5203     break;
5204   case X86ISD::PSHUFD:
5205   case X86ISD::VPERMILP:
5206     ImmN = N->getOperand(N->getNumOperands()-1);
5207     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5208     IsUnary = true;
5209     break;
5210   case X86ISD::PSHUFHW:
5211     ImmN = N->getOperand(N->getNumOperands()-1);
5212     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5213     IsUnary = true;
5214     break;
5215   case X86ISD::PSHUFLW:
5216     ImmN = N->getOperand(N->getNumOperands()-1);
5217     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5218     IsUnary = true;
5219     break;
5220   case X86ISD::PSHUFB: {
5221     IsUnary = true;
5222     SDValue MaskNode = N->getOperand(1);
5223     while (MaskNode->getOpcode() == ISD::BITCAST)
5224       MaskNode = MaskNode->getOperand(0);
5225
5226     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5227       // If we have a build-vector, then things are easy.
5228       EVT VT = MaskNode.getValueType();
5229       assert(VT.isVector() &&
5230              "Can't produce a non-vector with a build_vector!");
5231       if (!VT.isInteger())
5232         return false;
5233
5234       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5235
5236       SmallVector<uint64_t, 32> RawMask;
5237       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5238         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5239         if (!CN)
5240           return false;
5241         APInt MaskElement = CN->getAPIntValue();
5242
5243         // We now have to decode the element which could be any integer size and
5244         // extract each byte of it.
5245         for (int j = 0; j < NumBytesPerElement; ++j) {
5246           // Note that this is x86 and so always little endian: the low byte is
5247           // the first byte of the mask.
5248           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5249           MaskElement = MaskElement.lshr(8);
5250         }
5251       }
5252       DecodePSHUFBMask(RawMask, Mask);
5253       break;
5254     }
5255
5256     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5257     if (!MaskLoad)
5258       return false;
5259
5260     SDValue Ptr = MaskLoad->getBasePtr();
5261     if (Ptr->getOpcode() == X86ISD::Wrapper)
5262       Ptr = Ptr->getOperand(0);
5263
5264     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5265     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5266       return false;
5267
5268     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5269       // FIXME: Support AVX-512 here.
5270       if (!C->getType()->isVectorTy() ||
5271           (C->getNumElements() != 16 && C->getNumElements() != 32))
5272         return false;
5273
5274       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5275       DecodePSHUFBMask(C, Mask);
5276       break;
5277     }
5278
5279     return false;
5280   }
5281   case X86ISD::VPERMI:
5282     ImmN = N->getOperand(N->getNumOperands()-1);
5283     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5284     IsUnary = true;
5285     break;
5286   case X86ISD::MOVSS:
5287   case X86ISD::MOVSD: {
5288     // The index 0 always comes from the first element of the second source,
5289     // this is why MOVSS and MOVSD are used in the first place. The other
5290     // elements come from the other positions of the first source vector
5291     Mask.push_back(NumElems);
5292     for (unsigned i = 1; i != NumElems; ++i) {
5293       Mask.push_back(i);
5294     }
5295     break;
5296   }
5297   case X86ISD::VPERM2X128:
5298     ImmN = N->getOperand(N->getNumOperands()-1);
5299     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5300     if (Mask.empty()) return false;
5301     break;
5302   case X86ISD::MOVDDUP:
5303   case X86ISD::MOVLHPD:
5304   case X86ISD::MOVLPD:
5305   case X86ISD::MOVLPS:
5306   case X86ISD::MOVSHDUP:
5307   case X86ISD::MOVSLDUP:
5308     // Not yet implemented
5309     return false;
5310   default: llvm_unreachable("unknown target shuffle node");
5311   }
5312
5313   // If we have a fake unary shuffle, the shuffle mask is spread across two
5314   // inputs that are actually the same node. Re-map the mask to always point
5315   // into the first input.
5316   if (IsFakeUnary)
5317     for (int &M : Mask)
5318       if (M >= (int)Mask.size())
5319         M -= Mask.size();
5320
5321   return true;
5322 }
5323
5324 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5325 /// element of the result of the vector shuffle.
5326 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5327                                    unsigned Depth) {
5328   if (Depth == 6)
5329     return SDValue();  // Limit search depth.
5330
5331   SDValue V = SDValue(N, 0);
5332   EVT VT = V.getValueType();
5333   unsigned Opcode = V.getOpcode();
5334
5335   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5336   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5337     int Elt = SV->getMaskElt(Index);
5338
5339     if (Elt < 0)
5340       return DAG.getUNDEF(VT.getVectorElementType());
5341
5342     unsigned NumElems = VT.getVectorNumElements();
5343     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5344                                          : SV->getOperand(1);
5345     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5346   }
5347
5348   // Recurse into target specific vector shuffles to find scalars.
5349   if (isTargetShuffle(Opcode)) {
5350     MVT ShufVT = V.getSimpleValueType();
5351     unsigned NumElems = ShufVT.getVectorNumElements();
5352     SmallVector<int, 16> ShuffleMask;
5353     bool IsUnary;
5354
5355     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5356       return SDValue();
5357
5358     int Elt = ShuffleMask[Index];
5359     if (Elt < 0)
5360       return DAG.getUNDEF(ShufVT.getVectorElementType());
5361
5362     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5363                                          : N->getOperand(1);
5364     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5365                                Depth+1);
5366   }
5367
5368   // Actual nodes that may contain scalar elements
5369   if (Opcode == ISD::BITCAST) {
5370     V = V.getOperand(0);
5371     EVT SrcVT = V.getValueType();
5372     unsigned NumElems = VT.getVectorNumElements();
5373
5374     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5375       return SDValue();
5376   }
5377
5378   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5379     return (Index == 0) ? V.getOperand(0)
5380                         : DAG.getUNDEF(VT.getVectorElementType());
5381
5382   if (V.getOpcode() == ISD::BUILD_VECTOR)
5383     return V.getOperand(Index);
5384
5385   return SDValue();
5386 }
5387
5388 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5389 /// shuffle operation which come from a consecutively from a zero. The
5390 /// search can start in two different directions, from left or right.
5391 /// We count undefs as zeros until PreferredNum is reached.
5392 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5393                                          unsigned NumElems, bool ZerosFromLeft,
5394                                          SelectionDAG &DAG,
5395                                          unsigned PreferredNum = -1U) {
5396   unsigned NumZeros = 0;
5397   for (unsigned i = 0; i != NumElems; ++i) {
5398     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5399     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5400     if (!Elt.getNode())
5401       break;
5402
5403     if (X86::isZeroNode(Elt))
5404       ++NumZeros;
5405     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5406       NumZeros = std::min(NumZeros + 1, PreferredNum);
5407     else
5408       break;
5409   }
5410
5411   return NumZeros;
5412 }
5413
5414 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5415 /// correspond consecutively to elements from one of the vector operands,
5416 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5417 static
5418 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5419                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5420                               unsigned NumElems, unsigned &OpNum) {
5421   bool SeenV1 = false;
5422   bool SeenV2 = false;
5423
5424   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5425     int Idx = SVOp->getMaskElt(i);
5426     // Ignore undef indicies
5427     if (Idx < 0)
5428       continue;
5429
5430     if (Idx < (int)NumElems)
5431       SeenV1 = true;
5432     else
5433       SeenV2 = true;
5434
5435     // Only accept consecutive elements from the same vector
5436     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5437       return false;
5438   }
5439
5440   OpNum = SeenV1 ? 0 : 1;
5441   return true;
5442 }
5443
5444 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5445 /// logical left shift of a vector.
5446 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5447                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5448   unsigned NumElems =
5449     SVOp->getSimpleValueType(0).getVectorNumElements();
5450   unsigned NumZeros = getNumOfConsecutiveZeros(
5451       SVOp, NumElems, false /* check zeros from right */, DAG,
5452       SVOp->getMaskElt(0));
5453   unsigned OpSrc;
5454
5455   if (!NumZeros)
5456     return false;
5457
5458   // Considering the elements in the mask that are not consecutive zeros,
5459   // check if they consecutively come from only one of the source vectors.
5460   //
5461   //               V1 = {X, A, B, C}     0
5462   //                         \  \  \    /
5463   //   vector_shuffle V1, V2 <1, 2, 3, X>
5464   //
5465   if (!isShuffleMaskConsecutive(SVOp,
5466             0,                   // Mask Start Index
5467             NumElems-NumZeros,   // Mask End Index(exclusive)
5468             NumZeros,            // Where to start looking in the src vector
5469             NumElems,            // Number of elements in vector
5470             OpSrc))              // Which source operand ?
5471     return false;
5472
5473   isLeft = false;
5474   ShAmt = NumZeros;
5475   ShVal = SVOp->getOperand(OpSrc);
5476   return true;
5477 }
5478
5479 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5480 /// logical left shift of a vector.
5481 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5482                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5483   unsigned NumElems =
5484     SVOp->getSimpleValueType(0).getVectorNumElements();
5485   unsigned NumZeros = getNumOfConsecutiveZeros(
5486       SVOp, NumElems, true /* check zeros from left */, DAG,
5487       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5488   unsigned OpSrc;
5489
5490   if (!NumZeros)
5491     return false;
5492
5493   // Considering the elements in the mask that are not consecutive zeros,
5494   // check if they consecutively come from only one of the source vectors.
5495   //
5496   //                           0    { A, B, X, X } = V2
5497   //                          / \    /  /
5498   //   vector_shuffle V1, V2 <X, X, 4, 5>
5499   //
5500   if (!isShuffleMaskConsecutive(SVOp,
5501             NumZeros,     // Mask Start Index
5502             NumElems,     // Mask End Index(exclusive)
5503             0,            // Where to start looking in the src vector
5504             NumElems,     // Number of elements in vector
5505             OpSrc))       // Which source operand ?
5506     return false;
5507
5508   isLeft = true;
5509   ShAmt = NumZeros;
5510   ShVal = SVOp->getOperand(OpSrc);
5511   return true;
5512 }
5513
5514 /// isVectorShift - Returns true if the shuffle can be implemented as a
5515 /// logical left or right shift of a vector.
5516 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5517                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5518   // Although the logic below support any bitwidth size, there are no
5519   // shift instructions which handle more than 128-bit vectors.
5520   if (!SVOp->getSimpleValueType(0).is128BitVector())
5521     return false;
5522
5523   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5524       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5525     return true;
5526
5527   return false;
5528 }
5529
5530 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5531 ///
5532 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5533                                        unsigned NumNonZero, unsigned NumZero,
5534                                        SelectionDAG &DAG,
5535                                        const X86Subtarget* Subtarget,
5536                                        const TargetLowering &TLI) {
5537   if (NumNonZero > 8)
5538     return SDValue();
5539
5540   SDLoc dl(Op);
5541   SDValue V;
5542   bool First = true;
5543   for (unsigned i = 0; i < 16; ++i) {
5544     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5545     if (ThisIsNonZero && First) {
5546       if (NumZero)
5547         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5548       else
5549         V = DAG.getUNDEF(MVT::v8i16);
5550       First = false;
5551     }
5552
5553     if ((i & 1) != 0) {
5554       SDValue ThisElt, LastElt;
5555       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5556       if (LastIsNonZero) {
5557         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5558                               MVT::i16, Op.getOperand(i-1));
5559       }
5560       if (ThisIsNonZero) {
5561         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5562         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5563                               ThisElt, DAG.getConstant(8, MVT::i8));
5564         if (LastIsNonZero)
5565           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5566       } else
5567         ThisElt = LastElt;
5568
5569       if (ThisElt.getNode())
5570         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5571                         DAG.getIntPtrConstant(i/2));
5572     }
5573   }
5574
5575   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5576 }
5577
5578 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5579 ///
5580 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5581                                      unsigned NumNonZero, unsigned NumZero,
5582                                      SelectionDAG &DAG,
5583                                      const X86Subtarget* Subtarget,
5584                                      const TargetLowering &TLI) {
5585   if (NumNonZero > 4)
5586     return SDValue();
5587
5588   SDLoc dl(Op);
5589   SDValue V;
5590   bool First = true;
5591   for (unsigned i = 0; i < 8; ++i) {
5592     bool isNonZero = (NonZeros & (1 << i)) != 0;
5593     if (isNonZero) {
5594       if (First) {
5595         if (NumZero)
5596           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5597         else
5598           V = DAG.getUNDEF(MVT::v8i16);
5599         First = false;
5600       }
5601       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5602                       MVT::v8i16, V, Op.getOperand(i),
5603                       DAG.getIntPtrConstant(i));
5604     }
5605   }
5606
5607   return V;
5608 }
5609
5610 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5611 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5612                                      unsigned NonZeros, unsigned NumNonZero,
5613                                      unsigned NumZero, SelectionDAG &DAG,
5614                                      const X86Subtarget *Subtarget,
5615                                      const TargetLowering &TLI) {
5616   // We know there's at least one non-zero element
5617   unsigned FirstNonZeroIdx = 0;
5618   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5619   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5620          X86::isZeroNode(FirstNonZero)) {
5621     ++FirstNonZeroIdx;
5622     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5623   }
5624
5625   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5626       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5627     return SDValue();
5628
5629   SDValue V = FirstNonZero.getOperand(0);
5630   MVT VVT = V.getSimpleValueType();
5631   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5632     return SDValue();
5633
5634   unsigned FirstNonZeroDst =
5635       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5636   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5637   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5638   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5639
5640   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5641     SDValue Elem = Op.getOperand(Idx);
5642     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5643       continue;
5644
5645     // TODO: What else can be here? Deal with it.
5646     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5647       return SDValue();
5648
5649     // TODO: Some optimizations are still possible here
5650     // ex: Getting one element from a vector, and the rest from another.
5651     if (Elem.getOperand(0) != V)
5652       return SDValue();
5653
5654     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5655     if (Dst == Idx)
5656       ++CorrectIdx;
5657     else if (IncorrectIdx == -1U) {
5658       IncorrectIdx = Idx;
5659       IncorrectDst = Dst;
5660     } else
5661       // There was already one element with an incorrect index.
5662       // We can't optimize this case to an insertps.
5663       return SDValue();
5664   }
5665
5666   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5667     SDLoc dl(Op);
5668     EVT VT = Op.getSimpleValueType();
5669     unsigned ElementMoveMask = 0;
5670     if (IncorrectIdx == -1U)
5671       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5672     else
5673       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5674
5675     SDValue InsertpsMask =
5676         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5677     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5678   }
5679
5680   return SDValue();
5681 }
5682
5683 /// getVShift - Return a vector logical shift node.
5684 ///
5685 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5686                          unsigned NumBits, SelectionDAG &DAG,
5687                          const TargetLowering &TLI, SDLoc dl) {
5688   assert(VT.is128BitVector() && "Unknown type for VShift");
5689   EVT ShVT = MVT::v2i64;
5690   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5691   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5692   return DAG.getNode(ISD::BITCAST, dl, VT,
5693                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5694                              DAG.getConstant(NumBits,
5695                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5696 }
5697
5698 static SDValue
5699 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5700
5701   // Check if the scalar load can be widened into a vector load. And if
5702   // the address is "base + cst" see if the cst can be "absorbed" into
5703   // the shuffle mask.
5704   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5705     SDValue Ptr = LD->getBasePtr();
5706     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5707       return SDValue();
5708     EVT PVT = LD->getValueType(0);
5709     if (PVT != MVT::i32 && PVT != MVT::f32)
5710       return SDValue();
5711
5712     int FI = -1;
5713     int64_t Offset = 0;
5714     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5715       FI = FINode->getIndex();
5716       Offset = 0;
5717     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5718                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5719       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5720       Offset = Ptr.getConstantOperandVal(1);
5721       Ptr = Ptr.getOperand(0);
5722     } else {
5723       return SDValue();
5724     }
5725
5726     // FIXME: 256-bit vector instructions don't require a strict alignment,
5727     // improve this code to support it better.
5728     unsigned RequiredAlign = VT.getSizeInBits()/8;
5729     SDValue Chain = LD->getChain();
5730     // Make sure the stack object alignment is at least 16 or 32.
5731     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5732     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5733       if (MFI->isFixedObjectIndex(FI)) {
5734         // Can't change the alignment. FIXME: It's possible to compute
5735         // the exact stack offset and reference FI + adjust offset instead.
5736         // If someone *really* cares about this. That's the way to implement it.
5737         return SDValue();
5738       } else {
5739         MFI->setObjectAlignment(FI, RequiredAlign);
5740       }
5741     }
5742
5743     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5744     // Ptr + (Offset & ~15).
5745     if (Offset < 0)
5746       return SDValue();
5747     if ((Offset % RequiredAlign) & 3)
5748       return SDValue();
5749     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5750     if (StartOffset)
5751       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5752                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5753
5754     int EltNo = (Offset - StartOffset) >> 2;
5755     unsigned NumElems = VT.getVectorNumElements();
5756
5757     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5758     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5759                              LD->getPointerInfo().getWithOffset(StartOffset),
5760                              false, false, false, 0);
5761
5762     SmallVector<int, 8> Mask;
5763     for (unsigned i = 0; i != NumElems; ++i)
5764       Mask.push_back(EltNo);
5765
5766     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5767   }
5768
5769   return SDValue();
5770 }
5771
5772 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5773 /// vector of type 'VT', see if the elements can be replaced by a single large
5774 /// load which has the same value as a build_vector whose operands are 'elts'.
5775 ///
5776 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5777 ///
5778 /// FIXME: we'd also like to handle the case where the last elements are zero
5779 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5780 /// There's even a handy isZeroNode for that purpose.
5781 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5782                                         SDLoc &DL, SelectionDAG &DAG,
5783                                         bool isAfterLegalize) {
5784   EVT EltVT = VT.getVectorElementType();
5785   unsigned NumElems = Elts.size();
5786
5787   LoadSDNode *LDBase = nullptr;
5788   unsigned LastLoadedElt = -1U;
5789
5790   // For each element in the initializer, see if we've found a load or an undef.
5791   // If we don't find an initial load element, or later load elements are
5792   // non-consecutive, bail out.
5793   for (unsigned i = 0; i < NumElems; ++i) {
5794     SDValue Elt = Elts[i];
5795
5796     if (!Elt.getNode() ||
5797         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5798       return SDValue();
5799     if (!LDBase) {
5800       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5801         return SDValue();
5802       LDBase = cast<LoadSDNode>(Elt.getNode());
5803       LastLoadedElt = i;
5804       continue;
5805     }
5806     if (Elt.getOpcode() == ISD::UNDEF)
5807       continue;
5808
5809     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5810     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5811       return SDValue();
5812     LastLoadedElt = i;
5813   }
5814
5815   // If we have found an entire vector of loads and undefs, then return a large
5816   // load of the entire vector width starting at the base pointer.  If we found
5817   // consecutive loads for the low half, generate a vzext_load node.
5818   if (LastLoadedElt == NumElems - 1) {
5819
5820     if (isAfterLegalize &&
5821         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5822       return SDValue();
5823
5824     SDValue NewLd = SDValue();
5825
5826     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5827       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5828                           LDBase->getPointerInfo(),
5829                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5830                           LDBase->isInvariant(), 0);
5831     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5832                         LDBase->getPointerInfo(),
5833                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5834                         LDBase->isInvariant(), LDBase->getAlignment());
5835
5836     if (LDBase->hasAnyUseOfValue(1)) {
5837       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5838                                      SDValue(LDBase, 1),
5839                                      SDValue(NewLd.getNode(), 1));
5840       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5841       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5842                              SDValue(NewLd.getNode(), 1));
5843     }
5844
5845     return NewLd;
5846   }
5847   if (NumElems == 4 && LastLoadedElt == 1 &&
5848       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5849     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5850     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5851     SDValue ResNode =
5852         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5853                                 LDBase->getPointerInfo(),
5854                                 LDBase->getAlignment(),
5855                                 false/*isVolatile*/, true/*ReadMem*/,
5856                                 false/*WriteMem*/);
5857
5858     // Make sure the newly-created LOAD is in the same position as LDBase in
5859     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5860     // update uses of LDBase's output chain to use the TokenFactor.
5861     if (LDBase->hasAnyUseOfValue(1)) {
5862       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5863                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5864       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5865       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5866                              SDValue(ResNode.getNode(), 1));
5867     }
5868
5869     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5870   }
5871   return SDValue();
5872 }
5873
5874 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5875 /// to generate a splat value for the following cases:
5876 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5877 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5878 /// a scalar load, or a constant.
5879 /// The VBROADCAST node is returned when a pattern is found,
5880 /// or SDValue() otherwise.
5881 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5882                                     SelectionDAG &DAG) {
5883   if (!Subtarget->hasFp256())
5884     return SDValue();
5885
5886   MVT VT = Op.getSimpleValueType();
5887   SDLoc dl(Op);
5888
5889   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5890          "Unsupported vector type for broadcast.");
5891
5892   SDValue Ld;
5893   bool ConstSplatVal;
5894
5895   switch (Op.getOpcode()) {
5896     default:
5897       // Unknown pattern found.
5898       return SDValue();
5899
5900     case ISD::BUILD_VECTOR: {
5901       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5902       BitVector UndefElements;
5903       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5904
5905       // We need a splat of a single value to use broadcast, and it doesn't
5906       // make any sense if the value is only in one element of the vector.
5907       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5908         return SDValue();
5909
5910       Ld = Splat;
5911       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5912                        Ld.getOpcode() == ISD::ConstantFP);
5913
5914       // Make sure that all of the users of a non-constant load are from the
5915       // BUILD_VECTOR node.
5916       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5917         return SDValue();
5918       break;
5919     }
5920
5921     case ISD::VECTOR_SHUFFLE: {
5922       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5923
5924       // Shuffles must have a splat mask where the first element is
5925       // broadcasted.
5926       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5927         return SDValue();
5928
5929       SDValue Sc = Op.getOperand(0);
5930       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5931           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5932
5933         if (!Subtarget->hasInt256())
5934           return SDValue();
5935
5936         // Use the register form of the broadcast instruction available on AVX2.
5937         if (VT.getSizeInBits() >= 256)
5938           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5939         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5940       }
5941
5942       Ld = Sc.getOperand(0);
5943       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5944                        Ld.getOpcode() == ISD::ConstantFP);
5945
5946       // The scalar_to_vector node and the suspected
5947       // load node must have exactly one user.
5948       // Constants may have multiple users.
5949
5950       // AVX-512 has register version of the broadcast
5951       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5952         Ld.getValueType().getSizeInBits() >= 32;
5953       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5954           !hasRegVer))
5955         return SDValue();
5956       break;
5957     }
5958   }
5959
5960   bool IsGE256 = (VT.getSizeInBits() >= 256);
5961
5962   // Handle the broadcasting a single constant scalar from the constant pool
5963   // into a vector. On Sandybridge it is still better to load a constant vector
5964   // from the constant pool and not to broadcast it from a scalar.
5965   if (ConstSplatVal && Subtarget->hasInt256()) {
5966     EVT CVT = Ld.getValueType();
5967     assert(!CVT.isVector() && "Must not broadcast a vector type");
5968     unsigned ScalarSize = CVT.getSizeInBits();
5969
5970     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5971       const Constant *C = nullptr;
5972       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5973         C = CI->getConstantIntValue();
5974       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5975         C = CF->getConstantFPValue();
5976
5977       assert(C && "Invalid constant type");
5978
5979       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5980       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5981       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5982       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5983                        MachinePointerInfo::getConstantPool(),
5984                        false, false, false, Alignment);
5985
5986       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5987     }
5988   }
5989
5990   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5991   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5992
5993   // Handle AVX2 in-register broadcasts.
5994   if (!IsLoad && Subtarget->hasInt256() &&
5995       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5996     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5997
5998   // The scalar source must be a normal load.
5999   if (!IsLoad)
6000     return SDValue();
6001
6002   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6003     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6004
6005   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6006   // double since there is no vbroadcastsd xmm
6007   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6008     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6009       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6010   }
6011
6012   // Unsupported broadcast.
6013   return SDValue();
6014 }
6015
6016 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6017 /// underlying vector and index.
6018 ///
6019 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6020 /// index.
6021 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6022                                          SDValue ExtIdx) {
6023   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6024   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6025     return Idx;
6026
6027   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6028   // lowered this:
6029   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6030   // to:
6031   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6032   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6033   //                           undef)
6034   //                       Constant<0>)
6035   // In this case the vector is the extract_subvector expression and the index
6036   // is 2, as specified by the shuffle.
6037   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6038   SDValue ShuffleVec = SVOp->getOperand(0);
6039   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6040   assert(ShuffleVecVT.getVectorElementType() ==
6041          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6042
6043   int ShuffleIdx = SVOp->getMaskElt(Idx);
6044   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6045     ExtractedFromVec = ShuffleVec;
6046     return ShuffleIdx;
6047   }
6048   return Idx;
6049 }
6050
6051 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6052   MVT VT = Op.getSimpleValueType();
6053
6054   // Skip if insert_vec_elt is not supported.
6055   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6056   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6057     return SDValue();
6058
6059   SDLoc DL(Op);
6060   unsigned NumElems = Op.getNumOperands();
6061
6062   SDValue VecIn1;
6063   SDValue VecIn2;
6064   SmallVector<unsigned, 4> InsertIndices;
6065   SmallVector<int, 8> Mask(NumElems, -1);
6066
6067   for (unsigned i = 0; i != NumElems; ++i) {
6068     unsigned Opc = Op.getOperand(i).getOpcode();
6069
6070     if (Opc == ISD::UNDEF)
6071       continue;
6072
6073     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6074       // Quit if more than 1 elements need inserting.
6075       if (InsertIndices.size() > 1)
6076         return SDValue();
6077
6078       InsertIndices.push_back(i);
6079       continue;
6080     }
6081
6082     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6083     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6084     // Quit if non-constant index.
6085     if (!isa<ConstantSDNode>(ExtIdx))
6086       return SDValue();
6087     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6088
6089     // Quit if extracted from vector of different type.
6090     if (ExtractedFromVec.getValueType() != VT)
6091       return SDValue();
6092
6093     if (!VecIn1.getNode())
6094       VecIn1 = ExtractedFromVec;
6095     else if (VecIn1 != ExtractedFromVec) {
6096       if (!VecIn2.getNode())
6097         VecIn2 = ExtractedFromVec;
6098       else if (VecIn2 != ExtractedFromVec)
6099         // Quit if more than 2 vectors to shuffle
6100         return SDValue();
6101     }
6102
6103     if (ExtractedFromVec == VecIn1)
6104       Mask[i] = Idx;
6105     else if (ExtractedFromVec == VecIn2)
6106       Mask[i] = Idx + NumElems;
6107   }
6108
6109   if (!VecIn1.getNode())
6110     return SDValue();
6111
6112   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6113   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6114   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6115     unsigned Idx = InsertIndices[i];
6116     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6117                      DAG.getIntPtrConstant(Idx));
6118   }
6119
6120   return NV;
6121 }
6122
6123 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6124 SDValue
6125 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6126
6127   MVT VT = Op.getSimpleValueType();
6128   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6129          "Unexpected type in LowerBUILD_VECTORvXi1!");
6130
6131   SDLoc dl(Op);
6132   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6133     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6134     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6135     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6136   }
6137
6138   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6139     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6140     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6141     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6142   }
6143
6144   bool AllContants = true;
6145   uint64_t Immediate = 0;
6146   int NonConstIdx = -1;
6147   bool IsSplat = true;
6148   unsigned NumNonConsts = 0;
6149   unsigned NumConsts = 0;
6150   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6151     SDValue In = Op.getOperand(idx);
6152     if (In.getOpcode() == ISD::UNDEF)
6153       continue;
6154     if (!isa<ConstantSDNode>(In)) {
6155       AllContants = false;
6156       NonConstIdx = idx;
6157       NumNonConsts++;
6158     }
6159     else {
6160       NumConsts++;
6161       if (cast<ConstantSDNode>(In)->getZExtValue())
6162       Immediate |= (1ULL << idx);
6163     }
6164     if (In != Op.getOperand(0))
6165       IsSplat = false;
6166   }
6167
6168   if (AllContants) {
6169     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6170       DAG.getConstant(Immediate, MVT::i16));
6171     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6172                        DAG.getIntPtrConstant(0));
6173   }
6174
6175   if (NumNonConsts == 1 && NonConstIdx != 0) {
6176     SDValue DstVec;
6177     if (NumConsts) {
6178       SDValue VecAsImm = DAG.getConstant(Immediate,
6179                                          MVT::getIntegerVT(VT.getSizeInBits()));
6180       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6181     }
6182     else 
6183       DstVec = DAG.getUNDEF(VT);
6184     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6185                        Op.getOperand(NonConstIdx),
6186                        DAG.getIntPtrConstant(NonConstIdx));
6187   }
6188   if (!IsSplat && (NonConstIdx != 0))
6189     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6190   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6191   SDValue Select;
6192   if (IsSplat)
6193     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6194                           DAG.getConstant(-1, SelectVT),
6195                           DAG.getConstant(0, SelectVT));
6196   else
6197     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6198                          DAG.getConstant((Immediate | 1), SelectVT),
6199                          DAG.getConstant(Immediate, SelectVT));
6200   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6201 }
6202
6203 /// \brief Return true if \p N implements a horizontal binop and return the
6204 /// operands for the horizontal binop into V0 and V1.
6205 /// 
6206 /// This is a helper function of PerformBUILD_VECTORCombine.
6207 /// This function checks that the build_vector \p N in input implements a
6208 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6209 /// operation to match.
6210 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6211 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6212 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6213 /// arithmetic sub.
6214 ///
6215 /// This function only analyzes elements of \p N whose indices are
6216 /// in range [BaseIdx, LastIdx).
6217 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6218                               SelectionDAG &DAG,
6219                               unsigned BaseIdx, unsigned LastIdx,
6220                               SDValue &V0, SDValue &V1) {
6221   EVT VT = N->getValueType(0);
6222
6223   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6224   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6225          "Invalid Vector in input!");
6226   
6227   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6228   bool CanFold = true;
6229   unsigned ExpectedVExtractIdx = BaseIdx;
6230   unsigned NumElts = LastIdx - BaseIdx;
6231   V0 = DAG.getUNDEF(VT);
6232   V1 = DAG.getUNDEF(VT);
6233
6234   // Check if N implements a horizontal binop.
6235   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6236     SDValue Op = N->getOperand(i + BaseIdx);
6237
6238     // Skip UNDEFs.
6239     if (Op->getOpcode() == ISD::UNDEF) {
6240       // Update the expected vector extract index.
6241       if (i * 2 == NumElts)
6242         ExpectedVExtractIdx = BaseIdx;
6243       ExpectedVExtractIdx += 2;
6244       continue;
6245     }
6246
6247     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6248
6249     if (!CanFold)
6250       break;
6251
6252     SDValue Op0 = Op.getOperand(0);
6253     SDValue Op1 = Op.getOperand(1);
6254
6255     // Try to match the following pattern:
6256     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6257     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6258         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6259         Op0.getOperand(0) == Op1.getOperand(0) &&
6260         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6261         isa<ConstantSDNode>(Op1.getOperand(1)));
6262     if (!CanFold)
6263       break;
6264
6265     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6266     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6267
6268     if (i * 2 < NumElts) {
6269       if (V0.getOpcode() == ISD::UNDEF)
6270         V0 = Op0.getOperand(0);
6271     } else {
6272       if (V1.getOpcode() == ISD::UNDEF)
6273         V1 = Op0.getOperand(0);
6274       if (i * 2 == NumElts)
6275         ExpectedVExtractIdx = BaseIdx;
6276     }
6277
6278     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6279     if (I0 == ExpectedVExtractIdx)
6280       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6281     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6282       // Try to match the following dag sequence:
6283       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6284       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6285     } else
6286       CanFold = false;
6287
6288     ExpectedVExtractIdx += 2;
6289   }
6290
6291   return CanFold;
6292 }
6293
6294 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6295 /// a concat_vector. 
6296 ///
6297 /// This is a helper function of PerformBUILD_VECTORCombine.
6298 /// This function expects two 256-bit vectors called V0 and V1.
6299 /// At first, each vector is split into two separate 128-bit vectors.
6300 /// Then, the resulting 128-bit vectors are used to implement two
6301 /// horizontal binary operations. 
6302 ///
6303 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6304 ///
6305 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6306 /// the two new horizontal binop.
6307 /// When Mode is set, the first horizontal binop dag node would take as input
6308 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6309 /// horizontal binop dag node would take as input the lower 128-bit of V1
6310 /// and the upper 128-bit of V1.
6311 ///   Example:
6312 ///     HADD V0_LO, V0_HI
6313 ///     HADD V1_LO, V1_HI
6314 ///
6315 /// Otherwise, the first horizontal binop dag node takes as input the lower
6316 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6317 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6318 ///   Example:
6319 ///     HADD V0_LO, V1_LO
6320 ///     HADD V0_HI, V1_HI
6321 ///
6322 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6323 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6324 /// the upper 128-bits of the result.
6325 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6326                                      SDLoc DL, SelectionDAG &DAG,
6327                                      unsigned X86Opcode, bool Mode,
6328                                      bool isUndefLO, bool isUndefHI) {
6329   EVT VT = V0.getValueType();
6330   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6331          "Invalid nodes in input!");
6332
6333   unsigned NumElts = VT.getVectorNumElements();
6334   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6335   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6336   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6337   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6338   EVT NewVT = V0_LO.getValueType();
6339
6340   SDValue LO = DAG.getUNDEF(NewVT);
6341   SDValue HI = DAG.getUNDEF(NewVT);
6342
6343   if (Mode) {
6344     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6345     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6346       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6347     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6348       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6349   } else {
6350     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6351     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6352                        V1_LO->getOpcode() != ISD::UNDEF))
6353       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6354
6355     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6356                        V1_HI->getOpcode() != ISD::UNDEF))
6357       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6358   }
6359
6360   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6361 }
6362
6363 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6364 /// sequence of 'vadd + vsub + blendi'.
6365 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6366                            const X86Subtarget *Subtarget) {
6367   SDLoc DL(BV);
6368   EVT VT = BV->getValueType(0);
6369   unsigned NumElts = VT.getVectorNumElements();
6370   SDValue InVec0 = DAG.getUNDEF(VT);
6371   SDValue InVec1 = DAG.getUNDEF(VT);
6372
6373   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6374           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6375
6376   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6377   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6378   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6379     return SDValue();
6380
6381   // Odd-numbered elements in the input build vector are obtained from
6382   // adding two integer/float elements.
6383   // Even-numbered elements in the input build vector are obtained from
6384   // subtracting two integer/float elements.
6385   unsigned ExpectedOpcode = ISD::FSUB;
6386   unsigned NextExpectedOpcode = ISD::FADD;
6387   bool AddFound = false;
6388   bool SubFound = false;
6389
6390   for (unsigned i = 0, e = NumElts; i != e; i++) {
6391     SDValue Op = BV->getOperand(i);
6392       
6393     // Skip 'undef' values.
6394     unsigned Opcode = Op.getOpcode();
6395     if (Opcode == ISD::UNDEF) {
6396       std::swap(ExpectedOpcode, NextExpectedOpcode);
6397       continue;
6398     }
6399       
6400     // Early exit if we found an unexpected opcode.
6401     if (Opcode != ExpectedOpcode)
6402       return SDValue();
6403
6404     SDValue Op0 = Op.getOperand(0);
6405     SDValue Op1 = Op.getOperand(1);
6406
6407     // Try to match the following pattern:
6408     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6409     // Early exit if we cannot match that sequence.
6410     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6411         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6412         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6413         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6414         Op0.getOperand(1) != Op1.getOperand(1))
6415       return SDValue();
6416
6417     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6418     if (I0 != i)
6419       return SDValue();
6420
6421     // We found a valid add/sub node. Update the information accordingly.
6422     if (i & 1)
6423       AddFound = true;
6424     else
6425       SubFound = true;
6426
6427     // Update InVec0 and InVec1.
6428     if (InVec0.getOpcode() == ISD::UNDEF)
6429       InVec0 = Op0.getOperand(0);
6430     if (InVec1.getOpcode() == ISD::UNDEF)
6431       InVec1 = Op1.getOperand(0);
6432
6433     // Make sure that operands in input to each add/sub node always
6434     // come from a same pair of vectors.
6435     if (InVec0 != Op0.getOperand(0)) {
6436       if (ExpectedOpcode == ISD::FSUB)
6437         return SDValue();
6438
6439       // FADD is commutable. Try to commute the operands
6440       // and then test again.
6441       std::swap(Op0, Op1);
6442       if (InVec0 != Op0.getOperand(0))
6443         return SDValue();
6444     }
6445
6446     if (InVec1 != Op1.getOperand(0))
6447       return SDValue();
6448
6449     // Update the pair of expected opcodes.
6450     std::swap(ExpectedOpcode, NextExpectedOpcode);
6451   }
6452
6453   // Don't try to fold this build_vector into a VSELECT if it has
6454   // too many UNDEF operands.
6455   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6456       InVec1.getOpcode() != ISD::UNDEF) {
6457     // Emit a sequence of vector add and sub followed by a VSELECT.
6458     // The new VSELECT will be lowered into a BLENDI.
6459     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6460     // and emit a single ADDSUB instruction.
6461     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6462     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6463
6464     // Construct the VSELECT mask.
6465     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6466     EVT SVT = MaskVT.getVectorElementType();
6467     unsigned SVTBits = SVT.getSizeInBits();
6468     SmallVector<SDValue, 8> Ops;
6469
6470     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6471       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6472                             APInt::getAllOnesValue(SVTBits);
6473       SDValue Constant = DAG.getConstant(Value, SVT);
6474       Ops.push_back(Constant);
6475     }
6476
6477     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6478     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6479   }
6480   
6481   return SDValue();
6482 }
6483
6484 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6485                                           const X86Subtarget *Subtarget) {
6486   SDLoc DL(N);
6487   EVT VT = N->getValueType(0);
6488   unsigned NumElts = VT.getVectorNumElements();
6489   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6490   SDValue InVec0, InVec1;
6491
6492   // Try to match an ADDSUB.
6493   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6494       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6495     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6496     if (Value.getNode())
6497       return Value;
6498   }
6499
6500   // Try to match horizontal ADD/SUB.
6501   unsigned NumUndefsLO = 0;
6502   unsigned NumUndefsHI = 0;
6503   unsigned Half = NumElts/2;
6504
6505   // Count the number of UNDEF operands in the build_vector in input.
6506   for (unsigned i = 0, e = Half; i != e; ++i)
6507     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6508       NumUndefsLO++;
6509
6510   for (unsigned i = Half, e = NumElts; i != e; ++i)
6511     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6512       NumUndefsHI++;
6513
6514   // Early exit if this is either a build_vector of all UNDEFs or all the
6515   // operands but one are UNDEF.
6516   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6517     return SDValue();
6518
6519   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6520     // Try to match an SSE3 float HADD/HSUB.
6521     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6522       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6523     
6524     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6525       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6526   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6527     // Try to match an SSSE3 integer HADD/HSUB.
6528     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6529       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6530     
6531     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6532       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6533   }
6534   
6535   if (!Subtarget->hasAVX())
6536     return SDValue();
6537
6538   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6539     // Try to match an AVX horizontal add/sub of packed single/double
6540     // precision floating point values from 256-bit vectors.
6541     SDValue InVec2, InVec3;
6542     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6543         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6544         ((InVec0.getOpcode() == ISD::UNDEF ||
6545           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6546         ((InVec1.getOpcode() == ISD::UNDEF ||
6547           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6548       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6549
6550     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6551         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6552         ((InVec0.getOpcode() == ISD::UNDEF ||
6553           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6554         ((InVec1.getOpcode() == ISD::UNDEF ||
6555           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6556       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6557   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6558     // Try to match an AVX2 horizontal add/sub of signed integers.
6559     SDValue InVec2, InVec3;
6560     unsigned X86Opcode;
6561     bool CanFold = true;
6562
6563     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6564         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6565         ((InVec0.getOpcode() == ISD::UNDEF ||
6566           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6567         ((InVec1.getOpcode() == ISD::UNDEF ||
6568           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6569       X86Opcode = X86ISD::HADD;
6570     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6571         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6572         ((InVec0.getOpcode() == ISD::UNDEF ||
6573           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6574         ((InVec1.getOpcode() == ISD::UNDEF ||
6575           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6576       X86Opcode = X86ISD::HSUB;
6577     else
6578       CanFold = false;
6579
6580     if (CanFold) {
6581       // Fold this build_vector into a single horizontal add/sub.
6582       // Do this only if the target has AVX2.
6583       if (Subtarget->hasAVX2())
6584         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6585  
6586       // Do not try to expand this build_vector into a pair of horizontal
6587       // add/sub if we can emit a pair of scalar add/sub.
6588       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6589         return SDValue();
6590
6591       // Convert this build_vector into a pair of horizontal binop followed by
6592       // a concat vector.
6593       bool isUndefLO = NumUndefsLO == Half;
6594       bool isUndefHI = NumUndefsHI == Half;
6595       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6596                                    isUndefLO, isUndefHI);
6597     }
6598   }
6599
6600   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6601        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6602     unsigned X86Opcode;
6603     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6604       X86Opcode = X86ISD::HADD;
6605     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6606       X86Opcode = X86ISD::HSUB;
6607     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6608       X86Opcode = X86ISD::FHADD;
6609     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6610       X86Opcode = X86ISD::FHSUB;
6611     else
6612       return SDValue();
6613
6614     // Don't try to expand this build_vector into a pair of horizontal add/sub
6615     // if we can simply emit a pair of scalar add/sub.
6616     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6617       return SDValue();
6618
6619     // Convert this build_vector into two horizontal add/sub followed by
6620     // a concat vector.
6621     bool isUndefLO = NumUndefsLO == Half;
6622     bool isUndefHI = NumUndefsHI == Half;
6623     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6624                                  isUndefLO, isUndefHI);
6625   }
6626
6627   return SDValue();
6628 }
6629
6630 SDValue
6631 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6632   SDLoc dl(Op);
6633
6634   MVT VT = Op.getSimpleValueType();
6635   MVT ExtVT = VT.getVectorElementType();
6636   unsigned NumElems = Op.getNumOperands();
6637
6638   // Generate vectors for predicate vectors.
6639   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6640     return LowerBUILD_VECTORvXi1(Op, DAG);
6641
6642   // Vectors containing all zeros can be matched by pxor and xorps later
6643   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6644     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6645     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6646     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6647       return Op;
6648
6649     return getZeroVector(VT, Subtarget, DAG, dl);
6650   }
6651
6652   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6653   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6654   // vpcmpeqd on 256-bit vectors.
6655   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6656     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6657       return Op;
6658
6659     if (!VT.is512BitVector())
6660       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6661   }
6662
6663   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6664   if (Broadcast.getNode())
6665     return Broadcast;
6666
6667   unsigned EVTBits = ExtVT.getSizeInBits();
6668
6669   unsigned NumZero  = 0;
6670   unsigned NumNonZero = 0;
6671   unsigned NonZeros = 0;
6672   bool IsAllConstants = true;
6673   SmallSet<SDValue, 8> Values;
6674   for (unsigned i = 0; i < NumElems; ++i) {
6675     SDValue Elt = Op.getOperand(i);
6676     if (Elt.getOpcode() == ISD::UNDEF)
6677       continue;
6678     Values.insert(Elt);
6679     if (Elt.getOpcode() != ISD::Constant &&
6680         Elt.getOpcode() != ISD::ConstantFP)
6681       IsAllConstants = false;
6682     if (X86::isZeroNode(Elt))
6683       NumZero++;
6684     else {
6685       NonZeros |= (1 << i);
6686       NumNonZero++;
6687     }
6688   }
6689
6690   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6691   if (NumNonZero == 0)
6692     return DAG.getUNDEF(VT);
6693
6694   // Special case for single non-zero, non-undef, element.
6695   if (NumNonZero == 1) {
6696     unsigned Idx = countTrailingZeros(NonZeros);
6697     SDValue Item = Op.getOperand(Idx);
6698
6699     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6700     // the value are obviously zero, truncate the value to i32 and do the
6701     // insertion that way.  Only do this if the value is non-constant or if the
6702     // value is a constant being inserted into element 0.  It is cheaper to do
6703     // a constant pool load than it is to do a movd + shuffle.
6704     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6705         (!IsAllConstants || Idx == 0)) {
6706       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6707         // Handle SSE only.
6708         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6709         EVT VecVT = MVT::v4i32;
6710         unsigned VecElts = 4;
6711
6712         // Truncate the value (which may itself be a constant) to i32, and
6713         // convert it to a vector with movd (S2V+shuffle to zero extend).
6714         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6715         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6716         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6717
6718         // Now we have our 32-bit value zero extended in the low element of
6719         // a vector.  If Idx != 0, swizzle it into place.
6720         if (Idx != 0) {
6721           SmallVector<int, 4> Mask;
6722           Mask.push_back(Idx);
6723           for (unsigned i = 1; i != VecElts; ++i)
6724             Mask.push_back(i);
6725           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6726                                       &Mask[0]);
6727         }
6728         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6729       }
6730     }
6731
6732     // If we have a constant or non-constant insertion into the low element of
6733     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6734     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6735     // depending on what the source datatype is.
6736     if (Idx == 0) {
6737       if (NumZero == 0)
6738         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6739
6740       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6741           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6742         if (VT.is256BitVector() || VT.is512BitVector()) {
6743           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6744           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6745                              Item, DAG.getIntPtrConstant(0));
6746         }
6747         assert(VT.is128BitVector() && "Expected an SSE value type!");
6748         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6749         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6750         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6751       }
6752
6753       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6754         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6755         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6756         if (VT.is256BitVector()) {
6757           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6758           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6759         } else {
6760           assert(VT.is128BitVector() && "Expected an SSE value type!");
6761           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6762         }
6763         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6764       }
6765     }
6766
6767     // Is it a vector logical left shift?
6768     if (NumElems == 2 && Idx == 1 &&
6769         X86::isZeroNode(Op.getOperand(0)) &&
6770         !X86::isZeroNode(Op.getOperand(1))) {
6771       unsigned NumBits = VT.getSizeInBits();
6772       return getVShift(true, VT,
6773                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6774                                    VT, Op.getOperand(1)),
6775                        NumBits/2, DAG, *this, dl);
6776     }
6777
6778     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6779       return SDValue();
6780
6781     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6782     // is a non-constant being inserted into an element other than the low one,
6783     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6784     // movd/movss) to move this into the low element, then shuffle it into
6785     // place.
6786     if (EVTBits == 32) {
6787       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6788
6789       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6790       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6791       SmallVector<int, 8> MaskVec;
6792       for (unsigned i = 0; i != NumElems; ++i)
6793         MaskVec.push_back(i == Idx ? 0 : 1);
6794       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6795     }
6796   }
6797
6798   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6799   if (Values.size() == 1) {
6800     if (EVTBits == 32) {
6801       // Instead of a shuffle like this:
6802       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6803       // Check if it's possible to issue this instead.
6804       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6805       unsigned Idx = countTrailingZeros(NonZeros);
6806       SDValue Item = Op.getOperand(Idx);
6807       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6808         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6809     }
6810     return SDValue();
6811   }
6812
6813   // A vector full of immediates; various special cases are already
6814   // handled, so this is best done with a single constant-pool load.
6815   if (IsAllConstants)
6816     return SDValue();
6817
6818   // For AVX-length vectors, build the individual 128-bit pieces and use
6819   // shuffles to put them in place.
6820   if (VT.is256BitVector() || VT.is512BitVector()) {
6821     SmallVector<SDValue, 64> V;
6822     for (unsigned i = 0; i != NumElems; ++i)
6823       V.push_back(Op.getOperand(i));
6824
6825     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6826
6827     // Build both the lower and upper subvector.
6828     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6829                                 makeArrayRef(&V[0], NumElems/2));
6830     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6831                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6832
6833     // Recreate the wider vector with the lower and upper part.
6834     if (VT.is256BitVector())
6835       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6836     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6837   }
6838
6839   // Let legalizer expand 2-wide build_vectors.
6840   if (EVTBits == 64) {
6841     if (NumNonZero == 1) {
6842       // One half is zero or undef.
6843       unsigned Idx = countTrailingZeros(NonZeros);
6844       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6845                                  Op.getOperand(Idx));
6846       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6847     }
6848     return SDValue();
6849   }
6850
6851   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6852   if (EVTBits == 8 && NumElems == 16) {
6853     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6854                                         Subtarget, *this);
6855     if (V.getNode()) return V;
6856   }
6857
6858   if (EVTBits == 16 && NumElems == 8) {
6859     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6860                                       Subtarget, *this);
6861     if (V.getNode()) return V;
6862   }
6863
6864   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6865   if (EVTBits == 32 && NumElems == 4) {
6866     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6867                                       NumZero, DAG, Subtarget, *this);
6868     if (V.getNode())
6869       return V;
6870   }
6871
6872   // If element VT is == 32 bits, turn it into a number of shuffles.
6873   SmallVector<SDValue, 8> V(NumElems);
6874   if (NumElems == 4 && NumZero > 0) {
6875     for (unsigned i = 0; i < 4; ++i) {
6876       bool isZero = !(NonZeros & (1 << i));
6877       if (isZero)
6878         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6879       else
6880         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6881     }
6882
6883     for (unsigned i = 0; i < 2; ++i) {
6884       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6885         default: break;
6886         case 0:
6887           V[i] = V[i*2];  // Must be a zero vector.
6888           break;
6889         case 1:
6890           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6891           break;
6892         case 2:
6893           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6894           break;
6895         case 3:
6896           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6897           break;
6898       }
6899     }
6900
6901     bool Reverse1 = (NonZeros & 0x3) == 2;
6902     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6903     int MaskVec[] = {
6904       Reverse1 ? 1 : 0,
6905       Reverse1 ? 0 : 1,
6906       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6907       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6908     };
6909     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6910   }
6911
6912   if (Values.size() > 1 && VT.is128BitVector()) {
6913     // Check for a build vector of consecutive loads.
6914     for (unsigned i = 0; i < NumElems; ++i)
6915       V[i] = Op.getOperand(i);
6916
6917     // Check for elements which are consecutive loads.
6918     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6919     if (LD.getNode())
6920       return LD;
6921
6922     // Check for a build vector from mostly shuffle plus few inserting.
6923     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6924     if (Sh.getNode())
6925       return Sh;
6926
6927     // For SSE 4.1, use insertps to put the high elements into the low element.
6928     if (getSubtarget()->hasSSE41()) {
6929       SDValue Result;
6930       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6931         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6932       else
6933         Result = DAG.getUNDEF(VT);
6934
6935       for (unsigned i = 1; i < NumElems; ++i) {
6936         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6937         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6938                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6939       }
6940       return Result;
6941     }
6942
6943     // Otherwise, expand into a number of unpckl*, start by extending each of
6944     // our (non-undef) elements to the full vector width with the element in the
6945     // bottom slot of the vector (which generates no code for SSE).
6946     for (unsigned i = 0; i < NumElems; ++i) {
6947       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6948         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6949       else
6950         V[i] = DAG.getUNDEF(VT);
6951     }
6952
6953     // Next, we iteratively mix elements, e.g. for v4f32:
6954     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6955     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6956     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6957     unsigned EltStride = NumElems >> 1;
6958     while (EltStride != 0) {
6959       for (unsigned i = 0; i < EltStride; ++i) {
6960         // If V[i+EltStride] is undef and this is the first round of mixing,
6961         // then it is safe to just drop this shuffle: V[i] is already in the
6962         // right place, the one element (since it's the first round) being
6963         // inserted as undef can be dropped.  This isn't safe for successive
6964         // rounds because they will permute elements within both vectors.
6965         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6966             EltStride == NumElems/2)
6967           continue;
6968
6969         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6970       }
6971       EltStride >>= 1;
6972     }
6973     return V[0];
6974   }
6975   return SDValue();
6976 }
6977
6978 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6979 // to create 256-bit vectors from two other 128-bit ones.
6980 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6981   SDLoc dl(Op);
6982   MVT ResVT = Op.getSimpleValueType();
6983
6984   assert((ResVT.is256BitVector() ||
6985           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6986
6987   SDValue V1 = Op.getOperand(0);
6988   SDValue V2 = Op.getOperand(1);
6989   unsigned NumElems = ResVT.getVectorNumElements();
6990   if(ResVT.is256BitVector())
6991     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6992
6993   if (Op.getNumOperands() == 4) {
6994     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6995                                 ResVT.getVectorNumElements()/2);
6996     SDValue V3 = Op.getOperand(2);
6997     SDValue V4 = Op.getOperand(3);
6998     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6999       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7000   }
7001   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7002 }
7003
7004 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7005   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7006   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7007          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7008           Op.getNumOperands() == 4)));
7009
7010   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7011   // from two other 128-bit ones.
7012
7013   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7014   return LowerAVXCONCAT_VECTORS(Op, DAG);
7015 }
7016
7017
7018 //===----------------------------------------------------------------------===//
7019 // Vector shuffle lowering
7020 //
7021 // This is an experimental code path for lowering vector shuffles on x86. It is
7022 // designed to handle arbitrary vector shuffles and blends, gracefully
7023 // degrading performance as necessary. It works hard to recognize idiomatic
7024 // shuffles and lower them to optimal instruction patterns without leaving
7025 // a framework that allows reasonably efficient handling of all vector shuffle
7026 // patterns.
7027 //===----------------------------------------------------------------------===//
7028
7029 /// \brief Tiny helper function to identify a no-op mask.
7030 ///
7031 /// This is a somewhat boring predicate function. It checks whether the mask
7032 /// array input, which is assumed to be a single-input shuffle mask of the kind
7033 /// used by the X86 shuffle instructions (not a fully general
7034 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7035 /// in-place shuffle are 'no-op's.
7036 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7037   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7038     if (Mask[i] != -1 && Mask[i] != i)
7039       return false;
7040   return true;
7041 }
7042
7043 /// \brief Helper function to classify a mask as a single-input mask.
7044 ///
7045 /// This isn't a generic single-input test because in the vector shuffle
7046 /// lowering we canonicalize single inputs to be the first input operand. This
7047 /// means we can more quickly test for a single input by only checking whether
7048 /// an input from the second operand exists. We also assume that the size of
7049 /// mask corresponds to the size of the input vectors which isn't true in the
7050 /// fully general case.
7051 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7052   for (int M : Mask)
7053     if (M >= (int)Mask.size())
7054       return false;
7055   return true;
7056 }
7057
7058 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7059 ///
7060 /// This helper function produces an 8-bit shuffle immediate corresponding to
7061 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7062 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7063 /// example.
7064 ///
7065 /// NB: We rely heavily on "undef" masks preserving the input lane.
7066 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7067                                           SelectionDAG &DAG) {
7068   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7069   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7070   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7071   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7072   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7073
7074   unsigned Imm = 0;
7075   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7076   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7077   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7078   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7079   return DAG.getConstant(Imm, MVT::i8);
7080 }
7081
7082 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7083 ///
7084 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7085 /// support for floating point shuffles but not integer shuffles. These
7086 /// instructions will incur a domain crossing penalty on some chips though so
7087 /// it is better to avoid lowering through this for integer vectors where
7088 /// possible.
7089 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7090                                        const X86Subtarget *Subtarget,
7091                                        SelectionDAG &DAG) {
7092   SDLoc DL(Op);
7093   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7094   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7095   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7096   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7097   ArrayRef<int> Mask = SVOp->getMask();
7098   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7099
7100   if (isSingleInputShuffleMask(Mask)) {
7101     // Straight shuffle of a single input vector. Simulate this by using the
7102     // single input as both of the "inputs" to this instruction..
7103     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7104     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7105                        DAG.getConstant(SHUFPDMask, MVT::i8));
7106   }
7107   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7108   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7109
7110   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7111   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7112                      DAG.getConstant(SHUFPDMask, MVT::i8));
7113 }
7114
7115 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7116 ///
7117 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7118 /// the integer unit to minimize domain crossing penalties. However, for blends
7119 /// it falls back to the floating point shuffle operation with appropriate bit
7120 /// casting.
7121 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7122                                        const X86Subtarget *Subtarget,
7123                                        SelectionDAG &DAG) {
7124   SDLoc DL(Op);
7125   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7126   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7127   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7128   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7129   ArrayRef<int> Mask = SVOp->getMask();
7130   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7131
7132   if (isSingleInputShuffleMask(Mask)) {
7133     // Straight shuffle of a single input vector. For everything from SSE2
7134     // onward this has a single fast instruction with no scary immediates.
7135     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7136     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7137     int WidenedMask[4] = {
7138         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7139         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7140     return DAG.getNode(
7141         ISD::BITCAST, DL, MVT::v2i64,
7142         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7143                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7144   }
7145
7146   // We implement this with SHUFPD which is pretty lame because it will likely
7147   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7148   // However, all the alternatives are still more cycles and newer chips don't
7149   // have this problem. It would be really nice if x86 had better shuffles here.
7150   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7151   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7152   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7153                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7154 }
7155
7156 /// \brief Lower 4-lane 32-bit floating point shuffles.
7157 ///
7158 /// Uses instructions exclusively from the floating point unit to minimize
7159 /// domain crossing penalties, as these are sufficient to implement all v4f32
7160 /// shuffles.
7161 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7162                                        const X86Subtarget *Subtarget,
7163                                        SelectionDAG &DAG) {
7164   SDLoc DL(Op);
7165   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7166   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7167   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7168   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7169   ArrayRef<int> Mask = SVOp->getMask();
7170   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7171
7172   SDValue LowV = V1, HighV = V2;
7173   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7174
7175   int NumV2Elements =
7176       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7177
7178   if (NumV2Elements == 0)
7179     // Straight shuffle of a single input vector. We pass the input vector to
7180     // both operands to simulate this with a SHUFPS.
7181     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7182                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7183
7184   if (NumV2Elements == 1) {
7185     int V2Index =
7186         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7187         Mask.begin();
7188     // Compute the index adjacent to V2Index and in the same half by toggling
7189     // the low bit.
7190     int V2AdjIndex = V2Index ^ 1;
7191
7192     if (Mask[V2AdjIndex] == -1) {
7193       // Handles all the cases where we have a single V2 element and an undef.
7194       // This will only ever happen in the high lanes because we commute the
7195       // vector otherwise.
7196       if (V2Index < 2)
7197         std::swap(LowV, HighV);
7198       NewMask[V2Index] -= 4;
7199     } else {
7200       // Handle the case where the V2 element ends up adjacent to a V1 element.
7201       // To make this work, blend them together as the first step.
7202       int V1Index = V2AdjIndex;
7203       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7204       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7205                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7206
7207       // Now proceed to reconstruct the final blend as we have the necessary
7208       // high or low half formed.
7209       if (V2Index < 2) {
7210         LowV = V2;
7211         HighV = V1;
7212       } else {
7213         HighV = V2;
7214       }
7215       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7216       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7217     }
7218   } else if (NumV2Elements == 2) {
7219     if (Mask[0] < 4 && Mask[1] < 4) {
7220       // Handle the easy case where we have V1 in the low lanes and V2 in the
7221       // high lanes. We never see this reversed because we sort the shuffle.
7222       NewMask[2] -= 4;
7223       NewMask[3] -= 4;
7224     } else {
7225       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7226       // trying to place elements directly, just blend them and set up the final
7227       // shuffle to place them.
7228
7229       // The first two blend mask elements are for V1, the second two are for
7230       // V2.
7231       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7232                           Mask[2] < 4 ? Mask[2] : Mask[3],
7233                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7234                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7235       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7236                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7237
7238       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7239       // a blend.
7240       LowV = HighV = V1;
7241       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7242       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7243       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7244       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7245     }
7246   }
7247   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7248                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7249 }
7250
7251 /// \brief Lower 4-lane i32 vector shuffles.
7252 ///
7253 /// We try to handle these with integer-domain shuffles where we can, but for
7254 /// blends we use the floating point domain blend instructions.
7255 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7256                                        const X86Subtarget *Subtarget,
7257                                        SelectionDAG &DAG) {
7258   SDLoc DL(Op);
7259   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7260   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7261   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7262   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7263   ArrayRef<int> Mask = SVOp->getMask();
7264   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7265
7266   if (isSingleInputShuffleMask(Mask))
7267     // Straight shuffle of a single input vector. For everything from SSE2
7268     // onward this has a single fast instruction with no scary immediates.
7269     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7270                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7271
7272   // We implement this with SHUFPS because it can blend from two vectors.
7273   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7274   // up the inputs, bypassing domain shift penalties that we would encur if we
7275   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7276   // relevant.
7277   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7278                      DAG.getVectorShuffle(
7279                          MVT::v4f32, DL,
7280                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7281                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7282 }
7283
7284 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7285 /// shuffle lowering, and the most complex part.
7286 ///
7287 /// The lowering strategy is to try to form pairs of input lanes which are
7288 /// targeted at the same half of the final vector, and then use a dword shuffle
7289 /// to place them onto the right half, and finally unpack the paired lanes into
7290 /// their final position.
7291 ///
7292 /// The exact breakdown of how to form these dword pairs and align them on the
7293 /// correct sides is really tricky. See the comments within the function for
7294 /// more of the details.
7295 static SDValue lowerV8I16SingleInputVectorShuffle(
7296     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7297     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7298   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7299   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7300   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7301
7302   SmallVector<int, 4> LoInputs;
7303   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7304                [](int M) { return M >= 0; });
7305   std::sort(LoInputs.begin(), LoInputs.end());
7306   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7307   SmallVector<int, 4> HiInputs;
7308   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7309                [](int M) { return M >= 0; });
7310   std::sort(HiInputs.begin(), HiInputs.end());
7311   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7312   int NumLToL =
7313       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7314   int NumHToL = LoInputs.size() - NumLToL;
7315   int NumLToH =
7316       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7317   int NumHToH = HiInputs.size() - NumLToH;
7318   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7319   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7320   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7321   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7322
7323   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7324   // such inputs we can swap two of the dwords across the half mark and end up
7325   // with <=2 inputs to each half in each half. Once there, we can fall through
7326   // to the generic code below. For example:
7327   //
7328   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7329   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7330   //
7331   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7332   // and 2-2.
7333   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7334                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7335     // Compute the index of dword with only one word among the three inputs in
7336     // a half by taking the sum of the half with three inputs and subtracting
7337     // the sum of the actual three inputs. The difference is the remaining
7338     // slot.
7339     int DWordA = (ThreeInputHalfSum -
7340                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7341                  2;
7342     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7343
7344     int PSHUFDMask[] = {0, 1, 2, 3};
7345     PSHUFDMask[DWordA] = DWordB;
7346     PSHUFDMask[DWordB] = DWordA;
7347     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7348                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7349                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7350                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7351
7352     // Adjust the mask to match the new locations of A and B.
7353     for (int &M : Mask)
7354       if (M != -1 && M/2 == DWordA)
7355         M = 2 * DWordB + M % 2;
7356       else if (M != -1 && M/2 == DWordB)
7357         M = 2 * DWordA + M % 2;
7358
7359     // Recurse back into this routine to re-compute state now that this isn't
7360     // a 3 and 1 problem.
7361     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7362                                 Mask);
7363   };
7364   if (NumLToL == 3 && NumHToL == 1)
7365     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7366   else if (NumLToL == 1 && NumHToL == 3)
7367     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7368   else if (NumLToH == 1 && NumHToH == 3)
7369     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7370   else if (NumLToH == 3 && NumHToH == 1)
7371     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7372
7373   // At this point there are at most two inputs to the low and high halves from
7374   // each half. That means the inputs can always be grouped into dwords and
7375   // those dwords can then be moved to the correct half with a dword shuffle.
7376   // We use at most one low and one high word shuffle to collect these paired
7377   // inputs into dwords, and finally a dword shuffle to place them.
7378   int PSHUFLMask[4] = {-1, -1, -1, -1};
7379   int PSHUFHMask[4] = {-1, -1, -1, -1};
7380   int PSHUFDMask[4] = {-1, -1, -1, -1};
7381
7382   // First fix the masks for all the inputs that are staying in their
7383   // original halves. This will then dictate the targets of the cross-half
7384   // shuffles.
7385   auto fixInPlaceInputs =
7386       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7387                     MutableArrayRef<int> SourceHalfMask,
7388                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7389     if (InPlaceInputs.empty())
7390       return;
7391     if (InPlaceInputs.size() == 1) {
7392       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7393           InPlaceInputs[0] - HalfOffset;
7394       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7395       return;
7396     }
7397     if (IncomingInputs.empty()) {
7398       // Just fix all of the in place inputs.
7399       for (int Input : InPlaceInputs) {
7400         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7401         PSHUFDMask[Input / 2] = Input / 2;
7402       }
7403       return;
7404     }
7405
7406     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7407     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7408         InPlaceInputs[0] - HalfOffset;
7409     // Put the second input next to the first so that they are packed into
7410     // a dword. We find the adjacent index by toggling the low bit.
7411     int AdjIndex = InPlaceInputs[0] ^ 1;
7412     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7413     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7414     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7415   };
7416   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7417   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7418
7419   // Now gather the cross-half inputs and place them into a free dword of
7420   // their target half.
7421   // FIXME: This operation could almost certainly be simplified dramatically to
7422   // look more like the 3-1 fixing operation.
7423   auto moveInputsToRightHalf = [&PSHUFDMask](
7424       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7425       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7426       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7427       int DestOffset) {
7428     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7429       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7430     };
7431     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7432                                                int Word) {
7433       int LowWord = Word & ~1;
7434       int HighWord = Word | 1;
7435       return isWordClobbered(SourceHalfMask, LowWord) ||
7436              isWordClobbered(SourceHalfMask, HighWord);
7437     };
7438
7439     if (IncomingInputs.empty())
7440       return;
7441
7442     if (ExistingInputs.empty()) {
7443       // Map any dwords with inputs from them into the right half.
7444       for (int Input : IncomingInputs) {
7445         // If the source half mask maps over the inputs, turn those into
7446         // swaps and use the swapped lane.
7447         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7448           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7449             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7450                 Input - SourceOffset;
7451             // We have to swap the uses in our half mask in one sweep.
7452             for (int &M : HalfMask)
7453               if (M == SourceHalfMask[Input - SourceOffset])
7454                 M = Input;
7455               else if (M == Input)
7456                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7457           } else {
7458             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7459                        Input - SourceOffset &&
7460                    "Previous placement doesn't match!");
7461           }
7462           // Note that this correctly re-maps both when we do a swap and when
7463           // we observe the other side of the swap above. We rely on that to
7464           // avoid swapping the members of the input list directly.
7465           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7466         }
7467
7468         // Map the input's dword into the correct half.
7469         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7470           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7471         else
7472           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7473                      Input / 2 &&
7474                  "Previous placement doesn't match!");
7475       }
7476
7477       // And just directly shift any other-half mask elements to be same-half
7478       // as we will have mirrored the dword containing the element into the
7479       // same position within that half.
7480       for (int &M : HalfMask)
7481         if (M >= SourceOffset && M < SourceOffset + 4) {
7482           M = M - SourceOffset + DestOffset;
7483           assert(M >= 0 && "This should never wrap below zero!");
7484         }
7485       return;
7486     }
7487
7488     // Ensure we have the input in a viable dword of its current half. This
7489     // is particularly tricky because the original position may be clobbered
7490     // by inputs being moved and *staying* in that half.
7491     if (IncomingInputs.size() == 1) {
7492       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7493         int InputFixed = std::find(std::begin(SourceHalfMask),
7494                                    std::end(SourceHalfMask), -1) -
7495                          std::begin(SourceHalfMask) + SourceOffset;
7496         SourceHalfMask[InputFixed - SourceOffset] =
7497             IncomingInputs[0] - SourceOffset;
7498         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7499                      InputFixed);
7500         IncomingInputs[0] = InputFixed;
7501       }
7502     } else if (IncomingInputs.size() == 2) {
7503       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7504           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7505         // We have two non-adjacent or clobbered inputs we need to extract from
7506         // the source half. To do this, we need to map them into some adjacent
7507         // dword slot in the source mask.
7508         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7509                               IncomingInputs[1] - SourceOffset};
7510
7511         // If there is a free slot in the source half mask adjacent to one of
7512         // the inputs, place the other input in it. We use (Index XOR 1) to
7513         // compute an adjacent index.
7514         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7515             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7516           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7517           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7518           InputsFixed[1] = InputsFixed[0] ^ 1;
7519         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7520                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7521           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7522           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7523           InputsFixed[0] = InputsFixed[1] ^ 1;
7524         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7525                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7526           // The two inputs are in the same DWord but it is clobbered and the
7527           // adjacent DWord isn't used at all. Move both inputs to the free
7528           // slot.
7529           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7530           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7531           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7532           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7533         } else {
7534           // The only way we hit this point is if there is no clobbering
7535           // (because there are no off-half inputs to this half) and there is no
7536           // free slot adjacent to one of the inputs. In this case, we have to
7537           // swap an input with a non-input.
7538           for (int i = 0; i < 4; ++i)
7539             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7540                    "We can't handle any clobbers here!");
7541           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7542                  "Cannot have adjacent inputs here!");
7543
7544           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7545           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7546
7547           // We also have to update the final source mask in this case because
7548           // it may need to undo the above swap.
7549           for (int &M : FinalSourceHalfMask)
7550             if (M == (InputsFixed[0] ^ 1))
7551               M = InputsFixed[1];
7552             else if (M == InputsFixed[1])
7553               M = InputsFixed[0] ^ 1;
7554
7555           InputsFixed[1] = InputsFixed[0] ^ 1;
7556         }
7557
7558         // Point everything at the fixed inputs.
7559         for (int &M : HalfMask)
7560           if (M == IncomingInputs[0])
7561             M = InputsFixed[0] + SourceOffset;
7562           else if (M == IncomingInputs[1])
7563             M = InputsFixed[1] + SourceOffset;
7564
7565         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7566         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7567       }
7568     } else {
7569       llvm_unreachable("Unhandled input size!");
7570     }
7571
7572     // Now hoist the DWord down to the right half.
7573     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7574     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7575     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7576     for (int &M : HalfMask)
7577       for (int Input : IncomingInputs)
7578         if (M == Input)
7579           M = FreeDWord * 2 + Input % 2;
7580   };
7581   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7582                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7583   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7584                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7585
7586   // Now enact all the shuffles we've computed to move the inputs into their
7587   // target half.
7588   if (!isNoopShuffleMask(PSHUFLMask))
7589     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7590                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7591   if (!isNoopShuffleMask(PSHUFHMask))
7592     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7593                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7594   if (!isNoopShuffleMask(PSHUFDMask))
7595     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7596                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7597                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7598                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7599
7600   // At this point, each half should contain all its inputs, and we can then
7601   // just shuffle them into their final position.
7602   assert(std::count_if(LoMask.begin(), LoMask.end(),
7603                        [](int M) { return M >= 4; }) == 0 &&
7604          "Failed to lift all the high half inputs to the low mask!");
7605   assert(std::count_if(HiMask.begin(), HiMask.end(),
7606                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7607          "Failed to lift all the low half inputs to the high mask!");
7608
7609   // Do a half shuffle for the low mask.
7610   if (!isNoopShuffleMask(LoMask))
7611     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7612                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7613
7614   // Do a half shuffle with the high mask after shifting its values down.
7615   for (int &M : HiMask)
7616     if (M >= 0)
7617       M -= 4;
7618   if (!isNoopShuffleMask(HiMask))
7619     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7620                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7621
7622   return V;
7623 }
7624
7625 /// \brief Detect whether the mask pattern should be lowered through
7626 /// interleaving.
7627 ///
7628 /// This essentially tests whether viewing the mask as an interleaving of two
7629 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7630 /// lowering it through interleaving is a significantly better strategy.
7631 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7632   int NumEvenInputs[2] = {0, 0};
7633   int NumOddInputs[2] = {0, 0};
7634   int NumLoInputs[2] = {0, 0};
7635   int NumHiInputs[2] = {0, 0};
7636   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7637     if (Mask[i] < 0)
7638       continue;
7639
7640     int InputIdx = Mask[i] >= Size;
7641
7642     if (i < Size / 2)
7643       ++NumLoInputs[InputIdx];
7644     else
7645       ++NumHiInputs[InputIdx];
7646
7647     if ((i % 2) == 0)
7648       ++NumEvenInputs[InputIdx];
7649     else
7650       ++NumOddInputs[InputIdx];
7651   }
7652
7653   // The minimum number of cross-input results for both the interleaved and
7654   // split cases. If interleaving results in fewer cross-input results, return
7655   // true.
7656   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7657                                     NumEvenInputs[0] + NumOddInputs[1]);
7658   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7659                               NumLoInputs[0] + NumHiInputs[1]);
7660   return InterleavedCrosses < SplitCrosses;
7661 }
7662
7663 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7664 ///
7665 /// This strategy only works when the inputs from each vector fit into a single
7666 /// half of that vector, and generally there are not so many inputs as to leave
7667 /// the in-place shuffles required highly constrained (and thus expensive). It
7668 /// shifts all the inputs into a single side of both input vectors and then
7669 /// uses an unpack to interleave these inputs in a single vector. At that
7670 /// point, we will fall back on the generic single input shuffle lowering.
7671 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7672                                                  SDValue V2,
7673                                                  MutableArrayRef<int> Mask,
7674                                                  const X86Subtarget *Subtarget,
7675                                                  SelectionDAG &DAG) {
7676   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7677   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7678   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7679   for (int i = 0; i < 8; ++i)
7680     if (Mask[i] >= 0 && Mask[i] < 4)
7681       LoV1Inputs.push_back(i);
7682     else if (Mask[i] >= 4 && Mask[i] < 8)
7683       HiV1Inputs.push_back(i);
7684     else if (Mask[i] >= 8 && Mask[i] < 12)
7685       LoV2Inputs.push_back(i);
7686     else if (Mask[i] >= 12)
7687       HiV2Inputs.push_back(i);
7688
7689   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7690   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7691   (void)NumV1Inputs;
7692   (void)NumV2Inputs;
7693   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7694   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7695   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7696
7697   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7698                      HiV1Inputs.size() + HiV2Inputs.size();
7699
7700   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7701                               ArrayRef<int> HiInputs, bool MoveToLo,
7702                               int MaskOffset) {
7703     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7704     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7705     if (BadInputs.empty())
7706       return V;
7707
7708     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7709     int MoveOffset = MoveToLo ? 0 : 4;
7710
7711     if (GoodInputs.empty()) {
7712       for (int BadInput : BadInputs) {
7713         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7714         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7715       }
7716     } else {
7717       if (GoodInputs.size() == 2) {
7718         // If the low inputs are spread across two dwords, pack them into
7719         // a single dword.
7720         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7721         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7722         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7723         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7724       } else {
7725         // Otherwise pin the good inputs.
7726         for (int GoodInput : GoodInputs)
7727           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7728       }
7729
7730       if (BadInputs.size() == 2) {
7731         // If we have two bad inputs then there may be either one or two good
7732         // inputs fixed in place. Find a fixed input, and then find the *other*
7733         // two adjacent indices by using modular arithmetic.
7734         int GoodMaskIdx =
7735             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7736                          [](int M) { return M >= 0; }) -
7737             std::begin(MoveMask);
7738         int MoveMaskIdx =
7739             (((GoodMaskIdx - MoveOffset) & ~1) + 2 % 4) + MoveOffset;
7740         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7741         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7742         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7743         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7744         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7745         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7746       } else {
7747         assert(BadInputs.size() == 1 && "All sizes handled");
7748         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7749                                     std::end(MoveMask), -1) -
7750                           std::begin(MoveMask);
7751         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7752         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7753       }
7754     }
7755
7756     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7757                                 MoveMask);
7758   };
7759   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7760                         /*MaskOffset*/ 0);
7761   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7762                         /*MaskOffset*/ 8);
7763
7764   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7765   // cross-half traffic in the final shuffle.
7766
7767   // Munge the mask to be a single-input mask after the unpack merges the
7768   // results.
7769   for (int &M : Mask)
7770     if (M != -1)
7771       M = 2 * (M % 4) + (M / 8);
7772
7773   return DAG.getVectorShuffle(
7774       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7775                                   DL, MVT::v8i16, V1, V2),
7776       DAG.getUNDEF(MVT::v8i16), Mask);
7777 }
7778
7779 /// \brief Generic lowering of 8-lane i16 shuffles.
7780 ///
7781 /// This handles both single-input shuffles and combined shuffle/blends with
7782 /// two inputs. The single input shuffles are immediately delegated to
7783 /// a dedicated lowering routine.
7784 ///
7785 /// The blends are lowered in one of three fundamental ways. If there are few
7786 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7787 /// of the input is significantly cheaper when lowered as an interleaving of
7788 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7789 /// halves of the inputs separately (making them have relatively few inputs)
7790 /// and then concatenate them.
7791 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7792                                        const X86Subtarget *Subtarget,
7793                                        SelectionDAG &DAG) {
7794   SDLoc DL(Op);
7795   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7796   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7797   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7798   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7799   ArrayRef<int> OrigMask = SVOp->getMask();
7800   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7801                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7802   MutableArrayRef<int> Mask(MaskStorage);
7803
7804   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7805
7806   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7807   auto isV2 = [](int M) { return M >= 8; };
7808
7809   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7810   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7811
7812   if (NumV2Inputs == 0)
7813     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7814
7815   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7816                             "to be V1-input shuffles.");
7817
7818   if (NumV1Inputs + NumV2Inputs <= 4)
7819     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7820
7821   // Check whether an interleaving lowering is likely to be more efficient.
7822   // This isn't perfect but it is a strong heuristic that tends to work well on
7823   // the kinds of shuffles that show up in practice.
7824   //
7825   // FIXME: Handle 1x, 2x, and 4x interleaving.
7826   if (shouldLowerAsInterleaving(Mask)) {
7827     // FIXME: Figure out whether we should pack these into the low or high
7828     // halves.
7829
7830     int EMask[8], OMask[8];
7831     for (int i = 0; i < 4; ++i) {
7832       EMask[i] = Mask[2*i];
7833       OMask[i] = Mask[2*i + 1];
7834       EMask[i + 4] = -1;
7835       OMask[i + 4] = -1;
7836     }
7837
7838     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7839     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7840
7841     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7842   }
7843
7844   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7845   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7846
7847   for (int i = 0; i < 4; ++i) {
7848     LoBlendMask[i] = Mask[i];
7849     HiBlendMask[i] = Mask[i + 4];
7850   }
7851
7852   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7853   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7854   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7855   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7856
7857   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7858                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7859 }
7860
7861 /// \brief Check whether a compaction lowering can be done by dropping even
7862 /// elements and compute how many times even elements must be dropped.
7863 ///
7864 /// This handles shuffles which take every Nth element where N is a power of
7865 /// two. Example shuffle masks:
7866 ///
7867 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
7868 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
7869 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
7870 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
7871 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
7872 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
7873 ///
7874 /// Any of these lanes can of course be undef.
7875 ///
7876 /// This routine only supports N <= 3.
7877 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
7878 /// for larger N.
7879 ///
7880 /// \returns N above, or the number of times even elements must be dropped if
7881 /// there is such a number. Otherwise returns zero.
7882 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
7883   // Figure out whether we're looping over two inputs or just one.
7884   bool IsSingleInput = isSingleInputShuffleMask(Mask);
7885
7886   // The modulus for the shuffle vector entries is based on whether this is
7887   // a single input or not.
7888   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
7889   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
7890          "We should only be called with masks with a power-of-2 size!");
7891
7892   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
7893
7894   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
7895   // and 2^3 simultaneously. This is because we may have ambiguity with
7896   // partially undef inputs.
7897   bool ViableForN[3] = {true, true, true};
7898
7899   for (int i = 0, e = Mask.size(); i < e; ++i) {
7900     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
7901     // want.
7902     if (Mask[i] == -1)
7903       continue;
7904
7905     bool IsAnyViable = false;
7906     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7907       if (ViableForN[j]) {
7908         uint64_t N = j + 1;
7909
7910         // The shuffle mask must be equal to (i * 2^N) % M.
7911         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
7912           IsAnyViable = true;
7913         else
7914           ViableForN[j] = false;
7915       }
7916     // Early exit if we exhaust the possible powers of two.
7917     if (!IsAnyViable)
7918       break;
7919   }
7920
7921   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7922     if (ViableForN[j])
7923       return j + 1;
7924
7925   // Return 0 as there is no viable power of two.
7926   return 0;
7927 }
7928
7929 /// \brief Generic lowering of v16i8 shuffles.
7930 ///
7931 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7932 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7933 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7934 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7935 /// back together.
7936 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7937                                        const X86Subtarget *Subtarget,
7938                                        SelectionDAG &DAG) {
7939   SDLoc DL(Op);
7940   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7941   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7942   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7943   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7944   ArrayRef<int> OrigMask = SVOp->getMask();
7945   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7946   int MaskStorage[16] = {
7947       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7948       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7949       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7950       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7951   MutableArrayRef<int> Mask(MaskStorage);
7952   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7953   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7954
7955   // For single-input shuffles, there are some nicer lowering tricks we can use.
7956   if (isSingleInputShuffleMask(Mask)) {
7957     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7958     // Notably, this handles splat and partial-splat shuffles more efficiently.
7959     // However, it only makes sense if the pre-duplication shuffle simplifies
7960     // things significantly. Currently, this means we need to be able to
7961     // express the pre-duplication shuffle as an i16 shuffle.
7962     //
7963     // FIXME: We should check for other patterns which can be widened into an
7964     // i16 shuffle as well.
7965     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7966       for (int i = 0; i < 16; i += 2) {
7967         if (Mask[i] != Mask[i + 1])
7968           return false;
7969       }
7970       return true;
7971     };
7972     auto tryToWidenViaDuplication = [&]() -> SDValue {
7973       if (!canWidenViaDuplication(Mask))
7974         return SDValue();
7975       SmallVector<int, 4> LoInputs;
7976       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7977                    [](int M) { return M >= 0 && M < 8; });
7978       std::sort(LoInputs.begin(), LoInputs.end());
7979       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7980                      LoInputs.end());
7981       SmallVector<int, 4> HiInputs;
7982       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7983                    [](int M) { return M >= 8; });
7984       std::sort(HiInputs.begin(), HiInputs.end());
7985       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7986                      HiInputs.end());
7987
7988       bool TargetLo = LoInputs.size() >= HiInputs.size();
7989       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7990       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7991
7992       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7993       SmallDenseMap<int, int, 8> LaneMap;
7994       for (int I : InPlaceInputs) {
7995         PreDupI16Shuffle[I/2] = I/2;
7996         LaneMap[I] = I;
7997       }
7998       int j = TargetLo ? 0 : 4, je = j + 4;
7999       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8000         // Check if j is already a shuffle of this input. This happens when
8001         // there are two adjacent bytes after we move the low one.
8002         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8003           // If we haven't yet mapped the input, search for a slot into which
8004           // we can map it.
8005           while (j < je && PreDupI16Shuffle[j] != -1)
8006             ++j;
8007
8008           if (j == je)
8009             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8010             return SDValue();
8011
8012           // Map this input with the i16 shuffle.
8013           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8014         }
8015
8016         // Update the lane map based on the mapping we ended up with.
8017         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8018       }
8019       V1 = DAG.getNode(
8020           ISD::BITCAST, DL, MVT::v16i8,
8021           DAG.getVectorShuffle(MVT::v8i16, DL,
8022                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8023                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8024
8025       // Unpack the bytes to form the i16s that will be shuffled into place.
8026       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8027                        MVT::v16i8, V1, V1);
8028
8029       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8030       for (int i = 0; i < 16; i += 2) {
8031         if (Mask[i] != -1)
8032           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8033         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8034       }
8035       return DAG.getNode(
8036           ISD::BITCAST, DL, MVT::v16i8,
8037           DAG.getVectorShuffle(MVT::v8i16, DL,
8038                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8039                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8040     };
8041     if (SDValue V = tryToWidenViaDuplication())
8042       return V;
8043   }
8044
8045   // Check whether an interleaving lowering is likely to be more efficient.
8046   // This isn't perfect but it is a strong heuristic that tends to work well on
8047   // the kinds of shuffles that show up in practice.
8048   //
8049   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8050   if (shouldLowerAsInterleaving(Mask)) {
8051     // FIXME: Figure out whether we should pack these into the low or high
8052     // halves.
8053
8054     int EMask[16], OMask[16];
8055     for (int i = 0; i < 8; ++i) {
8056       EMask[i] = Mask[2*i];
8057       OMask[i] = Mask[2*i + 1];
8058       EMask[i + 8] = -1;
8059       OMask[i + 8] = -1;
8060     }
8061
8062     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8063     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8064
8065     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8066   }
8067
8068   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8069   // with PSHUFB. It is important to do this before we attempt to generate any
8070   // blends but after all of the single-input lowerings. If the single input
8071   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8072   // want to preserve that and we can DAG combine any longer sequences into
8073   // a PSHUFB in the end. But once we start blending from multiple inputs,
8074   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8075   // and there are *very* few patterns that would actually be faster than the
8076   // PSHUFB approach because of its ability to zero lanes.
8077   //
8078   // FIXME: The only exceptions to the above are blends which are exact
8079   // interleavings with direct instructions supporting them. We currently don't
8080   // handle those well here.
8081   if (Subtarget->hasSSSE3()) {
8082     SDValue V1Mask[16];
8083     SDValue V2Mask[16];
8084     for (int i = 0; i < 16; ++i)
8085       if (Mask[i] == -1) {
8086         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8087       } else {
8088         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8089         V2Mask[i] =
8090             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8091       }
8092     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8093                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8094     if (isSingleInputShuffleMask(Mask))
8095       return V1; // Single inputs are easy.
8096
8097     // Otherwise, blend the two.
8098     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8099                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8100     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8101   }
8102
8103   // Check whether a compaction lowering can be done. This handles shuffles
8104   // which take every Nth element for some even N. See the helper function for
8105   // details.
8106   //
8107   // We special case these as they can be particularly efficiently handled with
8108   // the PACKUSB instruction on x86 and they show up in common patterns of
8109   // rearranging bytes to truncate wide elements.
8110   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8111     // NumEvenDrops is the power of two stride of the elements. Another way of
8112     // thinking about it is that we need to drop the even elements this many
8113     // times to get the original input.
8114     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8115
8116     // First we need to zero all the dropped bytes.
8117     assert(NumEvenDrops <= 3 &&
8118            "No support for dropping even elements more than 3 times.");
8119     // We use the mask type to pick which bytes are preserved based on how many
8120     // elements are dropped.
8121     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8122     SDValue ByteClearMask =
8123         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8124                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8125     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8126     if (!IsSingleInput)
8127       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8128
8129     // Now pack things back together.
8130     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8131     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8132     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8133     for (int i = 1; i < NumEvenDrops; ++i) {
8134       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8135       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8136     }
8137
8138     return Result;
8139   }
8140
8141   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8142   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8143   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8144   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8145
8146   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8147                             MutableArrayRef<int> V1HalfBlendMask,
8148                             MutableArrayRef<int> V2HalfBlendMask) {
8149     for (int i = 0; i < 8; ++i)
8150       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8151         V1HalfBlendMask[i] = HalfMask[i];
8152         HalfMask[i] = i;
8153       } else if (HalfMask[i] >= 16) {
8154         V2HalfBlendMask[i] = HalfMask[i] - 16;
8155         HalfMask[i] = i + 8;
8156       }
8157   };
8158   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8159   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8160
8161   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8162
8163   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8164                              MutableArrayRef<int> HiBlendMask) {
8165     SDValue V1, V2;
8166     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8167     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8168     // i16s.
8169     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8170                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8171         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8172                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8173       // Use a mask to drop the high bytes.
8174       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8175       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8176                        DAG.getConstant(0x00FF, MVT::v8i16));
8177
8178       // This will be a single vector shuffle instead of a blend so nuke V2.
8179       V2 = DAG.getUNDEF(MVT::v8i16);
8180
8181       // Squash the masks to point directly into V1.
8182       for (int &M : LoBlendMask)
8183         if (M >= 0)
8184           M /= 2;
8185       for (int &M : HiBlendMask)
8186         if (M >= 0)
8187           M /= 2;
8188     } else {
8189       // Otherwise just unpack the low half of V into V1 and the high half into
8190       // V2 so that we can blend them as i16s.
8191       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8192                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8193       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8194                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8195     }
8196
8197     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8198     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8199     return std::make_pair(BlendedLo, BlendedHi);
8200   };
8201   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8202   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8203   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8204
8205   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8206   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8207
8208   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8209 }
8210
8211 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8212 ///
8213 /// This routine breaks down the specific type of 128-bit shuffle and
8214 /// dispatches to the lowering routines accordingly.
8215 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8216                                         MVT VT, const X86Subtarget *Subtarget,
8217                                         SelectionDAG &DAG) {
8218   switch (VT.SimpleTy) {
8219   case MVT::v2i64:
8220     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8221   case MVT::v2f64:
8222     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8223   case MVT::v4i32:
8224     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8225   case MVT::v4f32:
8226     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8227   case MVT::v8i16:
8228     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8229   case MVT::v16i8:
8230     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8231
8232   default:
8233     llvm_unreachable("Unimplemented!");
8234   }
8235 }
8236
8237 /// \brief Tiny helper function to test whether a shuffle mask could be
8238 /// simplified by widening the elements being shuffled.
8239 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8240   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8241     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8242       return false;
8243
8244   return true;
8245 }
8246
8247 /// \brief Top-level lowering for x86 vector shuffles.
8248 ///
8249 /// This handles decomposition, canonicalization, and lowering of all x86
8250 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8251 /// above in helper routines. The canonicalization attempts to widen shuffles
8252 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8253 /// s.t. only one of the two inputs needs to be tested, etc.
8254 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8255                                   SelectionDAG &DAG) {
8256   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8257   ArrayRef<int> Mask = SVOp->getMask();
8258   SDValue V1 = Op.getOperand(0);
8259   SDValue V2 = Op.getOperand(1);
8260   MVT VT = Op.getSimpleValueType();
8261   int NumElements = VT.getVectorNumElements();
8262   SDLoc dl(Op);
8263
8264   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8265
8266   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8267   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8268   if (V1IsUndef && V2IsUndef)
8269     return DAG.getUNDEF(VT);
8270
8271   // When we create a shuffle node we put the UNDEF node to second operand,
8272   // but in some cases the first operand may be transformed to UNDEF.
8273   // In this case we should just commute the node.
8274   if (V1IsUndef)
8275     return DAG.getCommutedVectorShuffle(*SVOp);
8276
8277   // Check for non-undef masks pointing at an undef vector and make the masks
8278   // undef as well. This makes it easier to match the shuffle based solely on
8279   // the mask.
8280   if (V2IsUndef)
8281     for (int M : Mask)
8282       if (M >= NumElements) {
8283         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8284         for (int &M : NewMask)
8285           if (M >= NumElements)
8286             M = -1;
8287         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8288       }
8289
8290   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8291   // lanes but wider integers. We cap this to not form integers larger than i64
8292   // but it might be interesting to form i128 integers to handle flipping the
8293   // low and high halves of AVX 256-bit vectors.
8294   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8295       canWidenShuffleElements(Mask)) {
8296     SmallVector<int, 8> NewMask;
8297     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8298       NewMask.push_back(Mask[i] / 2);
8299     MVT NewVT =
8300         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8301                          VT.getVectorNumElements() / 2);
8302     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8303     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8304     return DAG.getNode(ISD::BITCAST, dl, VT,
8305                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8306   }
8307
8308   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8309   for (int M : SVOp->getMask())
8310     if (M < 0)
8311       ++NumUndefElements;
8312     else if (M < NumElements)
8313       ++NumV1Elements;
8314     else
8315       ++NumV2Elements;
8316
8317   // Commute the shuffle as needed such that more elements come from V1 than
8318   // V2. This allows us to match the shuffle pattern strictly on how many
8319   // elements come from V1 without handling the symmetric cases.
8320   if (NumV2Elements > NumV1Elements)
8321     return DAG.getCommutedVectorShuffle(*SVOp);
8322
8323   // When the number of V1 and V2 elements are the same, try to minimize the
8324   // number of uses of V2 in the low half of the vector.
8325   if (NumV1Elements == NumV2Elements) {
8326     int LowV1Elements = 0, LowV2Elements = 0;
8327     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8328       if (M >= NumElements)
8329         ++LowV2Elements;
8330       else if (M >= 0)
8331         ++LowV1Elements;
8332     if (LowV2Elements > LowV1Elements)
8333       return DAG.getCommutedVectorShuffle(*SVOp);
8334   }
8335
8336   // For each vector width, delegate to a specialized lowering routine.
8337   if (VT.getSizeInBits() == 128)
8338     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8339
8340   llvm_unreachable("Unimplemented!");
8341 }
8342
8343
8344 //===----------------------------------------------------------------------===//
8345 // Legacy vector shuffle lowering
8346 //
8347 // This code is the legacy code handling vector shuffles until the above
8348 // replaces its functionality and performance.
8349 //===----------------------------------------------------------------------===//
8350
8351 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8352                         bool hasInt256, unsigned *MaskOut = nullptr) {
8353   MVT EltVT = VT.getVectorElementType();
8354
8355   // There is no blend with immediate in AVX-512.
8356   if (VT.is512BitVector())
8357     return false;
8358
8359   if (!hasSSE41 || EltVT == MVT::i8)
8360     return false;
8361   if (!hasInt256 && VT == MVT::v16i16)
8362     return false;
8363
8364   unsigned MaskValue = 0;
8365   unsigned NumElems = VT.getVectorNumElements();
8366   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8367   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8368   unsigned NumElemsInLane = NumElems / NumLanes;
8369
8370   // Blend for v16i16 should be symetric for the both lanes.
8371   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8372
8373     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8374     int EltIdx = MaskVals[i];
8375
8376     if ((EltIdx < 0 || EltIdx == (int)i) &&
8377         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8378       continue;
8379
8380     if (((unsigned)EltIdx == (i + NumElems)) &&
8381         (SndLaneEltIdx < 0 ||
8382          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8383       MaskValue |= (1 << i);
8384     else
8385       return false;
8386   }
8387
8388   if (MaskOut)
8389     *MaskOut = MaskValue;
8390   return true;
8391 }
8392
8393 // Try to lower a shuffle node into a simple blend instruction.
8394 // This function assumes isBlendMask returns true for this
8395 // SuffleVectorSDNode
8396 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8397                                           unsigned MaskValue,
8398                                           const X86Subtarget *Subtarget,
8399                                           SelectionDAG &DAG) {
8400   MVT VT = SVOp->getSimpleValueType(0);
8401   MVT EltVT = VT.getVectorElementType();
8402   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8403                      Subtarget->hasInt256() && "Trying to lower a "
8404                                                "VECTOR_SHUFFLE to a Blend but "
8405                                                "with the wrong mask"));
8406   SDValue V1 = SVOp->getOperand(0);
8407   SDValue V2 = SVOp->getOperand(1);
8408   SDLoc dl(SVOp);
8409   unsigned NumElems = VT.getVectorNumElements();
8410
8411   // Convert i32 vectors to floating point if it is not AVX2.
8412   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8413   MVT BlendVT = VT;
8414   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8415     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8416                                NumElems);
8417     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8418     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8419   }
8420
8421   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8422                             DAG.getConstant(MaskValue, MVT::i32));
8423   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8424 }
8425
8426 /// In vector type \p VT, return true if the element at index \p InputIdx
8427 /// falls on a different 128-bit lane than \p OutputIdx.
8428 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8429                                      unsigned OutputIdx) {
8430   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8431   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8432 }
8433
8434 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8435 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8436 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8437 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8438 /// zero.
8439 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8440                          SelectionDAG &DAG) {
8441   MVT VT = V1.getSimpleValueType();
8442   assert(VT.is128BitVector() || VT.is256BitVector());
8443
8444   MVT EltVT = VT.getVectorElementType();
8445   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8446   unsigned NumElts = VT.getVectorNumElements();
8447
8448   SmallVector<SDValue, 32> PshufbMask;
8449   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8450     int InputIdx = MaskVals[OutputIdx];
8451     unsigned InputByteIdx;
8452
8453     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8454       InputByteIdx = 0x80;
8455     else {
8456       // Cross lane is not allowed.
8457       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8458         return SDValue();
8459       InputByteIdx = InputIdx * EltSizeInBytes;
8460       // Index is an byte offset within the 128-bit lane.
8461       InputByteIdx &= 0xf;
8462     }
8463
8464     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8465       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8466       if (InputByteIdx != 0x80)
8467         ++InputByteIdx;
8468     }
8469   }
8470
8471   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8472   if (ShufVT != VT)
8473     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8474   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8475                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8476 }
8477
8478 // v8i16 shuffles - Prefer shuffles in the following order:
8479 // 1. [all]   pshuflw, pshufhw, optional move
8480 // 2. [ssse3] 1 x pshufb
8481 // 3. [ssse3] 2 x pshufb + 1 x por
8482 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8483 static SDValue
8484 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8485                          SelectionDAG &DAG) {
8486   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8487   SDValue V1 = SVOp->getOperand(0);
8488   SDValue V2 = SVOp->getOperand(1);
8489   SDLoc dl(SVOp);
8490   SmallVector<int, 8> MaskVals;
8491
8492   // Determine if more than 1 of the words in each of the low and high quadwords
8493   // of the result come from the same quadword of one of the two inputs.  Undef
8494   // mask values count as coming from any quadword, for better codegen.
8495   //
8496   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8497   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8498   unsigned LoQuad[] = { 0, 0, 0, 0 };
8499   unsigned HiQuad[] = { 0, 0, 0, 0 };
8500   // Indices of quads used.
8501   std::bitset<4> InputQuads;
8502   for (unsigned i = 0; i < 8; ++i) {
8503     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8504     int EltIdx = SVOp->getMaskElt(i);
8505     MaskVals.push_back(EltIdx);
8506     if (EltIdx < 0) {
8507       ++Quad[0];
8508       ++Quad[1];
8509       ++Quad[2];
8510       ++Quad[3];
8511       continue;
8512     }
8513     ++Quad[EltIdx / 4];
8514     InputQuads.set(EltIdx / 4);
8515   }
8516
8517   int BestLoQuad = -1;
8518   unsigned MaxQuad = 1;
8519   for (unsigned i = 0; i < 4; ++i) {
8520     if (LoQuad[i] > MaxQuad) {
8521       BestLoQuad = i;
8522       MaxQuad = LoQuad[i];
8523     }
8524   }
8525
8526   int BestHiQuad = -1;
8527   MaxQuad = 1;
8528   for (unsigned i = 0; i < 4; ++i) {
8529     if (HiQuad[i] > MaxQuad) {
8530       BestHiQuad = i;
8531       MaxQuad = HiQuad[i];
8532     }
8533   }
8534
8535   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8536   // of the two input vectors, shuffle them into one input vector so only a
8537   // single pshufb instruction is necessary. If there are more than 2 input
8538   // quads, disable the next transformation since it does not help SSSE3.
8539   bool V1Used = InputQuads[0] || InputQuads[1];
8540   bool V2Used = InputQuads[2] || InputQuads[3];
8541   if (Subtarget->hasSSSE3()) {
8542     if (InputQuads.count() == 2 && V1Used && V2Used) {
8543       BestLoQuad = InputQuads[0] ? 0 : 1;
8544       BestHiQuad = InputQuads[2] ? 2 : 3;
8545     }
8546     if (InputQuads.count() > 2) {
8547       BestLoQuad = -1;
8548       BestHiQuad = -1;
8549     }
8550   }
8551
8552   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8553   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8554   // words from all 4 input quadwords.
8555   SDValue NewV;
8556   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8557     int MaskV[] = {
8558       BestLoQuad < 0 ? 0 : BestLoQuad,
8559       BestHiQuad < 0 ? 1 : BestHiQuad
8560     };
8561     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8562                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8563                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8564     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8565
8566     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8567     // source words for the shuffle, to aid later transformations.
8568     bool AllWordsInNewV = true;
8569     bool InOrder[2] = { true, true };
8570     for (unsigned i = 0; i != 8; ++i) {
8571       int idx = MaskVals[i];
8572       if (idx != (int)i)
8573         InOrder[i/4] = false;
8574       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8575         continue;
8576       AllWordsInNewV = false;
8577       break;
8578     }
8579
8580     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8581     if (AllWordsInNewV) {
8582       for (int i = 0; i != 8; ++i) {
8583         int idx = MaskVals[i];
8584         if (idx < 0)
8585           continue;
8586         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8587         if ((idx != i) && idx < 4)
8588           pshufhw = false;
8589         if ((idx != i) && idx > 3)
8590           pshuflw = false;
8591       }
8592       V1 = NewV;
8593       V2Used = false;
8594       BestLoQuad = 0;
8595       BestHiQuad = 1;
8596     }
8597
8598     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8599     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8600     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8601       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8602       unsigned TargetMask = 0;
8603       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8604                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8605       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8606       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8607                              getShufflePSHUFLWImmediate(SVOp);
8608       V1 = NewV.getOperand(0);
8609       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8610     }
8611   }
8612
8613   // Promote splats to a larger type which usually leads to more efficient code.
8614   // FIXME: Is this true if pshufb is available?
8615   if (SVOp->isSplat())
8616     return PromoteSplat(SVOp, DAG);
8617
8618   // If we have SSSE3, and all words of the result are from 1 input vector,
8619   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8620   // is present, fall back to case 4.
8621   if (Subtarget->hasSSSE3()) {
8622     SmallVector<SDValue,16> pshufbMask;
8623
8624     // If we have elements from both input vectors, set the high bit of the
8625     // shuffle mask element to zero out elements that come from V2 in the V1
8626     // mask, and elements that come from V1 in the V2 mask, so that the two
8627     // results can be OR'd together.
8628     bool TwoInputs = V1Used && V2Used;
8629     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8630     if (!TwoInputs)
8631       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8632
8633     // Calculate the shuffle mask for the second input, shuffle it, and
8634     // OR it with the first shuffled input.
8635     CommuteVectorShuffleMask(MaskVals, 8);
8636     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8637     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8638     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8639   }
8640
8641   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8642   // and update MaskVals with new element order.
8643   std::bitset<8> InOrder;
8644   if (BestLoQuad >= 0) {
8645     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8646     for (int i = 0; i != 4; ++i) {
8647       int idx = MaskVals[i];
8648       if (idx < 0) {
8649         InOrder.set(i);
8650       } else if ((idx / 4) == BestLoQuad) {
8651         MaskV[i] = idx & 3;
8652         InOrder.set(i);
8653       }
8654     }
8655     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8656                                 &MaskV[0]);
8657
8658     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8659       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8660       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8661                                   NewV.getOperand(0),
8662                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8663     }
8664   }
8665
8666   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8667   // and update MaskVals with the new element order.
8668   if (BestHiQuad >= 0) {
8669     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8670     for (unsigned i = 4; i != 8; ++i) {
8671       int idx = MaskVals[i];
8672       if (idx < 0) {
8673         InOrder.set(i);
8674       } else if ((idx / 4) == BestHiQuad) {
8675         MaskV[i] = (idx & 3) + 4;
8676         InOrder.set(i);
8677       }
8678     }
8679     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8680                                 &MaskV[0]);
8681
8682     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8683       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8684       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8685                                   NewV.getOperand(0),
8686                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8687     }
8688   }
8689
8690   // In case BestHi & BestLo were both -1, which means each quadword has a word
8691   // from each of the four input quadwords, calculate the InOrder bitvector now
8692   // before falling through to the insert/extract cleanup.
8693   if (BestLoQuad == -1 && BestHiQuad == -1) {
8694     NewV = V1;
8695     for (int i = 0; i != 8; ++i)
8696       if (MaskVals[i] < 0 || MaskVals[i] == i)
8697         InOrder.set(i);
8698   }
8699
8700   // The other elements are put in the right place using pextrw and pinsrw.
8701   for (unsigned i = 0; i != 8; ++i) {
8702     if (InOrder[i])
8703       continue;
8704     int EltIdx = MaskVals[i];
8705     if (EltIdx < 0)
8706       continue;
8707     SDValue ExtOp = (EltIdx < 8) ?
8708       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8709                   DAG.getIntPtrConstant(EltIdx)) :
8710       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8711                   DAG.getIntPtrConstant(EltIdx - 8));
8712     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8713                        DAG.getIntPtrConstant(i));
8714   }
8715   return NewV;
8716 }
8717
8718 /// \brief v16i16 shuffles
8719 ///
8720 /// FIXME: We only support generation of a single pshufb currently.  We can
8721 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8722 /// well (e.g 2 x pshufb + 1 x por).
8723 static SDValue
8724 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8725   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8726   SDValue V1 = SVOp->getOperand(0);
8727   SDValue V2 = SVOp->getOperand(1);
8728   SDLoc dl(SVOp);
8729
8730   if (V2.getOpcode() != ISD::UNDEF)
8731     return SDValue();
8732
8733   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8734   return getPSHUFB(MaskVals, V1, dl, DAG);
8735 }
8736
8737 // v16i8 shuffles - Prefer shuffles in the following order:
8738 // 1. [ssse3] 1 x pshufb
8739 // 2. [ssse3] 2 x pshufb + 1 x por
8740 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8741 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8742                                         const X86Subtarget* Subtarget,
8743                                         SelectionDAG &DAG) {
8744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8745   SDValue V1 = SVOp->getOperand(0);
8746   SDValue V2 = SVOp->getOperand(1);
8747   SDLoc dl(SVOp);
8748   ArrayRef<int> MaskVals = SVOp->getMask();
8749
8750   // Promote splats to a larger type which usually leads to more efficient code.
8751   // FIXME: Is this true if pshufb is available?
8752   if (SVOp->isSplat())
8753     return PromoteSplat(SVOp, DAG);
8754
8755   // If we have SSSE3, case 1 is generated when all result bytes come from
8756   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8757   // present, fall back to case 3.
8758
8759   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8760   if (Subtarget->hasSSSE3()) {
8761     SmallVector<SDValue,16> pshufbMask;
8762
8763     // If all result elements are from one input vector, then only translate
8764     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8765     //
8766     // Otherwise, we have elements from both input vectors, and must zero out
8767     // elements that come from V2 in the first mask, and V1 in the second mask
8768     // so that we can OR them together.
8769     for (unsigned i = 0; i != 16; ++i) {
8770       int EltIdx = MaskVals[i];
8771       if (EltIdx < 0 || EltIdx >= 16)
8772         EltIdx = 0x80;
8773       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8774     }
8775     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8776                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8777                                  MVT::v16i8, pshufbMask));
8778
8779     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8780     // the 2nd operand if it's undefined or zero.
8781     if (V2.getOpcode() == ISD::UNDEF ||
8782         ISD::isBuildVectorAllZeros(V2.getNode()))
8783       return V1;
8784
8785     // Calculate the shuffle mask for the second input, shuffle it, and
8786     // OR it with the first shuffled input.
8787     pshufbMask.clear();
8788     for (unsigned i = 0; i != 16; ++i) {
8789       int EltIdx = MaskVals[i];
8790       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8791       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8792     }
8793     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8794                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8795                                  MVT::v16i8, pshufbMask));
8796     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8797   }
8798
8799   // No SSSE3 - Calculate in place words and then fix all out of place words
8800   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8801   // the 16 different words that comprise the two doublequadword input vectors.
8802   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8803   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8804   SDValue NewV = V1;
8805   for (int i = 0; i != 8; ++i) {
8806     int Elt0 = MaskVals[i*2];
8807     int Elt1 = MaskVals[i*2+1];
8808
8809     // This word of the result is all undef, skip it.
8810     if (Elt0 < 0 && Elt1 < 0)
8811       continue;
8812
8813     // This word of the result is already in the correct place, skip it.
8814     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8815       continue;
8816
8817     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8818     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8819     SDValue InsElt;
8820
8821     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8822     // using a single extract together, load it and store it.
8823     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8824       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8825                            DAG.getIntPtrConstant(Elt1 / 2));
8826       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8827                         DAG.getIntPtrConstant(i));
8828       continue;
8829     }
8830
8831     // If Elt1 is defined, extract it from the appropriate source.  If the
8832     // source byte is not also odd, shift the extracted word left 8 bits
8833     // otherwise clear the bottom 8 bits if we need to do an or.
8834     if (Elt1 >= 0) {
8835       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8836                            DAG.getIntPtrConstant(Elt1 / 2));
8837       if ((Elt1 & 1) == 0)
8838         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8839                              DAG.getConstant(8,
8840                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8841       else if (Elt0 >= 0)
8842         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8843                              DAG.getConstant(0xFF00, MVT::i16));
8844     }
8845     // If Elt0 is defined, extract it from the appropriate source.  If the
8846     // source byte is not also even, shift the extracted word right 8 bits. If
8847     // Elt1 was also defined, OR the extracted values together before
8848     // inserting them in the result.
8849     if (Elt0 >= 0) {
8850       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8851                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8852       if ((Elt0 & 1) != 0)
8853         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8854                               DAG.getConstant(8,
8855                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8856       else if (Elt1 >= 0)
8857         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8858                              DAG.getConstant(0x00FF, MVT::i16));
8859       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8860                          : InsElt0;
8861     }
8862     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8863                        DAG.getIntPtrConstant(i));
8864   }
8865   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8866 }
8867
8868 // v32i8 shuffles - Translate to VPSHUFB if possible.
8869 static
8870 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8871                                  const X86Subtarget *Subtarget,
8872                                  SelectionDAG &DAG) {
8873   MVT VT = SVOp->getSimpleValueType(0);
8874   SDValue V1 = SVOp->getOperand(0);
8875   SDValue V2 = SVOp->getOperand(1);
8876   SDLoc dl(SVOp);
8877   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8878
8879   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8880   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8881   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8882
8883   // VPSHUFB may be generated if
8884   // (1) one of input vector is undefined or zeroinitializer.
8885   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8886   // And (2) the mask indexes don't cross the 128-bit lane.
8887   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8888       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8889     return SDValue();
8890
8891   if (V1IsAllZero && !V2IsAllZero) {
8892     CommuteVectorShuffleMask(MaskVals, 32);
8893     V1 = V2;
8894   }
8895   return getPSHUFB(MaskVals, V1, dl, DAG);
8896 }
8897
8898 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8899 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8900 /// done when every pair / quad of shuffle mask elements point to elements in
8901 /// the right sequence. e.g.
8902 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8903 static
8904 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8905                                  SelectionDAG &DAG) {
8906   MVT VT = SVOp->getSimpleValueType(0);
8907   SDLoc dl(SVOp);
8908   unsigned NumElems = VT.getVectorNumElements();
8909   MVT NewVT;
8910   unsigned Scale;
8911   switch (VT.SimpleTy) {
8912   default: llvm_unreachable("Unexpected!");
8913   case MVT::v2i64:
8914   case MVT::v2f64:
8915            return SDValue(SVOp, 0);
8916   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8917   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8918   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8919   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8920   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8921   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8922   }
8923
8924   SmallVector<int, 8> MaskVec;
8925   for (unsigned i = 0; i != NumElems; i += Scale) {
8926     int StartIdx = -1;
8927     for (unsigned j = 0; j != Scale; ++j) {
8928       int EltIdx = SVOp->getMaskElt(i+j);
8929       if (EltIdx < 0)
8930         continue;
8931       if (StartIdx < 0)
8932         StartIdx = (EltIdx / Scale);
8933       if (EltIdx != (int)(StartIdx*Scale + j))
8934         return SDValue();
8935     }
8936     MaskVec.push_back(StartIdx);
8937   }
8938
8939   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8940   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8941   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8942 }
8943
8944 /// getVZextMovL - Return a zero-extending vector move low node.
8945 ///
8946 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8947                             SDValue SrcOp, SelectionDAG &DAG,
8948                             const X86Subtarget *Subtarget, SDLoc dl) {
8949   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8950     LoadSDNode *LD = nullptr;
8951     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8952       LD = dyn_cast<LoadSDNode>(SrcOp);
8953     if (!LD) {
8954       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8955       // instead.
8956       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8957       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8958           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8959           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8960           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8961         // PR2108
8962         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8963         return DAG.getNode(ISD::BITCAST, dl, VT,
8964                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8965                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8966                                                    OpVT,
8967                                                    SrcOp.getOperand(0)
8968                                                           .getOperand(0))));
8969       }
8970     }
8971   }
8972
8973   return DAG.getNode(ISD::BITCAST, dl, VT,
8974                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8975                                  DAG.getNode(ISD::BITCAST, dl,
8976                                              OpVT, SrcOp)));
8977 }
8978
8979 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8980 /// which could not be matched by any known target speficic shuffle
8981 static SDValue
8982 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8983
8984   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8985   if (NewOp.getNode())
8986     return NewOp;
8987
8988   MVT VT = SVOp->getSimpleValueType(0);
8989
8990   unsigned NumElems = VT.getVectorNumElements();
8991   unsigned NumLaneElems = NumElems / 2;
8992
8993   SDLoc dl(SVOp);
8994   MVT EltVT = VT.getVectorElementType();
8995   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8996   SDValue Output[2];
8997
8998   SmallVector<int, 16> Mask;
8999   for (unsigned l = 0; l < 2; ++l) {
9000     // Build a shuffle mask for the output, discovering on the fly which
9001     // input vectors to use as shuffle operands (recorded in InputUsed).
9002     // If building a suitable shuffle vector proves too hard, then bail
9003     // out with UseBuildVector set.
9004     bool UseBuildVector = false;
9005     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9006     unsigned LaneStart = l * NumLaneElems;
9007     for (unsigned i = 0; i != NumLaneElems; ++i) {
9008       // The mask element.  This indexes into the input.
9009       int Idx = SVOp->getMaskElt(i+LaneStart);
9010       if (Idx < 0) {
9011         // the mask element does not index into any input vector.
9012         Mask.push_back(-1);
9013         continue;
9014       }
9015
9016       // The input vector this mask element indexes into.
9017       int Input = Idx / NumLaneElems;
9018
9019       // Turn the index into an offset from the start of the input vector.
9020       Idx -= Input * NumLaneElems;
9021
9022       // Find or create a shuffle vector operand to hold this input.
9023       unsigned OpNo;
9024       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9025         if (InputUsed[OpNo] == Input)
9026           // This input vector is already an operand.
9027           break;
9028         if (InputUsed[OpNo] < 0) {
9029           // Create a new operand for this input vector.
9030           InputUsed[OpNo] = Input;
9031           break;
9032         }
9033       }
9034
9035       if (OpNo >= array_lengthof(InputUsed)) {
9036         // More than two input vectors used!  Give up on trying to create a
9037         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9038         UseBuildVector = true;
9039         break;
9040       }
9041
9042       // Add the mask index for the new shuffle vector.
9043       Mask.push_back(Idx + OpNo * NumLaneElems);
9044     }
9045
9046     if (UseBuildVector) {
9047       SmallVector<SDValue, 16> SVOps;
9048       for (unsigned i = 0; i != NumLaneElems; ++i) {
9049         // The mask element.  This indexes into the input.
9050         int Idx = SVOp->getMaskElt(i+LaneStart);
9051         if (Idx < 0) {
9052           SVOps.push_back(DAG.getUNDEF(EltVT));
9053           continue;
9054         }
9055
9056         // The input vector this mask element indexes into.
9057         int Input = Idx / NumElems;
9058
9059         // Turn the index into an offset from the start of the input vector.
9060         Idx -= Input * NumElems;
9061
9062         // Extract the vector element by hand.
9063         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9064                                     SVOp->getOperand(Input),
9065                                     DAG.getIntPtrConstant(Idx)));
9066       }
9067
9068       // Construct the output using a BUILD_VECTOR.
9069       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9070     } else if (InputUsed[0] < 0) {
9071       // No input vectors were used! The result is undefined.
9072       Output[l] = DAG.getUNDEF(NVT);
9073     } else {
9074       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9075                                         (InputUsed[0] % 2) * NumLaneElems,
9076                                         DAG, dl);
9077       // If only one input was used, use an undefined vector for the other.
9078       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9079         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9080                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9081       // At least one input vector was used. Create a new shuffle vector.
9082       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9083     }
9084
9085     Mask.clear();
9086   }
9087
9088   // Concatenate the result back
9089   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9090 }
9091
9092 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9093 /// 4 elements, and match them with several different shuffle types.
9094 static SDValue
9095 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9096   SDValue V1 = SVOp->getOperand(0);
9097   SDValue V2 = SVOp->getOperand(1);
9098   SDLoc dl(SVOp);
9099   MVT VT = SVOp->getSimpleValueType(0);
9100
9101   assert(VT.is128BitVector() && "Unsupported vector size");
9102
9103   std::pair<int, int> Locs[4];
9104   int Mask1[] = { -1, -1, -1, -1 };
9105   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9106
9107   unsigned NumHi = 0;
9108   unsigned NumLo = 0;
9109   for (unsigned i = 0; i != 4; ++i) {
9110     int Idx = PermMask[i];
9111     if (Idx < 0) {
9112       Locs[i] = std::make_pair(-1, -1);
9113     } else {
9114       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9115       if (Idx < 4) {
9116         Locs[i] = std::make_pair(0, NumLo);
9117         Mask1[NumLo] = Idx;
9118         NumLo++;
9119       } else {
9120         Locs[i] = std::make_pair(1, NumHi);
9121         if (2+NumHi < 4)
9122           Mask1[2+NumHi] = Idx;
9123         NumHi++;
9124       }
9125     }
9126   }
9127
9128   if (NumLo <= 2 && NumHi <= 2) {
9129     // If no more than two elements come from either vector. This can be
9130     // implemented with two shuffles. First shuffle gather the elements.
9131     // The second shuffle, which takes the first shuffle as both of its
9132     // vector operands, put the elements into the right order.
9133     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9134
9135     int Mask2[] = { -1, -1, -1, -1 };
9136
9137     for (unsigned i = 0; i != 4; ++i)
9138       if (Locs[i].first != -1) {
9139         unsigned Idx = (i < 2) ? 0 : 4;
9140         Idx += Locs[i].first * 2 + Locs[i].second;
9141         Mask2[i] = Idx;
9142       }
9143
9144     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9145   }
9146
9147   if (NumLo == 3 || NumHi == 3) {
9148     // Otherwise, we must have three elements from one vector, call it X, and
9149     // one element from the other, call it Y.  First, use a shufps to build an
9150     // intermediate vector with the one element from Y and the element from X
9151     // that will be in the same half in the final destination (the indexes don't
9152     // matter). Then, use a shufps to build the final vector, taking the half
9153     // containing the element from Y from the intermediate, and the other half
9154     // from X.
9155     if (NumHi == 3) {
9156       // Normalize it so the 3 elements come from V1.
9157       CommuteVectorShuffleMask(PermMask, 4);
9158       std::swap(V1, V2);
9159     }
9160
9161     // Find the element from V2.
9162     unsigned HiIndex;
9163     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9164       int Val = PermMask[HiIndex];
9165       if (Val < 0)
9166         continue;
9167       if (Val >= 4)
9168         break;
9169     }
9170
9171     Mask1[0] = PermMask[HiIndex];
9172     Mask1[1] = -1;
9173     Mask1[2] = PermMask[HiIndex^1];
9174     Mask1[3] = -1;
9175     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9176
9177     if (HiIndex >= 2) {
9178       Mask1[0] = PermMask[0];
9179       Mask1[1] = PermMask[1];
9180       Mask1[2] = HiIndex & 1 ? 6 : 4;
9181       Mask1[3] = HiIndex & 1 ? 4 : 6;
9182       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9183     }
9184
9185     Mask1[0] = HiIndex & 1 ? 2 : 0;
9186     Mask1[1] = HiIndex & 1 ? 0 : 2;
9187     Mask1[2] = PermMask[2];
9188     Mask1[3] = PermMask[3];
9189     if (Mask1[2] >= 0)
9190       Mask1[2] += 4;
9191     if (Mask1[3] >= 0)
9192       Mask1[3] += 4;
9193     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9194   }
9195
9196   // Break it into (shuffle shuffle_hi, shuffle_lo).
9197   int LoMask[] = { -1, -1, -1, -1 };
9198   int HiMask[] = { -1, -1, -1, -1 };
9199
9200   int *MaskPtr = LoMask;
9201   unsigned MaskIdx = 0;
9202   unsigned LoIdx = 0;
9203   unsigned HiIdx = 2;
9204   for (unsigned i = 0; i != 4; ++i) {
9205     if (i == 2) {
9206       MaskPtr = HiMask;
9207       MaskIdx = 1;
9208       LoIdx = 0;
9209       HiIdx = 2;
9210     }
9211     int Idx = PermMask[i];
9212     if (Idx < 0) {
9213       Locs[i] = std::make_pair(-1, -1);
9214     } else if (Idx < 4) {
9215       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9216       MaskPtr[LoIdx] = Idx;
9217       LoIdx++;
9218     } else {
9219       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9220       MaskPtr[HiIdx] = Idx;
9221       HiIdx++;
9222     }
9223   }
9224
9225   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9226   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9227   int MaskOps[] = { -1, -1, -1, -1 };
9228   for (unsigned i = 0; i != 4; ++i)
9229     if (Locs[i].first != -1)
9230       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9231   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9232 }
9233
9234 static bool MayFoldVectorLoad(SDValue V) {
9235   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9236     V = V.getOperand(0);
9237
9238   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9239     V = V.getOperand(0);
9240   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9241       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9242     // BUILD_VECTOR (load), undef
9243     V = V.getOperand(0);
9244
9245   return MayFoldLoad(V);
9246 }
9247
9248 static
9249 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9250   MVT VT = Op.getSimpleValueType();
9251
9252   // Canonizalize to v2f64.
9253   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9254   return DAG.getNode(ISD::BITCAST, dl, VT,
9255                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9256                                           V1, DAG));
9257 }
9258
9259 static
9260 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9261                         bool HasSSE2) {
9262   SDValue V1 = Op.getOperand(0);
9263   SDValue V2 = Op.getOperand(1);
9264   MVT VT = Op.getSimpleValueType();
9265
9266   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9267
9268   if (HasSSE2 && VT == MVT::v2f64)
9269     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9270
9271   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9272   return DAG.getNode(ISD::BITCAST, dl, VT,
9273                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9274                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9275                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9276 }
9277
9278 static
9279 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9280   SDValue V1 = Op.getOperand(0);
9281   SDValue V2 = Op.getOperand(1);
9282   MVT VT = Op.getSimpleValueType();
9283
9284   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9285          "unsupported shuffle type");
9286
9287   if (V2.getOpcode() == ISD::UNDEF)
9288     V2 = V1;
9289
9290   // v4i32 or v4f32
9291   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9292 }
9293
9294 static
9295 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9296   SDValue V1 = Op.getOperand(0);
9297   SDValue V2 = Op.getOperand(1);
9298   MVT VT = Op.getSimpleValueType();
9299   unsigned NumElems = VT.getVectorNumElements();
9300
9301   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9302   // operand of these instructions is only memory, so check if there's a
9303   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9304   // same masks.
9305   bool CanFoldLoad = false;
9306
9307   // Trivial case, when V2 comes from a load.
9308   if (MayFoldVectorLoad(V2))
9309     CanFoldLoad = true;
9310
9311   // When V1 is a load, it can be folded later into a store in isel, example:
9312   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9313   //    turns into:
9314   //  (MOVLPSmr addr:$src1, VR128:$src2)
9315   // So, recognize this potential and also use MOVLPS or MOVLPD
9316   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9317     CanFoldLoad = true;
9318
9319   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9320   if (CanFoldLoad) {
9321     if (HasSSE2 && NumElems == 2)
9322       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9323
9324     if (NumElems == 4)
9325       // If we don't care about the second element, proceed to use movss.
9326       if (SVOp->getMaskElt(1) != -1)
9327         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9328   }
9329
9330   // movl and movlp will both match v2i64, but v2i64 is never matched by
9331   // movl earlier because we make it strict to avoid messing with the movlp load
9332   // folding logic (see the code above getMOVLP call). Match it here then,
9333   // this is horrible, but will stay like this until we move all shuffle
9334   // matching to x86 specific nodes. Note that for the 1st condition all
9335   // types are matched with movsd.
9336   if (HasSSE2) {
9337     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9338     // as to remove this logic from here, as much as possible
9339     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9340       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9341     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9342   }
9343
9344   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9345
9346   // Invert the operand order and use SHUFPS to match it.
9347   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9348                               getShuffleSHUFImmediate(SVOp), DAG);
9349 }
9350
9351 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9352                                          SelectionDAG &DAG) {
9353   SDLoc dl(Load);
9354   MVT VT = Load->getSimpleValueType(0);
9355   MVT EVT = VT.getVectorElementType();
9356   SDValue Addr = Load->getOperand(1);
9357   SDValue NewAddr = DAG.getNode(
9358       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9359       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9360
9361   SDValue NewLoad =
9362       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9363                   DAG.getMachineFunction().getMachineMemOperand(
9364                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9365   return NewLoad;
9366 }
9367
9368 // It is only safe to call this function if isINSERTPSMask is true for
9369 // this shufflevector mask.
9370 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9371                            SelectionDAG &DAG) {
9372   // Generate an insertps instruction when inserting an f32 from memory onto a
9373   // v4f32 or when copying a member from one v4f32 to another.
9374   // We also use it for transferring i32 from one register to another,
9375   // since it simply copies the same bits.
9376   // If we're transferring an i32 from memory to a specific element in a
9377   // register, we output a generic DAG that will match the PINSRD
9378   // instruction.
9379   MVT VT = SVOp->getSimpleValueType(0);
9380   MVT EVT = VT.getVectorElementType();
9381   SDValue V1 = SVOp->getOperand(0);
9382   SDValue V2 = SVOp->getOperand(1);
9383   auto Mask = SVOp->getMask();
9384   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9385          "unsupported vector type for insertps/pinsrd");
9386
9387   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9388   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9389   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9390
9391   SDValue From;
9392   SDValue To;
9393   unsigned DestIndex;
9394   if (FromV1 == 1) {
9395     From = V1;
9396     To = V2;
9397     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9398                 Mask.begin();
9399
9400     // If we have 1 element from each vector, we have to check if we're
9401     // changing V1's element's place. If so, we're done. Otherwise, we
9402     // should assume we're changing V2's element's place and behave
9403     // accordingly.
9404     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9405     assert(DestIndex <= INT32_MAX && "truncated destination index");
9406     if (FromV1 == FromV2 &&
9407         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9408       From = V2;
9409       To = V1;
9410       DestIndex =
9411           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9412     }
9413   } else {
9414     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9415            "More than one element from V1 and from V2, or no elements from one "
9416            "of the vectors. This case should not have returned true from "
9417            "isINSERTPSMask");
9418     From = V2;
9419     To = V1;
9420     DestIndex =
9421         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9422   }
9423
9424   // Get an index into the source vector in the range [0,4) (the mask is
9425   // in the range [0,8) because it can address V1 and V2)
9426   unsigned SrcIndex = Mask[DestIndex] % 4;
9427   if (MayFoldLoad(From)) {
9428     // Trivial case, when From comes from a load and is only used by the
9429     // shuffle. Make it use insertps from the vector that we need from that
9430     // load.
9431     SDValue NewLoad =
9432         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9433     if (!NewLoad.getNode())
9434       return SDValue();
9435
9436     if (EVT == MVT::f32) {
9437       // Create this as a scalar to vector to match the instruction pattern.
9438       SDValue LoadScalarToVector =
9439           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9440       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9441       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9442                          InsertpsMask);
9443     } else { // EVT == MVT::i32
9444       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9445       // instruction, to match the PINSRD instruction, which loads an i32 to a
9446       // certain vector element.
9447       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9448                          DAG.getConstant(DestIndex, MVT::i32));
9449     }
9450   }
9451
9452   // Vector-element-to-vector
9453   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9454   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9455 }
9456
9457 // Reduce a vector shuffle to zext.
9458 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9459                                     SelectionDAG &DAG) {
9460   // PMOVZX is only available from SSE41.
9461   if (!Subtarget->hasSSE41())
9462     return SDValue();
9463
9464   MVT VT = Op.getSimpleValueType();
9465
9466   // Only AVX2 support 256-bit vector integer extending.
9467   if (!Subtarget->hasInt256() && VT.is256BitVector())
9468     return SDValue();
9469
9470   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9471   SDLoc DL(Op);
9472   SDValue V1 = Op.getOperand(0);
9473   SDValue V2 = Op.getOperand(1);
9474   unsigned NumElems = VT.getVectorNumElements();
9475
9476   // Extending is an unary operation and the element type of the source vector
9477   // won't be equal to or larger than i64.
9478   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9479       VT.getVectorElementType() == MVT::i64)
9480     return SDValue();
9481
9482   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9483   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9484   while ((1U << Shift) < NumElems) {
9485     if (SVOp->getMaskElt(1U << Shift) == 1)
9486       break;
9487     Shift += 1;
9488     // The maximal ratio is 8, i.e. from i8 to i64.
9489     if (Shift > 3)
9490       return SDValue();
9491   }
9492
9493   // Check the shuffle mask.
9494   unsigned Mask = (1U << Shift) - 1;
9495   for (unsigned i = 0; i != NumElems; ++i) {
9496     int EltIdx = SVOp->getMaskElt(i);
9497     if ((i & Mask) != 0 && EltIdx != -1)
9498       return SDValue();
9499     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9500       return SDValue();
9501   }
9502
9503   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9504   MVT NeVT = MVT::getIntegerVT(NBits);
9505   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9506
9507   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9508     return SDValue();
9509
9510   // Simplify the operand as it's prepared to be fed into shuffle.
9511   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9512   if (V1.getOpcode() == ISD::BITCAST &&
9513       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9514       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9515       V1.getOperand(0).getOperand(0)
9516         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9517     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9518     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9519     ConstantSDNode *CIdx =
9520       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9521     // If it's foldable, i.e. normal load with single use, we will let code
9522     // selection to fold it. Otherwise, we will short the conversion sequence.
9523     if (CIdx && CIdx->getZExtValue() == 0 &&
9524         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9525       MVT FullVT = V.getSimpleValueType();
9526       MVT V1VT = V1.getSimpleValueType();
9527       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9528         // The "ext_vec_elt" node is wider than the result node.
9529         // In this case we should extract subvector from V.
9530         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9531         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9532         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9533                                         FullVT.getVectorNumElements()/Ratio);
9534         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9535                         DAG.getIntPtrConstant(0));
9536       }
9537       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9538     }
9539   }
9540
9541   return DAG.getNode(ISD::BITCAST, DL, VT,
9542                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9543 }
9544
9545 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9546                                       SelectionDAG &DAG) {
9547   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9548   MVT VT = Op.getSimpleValueType();
9549   SDLoc dl(Op);
9550   SDValue V1 = Op.getOperand(0);
9551   SDValue V2 = Op.getOperand(1);
9552
9553   if (isZeroShuffle(SVOp))
9554     return getZeroVector(VT, Subtarget, DAG, dl);
9555
9556   // Handle splat operations
9557   if (SVOp->isSplat()) {
9558     // Use vbroadcast whenever the splat comes from a foldable load
9559     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9560     if (Broadcast.getNode())
9561       return Broadcast;
9562   }
9563
9564   // Check integer expanding shuffles.
9565   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9566   if (NewOp.getNode())
9567     return NewOp;
9568
9569   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9570   // do it!
9571   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9572       VT == MVT::v32i8) {
9573     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9574     if (NewOp.getNode())
9575       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9576   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9577     // FIXME: Figure out a cleaner way to do this.
9578     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9579       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9580       if (NewOp.getNode()) {
9581         MVT NewVT = NewOp.getSimpleValueType();
9582         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9583                                NewVT, true, false))
9584           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9585                               dl);
9586       }
9587     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9588       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9589       if (NewOp.getNode()) {
9590         MVT NewVT = NewOp.getSimpleValueType();
9591         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9592           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9593                               dl);
9594       }
9595     }
9596   }
9597   return SDValue();
9598 }
9599
9600 SDValue
9601 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9602   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9603   SDValue V1 = Op.getOperand(0);
9604   SDValue V2 = Op.getOperand(1);
9605   MVT VT = Op.getSimpleValueType();
9606   SDLoc dl(Op);
9607   unsigned NumElems = VT.getVectorNumElements();
9608   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9609   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9610   bool V1IsSplat = false;
9611   bool V2IsSplat = false;
9612   bool HasSSE2 = Subtarget->hasSSE2();
9613   bool HasFp256    = Subtarget->hasFp256();
9614   bool HasInt256   = Subtarget->hasInt256();
9615   MachineFunction &MF = DAG.getMachineFunction();
9616   bool OptForSize = MF.getFunction()->getAttributes().
9617     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9618
9619   // Check if we should use the experimental vector shuffle lowering. If so,
9620   // delegate completely to that code path.
9621   if (ExperimentalVectorShuffleLowering)
9622     return lowerVectorShuffle(Op, Subtarget, DAG);
9623
9624   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9625
9626   if (V1IsUndef && V2IsUndef)
9627     return DAG.getUNDEF(VT);
9628
9629   // When we create a shuffle node we put the UNDEF node to second operand,
9630   // but in some cases the first operand may be transformed to UNDEF.
9631   // In this case we should just commute the node.
9632   if (V1IsUndef)
9633     return DAG.getCommutedVectorShuffle(*SVOp);
9634
9635   // Vector shuffle lowering takes 3 steps:
9636   //
9637   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9638   //    narrowing and commutation of operands should be handled.
9639   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9640   //    shuffle nodes.
9641   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9642   //    so the shuffle can be broken into other shuffles and the legalizer can
9643   //    try the lowering again.
9644   //
9645   // The general idea is that no vector_shuffle operation should be left to
9646   // be matched during isel, all of them must be converted to a target specific
9647   // node here.
9648
9649   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9650   // narrowing and commutation of operands should be handled. The actual code
9651   // doesn't include all of those, work in progress...
9652   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9653   if (NewOp.getNode())
9654     return NewOp;
9655
9656   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9657
9658   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9659   // unpckh_undef). Only use pshufd if speed is more important than size.
9660   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9661     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9662   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9663     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9664
9665   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9666       V2IsUndef && MayFoldVectorLoad(V1))
9667     return getMOVDDup(Op, dl, V1, DAG);
9668
9669   if (isMOVHLPS_v_undef_Mask(M, VT))
9670     return getMOVHighToLow(Op, dl, DAG);
9671
9672   // Use to match splats
9673   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9674       (VT == MVT::v2f64 || VT == MVT::v2i64))
9675     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9676
9677   if (isPSHUFDMask(M, VT)) {
9678     // The actual implementation will match the mask in the if above and then
9679     // during isel it can match several different instructions, not only pshufd
9680     // as its name says, sad but true, emulate the behavior for now...
9681     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9682       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9683
9684     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9685
9686     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9687       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9688
9689     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9690       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9691                                   DAG);
9692
9693     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9694                                 TargetMask, DAG);
9695   }
9696
9697   if (isPALIGNRMask(M, VT, Subtarget))
9698     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9699                                 getShufflePALIGNRImmediate(SVOp),
9700                                 DAG);
9701
9702   if (isVALIGNMask(M, VT, Subtarget))
9703     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
9704                                 getShuffleVALIGNImmediate(SVOp),
9705                                 DAG);
9706
9707   // Check if this can be converted into a logical shift.
9708   bool isLeft = false;
9709   unsigned ShAmt = 0;
9710   SDValue ShVal;
9711   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9712   if (isShift && ShVal.hasOneUse()) {
9713     // If the shifted value has multiple uses, it may be cheaper to use
9714     // v_set0 + movlhps or movhlps, etc.
9715     MVT EltVT = VT.getVectorElementType();
9716     ShAmt *= EltVT.getSizeInBits();
9717     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9718   }
9719
9720   if (isMOVLMask(M, VT)) {
9721     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9722       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9723     if (!isMOVLPMask(M, VT)) {
9724       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9725         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9726
9727       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9728         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9729     }
9730   }
9731
9732   // FIXME: fold these into legal mask.
9733   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9734     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9735
9736   if (isMOVHLPSMask(M, VT))
9737     return getMOVHighToLow(Op, dl, DAG);
9738
9739   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9740     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9741
9742   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9743     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9744
9745   if (isMOVLPMask(M, VT))
9746     return getMOVLP(Op, dl, DAG, HasSSE2);
9747
9748   if (ShouldXformToMOVHLPS(M, VT) ||
9749       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9750     return DAG.getCommutedVectorShuffle(*SVOp);
9751
9752   if (isShift) {
9753     // No better options. Use a vshldq / vsrldq.
9754     MVT EltVT = VT.getVectorElementType();
9755     ShAmt *= EltVT.getSizeInBits();
9756     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9757   }
9758
9759   bool Commuted = false;
9760   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9761   // 1,1,1,1 -> v8i16 though.
9762   BitVector UndefElements;
9763   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9764     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9765       V1IsSplat = true;
9766   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9767     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9768       V2IsSplat = true;
9769
9770   // Canonicalize the splat or undef, if present, to be on the RHS.
9771   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9772     CommuteVectorShuffleMask(M, NumElems);
9773     std::swap(V1, V2);
9774     std::swap(V1IsSplat, V2IsSplat);
9775     Commuted = true;
9776   }
9777
9778   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9779     // Shuffling low element of v1 into undef, just return v1.
9780     if (V2IsUndef)
9781       return V1;
9782     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9783     // the instruction selector will not match, so get a canonical MOVL with
9784     // swapped operands to undo the commute.
9785     return getMOVL(DAG, dl, VT, V2, V1);
9786   }
9787
9788   if (isUNPCKLMask(M, VT, HasInt256))
9789     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9790
9791   if (isUNPCKHMask(M, VT, HasInt256))
9792     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9793
9794   if (V2IsSplat) {
9795     // Normalize mask so all entries that point to V2 points to its first
9796     // element then try to match unpck{h|l} again. If match, return a
9797     // new vector_shuffle with the corrected mask.p
9798     SmallVector<int, 8> NewMask(M.begin(), M.end());
9799     NormalizeMask(NewMask, NumElems);
9800     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9801       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9802     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9803       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9804   }
9805
9806   if (Commuted) {
9807     // Commute is back and try unpck* again.
9808     // FIXME: this seems wrong.
9809     CommuteVectorShuffleMask(M, NumElems);
9810     std::swap(V1, V2);
9811     std::swap(V1IsSplat, V2IsSplat);
9812
9813     if (isUNPCKLMask(M, VT, HasInt256))
9814       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9815
9816     if (isUNPCKHMask(M, VT, HasInt256))
9817       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9818   }
9819
9820   // Normalize the node to match x86 shuffle ops if needed
9821   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9822     return DAG.getCommutedVectorShuffle(*SVOp);
9823
9824   // The checks below are all present in isShuffleMaskLegal, but they are
9825   // inlined here right now to enable us to directly emit target specific
9826   // nodes, and remove one by one until they don't return Op anymore.
9827
9828   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9829       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9830     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9831       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9832   }
9833
9834   if (isPSHUFHWMask(M, VT, HasInt256))
9835     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9836                                 getShufflePSHUFHWImmediate(SVOp),
9837                                 DAG);
9838
9839   if (isPSHUFLWMask(M, VT, HasInt256))
9840     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9841                                 getShufflePSHUFLWImmediate(SVOp),
9842                                 DAG);
9843
9844   unsigned MaskValue;
9845   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9846                   &MaskValue))
9847     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9848
9849   if (isSHUFPMask(M, VT))
9850     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9851                                 getShuffleSHUFImmediate(SVOp), DAG);
9852
9853   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9854     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9855   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9856     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9857
9858   //===--------------------------------------------------------------------===//
9859   // Generate target specific nodes for 128 or 256-bit shuffles only
9860   // supported in the AVX instruction set.
9861   //
9862
9863   // Handle VMOVDDUPY permutations
9864   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9865     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9866
9867   // Handle VPERMILPS/D* permutations
9868   if (isVPERMILPMask(M, VT)) {
9869     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9870       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9871                                   getShuffleSHUFImmediate(SVOp), DAG);
9872     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9873                                 getShuffleSHUFImmediate(SVOp), DAG);
9874   }
9875
9876   unsigned Idx;
9877   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9878     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9879                               Idx*(NumElems/2), DAG, dl);
9880
9881   // Handle VPERM2F128/VPERM2I128 permutations
9882   if (isVPERM2X128Mask(M, VT, HasFp256))
9883     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9884                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9885
9886   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9887     return getINSERTPS(SVOp, dl, DAG);
9888
9889   unsigned Imm8;
9890   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9891     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9892
9893   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9894       VT.is512BitVector()) {
9895     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9896     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9897     SmallVector<SDValue, 16> permclMask;
9898     for (unsigned i = 0; i != NumElems; ++i) {
9899       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9900     }
9901
9902     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9903     if (V2IsUndef)
9904       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9905       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9906                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9907     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9908                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9909   }
9910
9911   //===--------------------------------------------------------------------===//
9912   // Since no target specific shuffle was selected for this generic one,
9913   // lower it into other known shuffles. FIXME: this isn't true yet, but
9914   // this is the plan.
9915   //
9916
9917   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9918   if (VT == MVT::v8i16) {
9919     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9920     if (NewOp.getNode())
9921       return NewOp;
9922   }
9923
9924   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9925     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9926     if (NewOp.getNode())
9927       return NewOp;
9928   }
9929
9930   if (VT == MVT::v16i8) {
9931     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9932     if (NewOp.getNode())
9933       return NewOp;
9934   }
9935
9936   if (VT == MVT::v32i8) {
9937     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9938     if (NewOp.getNode())
9939       return NewOp;
9940   }
9941
9942   // Handle all 128-bit wide vectors with 4 elements, and match them with
9943   // several different shuffle types.
9944   if (NumElems == 4 && VT.is128BitVector())
9945     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9946
9947   // Handle general 256-bit shuffles
9948   if (VT.is256BitVector())
9949     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9950
9951   return SDValue();
9952 }
9953
9954 // This function assumes its argument is a BUILD_VECTOR of constants or
9955 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9956 // true.
9957 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9958                                     unsigned &MaskValue) {
9959   MaskValue = 0;
9960   unsigned NumElems = BuildVector->getNumOperands();
9961   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9962   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9963   unsigned NumElemsInLane = NumElems / NumLanes;
9964
9965   // Blend for v16i16 should be symetric for the both lanes.
9966   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9967     SDValue EltCond = BuildVector->getOperand(i);
9968     SDValue SndLaneEltCond =
9969         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9970
9971     int Lane1Cond = -1, Lane2Cond = -1;
9972     if (isa<ConstantSDNode>(EltCond))
9973       Lane1Cond = !isZero(EltCond);
9974     if (isa<ConstantSDNode>(SndLaneEltCond))
9975       Lane2Cond = !isZero(SndLaneEltCond);
9976
9977     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9978       // Lane1Cond != 0, means we want the first argument.
9979       // Lane1Cond == 0, means we want the second argument.
9980       // The encoding of this argument is 0 for the first argument, 1
9981       // for the second. Therefore, invert the condition.
9982       MaskValue |= !Lane1Cond << i;
9983     else if (Lane1Cond < 0)
9984       MaskValue |= !Lane2Cond << i;
9985     else
9986       return false;
9987   }
9988   return true;
9989 }
9990
9991 // Try to lower a vselect node into a simple blend instruction.
9992 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9993                                    SelectionDAG &DAG) {
9994   SDValue Cond = Op.getOperand(0);
9995   SDValue LHS = Op.getOperand(1);
9996   SDValue RHS = Op.getOperand(2);
9997   SDLoc dl(Op);
9998   MVT VT = Op.getSimpleValueType();
9999   MVT EltVT = VT.getVectorElementType();
10000   unsigned NumElems = VT.getVectorNumElements();
10001
10002   // There is no blend with immediate in AVX-512.
10003   if (VT.is512BitVector())
10004     return SDValue();
10005
10006   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10007     return SDValue();
10008   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10009     return SDValue();
10010
10011   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10012     return SDValue();
10013
10014   // Check the mask for BLEND and build the value.
10015   unsigned MaskValue = 0;
10016   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10017     return SDValue();
10018
10019   // Convert i32 vectors to floating point if it is not AVX2.
10020   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10021   MVT BlendVT = VT;
10022   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10023     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10024                                NumElems);
10025     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10026     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10027   }
10028
10029   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10030                             DAG.getConstant(MaskValue, MVT::i32));
10031   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10032 }
10033
10034 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10035   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10036   if (BlendOp.getNode())
10037     return BlendOp;
10038
10039   // Some types for vselect were previously set to Expand, not Legal or
10040   // Custom. Return an empty SDValue so we fall-through to Expand, after
10041   // the Custom lowering phase.
10042   MVT VT = Op.getSimpleValueType();
10043   switch (VT.SimpleTy) {
10044   default:
10045     break;
10046   case MVT::v8i16:
10047   case MVT::v16i16:
10048     return SDValue();
10049   }
10050
10051   // We couldn't create a "Blend with immediate" node.
10052   // This node should still be legal, but we'll have to emit a blendv*
10053   // instruction.
10054   return Op;
10055 }
10056
10057 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10058   MVT VT = Op.getSimpleValueType();
10059   SDLoc dl(Op);
10060
10061   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10062     return SDValue();
10063
10064   if (VT.getSizeInBits() == 8) {
10065     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10066                                   Op.getOperand(0), Op.getOperand(1));
10067     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10068                                   DAG.getValueType(VT));
10069     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10070   }
10071
10072   if (VT.getSizeInBits() == 16) {
10073     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10074     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10075     if (Idx == 0)
10076       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10077                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10078                                      DAG.getNode(ISD::BITCAST, dl,
10079                                                  MVT::v4i32,
10080                                                  Op.getOperand(0)),
10081                                      Op.getOperand(1)));
10082     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10083                                   Op.getOperand(0), Op.getOperand(1));
10084     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10085                                   DAG.getValueType(VT));
10086     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10087   }
10088
10089   if (VT == MVT::f32) {
10090     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10091     // the result back to FR32 register. It's only worth matching if the
10092     // result has a single use which is a store or a bitcast to i32.  And in
10093     // the case of a store, it's not worth it if the index is a constant 0,
10094     // because a MOVSSmr can be used instead, which is smaller and faster.
10095     if (!Op.hasOneUse())
10096       return SDValue();
10097     SDNode *User = *Op.getNode()->use_begin();
10098     if ((User->getOpcode() != ISD::STORE ||
10099          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10100           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10101         (User->getOpcode() != ISD::BITCAST ||
10102          User->getValueType(0) != MVT::i32))
10103       return SDValue();
10104     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10105                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10106                                               Op.getOperand(0)),
10107                                               Op.getOperand(1));
10108     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10109   }
10110
10111   if (VT == MVT::i32 || VT == MVT::i64) {
10112     // ExtractPS/pextrq works with constant index.
10113     if (isa<ConstantSDNode>(Op.getOperand(1)))
10114       return Op;
10115   }
10116   return SDValue();
10117 }
10118
10119 /// Extract one bit from mask vector, like v16i1 or v8i1.
10120 /// AVX-512 feature.
10121 SDValue
10122 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10123   SDValue Vec = Op.getOperand(0);
10124   SDLoc dl(Vec);
10125   MVT VecVT = Vec.getSimpleValueType();
10126   SDValue Idx = Op.getOperand(1);
10127   MVT EltVT = Op.getSimpleValueType();
10128
10129   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10130
10131   // variable index can't be handled in mask registers,
10132   // extend vector to VR512
10133   if (!isa<ConstantSDNode>(Idx)) {
10134     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10135     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10136     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10137                               ExtVT.getVectorElementType(), Ext, Idx);
10138     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10139   }
10140
10141   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10142   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10143   unsigned MaxSift = rc->getSize()*8 - 1;
10144   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10145                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10146   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10147                     DAG.getConstant(MaxSift, MVT::i8));
10148   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10149                        DAG.getIntPtrConstant(0));
10150 }
10151
10152 SDValue
10153 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10154                                            SelectionDAG &DAG) const {
10155   SDLoc dl(Op);
10156   SDValue Vec = Op.getOperand(0);
10157   MVT VecVT = Vec.getSimpleValueType();
10158   SDValue Idx = Op.getOperand(1);
10159
10160   if (Op.getSimpleValueType() == MVT::i1)
10161     return ExtractBitFromMaskVector(Op, DAG);
10162
10163   if (!isa<ConstantSDNode>(Idx)) {
10164     if (VecVT.is512BitVector() ||
10165         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10166          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10167
10168       MVT MaskEltVT =
10169         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10170       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10171                                     MaskEltVT.getSizeInBits());
10172
10173       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10174       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10175                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10176                                 Idx, DAG.getConstant(0, getPointerTy()));
10177       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10178       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10179                         Perm, DAG.getConstant(0, getPointerTy()));
10180     }
10181     return SDValue();
10182   }
10183
10184   // If this is a 256-bit vector result, first extract the 128-bit vector and
10185   // then extract the element from the 128-bit vector.
10186   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10187
10188     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10189     // Get the 128-bit vector.
10190     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10191     MVT EltVT = VecVT.getVectorElementType();
10192
10193     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10194
10195     //if (IdxVal >= NumElems/2)
10196     //  IdxVal -= NumElems/2;
10197     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10198     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10199                        DAG.getConstant(IdxVal, MVT::i32));
10200   }
10201
10202   assert(VecVT.is128BitVector() && "Unexpected vector length");
10203
10204   if (Subtarget->hasSSE41()) {
10205     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10206     if (Res.getNode())
10207       return Res;
10208   }
10209
10210   MVT VT = Op.getSimpleValueType();
10211   // TODO: handle v16i8.
10212   if (VT.getSizeInBits() == 16) {
10213     SDValue Vec = Op.getOperand(0);
10214     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10215     if (Idx == 0)
10216       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10217                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10218                                      DAG.getNode(ISD::BITCAST, dl,
10219                                                  MVT::v4i32, Vec),
10220                                      Op.getOperand(1)));
10221     // Transform it so it match pextrw which produces a 32-bit result.
10222     MVT EltVT = MVT::i32;
10223     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10224                                   Op.getOperand(0), Op.getOperand(1));
10225     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10226                                   DAG.getValueType(VT));
10227     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10228   }
10229
10230   if (VT.getSizeInBits() == 32) {
10231     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10232     if (Idx == 0)
10233       return Op;
10234
10235     // SHUFPS the element to the lowest double word, then movss.
10236     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10237     MVT VVT = Op.getOperand(0).getSimpleValueType();
10238     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10239                                        DAG.getUNDEF(VVT), Mask);
10240     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10241                        DAG.getIntPtrConstant(0));
10242   }
10243
10244   if (VT.getSizeInBits() == 64) {
10245     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10246     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10247     //        to match extract_elt for f64.
10248     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10249     if (Idx == 0)
10250       return Op;
10251
10252     // UNPCKHPD the element to the lowest double word, then movsd.
10253     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10254     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10255     int Mask[2] = { 1, -1 };
10256     MVT VVT = Op.getOperand(0).getSimpleValueType();
10257     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10258                                        DAG.getUNDEF(VVT), Mask);
10259     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10260                        DAG.getIntPtrConstant(0));
10261   }
10262
10263   return SDValue();
10264 }
10265
10266 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10267   MVT VT = Op.getSimpleValueType();
10268   MVT EltVT = VT.getVectorElementType();
10269   SDLoc dl(Op);
10270
10271   SDValue N0 = Op.getOperand(0);
10272   SDValue N1 = Op.getOperand(1);
10273   SDValue N2 = Op.getOperand(2);
10274
10275   if (!VT.is128BitVector())
10276     return SDValue();
10277
10278   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10279       isa<ConstantSDNode>(N2)) {
10280     unsigned Opc;
10281     if (VT == MVT::v8i16)
10282       Opc = X86ISD::PINSRW;
10283     else if (VT == MVT::v16i8)
10284       Opc = X86ISD::PINSRB;
10285     else
10286       Opc = X86ISD::PINSRB;
10287
10288     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10289     // argument.
10290     if (N1.getValueType() != MVT::i32)
10291       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10292     if (N2.getValueType() != MVT::i32)
10293       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10294     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10295   }
10296
10297   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10298     // Bits [7:6] of the constant are the source select.  This will always be
10299     //  zero here.  The DAG Combiner may combine an extract_elt index into these
10300     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
10301     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10302     // Bits [5:4] of the constant are the destination select.  This is the
10303     //  value of the incoming immediate.
10304     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10305     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10306     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10307     // Create this as a scalar to vector..
10308     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10309     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10310   }
10311
10312   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10313     // PINSR* works with constant index.
10314     return Op;
10315   }
10316   return SDValue();
10317 }
10318
10319 /// Insert one bit to mask vector, like v16i1 or v8i1.
10320 /// AVX-512 feature.
10321 SDValue 
10322 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10323   SDLoc dl(Op);
10324   SDValue Vec = Op.getOperand(0);
10325   SDValue Elt = Op.getOperand(1);
10326   SDValue Idx = Op.getOperand(2);
10327   MVT VecVT = Vec.getSimpleValueType();
10328
10329   if (!isa<ConstantSDNode>(Idx)) {
10330     // Non constant index. Extend source and destination,
10331     // insert element and then truncate the result.
10332     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10333     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10334     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10335       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10336       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10337     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10338   }
10339
10340   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10341   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10342   if (Vec.getOpcode() == ISD::UNDEF)
10343     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10344                        DAG.getConstant(IdxVal, MVT::i8));
10345   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10346   unsigned MaxSift = rc->getSize()*8 - 1;
10347   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10348                     DAG.getConstant(MaxSift, MVT::i8));
10349   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10350                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10351   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10352 }
10353 SDValue
10354 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10355   MVT VT = Op.getSimpleValueType();
10356   MVT EltVT = VT.getVectorElementType();
10357   
10358   if (EltVT == MVT::i1)
10359     return InsertBitToMaskVector(Op, DAG);
10360
10361   SDLoc dl(Op);
10362   SDValue N0 = Op.getOperand(0);
10363   SDValue N1 = Op.getOperand(1);
10364   SDValue N2 = Op.getOperand(2);
10365
10366   // If this is a 256-bit vector result, first extract the 128-bit vector,
10367   // insert the element into the extracted half and then place it back.
10368   if (VT.is256BitVector() || VT.is512BitVector()) {
10369     if (!isa<ConstantSDNode>(N2))
10370       return SDValue();
10371
10372     // Get the desired 128-bit vector half.
10373     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10374     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10375
10376     // Insert the element into the desired half.
10377     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10378     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10379
10380     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10381                     DAG.getConstant(IdxIn128, MVT::i32));
10382
10383     // Insert the changed part back to the 256-bit vector
10384     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10385   }
10386
10387   if (Subtarget->hasSSE41())
10388     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10389
10390   if (EltVT == MVT::i8)
10391     return SDValue();
10392
10393   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10394     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10395     // as its second argument.
10396     if (N1.getValueType() != MVT::i32)
10397       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10398     if (N2.getValueType() != MVT::i32)
10399       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10400     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10401   }
10402   return SDValue();
10403 }
10404
10405 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10406   SDLoc dl(Op);
10407   MVT OpVT = Op.getSimpleValueType();
10408
10409   // If this is a 256-bit vector result, first insert into a 128-bit
10410   // vector and then insert into the 256-bit vector.
10411   if (!OpVT.is128BitVector()) {
10412     // Insert into a 128-bit vector.
10413     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10414     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10415                                  OpVT.getVectorNumElements() / SizeFactor);
10416
10417     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10418
10419     // Insert the 128-bit vector.
10420     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10421   }
10422
10423   if (OpVT == MVT::v1i64 &&
10424       Op.getOperand(0).getValueType() == MVT::i64)
10425     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10426
10427   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10428   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10429   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10430                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10431 }
10432
10433 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10434 // a simple subregister reference or explicit instructions to grab
10435 // upper bits of a vector.
10436 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10437                                       SelectionDAG &DAG) {
10438   SDLoc dl(Op);
10439   SDValue In =  Op.getOperand(0);
10440   SDValue Idx = Op.getOperand(1);
10441   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10442   MVT ResVT   = Op.getSimpleValueType();
10443   MVT InVT    = In.getSimpleValueType();
10444
10445   if (Subtarget->hasFp256()) {
10446     if (ResVT.is128BitVector() &&
10447         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10448         isa<ConstantSDNode>(Idx)) {
10449       return Extract128BitVector(In, IdxVal, DAG, dl);
10450     }
10451     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10452         isa<ConstantSDNode>(Idx)) {
10453       return Extract256BitVector(In, IdxVal, DAG, dl);
10454     }
10455   }
10456   return SDValue();
10457 }
10458
10459 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10460 // simple superregister reference or explicit instructions to insert
10461 // the upper bits of a vector.
10462 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10463                                      SelectionDAG &DAG) {
10464   if (Subtarget->hasFp256()) {
10465     SDLoc dl(Op.getNode());
10466     SDValue Vec = Op.getNode()->getOperand(0);
10467     SDValue SubVec = Op.getNode()->getOperand(1);
10468     SDValue Idx = Op.getNode()->getOperand(2);
10469
10470     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10471          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10472         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10473         isa<ConstantSDNode>(Idx)) {
10474       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10475       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10476     }
10477
10478     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10479         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10480         isa<ConstantSDNode>(Idx)) {
10481       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10482       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10483     }
10484   }
10485   return SDValue();
10486 }
10487
10488 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10489 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10490 // one of the above mentioned nodes. It has to be wrapped because otherwise
10491 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10492 // be used to form addressing mode. These wrapped nodes will be selected
10493 // into MOV32ri.
10494 SDValue
10495 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10496   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10497
10498   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10499   // global base reg.
10500   unsigned char OpFlag = 0;
10501   unsigned WrapperKind = X86ISD::Wrapper;
10502   CodeModel::Model M = DAG.getTarget().getCodeModel();
10503
10504   if (Subtarget->isPICStyleRIPRel() &&
10505       (M == CodeModel::Small || M == CodeModel::Kernel))
10506     WrapperKind = X86ISD::WrapperRIP;
10507   else if (Subtarget->isPICStyleGOT())
10508     OpFlag = X86II::MO_GOTOFF;
10509   else if (Subtarget->isPICStyleStubPIC())
10510     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10511
10512   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10513                                              CP->getAlignment(),
10514                                              CP->getOffset(), OpFlag);
10515   SDLoc DL(CP);
10516   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10517   // With PIC, the address is actually $g + Offset.
10518   if (OpFlag) {
10519     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10520                          DAG.getNode(X86ISD::GlobalBaseReg,
10521                                      SDLoc(), getPointerTy()),
10522                          Result);
10523   }
10524
10525   return Result;
10526 }
10527
10528 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10529   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10530
10531   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10532   // global base reg.
10533   unsigned char OpFlag = 0;
10534   unsigned WrapperKind = X86ISD::Wrapper;
10535   CodeModel::Model M = DAG.getTarget().getCodeModel();
10536
10537   if (Subtarget->isPICStyleRIPRel() &&
10538       (M == CodeModel::Small || M == CodeModel::Kernel))
10539     WrapperKind = X86ISD::WrapperRIP;
10540   else if (Subtarget->isPICStyleGOT())
10541     OpFlag = X86II::MO_GOTOFF;
10542   else if (Subtarget->isPICStyleStubPIC())
10543     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10544
10545   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10546                                           OpFlag);
10547   SDLoc DL(JT);
10548   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10549
10550   // With PIC, the address is actually $g + Offset.
10551   if (OpFlag)
10552     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10553                          DAG.getNode(X86ISD::GlobalBaseReg,
10554                                      SDLoc(), getPointerTy()),
10555                          Result);
10556
10557   return Result;
10558 }
10559
10560 SDValue
10561 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10562   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10563
10564   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10565   // global base reg.
10566   unsigned char OpFlag = 0;
10567   unsigned WrapperKind = X86ISD::Wrapper;
10568   CodeModel::Model M = DAG.getTarget().getCodeModel();
10569
10570   if (Subtarget->isPICStyleRIPRel() &&
10571       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10572     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10573       OpFlag = X86II::MO_GOTPCREL;
10574     WrapperKind = X86ISD::WrapperRIP;
10575   } else if (Subtarget->isPICStyleGOT()) {
10576     OpFlag = X86II::MO_GOT;
10577   } else if (Subtarget->isPICStyleStubPIC()) {
10578     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10579   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10580     OpFlag = X86II::MO_DARWIN_NONLAZY;
10581   }
10582
10583   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10584
10585   SDLoc DL(Op);
10586   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10587
10588   // With PIC, the address is actually $g + Offset.
10589   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10590       !Subtarget->is64Bit()) {
10591     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10592                          DAG.getNode(X86ISD::GlobalBaseReg,
10593                                      SDLoc(), getPointerTy()),
10594                          Result);
10595   }
10596
10597   // For symbols that require a load from a stub to get the address, emit the
10598   // load.
10599   if (isGlobalStubReference(OpFlag))
10600     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10601                          MachinePointerInfo::getGOT(), false, false, false, 0);
10602
10603   return Result;
10604 }
10605
10606 SDValue
10607 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10608   // Create the TargetBlockAddressAddress node.
10609   unsigned char OpFlags =
10610     Subtarget->ClassifyBlockAddressReference();
10611   CodeModel::Model M = DAG.getTarget().getCodeModel();
10612   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10613   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10614   SDLoc dl(Op);
10615   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10616                                              OpFlags);
10617
10618   if (Subtarget->isPICStyleRIPRel() &&
10619       (M == CodeModel::Small || M == CodeModel::Kernel))
10620     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10621   else
10622     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10623
10624   // With PIC, the address is actually $g + Offset.
10625   if (isGlobalRelativeToPICBase(OpFlags)) {
10626     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10627                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10628                          Result);
10629   }
10630
10631   return Result;
10632 }
10633
10634 SDValue
10635 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10636                                       int64_t Offset, SelectionDAG &DAG) const {
10637   // Create the TargetGlobalAddress node, folding in the constant
10638   // offset if it is legal.
10639   unsigned char OpFlags =
10640       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10641   CodeModel::Model M = DAG.getTarget().getCodeModel();
10642   SDValue Result;
10643   if (OpFlags == X86II::MO_NO_FLAG &&
10644       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10645     // A direct static reference to a global.
10646     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10647     Offset = 0;
10648   } else {
10649     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10650   }
10651
10652   if (Subtarget->isPICStyleRIPRel() &&
10653       (M == CodeModel::Small || M == CodeModel::Kernel))
10654     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10655   else
10656     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10657
10658   // With PIC, the address is actually $g + Offset.
10659   if (isGlobalRelativeToPICBase(OpFlags)) {
10660     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10661                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10662                          Result);
10663   }
10664
10665   // For globals that require a load from a stub to get the address, emit the
10666   // load.
10667   if (isGlobalStubReference(OpFlags))
10668     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10669                          MachinePointerInfo::getGOT(), false, false, false, 0);
10670
10671   // If there was a non-zero offset that we didn't fold, create an explicit
10672   // addition for it.
10673   if (Offset != 0)
10674     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10675                          DAG.getConstant(Offset, getPointerTy()));
10676
10677   return Result;
10678 }
10679
10680 SDValue
10681 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10682   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10683   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10684   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10685 }
10686
10687 static SDValue
10688 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10689            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10690            unsigned char OperandFlags, bool LocalDynamic = false) {
10691   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10692   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10693   SDLoc dl(GA);
10694   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10695                                            GA->getValueType(0),
10696                                            GA->getOffset(),
10697                                            OperandFlags);
10698
10699   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10700                                            : X86ISD::TLSADDR;
10701
10702   if (InFlag) {
10703     SDValue Ops[] = { Chain,  TGA, *InFlag };
10704     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10705   } else {
10706     SDValue Ops[]  = { Chain, TGA };
10707     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10708   }
10709
10710   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10711   MFI->setAdjustsStack(true);
10712
10713   SDValue Flag = Chain.getValue(1);
10714   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10715 }
10716
10717 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10718 static SDValue
10719 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10720                                 const EVT PtrVT) {
10721   SDValue InFlag;
10722   SDLoc dl(GA);  // ? function entry point might be better
10723   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10724                                    DAG.getNode(X86ISD::GlobalBaseReg,
10725                                                SDLoc(), PtrVT), InFlag);
10726   InFlag = Chain.getValue(1);
10727
10728   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10729 }
10730
10731 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10732 static SDValue
10733 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10734                                 const EVT PtrVT) {
10735   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10736                     X86::RAX, X86II::MO_TLSGD);
10737 }
10738
10739 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10740                                            SelectionDAG &DAG,
10741                                            const EVT PtrVT,
10742                                            bool is64Bit) {
10743   SDLoc dl(GA);
10744
10745   // Get the start address of the TLS block for this module.
10746   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10747       .getInfo<X86MachineFunctionInfo>();
10748   MFI->incNumLocalDynamicTLSAccesses();
10749
10750   SDValue Base;
10751   if (is64Bit) {
10752     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10753                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10754   } else {
10755     SDValue InFlag;
10756     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10757         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10758     InFlag = Chain.getValue(1);
10759     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10760                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10761   }
10762
10763   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10764   // of Base.
10765
10766   // Build x@dtpoff.
10767   unsigned char OperandFlags = X86II::MO_DTPOFF;
10768   unsigned WrapperKind = X86ISD::Wrapper;
10769   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10770                                            GA->getValueType(0),
10771                                            GA->getOffset(), OperandFlags);
10772   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10773
10774   // Add x@dtpoff with the base.
10775   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10776 }
10777
10778 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10779 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10780                                    const EVT PtrVT, TLSModel::Model model,
10781                                    bool is64Bit, bool isPIC) {
10782   SDLoc dl(GA);
10783
10784   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10785   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10786                                                          is64Bit ? 257 : 256));
10787
10788   SDValue ThreadPointer =
10789       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10790                   MachinePointerInfo(Ptr), false, false, false, 0);
10791
10792   unsigned char OperandFlags = 0;
10793   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10794   // initialexec.
10795   unsigned WrapperKind = X86ISD::Wrapper;
10796   if (model == TLSModel::LocalExec) {
10797     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10798   } else if (model == TLSModel::InitialExec) {
10799     if (is64Bit) {
10800       OperandFlags = X86II::MO_GOTTPOFF;
10801       WrapperKind = X86ISD::WrapperRIP;
10802     } else {
10803       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10804     }
10805   } else {
10806     llvm_unreachable("Unexpected model");
10807   }
10808
10809   // emit "addl x@ntpoff,%eax" (local exec)
10810   // or "addl x@indntpoff,%eax" (initial exec)
10811   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10812   SDValue TGA =
10813       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10814                                  GA->getOffset(), OperandFlags);
10815   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10816
10817   if (model == TLSModel::InitialExec) {
10818     if (isPIC && !is64Bit) {
10819       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10820                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10821                            Offset);
10822     }
10823
10824     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10825                          MachinePointerInfo::getGOT(), false, false, false, 0);
10826   }
10827
10828   // The address of the thread local variable is the add of the thread
10829   // pointer with the offset of the variable.
10830   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10831 }
10832
10833 SDValue
10834 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10835
10836   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10837   const GlobalValue *GV = GA->getGlobal();
10838
10839   if (Subtarget->isTargetELF()) {
10840     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10841
10842     switch (model) {
10843       case TLSModel::GeneralDynamic:
10844         if (Subtarget->is64Bit())
10845           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10846         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10847       case TLSModel::LocalDynamic:
10848         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10849                                            Subtarget->is64Bit());
10850       case TLSModel::InitialExec:
10851       case TLSModel::LocalExec:
10852         return LowerToTLSExecModel(
10853             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10854             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10855     }
10856     llvm_unreachable("Unknown TLS model.");
10857   }
10858
10859   if (Subtarget->isTargetDarwin()) {
10860     // Darwin only has one model of TLS.  Lower to that.
10861     unsigned char OpFlag = 0;
10862     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10863                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10864
10865     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10866     // global base reg.
10867     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10868                  !Subtarget->is64Bit();
10869     if (PIC32)
10870       OpFlag = X86II::MO_TLVP_PIC_BASE;
10871     else
10872       OpFlag = X86II::MO_TLVP;
10873     SDLoc DL(Op);
10874     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10875                                                 GA->getValueType(0),
10876                                                 GA->getOffset(), OpFlag);
10877     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10878
10879     // With PIC32, the address is actually $g + Offset.
10880     if (PIC32)
10881       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10882                            DAG.getNode(X86ISD::GlobalBaseReg,
10883                                        SDLoc(), getPointerTy()),
10884                            Offset);
10885
10886     // Lowering the machine isd will make sure everything is in the right
10887     // location.
10888     SDValue Chain = DAG.getEntryNode();
10889     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10890     SDValue Args[] = { Chain, Offset };
10891     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10892
10893     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10894     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10895     MFI->setAdjustsStack(true);
10896
10897     // And our return value (tls address) is in the standard call return value
10898     // location.
10899     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10900     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10901                               Chain.getValue(1));
10902   }
10903
10904   if (Subtarget->isTargetKnownWindowsMSVC() ||
10905       Subtarget->isTargetWindowsGNU()) {
10906     // Just use the implicit TLS architecture
10907     // Need to generate someting similar to:
10908     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10909     //                                  ; from TEB
10910     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10911     //   mov     rcx, qword [rdx+rcx*8]
10912     //   mov     eax, .tls$:tlsvar
10913     //   [rax+rcx] contains the address
10914     // Windows 64bit: gs:0x58
10915     // Windows 32bit: fs:__tls_array
10916
10917     SDLoc dl(GA);
10918     SDValue Chain = DAG.getEntryNode();
10919
10920     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10921     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10922     // use its literal value of 0x2C.
10923     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10924                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10925                                                              256)
10926                                         : Type::getInt32PtrTy(*DAG.getContext(),
10927                                                               257));
10928
10929     SDValue TlsArray =
10930         Subtarget->is64Bit()
10931             ? DAG.getIntPtrConstant(0x58)
10932             : (Subtarget->isTargetWindowsGNU()
10933                    ? DAG.getIntPtrConstant(0x2C)
10934                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10935
10936     SDValue ThreadPointer =
10937         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10938                     MachinePointerInfo(Ptr), false, false, false, 0);
10939
10940     // Load the _tls_index variable
10941     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10942     if (Subtarget->is64Bit())
10943       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10944                            IDX, MachinePointerInfo(), MVT::i32,
10945                            false, false, false, 0);
10946     else
10947       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10948                         false, false, false, 0);
10949
10950     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10951                                     getPointerTy());
10952     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10953
10954     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10955     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10956                       false, false, false, 0);
10957
10958     // Get the offset of start of .tls section
10959     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10960                                              GA->getValueType(0),
10961                                              GA->getOffset(), X86II::MO_SECREL);
10962     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10963
10964     // The address of the thread local variable is the add of the thread
10965     // pointer with the offset of the variable.
10966     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10967   }
10968
10969   llvm_unreachable("TLS not implemented for this target.");
10970 }
10971
10972 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10973 /// and take a 2 x i32 value to shift plus a shift amount.
10974 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10975   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10976   MVT VT = Op.getSimpleValueType();
10977   unsigned VTBits = VT.getSizeInBits();
10978   SDLoc dl(Op);
10979   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10980   SDValue ShOpLo = Op.getOperand(0);
10981   SDValue ShOpHi = Op.getOperand(1);
10982   SDValue ShAmt  = Op.getOperand(2);
10983   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10984   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10985   // during isel.
10986   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10987                                   DAG.getConstant(VTBits - 1, MVT::i8));
10988   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10989                                      DAG.getConstant(VTBits - 1, MVT::i8))
10990                        : DAG.getConstant(0, VT);
10991
10992   SDValue Tmp2, Tmp3;
10993   if (Op.getOpcode() == ISD::SHL_PARTS) {
10994     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10995     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10996   } else {
10997     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10998     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10999   }
11000
11001   // If the shift amount is larger or equal than the width of a part we can't
11002   // rely on the results of shld/shrd. Insert a test and select the appropriate
11003   // values for large shift amounts.
11004   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11005                                 DAG.getConstant(VTBits, MVT::i8));
11006   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11007                              AndNode, DAG.getConstant(0, MVT::i8));
11008
11009   SDValue Hi, Lo;
11010   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11011   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11012   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11013
11014   if (Op.getOpcode() == ISD::SHL_PARTS) {
11015     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11016     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11017   } else {
11018     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11019     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11020   }
11021
11022   SDValue Ops[2] = { Lo, Hi };
11023   return DAG.getMergeValues(Ops, dl);
11024 }
11025
11026 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11027                                            SelectionDAG &DAG) const {
11028   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11029
11030   if (SrcVT.isVector())
11031     return SDValue();
11032
11033   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11034          "Unknown SINT_TO_FP to lower!");
11035
11036   // These are really Legal; return the operand so the caller accepts it as
11037   // Legal.
11038   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11039     return Op;
11040   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11041       Subtarget->is64Bit()) {
11042     return Op;
11043   }
11044
11045   SDLoc dl(Op);
11046   unsigned Size = SrcVT.getSizeInBits()/8;
11047   MachineFunction &MF = DAG.getMachineFunction();
11048   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11049   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11050   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11051                                StackSlot,
11052                                MachinePointerInfo::getFixedStack(SSFI),
11053                                false, false, 0);
11054   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11055 }
11056
11057 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11058                                      SDValue StackSlot,
11059                                      SelectionDAG &DAG) const {
11060   // Build the FILD
11061   SDLoc DL(Op);
11062   SDVTList Tys;
11063   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11064   if (useSSE)
11065     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11066   else
11067     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11068
11069   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11070
11071   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11072   MachineMemOperand *MMO;
11073   if (FI) {
11074     int SSFI = FI->getIndex();
11075     MMO =
11076       DAG.getMachineFunction()
11077       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11078                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11079   } else {
11080     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11081     StackSlot = StackSlot.getOperand(1);
11082   }
11083   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11084   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11085                                            X86ISD::FILD, DL,
11086                                            Tys, Ops, SrcVT, MMO);
11087
11088   if (useSSE) {
11089     Chain = Result.getValue(1);
11090     SDValue InFlag = Result.getValue(2);
11091
11092     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11093     // shouldn't be necessary except that RFP cannot be live across
11094     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11095     MachineFunction &MF = DAG.getMachineFunction();
11096     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11097     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11098     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11099     Tys = DAG.getVTList(MVT::Other);
11100     SDValue Ops[] = {
11101       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11102     };
11103     MachineMemOperand *MMO =
11104       DAG.getMachineFunction()
11105       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11106                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11107
11108     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11109                                     Ops, Op.getValueType(), MMO);
11110     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11111                          MachinePointerInfo::getFixedStack(SSFI),
11112                          false, false, false, 0);
11113   }
11114
11115   return Result;
11116 }
11117
11118 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11119 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11120                                                SelectionDAG &DAG) const {
11121   // This algorithm is not obvious. Here it is what we're trying to output:
11122   /*
11123      movq       %rax,  %xmm0
11124      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11125      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11126      #ifdef __SSE3__
11127        haddpd   %xmm0, %xmm0
11128      #else
11129        pshufd   $0x4e, %xmm0, %xmm1
11130        addpd    %xmm1, %xmm0
11131      #endif
11132   */
11133
11134   SDLoc dl(Op);
11135   LLVMContext *Context = DAG.getContext();
11136
11137   // Build some magic constants.
11138   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11139   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11140   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11141
11142   SmallVector<Constant*,2> CV1;
11143   CV1.push_back(
11144     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11145                                       APInt(64, 0x4330000000000000ULL))));
11146   CV1.push_back(
11147     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11148                                       APInt(64, 0x4530000000000000ULL))));
11149   Constant *C1 = ConstantVector::get(CV1);
11150   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11151
11152   // Load the 64-bit value into an XMM register.
11153   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11154                             Op.getOperand(0));
11155   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11156                               MachinePointerInfo::getConstantPool(),
11157                               false, false, false, 16);
11158   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11159                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11160                               CLod0);
11161
11162   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11163                               MachinePointerInfo::getConstantPool(),
11164                               false, false, false, 16);
11165   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11166   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11167   SDValue Result;
11168
11169   if (Subtarget->hasSSE3()) {
11170     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11171     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11172   } else {
11173     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11174     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11175                                            S2F, 0x4E, DAG);
11176     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11177                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11178                          Sub);
11179   }
11180
11181   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11182                      DAG.getIntPtrConstant(0));
11183 }
11184
11185 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11186 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11187                                                SelectionDAG &DAG) const {
11188   SDLoc dl(Op);
11189   // FP constant to bias correct the final result.
11190   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11191                                    MVT::f64);
11192
11193   // Load the 32-bit value into an XMM register.
11194   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11195                              Op.getOperand(0));
11196
11197   // Zero out the upper parts of the register.
11198   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11199
11200   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11201                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11202                      DAG.getIntPtrConstant(0));
11203
11204   // Or the load with the bias.
11205   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11206                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11207                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11208                                                    MVT::v2f64, Load)),
11209                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11210                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11211                                                    MVT::v2f64, Bias)));
11212   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11213                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11214                    DAG.getIntPtrConstant(0));
11215
11216   // Subtract the bias.
11217   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11218
11219   // Handle final rounding.
11220   EVT DestVT = Op.getValueType();
11221
11222   if (DestVT.bitsLT(MVT::f64))
11223     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11224                        DAG.getIntPtrConstant(0));
11225   if (DestVT.bitsGT(MVT::f64))
11226     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11227
11228   // Handle final rounding.
11229   return Sub;
11230 }
11231
11232 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11233                                                SelectionDAG &DAG) const {
11234   SDValue N0 = Op.getOperand(0);
11235   MVT SVT = N0.getSimpleValueType();
11236   SDLoc dl(Op);
11237
11238   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11239           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11240          "Custom UINT_TO_FP is not supported!");
11241
11242   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11243   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11244                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11245 }
11246
11247 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11248                                            SelectionDAG &DAG) const {
11249   SDValue N0 = Op.getOperand(0);
11250   SDLoc dl(Op);
11251
11252   if (Op.getValueType().isVector())
11253     return lowerUINT_TO_FP_vec(Op, DAG);
11254
11255   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11256   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11257   // the optimization here.
11258   if (DAG.SignBitIsZero(N0))
11259     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11260
11261   MVT SrcVT = N0.getSimpleValueType();
11262   MVT DstVT = Op.getSimpleValueType();
11263   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11264     return LowerUINT_TO_FP_i64(Op, DAG);
11265   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11266     return LowerUINT_TO_FP_i32(Op, DAG);
11267   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11268     return SDValue();
11269
11270   // Make a 64-bit buffer, and use it to build an FILD.
11271   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11272   if (SrcVT == MVT::i32) {
11273     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11274     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11275                                      getPointerTy(), StackSlot, WordOff);
11276     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11277                                   StackSlot, MachinePointerInfo(),
11278                                   false, false, 0);
11279     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11280                                   OffsetSlot, MachinePointerInfo(),
11281                                   false, false, 0);
11282     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11283     return Fild;
11284   }
11285
11286   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11287   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11288                                StackSlot, MachinePointerInfo(),
11289                                false, false, 0);
11290   // For i64 source, we need to add the appropriate power of 2 if the input
11291   // was negative.  This is the same as the optimization in
11292   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11293   // we must be careful to do the computation in x87 extended precision, not
11294   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11295   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11296   MachineMemOperand *MMO =
11297     DAG.getMachineFunction()
11298     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11299                           MachineMemOperand::MOLoad, 8, 8);
11300
11301   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11302   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11303   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11304                                          MVT::i64, MMO);
11305
11306   APInt FF(32, 0x5F800000ULL);
11307
11308   // Check whether the sign bit is set.
11309   SDValue SignSet = DAG.getSetCC(dl,
11310                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11311                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11312                                  ISD::SETLT);
11313
11314   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11315   SDValue FudgePtr = DAG.getConstantPool(
11316                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11317                                          getPointerTy());
11318
11319   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11320   SDValue Zero = DAG.getIntPtrConstant(0);
11321   SDValue Four = DAG.getIntPtrConstant(4);
11322   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11323                                Zero, Four);
11324   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11325
11326   // Load the value out, extending it from f32 to f80.
11327   // FIXME: Avoid the extend by constructing the right constant pool?
11328   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11329                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11330                                  MVT::f32, false, false, false, 4);
11331   // Extend everything to 80 bits to force it to be done on x87.
11332   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11333   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11334 }
11335
11336 std::pair<SDValue,SDValue>
11337 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11338                                     bool IsSigned, bool IsReplace) const {
11339   SDLoc DL(Op);
11340
11341   EVT DstTy = Op.getValueType();
11342
11343   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11344     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11345     DstTy = MVT::i64;
11346   }
11347
11348   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11349          DstTy.getSimpleVT() >= MVT::i16 &&
11350          "Unknown FP_TO_INT to lower!");
11351
11352   // These are really Legal.
11353   if (DstTy == MVT::i32 &&
11354       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11355     return std::make_pair(SDValue(), SDValue());
11356   if (Subtarget->is64Bit() &&
11357       DstTy == MVT::i64 &&
11358       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11359     return std::make_pair(SDValue(), SDValue());
11360
11361   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11362   // stack slot, or into the FTOL runtime function.
11363   MachineFunction &MF = DAG.getMachineFunction();
11364   unsigned MemSize = DstTy.getSizeInBits()/8;
11365   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11366   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11367
11368   unsigned Opc;
11369   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11370     Opc = X86ISD::WIN_FTOL;
11371   else
11372     switch (DstTy.getSimpleVT().SimpleTy) {
11373     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11374     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11375     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11376     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11377     }
11378
11379   SDValue Chain = DAG.getEntryNode();
11380   SDValue Value = Op.getOperand(0);
11381   EVT TheVT = Op.getOperand(0).getValueType();
11382   // FIXME This causes a redundant load/store if the SSE-class value is already
11383   // in memory, such as if it is on the callstack.
11384   if (isScalarFPTypeInSSEReg(TheVT)) {
11385     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11386     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11387                          MachinePointerInfo::getFixedStack(SSFI),
11388                          false, false, 0);
11389     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11390     SDValue Ops[] = {
11391       Chain, StackSlot, DAG.getValueType(TheVT)
11392     };
11393
11394     MachineMemOperand *MMO =
11395       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11396                               MachineMemOperand::MOLoad, MemSize, MemSize);
11397     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11398     Chain = Value.getValue(1);
11399     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11400     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11401   }
11402
11403   MachineMemOperand *MMO =
11404     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11405                             MachineMemOperand::MOStore, MemSize, MemSize);
11406
11407   if (Opc != X86ISD::WIN_FTOL) {
11408     // Build the FP_TO_INT*_IN_MEM
11409     SDValue Ops[] = { Chain, Value, StackSlot };
11410     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11411                                            Ops, DstTy, MMO);
11412     return std::make_pair(FIST, StackSlot);
11413   } else {
11414     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11415       DAG.getVTList(MVT::Other, MVT::Glue),
11416       Chain, Value);
11417     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11418       MVT::i32, ftol.getValue(1));
11419     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11420       MVT::i32, eax.getValue(2));
11421     SDValue Ops[] = { eax, edx };
11422     SDValue pair = IsReplace
11423       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11424       : DAG.getMergeValues(Ops, DL);
11425     return std::make_pair(pair, SDValue());
11426   }
11427 }
11428
11429 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11430                               const X86Subtarget *Subtarget) {
11431   MVT VT = Op->getSimpleValueType(0);
11432   SDValue In = Op->getOperand(0);
11433   MVT InVT = In.getSimpleValueType();
11434   SDLoc dl(Op);
11435
11436   // Optimize vectors in AVX mode:
11437   //
11438   //   v8i16 -> v8i32
11439   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11440   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11441   //   Concat upper and lower parts.
11442   //
11443   //   v4i32 -> v4i64
11444   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11445   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11446   //   Concat upper and lower parts.
11447   //
11448
11449   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11450       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11451       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11452     return SDValue();
11453
11454   if (Subtarget->hasInt256())
11455     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11456
11457   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11458   SDValue Undef = DAG.getUNDEF(InVT);
11459   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11460   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11461   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11462
11463   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11464                              VT.getVectorNumElements()/2);
11465
11466   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11467   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11468
11469   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11470 }
11471
11472 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11473                                         SelectionDAG &DAG) {
11474   MVT VT = Op->getSimpleValueType(0);
11475   SDValue In = Op->getOperand(0);
11476   MVT InVT = In.getSimpleValueType();
11477   SDLoc DL(Op);
11478   unsigned int NumElts = VT.getVectorNumElements();
11479   if (NumElts != 8 && NumElts != 16)
11480     return SDValue();
11481
11482   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11483     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11484
11485   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11487   // Now we have only mask extension
11488   assert(InVT.getVectorElementType() == MVT::i1);
11489   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11490   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11491   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11492   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11493   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11494                            MachinePointerInfo::getConstantPool(),
11495                            false, false, false, Alignment);
11496
11497   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11498   if (VT.is512BitVector())
11499     return Brcst;
11500   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11501 }
11502
11503 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11504                                SelectionDAG &DAG) {
11505   if (Subtarget->hasFp256()) {
11506     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11507     if (Res.getNode())
11508       return Res;
11509   }
11510
11511   return SDValue();
11512 }
11513
11514 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11515                                 SelectionDAG &DAG) {
11516   SDLoc DL(Op);
11517   MVT VT = Op.getSimpleValueType();
11518   SDValue In = Op.getOperand(0);
11519   MVT SVT = In.getSimpleValueType();
11520
11521   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11522     return LowerZERO_EXTEND_AVX512(Op, DAG);
11523
11524   if (Subtarget->hasFp256()) {
11525     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11526     if (Res.getNode())
11527       return Res;
11528   }
11529
11530   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11531          VT.getVectorNumElements() != SVT.getVectorNumElements());
11532   return SDValue();
11533 }
11534
11535 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11536   SDLoc DL(Op);
11537   MVT VT = Op.getSimpleValueType();
11538   SDValue In = Op.getOperand(0);
11539   MVT InVT = In.getSimpleValueType();
11540
11541   if (VT == MVT::i1) {
11542     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11543            "Invalid scalar TRUNCATE operation");
11544     if (InVT == MVT::i32)
11545       return SDValue();
11546     if (InVT.getSizeInBits() == 64)
11547       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11548     else if (InVT.getSizeInBits() < 32)
11549       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11550     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11551   }
11552   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11553          "Invalid TRUNCATE operation");
11554
11555   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11556     if (VT.getVectorElementType().getSizeInBits() >=8)
11557       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11558
11559     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11560     unsigned NumElts = InVT.getVectorNumElements();
11561     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11562     if (InVT.getSizeInBits() < 512) {
11563       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11564       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11565       InVT = ExtVT;
11566     }
11567     
11568     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11569     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11570     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11571     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11572     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11573                            MachinePointerInfo::getConstantPool(),
11574                            false, false, false, Alignment);
11575     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11576     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11577     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11578   }
11579
11580   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11581     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11582     if (Subtarget->hasInt256()) {
11583       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11584       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11585       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11586                                 ShufMask);
11587       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11588                          DAG.getIntPtrConstant(0));
11589     }
11590
11591     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11592                                DAG.getIntPtrConstant(0));
11593     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11594                                DAG.getIntPtrConstant(2));
11595     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11596     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11597     static const int ShufMask[] = {0, 2, 4, 6};
11598     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11599   }
11600
11601   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11602     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11603     if (Subtarget->hasInt256()) {
11604       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11605
11606       SmallVector<SDValue,32> pshufbMask;
11607       for (unsigned i = 0; i < 2; ++i) {
11608         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11609         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11610         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11611         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11612         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11613         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11614         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11615         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11616         for (unsigned j = 0; j < 8; ++j)
11617           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11618       }
11619       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11620       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11621       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11622
11623       static const int ShufMask[] = {0,  2,  -1,  -1};
11624       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11625                                 &ShufMask[0]);
11626       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11627                        DAG.getIntPtrConstant(0));
11628       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11629     }
11630
11631     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11632                                DAG.getIntPtrConstant(0));
11633
11634     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11635                                DAG.getIntPtrConstant(4));
11636
11637     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11638     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11639
11640     // The PSHUFB mask:
11641     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11642                                    -1, -1, -1, -1, -1, -1, -1, -1};
11643
11644     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11645     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11646     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11647
11648     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11649     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11650
11651     // The MOVLHPS Mask:
11652     static const int ShufMask2[] = {0, 1, 4, 5};
11653     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11654     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11655   }
11656
11657   // Handle truncation of V256 to V128 using shuffles.
11658   if (!VT.is128BitVector() || !InVT.is256BitVector())
11659     return SDValue();
11660
11661   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11662
11663   unsigned NumElems = VT.getVectorNumElements();
11664   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11665
11666   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11667   // Prepare truncation shuffle mask
11668   for (unsigned i = 0; i != NumElems; ++i)
11669     MaskVec[i] = i * 2;
11670   SDValue V = DAG.getVectorShuffle(NVT, DL,
11671                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11672                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11673   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11674                      DAG.getIntPtrConstant(0));
11675 }
11676
11677 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11678                                            SelectionDAG &DAG) const {
11679   assert(!Op.getSimpleValueType().isVector());
11680
11681   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11682     /*IsSigned=*/ true, /*IsReplace=*/ false);
11683   SDValue FIST = Vals.first, StackSlot = Vals.second;
11684   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11685   if (!FIST.getNode()) return Op;
11686
11687   if (StackSlot.getNode())
11688     // Load the result.
11689     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11690                        FIST, StackSlot, MachinePointerInfo(),
11691                        false, false, false, 0);
11692
11693   // The node is the result.
11694   return FIST;
11695 }
11696
11697 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11698                                            SelectionDAG &DAG) const {
11699   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11700     /*IsSigned=*/ false, /*IsReplace=*/ false);
11701   SDValue FIST = Vals.first, StackSlot = Vals.second;
11702   assert(FIST.getNode() && "Unexpected failure");
11703
11704   if (StackSlot.getNode())
11705     // Load the result.
11706     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11707                        FIST, StackSlot, MachinePointerInfo(),
11708                        false, false, false, 0);
11709
11710   // The node is the result.
11711   return FIST;
11712 }
11713
11714 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11715   SDLoc DL(Op);
11716   MVT VT = Op.getSimpleValueType();
11717   SDValue In = Op.getOperand(0);
11718   MVT SVT = In.getSimpleValueType();
11719
11720   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11721
11722   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11723                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11724                                  In, DAG.getUNDEF(SVT)));
11725 }
11726
11727 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11728   LLVMContext *Context = DAG.getContext();
11729   SDLoc dl(Op);
11730   MVT VT = Op.getSimpleValueType();
11731   MVT EltVT = VT;
11732   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11733   if (VT.isVector()) {
11734     EltVT = VT.getVectorElementType();
11735     NumElts = VT.getVectorNumElements();
11736   }
11737   Constant *C;
11738   if (EltVT == MVT::f64)
11739     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11740                                           APInt(64, ~(1ULL << 63))));
11741   else
11742     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11743                                           APInt(32, ~(1U << 31))));
11744   C = ConstantVector::getSplat(NumElts, C);
11745   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11746   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11747   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11748   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11749                              MachinePointerInfo::getConstantPool(),
11750                              false, false, false, Alignment);
11751   if (VT.isVector()) {
11752     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11753     return DAG.getNode(ISD::BITCAST, dl, VT,
11754                        DAG.getNode(ISD::AND, dl, ANDVT,
11755                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11756                                                Op.getOperand(0)),
11757                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11758   }
11759   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11760 }
11761
11762 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11763   LLVMContext *Context = DAG.getContext();
11764   SDLoc dl(Op);
11765   MVT VT = Op.getSimpleValueType();
11766   MVT EltVT = VT;
11767   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11768   if (VT.isVector()) {
11769     EltVT = VT.getVectorElementType();
11770     NumElts = VT.getVectorNumElements();
11771   }
11772   Constant *C;
11773   if (EltVT == MVT::f64)
11774     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11775                                           APInt(64, 1ULL << 63)));
11776   else
11777     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11778                                           APInt(32, 1U << 31)));
11779   C = ConstantVector::getSplat(NumElts, C);
11780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11781   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11782   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11783   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11784                              MachinePointerInfo::getConstantPool(),
11785                              false, false, false, Alignment);
11786   if (VT.isVector()) {
11787     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11788     return DAG.getNode(ISD::BITCAST, dl, VT,
11789                        DAG.getNode(ISD::XOR, dl, XORVT,
11790                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11791                                                Op.getOperand(0)),
11792                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11793   }
11794
11795   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11796 }
11797
11798 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11799   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11800   LLVMContext *Context = DAG.getContext();
11801   SDValue Op0 = Op.getOperand(0);
11802   SDValue Op1 = Op.getOperand(1);
11803   SDLoc dl(Op);
11804   MVT VT = Op.getSimpleValueType();
11805   MVT SrcVT = Op1.getSimpleValueType();
11806
11807   // If second operand is smaller, extend it first.
11808   if (SrcVT.bitsLT(VT)) {
11809     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11810     SrcVT = VT;
11811   }
11812   // And if it is bigger, shrink it first.
11813   if (SrcVT.bitsGT(VT)) {
11814     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11815     SrcVT = VT;
11816   }
11817
11818   // At this point the operands and the result should have the same
11819   // type, and that won't be f80 since that is not custom lowered.
11820
11821   // First get the sign bit of second operand.
11822   SmallVector<Constant*,4> CV;
11823   if (SrcVT == MVT::f64) {
11824     const fltSemantics &Sem = APFloat::IEEEdouble;
11825     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11826     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11827   } else {
11828     const fltSemantics &Sem = APFloat::IEEEsingle;
11829     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11830     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11831     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11832     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11833   }
11834   Constant *C = ConstantVector::get(CV);
11835   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11836   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11837                               MachinePointerInfo::getConstantPool(),
11838                               false, false, false, 16);
11839   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11840
11841   // Shift sign bit right or left if the two operands have different types.
11842   if (SrcVT.bitsGT(VT)) {
11843     // Op0 is MVT::f32, Op1 is MVT::f64.
11844     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11845     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11846                           DAG.getConstant(32, MVT::i32));
11847     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11848     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11849                           DAG.getIntPtrConstant(0));
11850   }
11851
11852   // Clear first operand sign bit.
11853   CV.clear();
11854   if (VT == MVT::f64) {
11855     const fltSemantics &Sem = APFloat::IEEEdouble;
11856     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11857                                                    APInt(64, ~(1ULL << 63)))));
11858     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11859   } else {
11860     const fltSemantics &Sem = APFloat::IEEEsingle;
11861     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11862                                                    APInt(32, ~(1U << 31)))));
11863     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11864     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11865     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11866   }
11867   C = ConstantVector::get(CV);
11868   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11869   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11870                               MachinePointerInfo::getConstantPool(),
11871                               false, false, false, 16);
11872   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11873
11874   // Or the value with the sign bit.
11875   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11876 }
11877
11878 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11879   SDValue N0 = Op.getOperand(0);
11880   SDLoc dl(Op);
11881   MVT VT = Op.getSimpleValueType();
11882
11883   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11884   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11885                                   DAG.getConstant(1, VT));
11886   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11887 }
11888
11889 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11890 //
11891 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11892                                       SelectionDAG &DAG) {
11893   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11894
11895   if (!Subtarget->hasSSE41())
11896     return SDValue();
11897
11898   if (!Op->hasOneUse())
11899     return SDValue();
11900
11901   SDNode *N = Op.getNode();
11902   SDLoc DL(N);
11903
11904   SmallVector<SDValue, 8> Opnds;
11905   DenseMap<SDValue, unsigned> VecInMap;
11906   SmallVector<SDValue, 8> VecIns;
11907   EVT VT = MVT::Other;
11908
11909   // Recognize a special case where a vector is casted into wide integer to
11910   // test all 0s.
11911   Opnds.push_back(N->getOperand(0));
11912   Opnds.push_back(N->getOperand(1));
11913
11914   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11915     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11916     // BFS traverse all OR'd operands.
11917     if (I->getOpcode() == ISD::OR) {
11918       Opnds.push_back(I->getOperand(0));
11919       Opnds.push_back(I->getOperand(1));
11920       // Re-evaluate the number of nodes to be traversed.
11921       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11922       continue;
11923     }
11924
11925     // Quit if a non-EXTRACT_VECTOR_ELT
11926     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11927       return SDValue();
11928
11929     // Quit if without a constant index.
11930     SDValue Idx = I->getOperand(1);
11931     if (!isa<ConstantSDNode>(Idx))
11932       return SDValue();
11933
11934     SDValue ExtractedFromVec = I->getOperand(0);
11935     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11936     if (M == VecInMap.end()) {
11937       VT = ExtractedFromVec.getValueType();
11938       // Quit if not 128/256-bit vector.
11939       if (!VT.is128BitVector() && !VT.is256BitVector())
11940         return SDValue();
11941       // Quit if not the same type.
11942       if (VecInMap.begin() != VecInMap.end() &&
11943           VT != VecInMap.begin()->first.getValueType())
11944         return SDValue();
11945       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11946       VecIns.push_back(ExtractedFromVec);
11947     }
11948     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11949   }
11950
11951   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11952          "Not extracted from 128-/256-bit vector.");
11953
11954   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11955
11956   for (DenseMap<SDValue, unsigned>::const_iterator
11957         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11958     // Quit if not all elements are used.
11959     if (I->second != FullMask)
11960       return SDValue();
11961   }
11962
11963   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11964
11965   // Cast all vectors into TestVT for PTEST.
11966   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11967     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11968
11969   // If more than one full vectors are evaluated, OR them first before PTEST.
11970   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11971     // Each iteration will OR 2 nodes and append the result until there is only
11972     // 1 node left, i.e. the final OR'd value of all vectors.
11973     SDValue LHS = VecIns[Slot];
11974     SDValue RHS = VecIns[Slot + 1];
11975     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11976   }
11977
11978   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11979                      VecIns.back(), VecIns.back());
11980 }
11981
11982 /// \brief return true if \c Op has a use that doesn't just read flags.
11983 static bool hasNonFlagsUse(SDValue Op) {
11984   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11985        ++UI) {
11986     SDNode *User = *UI;
11987     unsigned UOpNo = UI.getOperandNo();
11988     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11989       // Look pass truncate.
11990       UOpNo = User->use_begin().getOperandNo();
11991       User = *User->use_begin();
11992     }
11993
11994     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11995         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11996       return true;
11997   }
11998   return false;
11999 }
12000
12001 /// Emit nodes that will be selected as "test Op0,Op0", or something
12002 /// equivalent.
12003 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12004                                     SelectionDAG &DAG) const {
12005   if (Op.getValueType() == MVT::i1)
12006     // KORTEST instruction should be selected
12007     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12008                        DAG.getConstant(0, Op.getValueType()));
12009
12010   // CF and OF aren't always set the way we want. Determine which
12011   // of these we need.
12012   bool NeedCF = false;
12013   bool NeedOF = false;
12014   switch (X86CC) {
12015   default: break;
12016   case X86::COND_A: case X86::COND_AE:
12017   case X86::COND_B: case X86::COND_BE:
12018     NeedCF = true;
12019     break;
12020   case X86::COND_G: case X86::COND_GE:
12021   case X86::COND_L: case X86::COND_LE:
12022   case X86::COND_O: case X86::COND_NO: {
12023     // Check if we really need to set the
12024     // Overflow flag. If NoSignedWrap is present
12025     // that is not actually needed.
12026     switch (Op->getOpcode()) {
12027     case ISD::ADD:
12028     case ISD::SUB:
12029     case ISD::MUL:
12030     case ISD::SHL: {
12031       const BinaryWithFlagsSDNode *BinNode =
12032           cast<BinaryWithFlagsSDNode>(Op.getNode());
12033       if (BinNode->hasNoSignedWrap())
12034         break;
12035     }
12036     default:
12037       NeedOF = true;
12038       break;
12039     }
12040     break;
12041   }
12042   }
12043   // See if we can use the EFLAGS value from the operand instead of
12044   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12045   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12046   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12047     // Emit a CMP with 0, which is the TEST pattern.
12048     //if (Op.getValueType() == MVT::i1)
12049     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12050     //                     DAG.getConstant(0, MVT::i1));
12051     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12052                        DAG.getConstant(0, Op.getValueType()));
12053   }
12054   unsigned Opcode = 0;
12055   unsigned NumOperands = 0;
12056
12057   // Truncate operations may prevent the merge of the SETCC instruction
12058   // and the arithmetic instruction before it. Attempt to truncate the operands
12059   // of the arithmetic instruction and use a reduced bit-width instruction.
12060   bool NeedTruncation = false;
12061   SDValue ArithOp = Op;
12062   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12063     SDValue Arith = Op->getOperand(0);
12064     // Both the trunc and the arithmetic op need to have one user each.
12065     if (Arith->hasOneUse())
12066       switch (Arith.getOpcode()) {
12067         default: break;
12068         case ISD::ADD:
12069         case ISD::SUB:
12070         case ISD::AND:
12071         case ISD::OR:
12072         case ISD::XOR: {
12073           NeedTruncation = true;
12074           ArithOp = Arith;
12075         }
12076       }
12077   }
12078
12079   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12080   // which may be the result of a CAST.  We use the variable 'Op', which is the
12081   // non-casted variable when we check for possible users.
12082   switch (ArithOp.getOpcode()) {
12083   case ISD::ADD:
12084     // Due to an isel shortcoming, be conservative if this add is likely to be
12085     // selected as part of a load-modify-store instruction. When the root node
12086     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12087     // uses of other nodes in the match, such as the ADD in this case. This
12088     // leads to the ADD being left around and reselected, with the result being
12089     // two adds in the output.  Alas, even if none our users are stores, that
12090     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12091     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12092     // climbing the DAG back to the root, and it doesn't seem to be worth the
12093     // effort.
12094     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12095          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12096       if (UI->getOpcode() != ISD::CopyToReg &&
12097           UI->getOpcode() != ISD::SETCC &&
12098           UI->getOpcode() != ISD::STORE)
12099         goto default_case;
12100
12101     if (ConstantSDNode *C =
12102         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12103       // An add of one will be selected as an INC.
12104       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12105         Opcode = X86ISD::INC;
12106         NumOperands = 1;
12107         break;
12108       }
12109
12110       // An add of negative one (subtract of one) will be selected as a DEC.
12111       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12112         Opcode = X86ISD::DEC;
12113         NumOperands = 1;
12114         break;
12115       }
12116     }
12117
12118     // Otherwise use a regular EFLAGS-setting add.
12119     Opcode = X86ISD::ADD;
12120     NumOperands = 2;
12121     break;
12122   case ISD::SHL:
12123   case ISD::SRL:
12124     // If we have a constant logical shift that's only used in a comparison
12125     // against zero turn it into an equivalent AND. This allows turning it into
12126     // a TEST instruction later.
12127     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12128         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12129       EVT VT = Op.getValueType();
12130       unsigned BitWidth = VT.getSizeInBits();
12131       unsigned ShAmt = Op->getConstantOperandVal(1);
12132       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12133         break;
12134       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12135                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12136                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12137       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12138         break;
12139       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12140                                 DAG.getConstant(Mask, VT));
12141       DAG.ReplaceAllUsesWith(Op, New);
12142       Op = New;
12143     }
12144     break;
12145
12146   case ISD::AND:
12147     // If the primary and result isn't used, don't bother using X86ISD::AND,
12148     // because a TEST instruction will be better.
12149     if (!hasNonFlagsUse(Op))
12150       break;
12151     // FALL THROUGH
12152   case ISD::SUB:
12153   case ISD::OR:
12154   case ISD::XOR:
12155     // Due to the ISEL shortcoming noted above, be conservative if this op is
12156     // likely to be selected as part of a load-modify-store instruction.
12157     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12158            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12159       if (UI->getOpcode() == ISD::STORE)
12160         goto default_case;
12161
12162     // Otherwise use a regular EFLAGS-setting instruction.
12163     switch (ArithOp.getOpcode()) {
12164     default: llvm_unreachable("unexpected operator!");
12165     case ISD::SUB: Opcode = X86ISD::SUB; break;
12166     case ISD::XOR: Opcode = X86ISD::XOR; break;
12167     case ISD::AND: Opcode = X86ISD::AND; break;
12168     case ISD::OR: {
12169       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12170         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12171         if (EFLAGS.getNode())
12172           return EFLAGS;
12173       }
12174       Opcode = X86ISD::OR;
12175       break;
12176     }
12177     }
12178
12179     NumOperands = 2;
12180     break;
12181   case X86ISD::ADD:
12182   case X86ISD::SUB:
12183   case X86ISD::INC:
12184   case X86ISD::DEC:
12185   case X86ISD::OR:
12186   case X86ISD::XOR:
12187   case X86ISD::AND:
12188     return SDValue(Op.getNode(), 1);
12189   default:
12190   default_case:
12191     break;
12192   }
12193
12194   // If we found that truncation is beneficial, perform the truncation and
12195   // update 'Op'.
12196   if (NeedTruncation) {
12197     EVT VT = Op.getValueType();
12198     SDValue WideVal = Op->getOperand(0);
12199     EVT WideVT = WideVal.getValueType();
12200     unsigned ConvertedOp = 0;
12201     // Use a target machine opcode to prevent further DAGCombine
12202     // optimizations that may separate the arithmetic operations
12203     // from the setcc node.
12204     switch (WideVal.getOpcode()) {
12205       default: break;
12206       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12207       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12208       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12209       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12210       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12211     }
12212
12213     if (ConvertedOp) {
12214       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12215       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12216         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12217         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12218         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12219       }
12220     }
12221   }
12222
12223   if (Opcode == 0)
12224     // Emit a CMP with 0, which is the TEST pattern.
12225     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12226                        DAG.getConstant(0, Op.getValueType()));
12227
12228   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12229   SmallVector<SDValue, 4> Ops;
12230   for (unsigned i = 0; i != NumOperands; ++i)
12231     Ops.push_back(Op.getOperand(i));
12232
12233   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12234   DAG.ReplaceAllUsesWith(Op, New);
12235   return SDValue(New.getNode(), 1);
12236 }
12237
12238 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12239 /// equivalent.
12240 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12241                                    SDLoc dl, SelectionDAG &DAG) const {
12242   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12243     if (C->getAPIntValue() == 0)
12244       return EmitTest(Op0, X86CC, dl, DAG);
12245
12246      if (Op0.getValueType() == MVT::i1)
12247        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12248   }
12249  
12250   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12251        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12252     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12253     // This avoids subregister aliasing issues. Keep the smaller reference 
12254     // if we're optimizing for size, however, as that'll allow better folding 
12255     // of memory operations.
12256     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12257         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12258              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12259         !Subtarget->isAtom()) {
12260       unsigned ExtendOp =
12261           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12262       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12263       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12264     }
12265     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12266     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12267     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12268                               Op0, Op1);
12269     return SDValue(Sub.getNode(), 1);
12270   }
12271   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12272 }
12273
12274 /// Convert a comparison if required by the subtarget.
12275 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12276                                                  SelectionDAG &DAG) const {
12277   // If the subtarget does not support the FUCOMI instruction, floating-point
12278   // comparisons have to be converted.
12279   if (Subtarget->hasCMov() ||
12280       Cmp.getOpcode() != X86ISD::CMP ||
12281       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12282       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12283     return Cmp;
12284
12285   // The instruction selector will select an FUCOM instruction instead of
12286   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12287   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12288   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12289   SDLoc dl(Cmp);
12290   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12291   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12292   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12293                             DAG.getConstant(8, MVT::i8));
12294   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12295   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12296 }
12297
12298 static bool isAllOnes(SDValue V) {
12299   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12300   return C && C->isAllOnesValue();
12301 }
12302
12303 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12304 /// if it's possible.
12305 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12306                                      SDLoc dl, SelectionDAG &DAG) const {
12307   SDValue Op0 = And.getOperand(0);
12308   SDValue Op1 = And.getOperand(1);
12309   if (Op0.getOpcode() == ISD::TRUNCATE)
12310     Op0 = Op0.getOperand(0);
12311   if (Op1.getOpcode() == ISD::TRUNCATE)
12312     Op1 = Op1.getOperand(0);
12313
12314   SDValue LHS, RHS;
12315   if (Op1.getOpcode() == ISD::SHL)
12316     std::swap(Op0, Op1);
12317   if (Op0.getOpcode() == ISD::SHL) {
12318     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12319       if (And00C->getZExtValue() == 1) {
12320         // If we looked past a truncate, check that it's only truncating away
12321         // known zeros.
12322         unsigned BitWidth = Op0.getValueSizeInBits();
12323         unsigned AndBitWidth = And.getValueSizeInBits();
12324         if (BitWidth > AndBitWidth) {
12325           APInt Zeros, Ones;
12326           DAG.computeKnownBits(Op0, Zeros, Ones);
12327           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12328             return SDValue();
12329         }
12330         LHS = Op1;
12331         RHS = Op0.getOperand(1);
12332       }
12333   } else if (Op1.getOpcode() == ISD::Constant) {
12334     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12335     uint64_t AndRHSVal = AndRHS->getZExtValue();
12336     SDValue AndLHS = Op0;
12337
12338     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12339       LHS = AndLHS.getOperand(0);
12340       RHS = AndLHS.getOperand(1);
12341     }
12342
12343     // Use BT if the immediate can't be encoded in a TEST instruction.
12344     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12345       LHS = AndLHS;
12346       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12347     }
12348   }
12349
12350   if (LHS.getNode()) {
12351     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12352     // instruction.  Since the shift amount is in-range-or-undefined, we know
12353     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12354     // the encoding for the i16 version is larger than the i32 version.
12355     // Also promote i16 to i32 for performance / code size reason.
12356     if (LHS.getValueType() == MVT::i8 ||
12357         LHS.getValueType() == MVT::i16)
12358       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12359
12360     // If the operand types disagree, extend the shift amount to match.  Since
12361     // BT ignores high bits (like shifts) we can use anyextend.
12362     if (LHS.getValueType() != RHS.getValueType())
12363       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12364
12365     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12366     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12367     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12368                        DAG.getConstant(Cond, MVT::i8), BT);
12369   }
12370
12371   return SDValue();
12372 }
12373
12374 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12375 /// mask CMPs.
12376 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12377                               SDValue &Op1) {
12378   unsigned SSECC;
12379   bool Swap = false;
12380
12381   // SSE Condition code mapping:
12382   //  0 - EQ
12383   //  1 - LT
12384   //  2 - LE
12385   //  3 - UNORD
12386   //  4 - NEQ
12387   //  5 - NLT
12388   //  6 - NLE
12389   //  7 - ORD
12390   switch (SetCCOpcode) {
12391   default: llvm_unreachable("Unexpected SETCC condition");
12392   case ISD::SETOEQ:
12393   case ISD::SETEQ:  SSECC = 0; break;
12394   case ISD::SETOGT:
12395   case ISD::SETGT:  Swap = true; // Fallthrough
12396   case ISD::SETLT:
12397   case ISD::SETOLT: SSECC = 1; break;
12398   case ISD::SETOGE:
12399   case ISD::SETGE:  Swap = true; // Fallthrough
12400   case ISD::SETLE:
12401   case ISD::SETOLE: SSECC = 2; break;
12402   case ISD::SETUO:  SSECC = 3; break;
12403   case ISD::SETUNE:
12404   case ISD::SETNE:  SSECC = 4; break;
12405   case ISD::SETULE: Swap = true; // Fallthrough
12406   case ISD::SETUGE: SSECC = 5; break;
12407   case ISD::SETULT: Swap = true; // Fallthrough
12408   case ISD::SETUGT: SSECC = 6; break;
12409   case ISD::SETO:   SSECC = 7; break;
12410   case ISD::SETUEQ:
12411   case ISD::SETONE: SSECC = 8; break;
12412   }
12413   if (Swap)
12414     std::swap(Op0, Op1);
12415
12416   return SSECC;
12417 }
12418
12419 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12420 // ones, and then concatenate the result back.
12421 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12422   MVT VT = Op.getSimpleValueType();
12423
12424   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12425          "Unsupported value type for operation");
12426
12427   unsigned NumElems = VT.getVectorNumElements();
12428   SDLoc dl(Op);
12429   SDValue CC = Op.getOperand(2);
12430
12431   // Extract the LHS vectors
12432   SDValue LHS = Op.getOperand(0);
12433   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12434   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12435
12436   // Extract the RHS vectors
12437   SDValue RHS = Op.getOperand(1);
12438   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12439   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12440
12441   // Issue the operation on the smaller types and concatenate the result back
12442   MVT EltVT = VT.getVectorElementType();
12443   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12444   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12445                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12446                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12447 }
12448
12449 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12450                                      const X86Subtarget *Subtarget) {
12451   SDValue Op0 = Op.getOperand(0);
12452   SDValue Op1 = Op.getOperand(1);
12453   SDValue CC = Op.getOperand(2);
12454   MVT VT = Op.getSimpleValueType();
12455   SDLoc dl(Op);
12456
12457   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12458          Op.getValueType().getScalarType() == MVT::i1 &&
12459          "Cannot set masked compare for this operation");
12460
12461   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12462   unsigned  Opc = 0;
12463   bool Unsigned = false;
12464   bool Swap = false;
12465   unsigned SSECC;
12466   switch (SetCCOpcode) {
12467   default: llvm_unreachable("Unexpected SETCC condition");
12468   case ISD::SETNE:  SSECC = 4; break;
12469   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12470   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12471   case ISD::SETLT:  Swap = true; //fall-through
12472   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12473   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12474   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12475   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12476   case ISD::SETULE: Unsigned = true; //fall-through
12477   case ISD::SETLE:  SSECC = 2; break;
12478   }
12479
12480   if (Swap)
12481     std::swap(Op0, Op1);
12482   if (Opc)
12483     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12484   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12485   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12486                      DAG.getConstant(SSECC, MVT::i8));
12487 }
12488
12489 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12490 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12491 /// return an empty value.
12492 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12493 {
12494   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12495   if (!BV)
12496     return SDValue();
12497
12498   MVT VT = Op1.getSimpleValueType();
12499   MVT EVT = VT.getVectorElementType();
12500   unsigned n = VT.getVectorNumElements();
12501   SmallVector<SDValue, 8> ULTOp1;
12502
12503   for (unsigned i = 0; i < n; ++i) {
12504     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12505     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12506       return SDValue();
12507
12508     // Avoid underflow.
12509     APInt Val = Elt->getAPIntValue();
12510     if (Val == 0)
12511       return SDValue();
12512
12513     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12514   }
12515
12516   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12517 }
12518
12519 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12520                            SelectionDAG &DAG) {
12521   SDValue Op0 = Op.getOperand(0);
12522   SDValue Op1 = Op.getOperand(1);
12523   SDValue CC = Op.getOperand(2);
12524   MVT VT = Op.getSimpleValueType();
12525   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12526   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12527   SDLoc dl(Op);
12528
12529   if (isFP) {
12530 #ifndef NDEBUG
12531     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12532     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12533 #endif
12534
12535     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12536     unsigned Opc = X86ISD::CMPP;
12537     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12538       assert(VT.getVectorNumElements() <= 16);
12539       Opc = X86ISD::CMPM;
12540     }
12541     // In the two special cases we can't handle, emit two comparisons.
12542     if (SSECC == 8) {
12543       unsigned CC0, CC1;
12544       unsigned CombineOpc;
12545       if (SetCCOpcode == ISD::SETUEQ) {
12546         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12547       } else {
12548         assert(SetCCOpcode == ISD::SETONE);
12549         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12550       }
12551
12552       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12553                                  DAG.getConstant(CC0, MVT::i8));
12554       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12555                                  DAG.getConstant(CC1, MVT::i8));
12556       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12557     }
12558     // Handle all other FP comparisons here.
12559     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12560                        DAG.getConstant(SSECC, MVT::i8));
12561   }
12562
12563   // Break 256-bit integer vector compare into smaller ones.
12564   if (VT.is256BitVector() && !Subtarget->hasInt256())
12565     return Lower256IntVSETCC(Op, DAG);
12566
12567   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12568   EVT OpVT = Op1.getValueType();
12569   if (Subtarget->hasAVX512()) {
12570     if (Op1.getValueType().is512BitVector() ||
12571         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12572       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12573
12574     // In AVX-512 architecture setcc returns mask with i1 elements,
12575     // But there is no compare instruction for i8 and i16 elements.
12576     // We are not talking about 512-bit operands in this case, these
12577     // types are illegal.
12578     if (MaskResult &&
12579         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12580          OpVT.getVectorElementType().getSizeInBits() >= 8))
12581       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12582                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12583   }
12584
12585   // We are handling one of the integer comparisons here.  Since SSE only has
12586   // GT and EQ comparisons for integer, swapping operands and multiple
12587   // operations may be required for some comparisons.
12588   unsigned Opc;
12589   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12590   bool Subus = false;
12591
12592   switch (SetCCOpcode) {
12593   default: llvm_unreachable("Unexpected SETCC condition");
12594   case ISD::SETNE:  Invert = true;
12595   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12596   case ISD::SETLT:  Swap = true;
12597   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12598   case ISD::SETGE:  Swap = true;
12599   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12600                     Invert = true; break;
12601   case ISD::SETULT: Swap = true;
12602   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12603                     FlipSigns = true; break;
12604   case ISD::SETUGE: Swap = true;
12605   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12606                     FlipSigns = true; Invert = true; break;
12607   }
12608
12609   // Special case: Use min/max operations for SETULE/SETUGE
12610   MVT VET = VT.getVectorElementType();
12611   bool hasMinMax =
12612        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12613     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12614
12615   if (hasMinMax) {
12616     switch (SetCCOpcode) {
12617     default: break;
12618     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12619     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12620     }
12621
12622     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12623   }
12624
12625   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12626   if (!MinMax && hasSubus) {
12627     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12628     // Op0 u<= Op1:
12629     //   t = psubus Op0, Op1
12630     //   pcmpeq t, <0..0>
12631     switch (SetCCOpcode) {
12632     default: break;
12633     case ISD::SETULT: {
12634       // If the comparison is against a constant we can turn this into a
12635       // setule.  With psubus, setule does not require a swap.  This is
12636       // beneficial because the constant in the register is no longer
12637       // destructed as the destination so it can be hoisted out of a loop.
12638       // Only do this pre-AVX since vpcmp* is no longer destructive.
12639       if (Subtarget->hasAVX())
12640         break;
12641       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12642       if (ULEOp1.getNode()) {
12643         Op1 = ULEOp1;
12644         Subus = true; Invert = false; Swap = false;
12645       }
12646       break;
12647     }
12648     // Psubus is better than flip-sign because it requires no inversion.
12649     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12650     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12651     }
12652
12653     if (Subus) {
12654       Opc = X86ISD::SUBUS;
12655       FlipSigns = false;
12656     }
12657   }
12658
12659   if (Swap)
12660     std::swap(Op0, Op1);
12661
12662   // Check that the operation in question is available (most are plain SSE2,
12663   // but PCMPGTQ and PCMPEQQ have different requirements).
12664   if (VT == MVT::v2i64) {
12665     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12666       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12667
12668       // First cast everything to the right type.
12669       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12670       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12671
12672       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12673       // bits of the inputs before performing those operations. The lower
12674       // compare is always unsigned.
12675       SDValue SB;
12676       if (FlipSigns) {
12677         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12678       } else {
12679         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12680         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12681         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12682                          Sign, Zero, Sign, Zero);
12683       }
12684       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12685       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12686
12687       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12688       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12689       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12690
12691       // Create masks for only the low parts/high parts of the 64 bit integers.
12692       static const int MaskHi[] = { 1, 1, 3, 3 };
12693       static const int MaskLo[] = { 0, 0, 2, 2 };
12694       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12695       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12696       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12697
12698       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12699       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12700
12701       if (Invert)
12702         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12703
12704       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12705     }
12706
12707     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12708       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12709       // pcmpeqd + pshufd + pand.
12710       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12711
12712       // First cast everything to the right type.
12713       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12714       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12715
12716       // Do the compare.
12717       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12718
12719       // Make sure the lower and upper halves are both all-ones.
12720       static const int Mask[] = { 1, 0, 3, 2 };
12721       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12722       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12723
12724       if (Invert)
12725         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12726
12727       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12728     }
12729   }
12730
12731   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12732   // bits of the inputs before performing those operations.
12733   if (FlipSigns) {
12734     EVT EltVT = VT.getVectorElementType();
12735     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12736     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12737     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12738   }
12739
12740   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12741
12742   // If the logical-not of the result is required, perform that now.
12743   if (Invert)
12744     Result = DAG.getNOT(dl, Result, VT);
12745
12746   if (MinMax)
12747     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12748
12749   if (Subus)
12750     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12751                          getZeroVector(VT, Subtarget, DAG, dl));
12752
12753   return Result;
12754 }
12755
12756 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12757
12758   MVT VT = Op.getSimpleValueType();
12759
12760   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12761
12762   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12763          && "SetCC type must be 8-bit or 1-bit integer");
12764   SDValue Op0 = Op.getOperand(0);
12765   SDValue Op1 = Op.getOperand(1);
12766   SDLoc dl(Op);
12767   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12768
12769   // Optimize to BT if possible.
12770   // Lower (X & (1 << N)) == 0 to BT(X, N).
12771   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12772   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12773   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12774       Op1.getOpcode() == ISD::Constant &&
12775       cast<ConstantSDNode>(Op1)->isNullValue() &&
12776       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12777     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12778     if (NewSetCC.getNode())
12779       return NewSetCC;
12780   }
12781
12782   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12783   // these.
12784   if (Op1.getOpcode() == ISD::Constant &&
12785       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12786        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12787       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12788
12789     // If the input is a setcc, then reuse the input setcc or use a new one with
12790     // the inverted condition.
12791     if (Op0.getOpcode() == X86ISD::SETCC) {
12792       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12793       bool Invert = (CC == ISD::SETNE) ^
12794         cast<ConstantSDNode>(Op1)->isNullValue();
12795       if (!Invert)
12796         return Op0;
12797
12798       CCode = X86::GetOppositeBranchCondition(CCode);
12799       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12800                                   DAG.getConstant(CCode, MVT::i8),
12801                                   Op0.getOperand(1));
12802       if (VT == MVT::i1)
12803         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12804       return SetCC;
12805     }
12806   }
12807   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12808       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12809       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12810
12811     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12812     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12813   }
12814
12815   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12816   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12817   if (X86CC == X86::COND_INVALID)
12818     return SDValue();
12819
12820   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12821   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12822   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12823                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12824   if (VT == MVT::i1)
12825     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12826   return SetCC;
12827 }
12828
12829 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12830 static bool isX86LogicalCmp(SDValue Op) {
12831   unsigned Opc = Op.getNode()->getOpcode();
12832   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12833       Opc == X86ISD::SAHF)
12834     return true;
12835   if (Op.getResNo() == 1 &&
12836       (Opc == X86ISD::ADD ||
12837        Opc == X86ISD::SUB ||
12838        Opc == X86ISD::ADC ||
12839        Opc == X86ISD::SBB ||
12840        Opc == X86ISD::SMUL ||
12841        Opc == X86ISD::UMUL ||
12842        Opc == X86ISD::INC ||
12843        Opc == X86ISD::DEC ||
12844        Opc == X86ISD::OR ||
12845        Opc == X86ISD::XOR ||
12846        Opc == X86ISD::AND))
12847     return true;
12848
12849   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12850     return true;
12851
12852   return false;
12853 }
12854
12855 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12856   if (V.getOpcode() != ISD::TRUNCATE)
12857     return false;
12858
12859   SDValue VOp0 = V.getOperand(0);
12860   unsigned InBits = VOp0.getValueSizeInBits();
12861   unsigned Bits = V.getValueSizeInBits();
12862   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12863 }
12864
12865 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12866   bool addTest = true;
12867   SDValue Cond  = Op.getOperand(0);
12868   SDValue Op1 = Op.getOperand(1);
12869   SDValue Op2 = Op.getOperand(2);
12870   SDLoc DL(Op);
12871   EVT VT = Op1.getValueType();
12872   SDValue CC;
12873
12874   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12875   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12876   // sequence later on.
12877   if (Cond.getOpcode() == ISD::SETCC &&
12878       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12879        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12880       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12881     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12882     int SSECC = translateX86FSETCC(
12883         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12884
12885     if (SSECC != 8) {
12886       if (Subtarget->hasAVX512()) {
12887         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12888                                   DAG.getConstant(SSECC, MVT::i8));
12889         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12890       }
12891       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12892                                 DAG.getConstant(SSECC, MVT::i8));
12893       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12894       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12895       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12896     }
12897   }
12898
12899   if (Cond.getOpcode() == ISD::SETCC) {
12900     SDValue NewCond = LowerSETCC(Cond, DAG);
12901     if (NewCond.getNode())
12902       Cond = NewCond;
12903   }
12904
12905   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12906   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12907   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12908   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12909   if (Cond.getOpcode() == X86ISD::SETCC &&
12910       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12911       isZero(Cond.getOperand(1).getOperand(1))) {
12912     SDValue Cmp = Cond.getOperand(1);
12913
12914     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12915
12916     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12917         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12918       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12919
12920       SDValue CmpOp0 = Cmp.getOperand(0);
12921       // Apply further optimizations for special cases
12922       // (select (x != 0), -1, 0) -> neg & sbb
12923       // (select (x == 0), 0, -1) -> neg & sbb
12924       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12925         if (YC->isNullValue() &&
12926             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12927           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12928           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12929                                     DAG.getConstant(0, CmpOp0.getValueType()),
12930                                     CmpOp0);
12931           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12932                                     DAG.getConstant(X86::COND_B, MVT::i8),
12933                                     SDValue(Neg.getNode(), 1));
12934           return Res;
12935         }
12936
12937       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12938                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12939       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12940
12941       SDValue Res =   // Res = 0 or -1.
12942         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12943                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12944
12945       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12946         Res = DAG.getNOT(DL, Res, Res.getValueType());
12947
12948       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12949       if (!N2C || !N2C->isNullValue())
12950         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12951       return Res;
12952     }
12953   }
12954
12955   // Look past (and (setcc_carry (cmp ...)), 1).
12956   if (Cond.getOpcode() == ISD::AND &&
12957       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12958     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12959     if (C && C->getAPIntValue() == 1)
12960       Cond = Cond.getOperand(0);
12961   }
12962
12963   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12964   // setting operand in place of the X86ISD::SETCC.
12965   unsigned CondOpcode = Cond.getOpcode();
12966   if (CondOpcode == X86ISD::SETCC ||
12967       CondOpcode == X86ISD::SETCC_CARRY) {
12968     CC = Cond.getOperand(0);
12969
12970     SDValue Cmp = Cond.getOperand(1);
12971     unsigned Opc = Cmp.getOpcode();
12972     MVT VT = Op.getSimpleValueType();
12973
12974     bool IllegalFPCMov = false;
12975     if (VT.isFloatingPoint() && !VT.isVector() &&
12976         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12977       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12978
12979     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12980         Opc == X86ISD::BT) { // FIXME
12981       Cond = Cmp;
12982       addTest = false;
12983     }
12984   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12985              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12986              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12987               Cond.getOperand(0).getValueType() != MVT::i8)) {
12988     SDValue LHS = Cond.getOperand(0);
12989     SDValue RHS = Cond.getOperand(1);
12990     unsigned X86Opcode;
12991     unsigned X86Cond;
12992     SDVTList VTs;
12993     switch (CondOpcode) {
12994     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12995     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12996     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12997     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12998     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12999     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13000     default: llvm_unreachable("unexpected overflowing operator");
13001     }
13002     if (CondOpcode == ISD::UMULO)
13003       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13004                           MVT::i32);
13005     else
13006       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13007
13008     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13009
13010     if (CondOpcode == ISD::UMULO)
13011       Cond = X86Op.getValue(2);
13012     else
13013       Cond = X86Op.getValue(1);
13014
13015     CC = DAG.getConstant(X86Cond, MVT::i8);
13016     addTest = false;
13017   }
13018
13019   if (addTest) {
13020     // Look pass the truncate if the high bits are known zero.
13021     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13022         Cond = Cond.getOperand(0);
13023
13024     // We know the result of AND is compared against zero. Try to match
13025     // it to BT.
13026     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13027       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13028       if (NewSetCC.getNode()) {
13029         CC = NewSetCC.getOperand(0);
13030         Cond = NewSetCC.getOperand(1);
13031         addTest = false;
13032       }
13033     }
13034   }
13035
13036   if (addTest) {
13037     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13038     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13039   }
13040
13041   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13042   // a <  b ?  0 : -1 -> RES = setcc_carry
13043   // a >= b ? -1 :  0 -> RES = setcc_carry
13044   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13045   if (Cond.getOpcode() == X86ISD::SUB) {
13046     Cond = ConvertCmpIfNecessary(Cond, DAG);
13047     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13048
13049     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13050         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13051       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13052                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13053       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13054         return DAG.getNOT(DL, Res, Res.getValueType());
13055       return Res;
13056     }
13057   }
13058
13059   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13060   // widen the cmov and push the truncate through. This avoids introducing a new
13061   // branch during isel and doesn't add any extensions.
13062   if (Op.getValueType() == MVT::i8 &&
13063       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13064     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13065     if (T1.getValueType() == T2.getValueType() &&
13066         // Blacklist CopyFromReg to avoid partial register stalls.
13067         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13068       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13069       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13070       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13071     }
13072   }
13073
13074   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13075   // condition is true.
13076   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13077   SDValue Ops[] = { Op2, Op1, CC, Cond };
13078   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13079 }
13080
13081 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13082   MVT VT = Op->getSimpleValueType(0);
13083   SDValue In = Op->getOperand(0);
13084   MVT InVT = In.getSimpleValueType();
13085   SDLoc dl(Op);
13086
13087   unsigned int NumElts = VT.getVectorNumElements();
13088   if (NumElts != 8 && NumElts != 16)
13089     return SDValue();
13090
13091   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13092     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13093
13094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13095   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13096
13097   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13098   Constant *C = ConstantInt::get(*DAG.getContext(),
13099     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13100
13101   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13102   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13103   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13104                           MachinePointerInfo::getConstantPool(),
13105                           false, false, false, Alignment);
13106   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13107   if (VT.is512BitVector())
13108     return Brcst;
13109   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13110 }
13111
13112 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13113                                 SelectionDAG &DAG) {
13114   MVT VT = Op->getSimpleValueType(0);
13115   SDValue In = Op->getOperand(0);
13116   MVT InVT = In.getSimpleValueType();
13117   SDLoc dl(Op);
13118
13119   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13120     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13121
13122   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13123       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13124       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13125     return SDValue();
13126
13127   if (Subtarget->hasInt256())
13128     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13129
13130   // Optimize vectors in AVX mode
13131   // Sign extend  v8i16 to v8i32 and
13132   //              v4i32 to v4i64
13133   //
13134   // Divide input vector into two parts
13135   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13136   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13137   // concat the vectors to original VT
13138
13139   unsigned NumElems = InVT.getVectorNumElements();
13140   SDValue Undef = DAG.getUNDEF(InVT);
13141
13142   SmallVector<int,8> ShufMask1(NumElems, -1);
13143   for (unsigned i = 0; i != NumElems/2; ++i)
13144     ShufMask1[i] = i;
13145
13146   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13147
13148   SmallVector<int,8> ShufMask2(NumElems, -1);
13149   for (unsigned i = 0; i != NumElems/2; ++i)
13150     ShufMask2[i] = i + NumElems/2;
13151
13152   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13153
13154   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13155                                 VT.getVectorNumElements()/2);
13156
13157   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13158   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13159
13160   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13161 }
13162
13163 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13164 // may emit an illegal shuffle but the expansion is still better than scalar
13165 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13166 // we'll emit a shuffle and a arithmetic shift.
13167 // TODO: It is possible to support ZExt by zeroing the undef values during
13168 // the shuffle phase or after the shuffle.
13169 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13170                                  SelectionDAG &DAG) {
13171   MVT RegVT = Op.getSimpleValueType();
13172   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13173   assert(RegVT.isInteger() &&
13174          "We only custom lower integer vector sext loads.");
13175
13176   // Nothing useful we can do without SSE2 shuffles.
13177   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13178
13179   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13180   SDLoc dl(Ld);
13181   EVT MemVT = Ld->getMemoryVT();
13182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13183   unsigned RegSz = RegVT.getSizeInBits();
13184
13185   ISD::LoadExtType Ext = Ld->getExtensionType();
13186
13187   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13188          && "Only anyext and sext are currently implemented.");
13189   assert(MemVT != RegVT && "Cannot extend to the same type");
13190   assert(MemVT.isVector() && "Must load a vector from memory");
13191
13192   unsigned NumElems = RegVT.getVectorNumElements();
13193   unsigned MemSz = MemVT.getSizeInBits();
13194   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13195
13196   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13197     // The only way in which we have a legal 256-bit vector result but not the
13198     // integer 256-bit operations needed to directly lower a sextload is if we
13199     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13200     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13201     // correctly legalized. We do this late to allow the canonical form of
13202     // sextload to persist throughout the rest of the DAG combiner -- it wants
13203     // to fold together any extensions it can, and so will fuse a sign_extend
13204     // of an sextload into an sextload targeting a wider value.
13205     SDValue Load;
13206     if (MemSz == 128) {
13207       // Just switch this to a normal load.
13208       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13209                                        "it must be a legal 128-bit vector "
13210                                        "type!");
13211       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13212                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13213                   Ld->isInvariant(), Ld->getAlignment());
13214     } else {
13215       assert(MemSz < 128 &&
13216              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13217       // Do an sext load to a 128-bit vector type. We want to use the same
13218       // number of elements, but elements half as wide. This will end up being
13219       // recursively lowered by this routine, but will succeed as we definitely
13220       // have all the necessary features if we're using AVX1.
13221       EVT HalfEltVT =
13222           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13223       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13224       Load =
13225           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13226                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13227                          Ld->isNonTemporal(), Ld->isInvariant(),
13228                          Ld->getAlignment());
13229     }
13230
13231     // Replace chain users with the new chain.
13232     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13233     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13234
13235     // Finally, do a normal sign-extend to the desired register.
13236     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13237   }
13238
13239   // All sizes must be a power of two.
13240   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13241          "Non-power-of-two elements are not custom lowered!");
13242
13243   // Attempt to load the original value using scalar loads.
13244   // Find the largest scalar type that divides the total loaded size.
13245   MVT SclrLoadTy = MVT::i8;
13246   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13247        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13248     MVT Tp = (MVT::SimpleValueType)tp;
13249     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13250       SclrLoadTy = Tp;
13251     }
13252   }
13253
13254   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13255   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13256       (64 <= MemSz))
13257     SclrLoadTy = MVT::f64;
13258
13259   // Calculate the number of scalar loads that we need to perform
13260   // in order to load our vector from memory.
13261   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13262
13263   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13264          "Can only lower sext loads with a single scalar load!");
13265
13266   unsigned loadRegZize = RegSz;
13267   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13268     loadRegZize /= 2;
13269
13270   // Represent our vector as a sequence of elements which are the
13271   // largest scalar that we can load.
13272   EVT LoadUnitVecVT = EVT::getVectorVT(
13273       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13274
13275   // Represent the data using the same element type that is stored in
13276   // memory. In practice, we ''widen'' MemVT.
13277   EVT WideVecVT =
13278       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13279                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13280
13281   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13282          "Invalid vector type");
13283
13284   // We can't shuffle using an illegal type.
13285   assert(TLI.isTypeLegal(WideVecVT) &&
13286          "We only lower types that form legal widened vector types");
13287
13288   SmallVector<SDValue, 8> Chains;
13289   SDValue Ptr = Ld->getBasePtr();
13290   SDValue Increment =
13291       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13292   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13293
13294   for (unsigned i = 0; i < NumLoads; ++i) {
13295     // Perform a single load.
13296     SDValue ScalarLoad =
13297         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13298                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13299                     Ld->getAlignment());
13300     Chains.push_back(ScalarLoad.getValue(1));
13301     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13302     // another round of DAGCombining.
13303     if (i == 0)
13304       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13305     else
13306       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13307                         ScalarLoad, DAG.getIntPtrConstant(i));
13308
13309     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13310   }
13311
13312   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13313
13314   // Bitcast the loaded value to a vector of the original element type, in
13315   // the size of the target vector type.
13316   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13317   unsigned SizeRatio = RegSz / MemSz;
13318
13319   if (Ext == ISD::SEXTLOAD) {
13320     // If we have SSE4.1 we can directly emit a VSEXT node.
13321     if (Subtarget->hasSSE41()) {
13322       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13323       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13324       return Sext;
13325     }
13326
13327     // Otherwise we'll shuffle the small elements in the high bits of the
13328     // larger type and perform an arithmetic shift. If the shift is not legal
13329     // it's better to scalarize.
13330     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13331            "We can't implement an sext load without a arithmetic right shift!");
13332
13333     // Redistribute the loaded elements into the different locations.
13334     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13335     for (unsigned i = 0; i != NumElems; ++i)
13336       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13337
13338     SDValue Shuff = DAG.getVectorShuffle(
13339         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13340
13341     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13342
13343     // Build the arithmetic shift.
13344     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13345                    MemVT.getVectorElementType().getSizeInBits();
13346     Shuff =
13347         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13348
13349     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13350     return Shuff;
13351   }
13352
13353   // Redistribute the loaded elements into the different locations.
13354   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13355   for (unsigned i = 0; i != NumElems; ++i)
13356     ShuffleVec[i * SizeRatio] = i;
13357
13358   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13359                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13360
13361   // Bitcast to the requested type.
13362   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13363   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13364   return Shuff;
13365 }
13366
13367 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13368 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13369 // from the AND / OR.
13370 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13371   Opc = Op.getOpcode();
13372   if (Opc != ISD::OR && Opc != ISD::AND)
13373     return false;
13374   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13375           Op.getOperand(0).hasOneUse() &&
13376           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13377           Op.getOperand(1).hasOneUse());
13378 }
13379
13380 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13381 // 1 and that the SETCC node has a single use.
13382 static bool isXor1OfSetCC(SDValue Op) {
13383   if (Op.getOpcode() != ISD::XOR)
13384     return false;
13385   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13386   if (N1C && N1C->getAPIntValue() == 1) {
13387     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13388       Op.getOperand(0).hasOneUse();
13389   }
13390   return false;
13391 }
13392
13393 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13394   bool addTest = true;
13395   SDValue Chain = Op.getOperand(0);
13396   SDValue Cond  = Op.getOperand(1);
13397   SDValue Dest  = Op.getOperand(2);
13398   SDLoc dl(Op);
13399   SDValue CC;
13400   bool Inverted = false;
13401
13402   if (Cond.getOpcode() == ISD::SETCC) {
13403     // Check for setcc([su]{add,sub,mul}o == 0).
13404     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13405         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13406         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13407         Cond.getOperand(0).getResNo() == 1 &&
13408         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13409          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13410          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13411          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13412          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13413          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13414       Inverted = true;
13415       Cond = Cond.getOperand(0);
13416     } else {
13417       SDValue NewCond = LowerSETCC(Cond, DAG);
13418       if (NewCond.getNode())
13419         Cond = NewCond;
13420     }
13421   }
13422 #if 0
13423   // FIXME: LowerXALUO doesn't handle these!!
13424   else if (Cond.getOpcode() == X86ISD::ADD  ||
13425            Cond.getOpcode() == X86ISD::SUB  ||
13426            Cond.getOpcode() == X86ISD::SMUL ||
13427            Cond.getOpcode() == X86ISD::UMUL)
13428     Cond = LowerXALUO(Cond, DAG);
13429 #endif
13430
13431   // Look pass (and (setcc_carry (cmp ...)), 1).
13432   if (Cond.getOpcode() == ISD::AND &&
13433       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13434     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13435     if (C && C->getAPIntValue() == 1)
13436       Cond = Cond.getOperand(0);
13437   }
13438
13439   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13440   // setting operand in place of the X86ISD::SETCC.
13441   unsigned CondOpcode = Cond.getOpcode();
13442   if (CondOpcode == X86ISD::SETCC ||
13443       CondOpcode == X86ISD::SETCC_CARRY) {
13444     CC = Cond.getOperand(0);
13445
13446     SDValue Cmp = Cond.getOperand(1);
13447     unsigned Opc = Cmp.getOpcode();
13448     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13449     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13450       Cond = Cmp;
13451       addTest = false;
13452     } else {
13453       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13454       default: break;
13455       case X86::COND_O:
13456       case X86::COND_B:
13457         // These can only come from an arithmetic instruction with overflow,
13458         // e.g. SADDO, UADDO.
13459         Cond = Cond.getNode()->getOperand(1);
13460         addTest = false;
13461         break;
13462       }
13463     }
13464   }
13465   CondOpcode = Cond.getOpcode();
13466   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13467       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13468       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13469        Cond.getOperand(0).getValueType() != MVT::i8)) {
13470     SDValue LHS = Cond.getOperand(0);
13471     SDValue RHS = Cond.getOperand(1);
13472     unsigned X86Opcode;
13473     unsigned X86Cond;
13474     SDVTList VTs;
13475     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13476     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13477     // X86ISD::INC).
13478     switch (CondOpcode) {
13479     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13480     case ISD::SADDO:
13481       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13482         if (C->isOne()) {
13483           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13484           break;
13485         }
13486       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13487     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13488     case ISD::SSUBO:
13489       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13490         if (C->isOne()) {
13491           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13492           break;
13493         }
13494       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13495     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13496     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13497     default: llvm_unreachable("unexpected overflowing operator");
13498     }
13499     if (Inverted)
13500       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13501     if (CondOpcode == ISD::UMULO)
13502       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13503                           MVT::i32);
13504     else
13505       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13506
13507     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13508
13509     if (CondOpcode == ISD::UMULO)
13510       Cond = X86Op.getValue(2);
13511     else
13512       Cond = X86Op.getValue(1);
13513
13514     CC = DAG.getConstant(X86Cond, MVT::i8);
13515     addTest = false;
13516   } else {
13517     unsigned CondOpc;
13518     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13519       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13520       if (CondOpc == ISD::OR) {
13521         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13522         // two branches instead of an explicit OR instruction with a
13523         // separate test.
13524         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13525             isX86LogicalCmp(Cmp)) {
13526           CC = Cond.getOperand(0).getOperand(0);
13527           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13528                               Chain, Dest, CC, Cmp);
13529           CC = Cond.getOperand(1).getOperand(0);
13530           Cond = Cmp;
13531           addTest = false;
13532         }
13533       } else { // ISD::AND
13534         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13535         // two branches instead of an explicit AND instruction with a
13536         // separate test. However, we only do this if this block doesn't
13537         // have a fall-through edge, because this requires an explicit
13538         // jmp when the condition is false.
13539         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13540             isX86LogicalCmp(Cmp) &&
13541             Op.getNode()->hasOneUse()) {
13542           X86::CondCode CCode =
13543             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13544           CCode = X86::GetOppositeBranchCondition(CCode);
13545           CC = DAG.getConstant(CCode, MVT::i8);
13546           SDNode *User = *Op.getNode()->use_begin();
13547           // Look for an unconditional branch following this conditional branch.
13548           // We need this because we need to reverse the successors in order
13549           // to implement FCMP_OEQ.
13550           if (User->getOpcode() == ISD::BR) {
13551             SDValue FalseBB = User->getOperand(1);
13552             SDNode *NewBR =
13553               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13554             assert(NewBR == User);
13555             (void)NewBR;
13556             Dest = FalseBB;
13557
13558             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13559                                 Chain, Dest, CC, Cmp);
13560             X86::CondCode CCode =
13561               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13562             CCode = X86::GetOppositeBranchCondition(CCode);
13563             CC = DAG.getConstant(CCode, MVT::i8);
13564             Cond = Cmp;
13565             addTest = false;
13566           }
13567         }
13568       }
13569     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13570       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13571       // It should be transformed during dag combiner except when the condition
13572       // is set by a arithmetics with overflow node.
13573       X86::CondCode CCode =
13574         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13575       CCode = X86::GetOppositeBranchCondition(CCode);
13576       CC = DAG.getConstant(CCode, MVT::i8);
13577       Cond = Cond.getOperand(0).getOperand(1);
13578       addTest = false;
13579     } else if (Cond.getOpcode() == ISD::SETCC &&
13580                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13581       // For FCMP_OEQ, we can emit
13582       // two branches instead of an explicit AND instruction with a
13583       // separate test. However, we only do this if this block doesn't
13584       // have a fall-through edge, because this requires an explicit
13585       // jmp when the condition is false.
13586       if (Op.getNode()->hasOneUse()) {
13587         SDNode *User = *Op.getNode()->use_begin();
13588         // Look for an unconditional branch following this conditional branch.
13589         // We need this because we need to reverse the successors in order
13590         // to implement FCMP_OEQ.
13591         if (User->getOpcode() == ISD::BR) {
13592           SDValue FalseBB = User->getOperand(1);
13593           SDNode *NewBR =
13594             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13595           assert(NewBR == User);
13596           (void)NewBR;
13597           Dest = FalseBB;
13598
13599           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13600                                     Cond.getOperand(0), Cond.getOperand(1));
13601           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13602           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13603           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13604                               Chain, Dest, CC, Cmp);
13605           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13606           Cond = Cmp;
13607           addTest = false;
13608         }
13609       }
13610     } else if (Cond.getOpcode() == ISD::SETCC &&
13611                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13612       // For FCMP_UNE, we can emit
13613       // two branches instead of an explicit AND instruction with a
13614       // separate test. However, we only do this if this block doesn't
13615       // have a fall-through edge, because this requires an explicit
13616       // jmp when the condition is false.
13617       if (Op.getNode()->hasOneUse()) {
13618         SDNode *User = *Op.getNode()->use_begin();
13619         // Look for an unconditional branch following this conditional branch.
13620         // We need this because we need to reverse the successors in order
13621         // to implement FCMP_UNE.
13622         if (User->getOpcode() == ISD::BR) {
13623           SDValue FalseBB = User->getOperand(1);
13624           SDNode *NewBR =
13625             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13626           assert(NewBR == User);
13627           (void)NewBR;
13628
13629           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13630                                     Cond.getOperand(0), Cond.getOperand(1));
13631           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13632           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13633           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13634                               Chain, Dest, CC, Cmp);
13635           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13636           Cond = Cmp;
13637           addTest = false;
13638           Dest = FalseBB;
13639         }
13640       }
13641     }
13642   }
13643
13644   if (addTest) {
13645     // Look pass the truncate if the high bits are known zero.
13646     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13647         Cond = Cond.getOperand(0);
13648
13649     // We know the result of AND is compared against zero. Try to match
13650     // it to BT.
13651     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13652       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13653       if (NewSetCC.getNode()) {
13654         CC = NewSetCC.getOperand(0);
13655         Cond = NewSetCC.getOperand(1);
13656         addTest = false;
13657       }
13658     }
13659   }
13660
13661   if (addTest) {
13662     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13663     CC = DAG.getConstant(X86Cond, MVT::i8);
13664     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13665   }
13666   Cond = ConvertCmpIfNecessary(Cond, DAG);
13667   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13668                      Chain, Dest, CC, Cond);
13669 }
13670
13671 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13672 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13673 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13674 // that the guard pages used by the OS virtual memory manager are allocated in
13675 // correct sequence.
13676 SDValue
13677 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13678                                            SelectionDAG &DAG) const {
13679   MachineFunction &MF = DAG.getMachineFunction();
13680   bool SplitStack = MF.shouldSplitStack();
13681   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13682                SplitStack;
13683   SDLoc dl(Op);
13684
13685   if (!Lower) {
13686     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13687     SDNode* Node = Op.getNode();
13688
13689     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13690     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13691         " not tell us which reg is the stack pointer!");
13692     EVT VT = Node->getValueType(0);
13693     SDValue Tmp1 = SDValue(Node, 0);
13694     SDValue Tmp2 = SDValue(Node, 1);
13695     SDValue Tmp3 = Node->getOperand(2);
13696     SDValue Chain = Tmp1.getOperand(0);
13697
13698     // Chain the dynamic stack allocation so that it doesn't modify the stack
13699     // pointer when other instructions are using the stack.
13700     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13701         SDLoc(Node));
13702
13703     SDValue Size = Tmp2.getOperand(1);
13704     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13705     Chain = SP.getValue(1);
13706     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13707     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
13708     unsigned StackAlign = TFI.getStackAlignment();
13709     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13710     if (Align > StackAlign)
13711       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13712           DAG.getConstant(-(uint64_t)Align, VT));
13713     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13714
13715     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13716         DAG.getIntPtrConstant(0, true), SDValue(),
13717         SDLoc(Node));
13718
13719     SDValue Ops[2] = { Tmp1, Tmp2 };
13720     return DAG.getMergeValues(Ops, dl);
13721   }
13722
13723   // Get the inputs.
13724   SDValue Chain = Op.getOperand(0);
13725   SDValue Size  = Op.getOperand(1);
13726   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13727   EVT VT = Op.getNode()->getValueType(0);
13728
13729   bool Is64Bit = Subtarget->is64Bit();
13730   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13731
13732   if (SplitStack) {
13733     MachineRegisterInfo &MRI = MF.getRegInfo();
13734
13735     if (Is64Bit) {
13736       // The 64 bit implementation of segmented stacks needs to clobber both r10
13737       // r11. This makes it impossible to use it along with nested parameters.
13738       const Function *F = MF.getFunction();
13739
13740       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13741            I != E; ++I)
13742         if (I->hasNestAttr())
13743           report_fatal_error("Cannot use segmented stacks with functions that "
13744                              "have nested arguments.");
13745     }
13746
13747     const TargetRegisterClass *AddrRegClass =
13748       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13749     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13750     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13751     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13752                                 DAG.getRegister(Vreg, SPTy));
13753     SDValue Ops1[2] = { Value, Chain };
13754     return DAG.getMergeValues(Ops1, dl);
13755   } else {
13756     SDValue Flag;
13757     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13758
13759     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13760     Flag = Chain.getValue(1);
13761     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13762
13763     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13764
13765     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
13766         DAG.getSubtarget().getRegisterInfo());
13767     unsigned SPReg = RegInfo->getStackRegister();
13768     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13769     Chain = SP.getValue(1);
13770
13771     if (Align) {
13772       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13773                        DAG.getConstant(-(uint64_t)Align, VT));
13774       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13775     }
13776
13777     SDValue Ops1[2] = { SP, Chain };
13778     return DAG.getMergeValues(Ops1, dl);
13779   }
13780 }
13781
13782 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13783   MachineFunction &MF = DAG.getMachineFunction();
13784   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13785
13786   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13787   SDLoc DL(Op);
13788
13789   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13790     // vastart just stores the address of the VarArgsFrameIndex slot into the
13791     // memory location argument.
13792     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13793                                    getPointerTy());
13794     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13795                         MachinePointerInfo(SV), false, false, 0);
13796   }
13797
13798   // __va_list_tag:
13799   //   gp_offset         (0 - 6 * 8)
13800   //   fp_offset         (48 - 48 + 8 * 16)
13801   //   overflow_arg_area (point to parameters coming in memory).
13802   //   reg_save_area
13803   SmallVector<SDValue, 8> MemOps;
13804   SDValue FIN = Op.getOperand(1);
13805   // Store gp_offset
13806   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13807                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13808                                                MVT::i32),
13809                                FIN, MachinePointerInfo(SV), false, false, 0);
13810   MemOps.push_back(Store);
13811
13812   // Store fp_offset
13813   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13814                     FIN, DAG.getIntPtrConstant(4));
13815   Store = DAG.getStore(Op.getOperand(0), DL,
13816                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13817                                        MVT::i32),
13818                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13819   MemOps.push_back(Store);
13820
13821   // Store ptr to overflow_arg_area
13822   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13823                     FIN, DAG.getIntPtrConstant(4));
13824   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13825                                     getPointerTy());
13826   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13827                        MachinePointerInfo(SV, 8),
13828                        false, false, 0);
13829   MemOps.push_back(Store);
13830
13831   // Store ptr to reg_save_area.
13832   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13833                     FIN, DAG.getIntPtrConstant(8));
13834   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13835                                     getPointerTy());
13836   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13837                        MachinePointerInfo(SV, 16), false, false, 0);
13838   MemOps.push_back(Store);
13839   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13840 }
13841
13842 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13843   assert(Subtarget->is64Bit() &&
13844          "LowerVAARG only handles 64-bit va_arg!");
13845   assert((Subtarget->isTargetLinux() ||
13846           Subtarget->isTargetDarwin()) &&
13847           "Unhandled target in LowerVAARG");
13848   assert(Op.getNode()->getNumOperands() == 4);
13849   SDValue Chain = Op.getOperand(0);
13850   SDValue SrcPtr = Op.getOperand(1);
13851   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13852   unsigned Align = Op.getConstantOperandVal(3);
13853   SDLoc dl(Op);
13854
13855   EVT ArgVT = Op.getNode()->getValueType(0);
13856   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13857   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13858   uint8_t ArgMode;
13859
13860   // Decide which area this value should be read from.
13861   // TODO: Implement the AMD64 ABI in its entirety. This simple
13862   // selection mechanism works only for the basic types.
13863   if (ArgVT == MVT::f80) {
13864     llvm_unreachable("va_arg for f80 not yet implemented");
13865   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13866     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13867   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13868     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13869   } else {
13870     llvm_unreachable("Unhandled argument type in LowerVAARG");
13871   }
13872
13873   if (ArgMode == 2) {
13874     // Sanity Check: Make sure using fp_offset makes sense.
13875     assert(!DAG.getTarget().Options.UseSoftFloat &&
13876            !(DAG.getMachineFunction()
13877                 .getFunction()->getAttributes()
13878                 .hasAttribute(AttributeSet::FunctionIndex,
13879                               Attribute::NoImplicitFloat)) &&
13880            Subtarget->hasSSE1());
13881   }
13882
13883   // Insert VAARG_64 node into the DAG
13884   // VAARG_64 returns two values: Variable Argument Address, Chain
13885   SmallVector<SDValue, 11> InstOps;
13886   InstOps.push_back(Chain);
13887   InstOps.push_back(SrcPtr);
13888   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13889   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13890   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13891   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13892   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13893                                           VTs, InstOps, MVT::i64,
13894                                           MachinePointerInfo(SV),
13895                                           /*Align=*/0,
13896                                           /*Volatile=*/false,
13897                                           /*ReadMem=*/true,
13898                                           /*WriteMem=*/true);
13899   Chain = VAARG.getValue(1);
13900
13901   // Load the next argument and return it
13902   return DAG.getLoad(ArgVT, dl,
13903                      Chain,
13904                      VAARG,
13905                      MachinePointerInfo(),
13906                      false, false, false, 0);
13907 }
13908
13909 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13910                            SelectionDAG &DAG) {
13911   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13912   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13913   SDValue Chain = Op.getOperand(0);
13914   SDValue DstPtr = Op.getOperand(1);
13915   SDValue SrcPtr = Op.getOperand(2);
13916   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13917   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13918   SDLoc DL(Op);
13919
13920   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13921                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13922                        false,
13923                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13924 }
13925
13926 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13927 // amount is a constant. Takes immediate version of shift as input.
13928 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13929                                           SDValue SrcOp, uint64_t ShiftAmt,
13930                                           SelectionDAG &DAG) {
13931   MVT ElementType = VT.getVectorElementType();
13932
13933   // Fold this packed shift into its first operand if ShiftAmt is 0.
13934   if (ShiftAmt == 0)
13935     return SrcOp;
13936
13937   // Check for ShiftAmt >= element width
13938   if (ShiftAmt >= ElementType.getSizeInBits()) {
13939     if (Opc == X86ISD::VSRAI)
13940       ShiftAmt = ElementType.getSizeInBits() - 1;
13941     else
13942       return DAG.getConstant(0, VT);
13943   }
13944
13945   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13946          && "Unknown target vector shift-by-constant node");
13947
13948   // Fold this packed vector shift into a build vector if SrcOp is a
13949   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13950   if (VT == SrcOp.getSimpleValueType() &&
13951       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13952     SmallVector<SDValue, 8> Elts;
13953     unsigned NumElts = SrcOp->getNumOperands();
13954     ConstantSDNode *ND;
13955
13956     switch(Opc) {
13957     default: llvm_unreachable(nullptr);
13958     case X86ISD::VSHLI:
13959       for (unsigned i=0; i!=NumElts; ++i) {
13960         SDValue CurrentOp = SrcOp->getOperand(i);
13961         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13962           Elts.push_back(CurrentOp);
13963           continue;
13964         }
13965         ND = cast<ConstantSDNode>(CurrentOp);
13966         const APInt &C = ND->getAPIntValue();
13967         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13968       }
13969       break;
13970     case X86ISD::VSRLI:
13971       for (unsigned i=0; i!=NumElts; ++i) {
13972         SDValue CurrentOp = SrcOp->getOperand(i);
13973         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13974           Elts.push_back(CurrentOp);
13975           continue;
13976         }
13977         ND = cast<ConstantSDNode>(CurrentOp);
13978         const APInt &C = ND->getAPIntValue();
13979         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13980       }
13981       break;
13982     case X86ISD::VSRAI:
13983       for (unsigned i=0; i!=NumElts; ++i) {
13984         SDValue CurrentOp = SrcOp->getOperand(i);
13985         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13986           Elts.push_back(CurrentOp);
13987           continue;
13988         }
13989         ND = cast<ConstantSDNode>(CurrentOp);
13990         const APInt &C = ND->getAPIntValue();
13991         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13992       }
13993       break;
13994     }
13995
13996     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13997   }
13998
13999   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14000 }
14001
14002 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14003 // may or may not be a constant. Takes immediate version of shift as input.
14004 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14005                                    SDValue SrcOp, SDValue ShAmt,
14006                                    SelectionDAG &DAG) {
14007   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14008
14009   // Catch shift-by-constant.
14010   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14011     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14012                                       CShAmt->getZExtValue(), DAG);
14013
14014   // Change opcode to non-immediate version
14015   switch (Opc) {
14016     default: llvm_unreachable("Unknown target vector shift node");
14017     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14018     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14019     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14020   }
14021
14022   // Need to build a vector containing shift amount
14023   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14024   SDValue ShOps[4];
14025   ShOps[0] = ShAmt;
14026   ShOps[1] = DAG.getConstant(0, MVT::i32);
14027   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14028   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14029
14030   // The return type has to be a 128-bit type with the same element
14031   // type as the input type.
14032   MVT EltVT = VT.getVectorElementType();
14033   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14034
14035   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14036   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14037 }
14038
14039 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14040   SDLoc dl(Op);
14041   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14042   switch (IntNo) {
14043   default: return SDValue();    // Don't custom lower most intrinsics.
14044   // Comparison intrinsics.
14045   case Intrinsic::x86_sse_comieq_ss:
14046   case Intrinsic::x86_sse_comilt_ss:
14047   case Intrinsic::x86_sse_comile_ss:
14048   case Intrinsic::x86_sse_comigt_ss:
14049   case Intrinsic::x86_sse_comige_ss:
14050   case Intrinsic::x86_sse_comineq_ss:
14051   case Intrinsic::x86_sse_ucomieq_ss:
14052   case Intrinsic::x86_sse_ucomilt_ss:
14053   case Intrinsic::x86_sse_ucomile_ss:
14054   case Intrinsic::x86_sse_ucomigt_ss:
14055   case Intrinsic::x86_sse_ucomige_ss:
14056   case Intrinsic::x86_sse_ucomineq_ss:
14057   case Intrinsic::x86_sse2_comieq_sd:
14058   case Intrinsic::x86_sse2_comilt_sd:
14059   case Intrinsic::x86_sse2_comile_sd:
14060   case Intrinsic::x86_sse2_comigt_sd:
14061   case Intrinsic::x86_sse2_comige_sd:
14062   case Intrinsic::x86_sse2_comineq_sd:
14063   case Intrinsic::x86_sse2_ucomieq_sd:
14064   case Intrinsic::x86_sse2_ucomilt_sd:
14065   case Intrinsic::x86_sse2_ucomile_sd:
14066   case Intrinsic::x86_sse2_ucomigt_sd:
14067   case Intrinsic::x86_sse2_ucomige_sd:
14068   case Intrinsic::x86_sse2_ucomineq_sd: {
14069     unsigned Opc;
14070     ISD::CondCode CC;
14071     switch (IntNo) {
14072     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14073     case Intrinsic::x86_sse_comieq_ss:
14074     case Intrinsic::x86_sse2_comieq_sd:
14075       Opc = X86ISD::COMI;
14076       CC = ISD::SETEQ;
14077       break;
14078     case Intrinsic::x86_sse_comilt_ss:
14079     case Intrinsic::x86_sse2_comilt_sd:
14080       Opc = X86ISD::COMI;
14081       CC = ISD::SETLT;
14082       break;
14083     case Intrinsic::x86_sse_comile_ss:
14084     case Intrinsic::x86_sse2_comile_sd:
14085       Opc = X86ISD::COMI;
14086       CC = ISD::SETLE;
14087       break;
14088     case Intrinsic::x86_sse_comigt_ss:
14089     case Intrinsic::x86_sse2_comigt_sd:
14090       Opc = X86ISD::COMI;
14091       CC = ISD::SETGT;
14092       break;
14093     case Intrinsic::x86_sse_comige_ss:
14094     case Intrinsic::x86_sse2_comige_sd:
14095       Opc = X86ISD::COMI;
14096       CC = ISD::SETGE;
14097       break;
14098     case Intrinsic::x86_sse_comineq_ss:
14099     case Intrinsic::x86_sse2_comineq_sd:
14100       Opc = X86ISD::COMI;
14101       CC = ISD::SETNE;
14102       break;
14103     case Intrinsic::x86_sse_ucomieq_ss:
14104     case Intrinsic::x86_sse2_ucomieq_sd:
14105       Opc = X86ISD::UCOMI;
14106       CC = ISD::SETEQ;
14107       break;
14108     case Intrinsic::x86_sse_ucomilt_ss:
14109     case Intrinsic::x86_sse2_ucomilt_sd:
14110       Opc = X86ISD::UCOMI;
14111       CC = ISD::SETLT;
14112       break;
14113     case Intrinsic::x86_sse_ucomile_ss:
14114     case Intrinsic::x86_sse2_ucomile_sd:
14115       Opc = X86ISD::UCOMI;
14116       CC = ISD::SETLE;
14117       break;
14118     case Intrinsic::x86_sse_ucomigt_ss:
14119     case Intrinsic::x86_sse2_ucomigt_sd:
14120       Opc = X86ISD::UCOMI;
14121       CC = ISD::SETGT;
14122       break;
14123     case Intrinsic::x86_sse_ucomige_ss:
14124     case Intrinsic::x86_sse2_ucomige_sd:
14125       Opc = X86ISD::UCOMI;
14126       CC = ISD::SETGE;
14127       break;
14128     case Intrinsic::x86_sse_ucomineq_ss:
14129     case Intrinsic::x86_sse2_ucomineq_sd:
14130       Opc = X86ISD::UCOMI;
14131       CC = ISD::SETNE;
14132       break;
14133     }
14134
14135     SDValue LHS = Op.getOperand(1);
14136     SDValue RHS = Op.getOperand(2);
14137     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14138     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14139     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14140     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14141                                 DAG.getConstant(X86CC, MVT::i8), Cond);
14142     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14143   }
14144
14145   // Arithmetic intrinsics.
14146   case Intrinsic::x86_sse2_pmulu_dq:
14147   case Intrinsic::x86_avx2_pmulu_dq:
14148     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14149                        Op.getOperand(1), Op.getOperand(2));
14150
14151   case Intrinsic::x86_sse41_pmuldq:
14152   case Intrinsic::x86_avx2_pmul_dq:
14153     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14154                        Op.getOperand(1), Op.getOperand(2));
14155
14156   case Intrinsic::x86_sse2_pmulhu_w:
14157   case Intrinsic::x86_avx2_pmulhu_w:
14158     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14159                        Op.getOperand(1), Op.getOperand(2));
14160
14161   case Intrinsic::x86_sse2_pmulh_w:
14162   case Intrinsic::x86_avx2_pmulh_w:
14163     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14164                        Op.getOperand(1), Op.getOperand(2));
14165
14166   // SSE2/AVX2 sub with unsigned saturation intrinsics
14167   case Intrinsic::x86_sse2_psubus_b:
14168   case Intrinsic::x86_sse2_psubus_w:
14169   case Intrinsic::x86_avx2_psubus_b:
14170   case Intrinsic::x86_avx2_psubus_w:
14171     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14172                        Op.getOperand(1), Op.getOperand(2));
14173
14174   // SSE3/AVX horizontal add/sub intrinsics
14175   case Intrinsic::x86_sse3_hadd_ps:
14176   case Intrinsic::x86_sse3_hadd_pd:
14177   case Intrinsic::x86_avx_hadd_ps_256:
14178   case Intrinsic::x86_avx_hadd_pd_256:
14179   case Intrinsic::x86_sse3_hsub_ps:
14180   case Intrinsic::x86_sse3_hsub_pd:
14181   case Intrinsic::x86_avx_hsub_ps_256:
14182   case Intrinsic::x86_avx_hsub_pd_256:
14183   case Intrinsic::x86_ssse3_phadd_w_128:
14184   case Intrinsic::x86_ssse3_phadd_d_128:
14185   case Intrinsic::x86_avx2_phadd_w:
14186   case Intrinsic::x86_avx2_phadd_d:
14187   case Intrinsic::x86_ssse3_phsub_w_128:
14188   case Intrinsic::x86_ssse3_phsub_d_128:
14189   case Intrinsic::x86_avx2_phsub_w:
14190   case Intrinsic::x86_avx2_phsub_d: {
14191     unsigned Opcode;
14192     switch (IntNo) {
14193     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14194     case Intrinsic::x86_sse3_hadd_ps:
14195     case Intrinsic::x86_sse3_hadd_pd:
14196     case Intrinsic::x86_avx_hadd_ps_256:
14197     case Intrinsic::x86_avx_hadd_pd_256:
14198       Opcode = X86ISD::FHADD;
14199       break;
14200     case Intrinsic::x86_sse3_hsub_ps:
14201     case Intrinsic::x86_sse3_hsub_pd:
14202     case Intrinsic::x86_avx_hsub_ps_256:
14203     case Intrinsic::x86_avx_hsub_pd_256:
14204       Opcode = X86ISD::FHSUB;
14205       break;
14206     case Intrinsic::x86_ssse3_phadd_w_128:
14207     case Intrinsic::x86_ssse3_phadd_d_128:
14208     case Intrinsic::x86_avx2_phadd_w:
14209     case Intrinsic::x86_avx2_phadd_d:
14210       Opcode = X86ISD::HADD;
14211       break;
14212     case Intrinsic::x86_ssse3_phsub_w_128:
14213     case Intrinsic::x86_ssse3_phsub_d_128:
14214     case Intrinsic::x86_avx2_phsub_w:
14215     case Intrinsic::x86_avx2_phsub_d:
14216       Opcode = X86ISD::HSUB;
14217       break;
14218     }
14219     return DAG.getNode(Opcode, dl, Op.getValueType(),
14220                        Op.getOperand(1), Op.getOperand(2));
14221   }
14222
14223   // SSE2/SSE41/AVX2 integer max/min intrinsics.
14224   case Intrinsic::x86_sse2_pmaxu_b:
14225   case Intrinsic::x86_sse41_pmaxuw:
14226   case Intrinsic::x86_sse41_pmaxud:
14227   case Intrinsic::x86_avx2_pmaxu_b:
14228   case Intrinsic::x86_avx2_pmaxu_w:
14229   case Intrinsic::x86_avx2_pmaxu_d:
14230   case Intrinsic::x86_sse2_pminu_b:
14231   case Intrinsic::x86_sse41_pminuw:
14232   case Intrinsic::x86_sse41_pminud:
14233   case Intrinsic::x86_avx2_pminu_b:
14234   case Intrinsic::x86_avx2_pminu_w:
14235   case Intrinsic::x86_avx2_pminu_d:
14236   case Intrinsic::x86_sse41_pmaxsb:
14237   case Intrinsic::x86_sse2_pmaxs_w:
14238   case Intrinsic::x86_sse41_pmaxsd:
14239   case Intrinsic::x86_avx2_pmaxs_b:
14240   case Intrinsic::x86_avx2_pmaxs_w:
14241   case Intrinsic::x86_avx2_pmaxs_d:
14242   case Intrinsic::x86_sse41_pminsb:
14243   case Intrinsic::x86_sse2_pmins_w:
14244   case Intrinsic::x86_sse41_pminsd:
14245   case Intrinsic::x86_avx2_pmins_b:
14246   case Intrinsic::x86_avx2_pmins_w:
14247   case Intrinsic::x86_avx2_pmins_d: {
14248     unsigned Opcode;
14249     switch (IntNo) {
14250     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14251     case Intrinsic::x86_sse2_pmaxu_b:
14252     case Intrinsic::x86_sse41_pmaxuw:
14253     case Intrinsic::x86_sse41_pmaxud:
14254     case Intrinsic::x86_avx2_pmaxu_b:
14255     case Intrinsic::x86_avx2_pmaxu_w:
14256     case Intrinsic::x86_avx2_pmaxu_d:
14257       Opcode = X86ISD::UMAX;
14258       break;
14259     case Intrinsic::x86_sse2_pminu_b:
14260     case Intrinsic::x86_sse41_pminuw:
14261     case Intrinsic::x86_sse41_pminud:
14262     case Intrinsic::x86_avx2_pminu_b:
14263     case Intrinsic::x86_avx2_pminu_w:
14264     case Intrinsic::x86_avx2_pminu_d:
14265       Opcode = X86ISD::UMIN;
14266       break;
14267     case Intrinsic::x86_sse41_pmaxsb:
14268     case Intrinsic::x86_sse2_pmaxs_w:
14269     case Intrinsic::x86_sse41_pmaxsd:
14270     case Intrinsic::x86_avx2_pmaxs_b:
14271     case Intrinsic::x86_avx2_pmaxs_w:
14272     case Intrinsic::x86_avx2_pmaxs_d:
14273       Opcode = X86ISD::SMAX;
14274       break;
14275     case Intrinsic::x86_sse41_pminsb:
14276     case Intrinsic::x86_sse2_pmins_w:
14277     case Intrinsic::x86_sse41_pminsd:
14278     case Intrinsic::x86_avx2_pmins_b:
14279     case Intrinsic::x86_avx2_pmins_w:
14280     case Intrinsic::x86_avx2_pmins_d:
14281       Opcode = X86ISD::SMIN;
14282       break;
14283     }
14284     return DAG.getNode(Opcode, dl, Op.getValueType(),
14285                        Op.getOperand(1), Op.getOperand(2));
14286   }
14287
14288   // SSE/SSE2/AVX floating point max/min intrinsics.
14289   case Intrinsic::x86_sse_max_ps:
14290   case Intrinsic::x86_sse2_max_pd:
14291   case Intrinsic::x86_avx_max_ps_256:
14292   case Intrinsic::x86_avx_max_pd_256:
14293   case Intrinsic::x86_sse_min_ps:
14294   case Intrinsic::x86_sse2_min_pd:
14295   case Intrinsic::x86_avx_min_ps_256:
14296   case Intrinsic::x86_avx_min_pd_256: {
14297     unsigned Opcode;
14298     switch (IntNo) {
14299     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14300     case Intrinsic::x86_sse_max_ps:
14301     case Intrinsic::x86_sse2_max_pd:
14302     case Intrinsic::x86_avx_max_ps_256:
14303     case Intrinsic::x86_avx_max_pd_256:
14304       Opcode = X86ISD::FMAX;
14305       break;
14306     case Intrinsic::x86_sse_min_ps:
14307     case Intrinsic::x86_sse2_min_pd:
14308     case Intrinsic::x86_avx_min_ps_256:
14309     case Intrinsic::x86_avx_min_pd_256:
14310       Opcode = X86ISD::FMIN;
14311       break;
14312     }
14313     return DAG.getNode(Opcode, dl, Op.getValueType(),
14314                        Op.getOperand(1), Op.getOperand(2));
14315   }
14316
14317   // AVX2 variable shift intrinsics
14318   case Intrinsic::x86_avx2_psllv_d:
14319   case Intrinsic::x86_avx2_psllv_q:
14320   case Intrinsic::x86_avx2_psllv_d_256:
14321   case Intrinsic::x86_avx2_psllv_q_256:
14322   case Intrinsic::x86_avx2_psrlv_d:
14323   case Intrinsic::x86_avx2_psrlv_q:
14324   case Intrinsic::x86_avx2_psrlv_d_256:
14325   case Intrinsic::x86_avx2_psrlv_q_256:
14326   case Intrinsic::x86_avx2_psrav_d:
14327   case Intrinsic::x86_avx2_psrav_d_256: {
14328     unsigned Opcode;
14329     switch (IntNo) {
14330     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14331     case Intrinsic::x86_avx2_psllv_d:
14332     case Intrinsic::x86_avx2_psllv_q:
14333     case Intrinsic::x86_avx2_psllv_d_256:
14334     case Intrinsic::x86_avx2_psllv_q_256:
14335       Opcode = ISD::SHL;
14336       break;
14337     case Intrinsic::x86_avx2_psrlv_d:
14338     case Intrinsic::x86_avx2_psrlv_q:
14339     case Intrinsic::x86_avx2_psrlv_d_256:
14340     case Intrinsic::x86_avx2_psrlv_q_256:
14341       Opcode = ISD::SRL;
14342       break;
14343     case Intrinsic::x86_avx2_psrav_d:
14344     case Intrinsic::x86_avx2_psrav_d_256:
14345       Opcode = ISD::SRA;
14346       break;
14347     }
14348     return DAG.getNode(Opcode, dl, Op.getValueType(),
14349                        Op.getOperand(1), Op.getOperand(2));
14350   }
14351
14352   case Intrinsic::x86_sse2_packssdw_128:
14353   case Intrinsic::x86_sse2_packsswb_128:
14354   case Intrinsic::x86_avx2_packssdw:
14355   case Intrinsic::x86_avx2_packsswb:
14356     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14357                        Op.getOperand(1), Op.getOperand(2));
14358
14359   case Intrinsic::x86_sse2_packuswb_128:
14360   case Intrinsic::x86_sse41_packusdw:
14361   case Intrinsic::x86_avx2_packuswb:
14362   case Intrinsic::x86_avx2_packusdw:
14363     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14364                        Op.getOperand(1), Op.getOperand(2));
14365
14366   case Intrinsic::x86_ssse3_pshuf_b_128:
14367   case Intrinsic::x86_avx2_pshuf_b:
14368     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14369                        Op.getOperand(1), Op.getOperand(2));
14370
14371   case Intrinsic::x86_sse2_pshuf_d:
14372     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14373                        Op.getOperand(1), Op.getOperand(2));
14374
14375   case Intrinsic::x86_sse2_pshufl_w:
14376     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14377                        Op.getOperand(1), Op.getOperand(2));
14378
14379   case Intrinsic::x86_sse2_pshufh_w:
14380     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14381                        Op.getOperand(1), Op.getOperand(2));
14382
14383   case Intrinsic::x86_ssse3_psign_b_128:
14384   case Intrinsic::x86_ssse3_psign_w_128:
14385   case Intrinsic::x86_ssse3_psign_d_128:
14386   case Intrinsic::x86_avx2_psign_b:
14387   case Intrinsic::x86_avx2_psign_w:
14388   case Intrinsic::x86_avx2_psign_d:
14389     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14390                        Op.getOperand(1), Op.getOperand(2));
14391
14392   case Intrinsic::x86_sse41_insertps:
14393     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14394                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14395
14396   case Intrinsic::x86_avx_vperm2f128_ps_256:
14397   case Intrinsic::x86_avx_vperm2f128_pd_256:
14398   case Intrinsic::x86_avx_vperm2f128_si_256:
14399   case Intrinsic::x86_avx2_vperm2i128:
14400     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14401                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14402
14403   case Intrinsic::x86_avx2_permd:
14404   case Intrinsic::x86_avx2_permps:
14405     // Operands intentionally swapped. Mask is last operand to intrinsic,
14406     // but second operand for node/instruction.
14407     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14408                        Op.getOperand(2), Op.getOperand(1));
14409
14410   case Intrinsic::x86_sse_sqrt_ps:
14411   case Intrinsic::x86_sse2_sqrt_pd:
14412   case Intrinsic::x86_avx_sqrt_ps_256:
14413   case Intrinsic::x86_avx_sqrt_pd_256:
14414     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14415
14416   // ptest and testp intrinsics. The intrinsic these come from are designed to
14417   // return an integer value, not just an instruction so lower it to the ptest
14418   // or testp pattern and a setcc for the result.
14419   case Intrinsic::x86_sse41_ptestz:
14420   case Intrinsic::x86_sse41_ptestc:
14421   case Intrinsic::x86_sse41_ptestnzc:
14422   case Intrinsic::x86_avx_ptestz_256:
14423   case Intrinsic::x86_avx_ptestc_256:
14424   case Intrinsic::x86_avx_ptestnzc_256:
14425   case Intrinsic::x86_avx_vtestz_ps:
14426   case Intrinsic::x86_avx_vtestc_ps:
14427   case Intrinsic::x86_avx_vtestnzc_ps:
14428   case Intrinsic::x86_avx_vtestz_pd:
14429   case Intrinsic::x86_avx_vtestc_pd:
14430   case Intrinsic::x86_avx_vtestnzc_pd:
14431   case Intrinsic::x86_avx_vtestz_ps_256:
14432   case Intrinsic::x86_avx_vtestc_ps_256:
14433   case Intrinsic::x86_avx_vtestnzc_ps_256:
14434   case Intrinsic::x86_avx_vtestz_pd_256:
14435   case Intrinsic::x86_avx_vtestc_pd_256:
14436   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14437     bool IsTestPacked = false;
14438     unsigned X86CC;
14439     switch (IntNo) {
14440     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14441     case Intrinsic::x86_avx_vtestz_ps:
14442     case Intrinsic::x86_avx_vtestz_pd:
14443     case Intrinsic::x86_avx_vtestz_ps_256:
14444     case Intrinsic::x86_avx_vtestz_pd_256:
14445       IsTestPacked = true; // Fallthrough
14446     case Intrinsic::x86_sse41_ptestz:
14447     case Intrinsic::x86_avx_ptestz_256:
14448       // ZF = 1
14449       X86CC = X86::COND_E;
14450       break;
14451     case Intrinsic::x86_avx_vtestc_ps:
14452     case Intrinsic::x86_avx_vtestc_pd:
14453     case Intrinsic::x86_avx_vtestc_ps_256:
14454     case Intrinsic::x86_avx_vtestc_pd_256:
14455       IsTestPacked = true; // Fallthrough
14456     case Intrinsic::x86_sse41_ptestc:
14457     case Intrinsic::x86_avx_ptestc_256:
14458       // CF = 1
14459       X86CC = X86::COND_B;
14460       break;
14461     case Intrinsic::x86_avx_vtestnzc_ps:
14462     case Intrinsic::x86_avx_vtestnzc_pd:
14463     case Intrinsic::x86_avx_vtestnzc_ps_256:
14464     case Intrinsic::x86_avx_vtestnzc_pd_256:
14465       IsTestPacked = true; // Fallthrough
14466     case Intrinsic::x86_sse41_ptestnzc:
14467     case Intrinsic::x86_avx_ptestnzc_256:
14468       // ZF and CF = 0
14469       X86CC = X86::COND_A;
14470       break;
14471     }
14472
14473     SDValue LHS = Op.getOperand(1);
14474     SDValue RHS = Op.getOperand(2);
14475     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14476     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14477     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14478     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14479     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14480   }
14481   case Intrinsic::x86_avx512_kortestz_w:
14482   case Intrinsic::x86_avx512_kortestc_w: {
14483     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14484     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14485     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14486     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14487     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14488     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14489     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14490   }
14491
14492   // SSE/AVX shift intrinsics
14493   case Intrinsic::x86_sse2_psll_w:
14494   case Intrinsic::x86_sse2_psll_d:
14495   case Intrinsic::x86_sse2_psll_q:
14496   case Intrinsic::x86_avx2_psll_w:
14497   case Intrinsic::x86_avx2_psll_d:
14498   case Intrinsic::x86_avx2_psll_q:
14499   case Intrinsic::x86_sse2_psrl_w:
14500   case Intrinsic::x86_sse2_psrl_d:
14501   case Intrinsic::x86_sse2_psrl_q:
14502   case Intrinsic::x86_avx2_psrl_w:
14503   case Intrinsic::x86_avx2_psrl_d:
14504   case Intrinsic::x86_avx2_psrl_q:
14505   case Intrinsic::x86_sse2_psra_w:
14506   case Intrinsic::x86_sse2_psra_d:
14507   case Intrinsic::x86_avx2_psra_w:
14508   case Intrinsic::x86_avx2_psra_d: {
14509     unsigned Opcode;
14510     switch (IntNo) {
14511     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14512     case Intrinsic::x86_sse2_psll_w:
14513     case Intrinsic::x86_sse2_psll_d:
14514     case Intrinsic::x86_sse2_psll_q:
14515     case Intrinsic::x86_avx2_psll_w:
14516     case Intrinsic::x86_avx2_psll_d:
14517     case Intrinsic::x86_avx2_psll_q:
14518       Opcode = X86ISD::VSHL;
14519       break;
14520     case Intrinsic::x86_sse2_psrl_w:
14521     case Intrinsic::x86_sse2_psrl_d:
14522     case Intrinsic::x86_sse2_psrl_q:
14523     case Intrinsic::x86_avx2_psrl_w:
14524     case Intrinsic::x86_avx2_psrl_d:
14525     case Intrinsic::x86_avx2_psrl_q:
14526       Opcode = X86ISD::VSRL;
14527       break;
14528     case Intrinsic::x86_sse2_psra_w:
14529     case Intrinsic::x86_sse2_psra_d:
14530     case Intrinsic::x86_avx2_psra_w:
14531     case Intrinsic::x86_avx2_psra_d:
14532       Opcode = X86ISD::VSRA;
14533       break;
14534     }
14535     return DAG.getNode(Opcode, dl, Op.getValueType(),
14536                        Op.getOperand(1), Op.getOperand(2));
14537   }
14538
14539   // SSE/AVX immediate shift intrinsics
14540   case Intrinsic::x86_sse2_pslli_w:
14541   case Intrinsic::x86_sse2_pslli_d:
14542   case Intrinsic::x86_sse2_pslli_q:
14543   case Intrinsic::x86_avx2_pslli_w:
14544   case Intrinsic::x86_avx2_pslli_d:
14545   case Intrinsic::x86_avx2_pslli_q:
14546   case Intrinsic::x86_sse2_psrli_w:
14547   case Intrinsic::x86_sse2_psrli_d:
14548   case Intrinsic::x86_sse2_psrli_q:
14549   case Intrinsic::x86_avx2_psrli_w:
14550   case Intrinsic::x86_avx2_psrli_d:
14551   case Intrinsic::x86_avx2_psrli_q:
14552   case Intrinsic::x86_sse2_psrai_w:
14553   case Intrinsic::x86_sse2_psrai_d:
14554   case Intrinsic::x86_avx2_psrai_w:
14555   case Intrinsic::x86_avx2_psrai_d: {
14556     unsigned Opcode;
14557     switch (IntNo) {
14558     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14559     case Intrinsic::x86_sse2_pslli_w:
14560     case Intrinsic::x86_sse2_pslli_d:
14561     case Intrinsic::x86_sse2_pslli_q:
14562     case Intrinsic::x86_avx2_pslli_w:
14563     case Intrinsic::x86_avx2_pslli_d:
14564     case Intrinsic::x86_avx2_pslli_q:
14565       Opcode = X86ISD::VSHLI;
14566       break;
14567     case Intrinsic::x86_sse2_psrli_w:
14568     case Intrinsic::x86_sse2_psrli_d:
14569     case Intrinsic::x86_sse2_psrli_q:
14570     case Intrinsic::x86_avx2_psrli_w:
14571     case Intrinsic::x86_avx2_psrli_d:
14572     case Intrinsic::x86_avx2_psrli_q:
14573       Opcode = X86ISD::VSRLI;
14574       break;
14575     case Intrinsic::x86_sse2_psrai_w:
14576     case Intrinsic::x86_sse2_psrai_d:
14577     case Intrinsic::x86_avx2_psrai_w:
14578     case Intrinsic::x86_avx2_psrai_d:
14579       Opcode = X86ISD::VSRAI;
14580       break;
14581     }
14582     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14583                                Op.getOperand(1), Op.getOperand(2), DAG);
14584   }
14585
14586   case Intrinsic::x86_sse42_pcmpistria128:
14587   case Intrinsic::x86_sse42_pcmpestria128:
14588   case Intrinsic::x86_sse42_pcmpistric128:
14589   case Intrinsic::x86_sse42_pcmpestric128:
14590   case Intrinsic::x86_sse42_pcmpistrio128:
14591   case Intrinsic::x86_sse42_pcmpestrio128:
14592   case Intrinsic::x86_sse42_pcmpistris128:
14593   case Intrinsic::x86_sse42_pcmpestris128:
14594   case Intrinsic::x86_sse42_pcmpistriz128:
14595   case Intrinsic::x86_sse42_pcmpestriz128: {
14596     unsigned Opcode;
14597     unsigned X86CC;
14598     switch (IntNo) {
14599     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14600     case Intrinsic::x86_sse42_pcmpistria128:
14601       Opcode = X86ISD::PCMPISTRI;
14602       X86CC = X86::COND_A;
14603       break;
14604     case Intrinsic::x86_sse42_pcmpestria128:
14605       Opcode = X86ISD::PCMPESTRI;
14606       X86CC = X86::COND_A;
14607       break;
14608     case Intrinsic::x86_sse42_pcmpistric128:
14609       Opcode = X86ISD::PCMPISTRI;
14610       X86CC = X86::COND_B;
14611       break;
14612     case Intrinsic::x86_sse42_pcmpestric128:
14613       Opcode = X86ISD::PCMPESTRI;
14614       X86CC = X86::COND_B;
14615       break;
14616     case Intrinsic::x86_sse42_pcmpistrio128:
14617       Opcode = X86ISD::PCMPISTRI;
14618       X86CC = X86::COND_O;
14619       break;
14620     case Intrinsic::x86_sse42_pcmpestrio128:
14621       Opcode = X86ISD::PCMPESTRI;
14622       X86CC = X86::COND_O;
14623       break;
14624     case Intrinsic::x86_sse42_pcmpistris128:
14625       Opcode = X86ISD::PCMPISTRI;
14626       X86CC = X86::COND_S;
14627       break;
14628     case Intrinsic::x86_sse42_pcmpestris128:
14629       Opcode = X86ISD::PCMPESTRI;
14630       X86CC = X86::COND_S;
14631       break;
14632     case Intrinsic::x86_sse42_pcmpistriz128:
14633       Opcode = X86ISD::PCMPISTRI;
14634       X86CC = X86::COND_E;
14635       break;
14636     case Intrinsic::x86_sse42_pcmpestriz128:
14637       Opcode = X86ISD::PCMPESTRI;
14638       X86CC = X86::COND_E;
14639       break;
14640     }
14641     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14642     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14643     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14644     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14645                                 DAG.getConstant(X86CC, MVT::i8),
14646                                 SDValue(PCMP.getNode(), 1));
14647     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14648   }
14649
14650   case Intrinsic::x86_sse42_pcmpistri128:
14651   case Intrinsic::x86_sse42_pcmpestri128: {
14652     unsigned Opcode;
14653     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14654       Opcode = X86ISD::PCMPISTRI;
14655     else
14656       Opcode = X86ISD::PCMPESTRI;
14657
14658     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14659     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14660     return DAG.getNode(Opcode, dl, VTs, NewOps);
14661   }
14662   case Intrinsic::x86_fma_vfmadd_ps:
14663   case Intrinsic::x86_fma_vfmadd_pd:
14664   case Intrinsic::x86_fma_vfmsub_ps:
14665   case Intrinsic::x86_fma_vfmsub_pd:
14666   case Intrinsic::x86_fma_vfnmadd_ps:
14667   case Intrinsic::x86_fma_vfnmadd_pd:
14668   case Intrinsic::x86_fma_vfnmsub_ps:
14669   case Intrinsic::x86_fma_vfnmsub_pd:
14670   case Intrinsic::x86_fma_vfmaddsub_ps:
14671   case Intrinsic::x86_fma_vfmaddsub_pd:
14672   case Intrinsic::x86_fma_vfmsubadd_ps:
14673   case Intrinsic::x86_fma_vfmsubadd_pd:
14674   case Intrinsic::x86_fma_vfmadd_ps_256:
14675   case Intrinsic::x86_fma_vfmadd_pd_256:
14676   case Intrinsic::x86_fma_vfmsub_ps_256:
14677   case Intrinsic::x86_fma_vfmsub_pd_256:
14678   case Intrinsic::x86_fma_vfnmadd_ps_256:
14679   case Intrinsic::x86_fma_vfnmadd_pd_256:
14680   case Intrinsic::x86_fma_vfnmsub_ps_256:
14681   case Intrinsic::x86_fma_vfnmsub_pd_256:
14682   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14683   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14684   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14685   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14686   case Intrinsic::x86_fma_vfmadd_ps_512:
14687   case Intrinsic::x86_fma_vfmadd_pd_512:
14688   case Intrinsic::x86_fma_vfmsub_ps_512:
14689   case Intrinsic::x86_fma_vfmsub_pd_512:
14690   case Intrinsic::x86_fma_vfnmadd_ps_512:
14691   case Intrinsic::x86_fma_vfnmadd_pd_512:
14692   case Intrinsic::x86_fma_vfnmsub_ps_512:
14693   case Intrinsic::x86_fma_vfnmsub_pd_512:
14694   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14695   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14696   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14697   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14698     unsigned Opc;
14699     switch (IntNo) {
14700     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14701     case Intrinsic::x86_fma_vfmadd_ps:
14702     case Intrinsic::x86_fma_vfmadd_pd:
14703     case Intrinsic::x86_fma_vfmadd_ps_256:
14704     case Intrinsic::x86_fma_vfmadd_pd_256:
14705     case Intrinsic::x86_fma_vfmadd_ps_512:
14706     case Intrinsic::x86_fma_vfmadd_pd_512:
14707       Opc = X86ISD::FMADD;
14708       break;
14709     case Intrinsic::x86_fma_vfmsub_ps:
14710     case Intrinsic::x86_fma_vfmsub_pd:
14711     case Intrinsic::x86_fma_vfmsub_ps_256:
14712     case Intrinsic::x86_fma_vfmsub_pd_256:
14713     case Intrinsic::x86_fma_vfmsub_ps_512:
14714     case Intrinsic::x86_fma_vfmsub_pd_512:
14715       Opc = X86ISD::FMSUB;
14716       break;
14717     case Intrinsic::x86_fma_vfnmadd_ps:
14718     case Intrinsic::x86_fma_vfnmadd_pd:
14719     case Intrinsic::x86_fma_vfnmadd_ps_256:
14720     case Intrinsic::x86_fma_vfnmadd_pd_256:
14721     case Intrinsic::x86_fma_vfnmadd_ps_512:
14722     case Intrinsic::x86_fma_vfnmadd_pd_512:
14723       Opc = X86ISD::FNMADD;
14724       break;
14725     case Intrinsic::x86_fma_vfnmsub_ps:
14726     case Intrinsic::x86_fma_vfnmsub_pd:
14727     case Intrinsic::x86_fma_vfnmsub_ps_256:
14728     case Intrinsic::x86_fma_vfnmsub_pd_256:
14729     case Intrinsic::x86_fma_vfnmsub_ps_512:
14730     case Intrinsic::x86_fma_vfnmsub_pd_512:
14731       Opc = X86ISD::FNMSUB;
14732       break;
14733     case Intrinsic::x86_fma_vfmaddsub_ps:
14734     case Intrinsic::x86_fma_vfmaddsub_pd:
14735     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14736     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14737     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14738     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14739       Opc = X86ISD::FMADDSUB;
14740       break;
14741     case Intrinsic::x86_fma_vfmsubadd_ps:
14742     case Intrinsic::x86_fma_vfmsubadd_pd:
14743     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14744     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14745     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14746     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14747       Opc = X86ISD::FMSUBADD;
14748       break;
14749     }
14750
14751     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14752                        Op.getOperand(2), Op.getOperand(3));
14753   }
14754   }
14755 }
14756
14757 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14758                               SDValue Src, SDValue Mask, SDValue Base,
14759                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14760                               const X86Subtarget * Subtarget) {
14761   SDLoc dl(Op);
14762   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14763   assert(C && "Invalid scale type");
14764   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14765   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14766                              Index.getSimpleValueType().getVectorNumElements());
14767   SDValue MaskInReg;
14768   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14769   if (MaskC)
14770     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14771   else
14772     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14773   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14774   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14775   SDValue Segment = DAG.getRegister(0, MVT::i32);
14776   if (Src.getOpcode() == ISD::UNDEF)
14777     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14778   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14779   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14780   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14781   return DAG.getMergeValues(RetOps, dl);
14782 }
14783
14784 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14785                                SDValue Src, SDValue Mask, SDValue Base,
14786                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14787   SDLoc dl(Op);
14788   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14789   assert(C && "Invalid scale type");
14790   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14791   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14792   SDValue Segment = DAG.getRegister(0, MVT::i32);
14793   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14794                              Index.getSimpleValueType().getVectorNumElements());
14795   SDValue MaskInReg;
14796   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14797   if (MaskC)
14798     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14799   else
14800     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14801   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14802   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14803   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14804   return SDValue(Res, 1);
14805 }
14806
14807 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14808                                SDValue Mask, SDValue Base, SDValue Index,
14809                                SDValue ScaleOp, SDValue Chain) {
14810   SDLoc dl(Op);
14811   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14812   assert(C && "Invalid scale type");
14813   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14814   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14815   SDValue Segment = DAG.getRegister(0, MVT::i32);
14816   EVT MaskVT =
14817     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14818   SDValue MaskInReg;
14819   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14820   if (MaskC)
14821     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14822   else
14823     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14824   //SDVTList VTs = DAG.getVTList(MVT::Other);
14825   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14826   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14827   return SDValue(Res, 0);
14828 }
14829
14830 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14831 // read performance monitor counters (x86_rdpmc).
14832 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14833                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14834                               SmallVectorImpl<SDValue> &Results) {
14835   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14836   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14837   SDValue LO, HI;
14838
14839   // The ECX register is used to select the index of the performance counter
14840   // to read.
14841   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14842                                    N->getOperand(2));
14843   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14844
14845   // Reads the content of a 64-bit performance counter and returns it in the
14846   // registers EDX:EAX.
14847   if (Subtarget->is64Bit()) {
14848     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14849     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14850                             LO.getValue(2));
14851   } else {
14852     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14853     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14854                             LO.getValue(2));
14855   }
14856   Chain = HI.getValue(1);
14857
14858   if (Subtarget->is64Bit()) {
14859     // The EAX register is loaded with the low-order 32 bits. The EDX register
14860     // is loaded with the supported high-order bits of the counter.
14861     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14862                               DAG.getConstant(32, MVT::i8));
14863     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14864     Results.push_back(Chain);
14865     return;
14866   }
14867
14868   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14869   SDValue Ops[] = { LO, HI };
14870   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14871   Results.push_back(Pair);
14872   Results.push_back(Chain);
14873 }
14874
14875 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14876 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14877 // also used to custom lower READCYCLECOUNTER nodes.
14878 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14879                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14880                               SmallVectorImpl<SDValue> &Results) {
14881   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14882   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14883   SDValue LO, HI;
14884
14885   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14886   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14887   // and the EAX register is loaded with the low-order 32 bits.
14888   if (Subtarget->is64Bit()) {
14889     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14890     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14891                             LO.getValue(2));
14892   } else {
14893     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14894     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14895                             LO.getValue(2));
14896   }
14897   SDValue Chain = HI.getValue(1);
14898
14899   if (Opcode == X86ISD::RDTSCP_DAG) {
14900     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14901
14902     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14903     // the ECX register. Add 'ecx' explicitly to the chain.
14904     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14905                                      HI.getValue(2));
14906     // Explicitly store the content of ECX at the location passed in input
14907     // to the 'rdtscp' intrinsic.
14908     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14909                          MachinePointerInfo(), false, false, 0);
14910   }
14911
14912   if (Subtarget->is64Bit()) {
14913     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14914     // the EAX register is loaded with the low-order 32 bits.
14915     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14916                               DAG.getConstant(32, MVT::i8));
14917     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14918     Results.push_back(Chain);
14919     return;
14920   }
14921
14922   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14923   SDValue Ops[] = { LO, HI };
14924   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14925   Results.push_back(Pair);
14926   Results.push_back(Chain);
14927 }
14928
14929 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14930                                      SelectionDAG &DAG) {
14931   SmallVector<SDValue, 2> Results;
14932   SDLoc DL(Op);
14933   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14934                           Results);
14935   return DAG.getMergeValues(Results, DL);
14936 }
14937
14938 enum IntrinsicType {
14939   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14940 };
14941
14942 struct IntrinsicData {
14943   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14944     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14945   IntrinsicType Type;
14946   unsigned      Opc0;
14947   unsigned      Opc1;
14948 };
14949
14950 std::map < unsigned, IntrinsicData> IntrMap;
14951 static void InitIntinsicsMap() {
14952   static bool Initialized = false;
14953   if (Initialized) 
14954     return;
14955   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14956                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14957   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14958                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14959   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14960                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14961   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14962                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14963   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14964                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14965   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14966                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14967   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14968                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14969   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14970                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14971   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14972                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14973
14974   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14975                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14976   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14977                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14978   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14979                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14980   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14981                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14982   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14983                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14984   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14985                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14986   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14987                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14988   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14989                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14990    
14991   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14992                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14993                                                         X86::VGATHERPF1QPSm)));
14994   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14995                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14996                                                         X86::VGATHERPF1QPDm)));
14997   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14998                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14999                                                         X86::VGATHERPF1DPDm)));
15000   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
15001                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
15002                                                         X86::VGATHERPF1DPSm)));
15003   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
15004                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
15005                                                         X86::VSCATTERPF1QPSm)));
15006   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
15007                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
15008                                                         X86::VSCATTERPF1QPDm)));
15009   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
15010                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
15011                                                         X86::VSCATTERPF1DPDm)));
15012   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
15013                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
15014                                                         X86::VSCATTERPF1DPSm)));
15015   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
15016                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15017   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
15018                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15019   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
15020                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15021   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
15022                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15023   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
15024                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15025   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
15026                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15027   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
15028                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
15029   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
15030                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
15031   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
15032                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
15033   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
15034                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
15035   Initialized = true;
15036 }
15037
15038 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15039                                       SelectionDAG &DAG) {
15040   InitIntinsicsMap();
15041   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15042   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
15043   if (itr == IntrMap.end())
15044     return SDValue();
15045
15046   SDLoc dl(Op);
15047   IntrinsicData Intr = itr->second;
15048   switch(Intr.Type) {
15049   case RDSEED:
15050   case RDRAND: {
15051     // Emit the node with the right value type.
15052     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15053     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
15054
15055     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15056     // Otherwise return the value from Rand, which is always 0, casted to i32.
15057     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15058                       DAG.getConstant(1, Op->getValueType(1)),
15059                       DAG.getConstant(X86::COND_B, MVT::i32),
15060                       SDValue(Result.getNode(), 1) };
15061     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15062                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15063                                   Ops);
15064
15065     // Return { result, isValid, chain }.
15066     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15067                        SDValue(Result.getNode(), 2));
15068   }
15069   case GATHER: {
15070   //gather(v1, mask, index, base, scale);
15071     SDValue Chain = Op.getOperand(0);
15072     SDValue Src   = Op.getOperand(2);
15073     SDValue Base  = Op.getOperand(3);
15074     SDValue Index = Op.getOperand(4);
15075     SDValue Mask  = Op.getOperand(5);
15076     SDValue Scale = Op.getOperand(6);
15077     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15078                           Subtarget);
15079   }
15080   case SCATTER: {
15081   //scatter(base, mask, index, v1, scale);
15082     SDValue Chain = Op.getOperand(0);
15083     SDValue Base  = Op.getOperand(2);
15084     SDValue Mask  = Op.getOperand(3);
15085     SDValue Index = Op.getOperand(4);
15086     SDValue Src   = Op.getOperand(5);
15087     SDValue Scale = Op.getOperand(6);
15088     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15089   }
15090   case PREFETCH: {
15091     SDValue Hint = Op.getOperand(6);
15092     unsigned HintVal;
15093     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15094         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15095       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15096     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15097     SDValue Chain = Op.getOperand(0);
15098     SDValue Mask  = Op.getOperand(2);
15099     SDValue Index = Op.getOperand(3);
15100     SDValue Base  = Op.getOperand(4);
15101     SDValue Scale = Op.getOperand(5);
15102     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15103   }
15104   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15105   case RDTSC: {
15106     SmallVector<SDValue, 2> Results;
15107     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15108     return DAG.getMergeValues(Results, dl);
15109   }
15110   // Read Performance Monitoring Counters.
15111   case RDPMC: {
15112     SmallVector<SDValue, 2> Results;
15113     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15114     return DAG.getMergeValues(Results, dl);
15115   }
15116   // XTEST intrinsics.
15117   case XTEST: {
15118     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15119     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15120     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15121                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15122                                 InTrans);
15123     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15124     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15125                        Ret, SDValue(InTrans.getNode(), 1));
15126   }
15127   }
15128   llvm_unreachable("Unknown Intrinsic Type");
15129 }
15130
15131 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15132                                            SelectionDAG &DAG) const {
15133   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15134   MFI->setReturnAddressIsTaken(true);
15135
15136   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15137     return SDValue();
15138
15139   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15140   SDLoc dl(Op);
15141   EVT PtrVT = getPointerTy();
15142
15143   if (Depth > 0) {
15144     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15145     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15146         DAG.getSubtarget().getRegisterInfo());
15147     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15148     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15149                        DAG.getNode(ISD::ADD, dl, PtrVT,
15150                                    FrameAddr, Offset),
15151                        MachinePointerInfo(), false, false, false, 0);
15152   }
15153
15154   // Just load the return address.
15155   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15156   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15157                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15158 }
15159
15160 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15161   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15162   MFI->setFrameAddressIsTaken(true);
15163
15164   EVT VT = Op.getValueType();
15165   SDLoc dl(Op);  // FIXME probably not meaningful
15166   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15167   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15168       DAG.getSubtarget().getRegisterInfo());
15169   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15170   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15171           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15172          "Invalid Frame Register!");
15173   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15174   while (Depth--)
15175     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15176                             MachinePointerInfo(),
15177                             false, false, false, 0);
15178   return FrameAddr;
15179 }
15180
15181 // FIXME? Maybe this could be a TableGen attribute on some registers and
15182 // this table could be generated automatically from RegInfo.
15183 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15184                                               EVT VT) const {
15185   unsigned Reg = StringSwitch<unsigned>(RegName)
15186                        .Case("esp", X86::ESP)
15187                        .Case("rsp", X86::RSP)
15188                        .Default(0);
15189   if (Reg)
15190     return Reg;
15191   report_fatal_error("Invalid register name global variable");
15192 }
15193
15194 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15195                                                      SelectionDAG &DAG) const {
15196   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15197       DAG.getSubtarget().getRegisterInfo());
15198   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15199 }
15200
15201 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15202   SDValue Chain     = Op.getOperand(0);
15203   SDValue Offset    = Op.getOperand(1);
15204   SDValue Handler   = Op.getOperand(2);
15205   SDLoc dl      (Op);
15206
15207   EVT PtrVT = getPointerTy();
15208   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15209       DAG.getSubtarget().getRegisterInfo());
15210   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15211   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15212           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15213          "Invalid Frame Register!");
15214   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15215   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15216
15217   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15218                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15219   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15220   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15221                        false, false, 0);
15222   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15223
15224   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15225                      DAG.getRegister(StoreAddrReg, PtrVT));
15226 }
15227
15228 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15229                                                SelectionDAG &DAG) const {
15230   SDLoc DL(Op);
15231   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15232                      DAG.getVTList(MVT::i32, MVT::Other),
15233                      Op.getOperand(0), Op.getOperand(1));
15234 }
15235
15236 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15237                                                 SelectionDAG &DAG) const {
15238   SDLoc DL(Op);
15239   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15240                      Op.getOperand(0), Op.getOperand(1));
15241 }
15242
15243 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15244   return Op.getOperand(0);
15245 }
15246
15247 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15248                                                 SelectionDAG &DAG) const {
15249   SDValue Root = Op.getOperand(0);
15250   SDValue Trmp = Op.getOperand(1); // trampoline
15251   SDValue FPtr = Op.getOperand(2); // nested function
15252   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15253   SDLoc dl (Op);
15254
15255   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15256   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15257
15258   if (Subtarget->is64Bit()) {
15259     SDValue OutChains[6];
15260
15261     // Large code-model.
15262     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15263     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15264
15265     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15266     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15267
15268     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15269
15270     // Load the pointer to the nested function into R11.
15271     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15272     SDValue Addr = Trmp;
15273     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15274                                 Addr, MachinePointerInfo(TrmpAddr),
15275                                 false, false, 0);
15276
15277     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15278                        DAG.getConstant(2, MVT::i64));
15279     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15280                                 MachinePointerInfo(TrmpAddr, 2),
15281                                 false, false, 2);
15282
15283     // Load the 'nest' parameter value into R10.
15284     // R10 is specified in X86CallingConv.td
15285     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15286     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15287                        DAG.getConstant(10, MVT::i64));
15288     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15289                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15290                                 false, false, 0);
15291
15292     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15293                        DAG.getConstant(12, MVT::i64));
15294     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15295                                 MachinePointerInfo(TrmpAddr, 12),
15296                                 false, false, 2);
15297
15298     // Jump to the nested function.
15299     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15300     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15301                        DAG.getConstant(20, MVT::i64));
15302     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15303                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15304                                 false, false, 0);
15305
15306     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15307     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15308                        DAG.getConstant(22, MVT::i64));
15309     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15310                                 MachinePointerInfo(TrmpAddr, 22),
15311                                 false, false, 0);
15312
15313     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15314   } else {
15315     const Function *Func =
15316       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15317     CallingConv::ID CC = Func->getCallingConv();
15318     unsigned NestReg;
15319
15320     switch (CC) {
15321     default:
15322       llvm_unreachable("Unsupported calling convention");
15323     case CallingConv::C:
15324     case CallingConv::X86_StdCall: {
15325       // Pass 'nest' parameter in ECX.
15326       // Must be kept in sync with X86CallingConv.td
15327       NestReg = X86::ECX;
15328
15329       // Check that ECX wasn't needed by an 'inreg' parameter.
15330       FunctionType *FTy = Func->getFunctionType();
15331       const AttributeSet &Attrs = Func->getAttributes();
15332
15333       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15334         unsigned InRegCount = 0;
15335         unsigned Idx = 1;
15336
15337         for (FunctionType::param_iterator I = FTy->param_begin(),
15338              E = FTy->param_end(); I != E; ++I, ++Idx)
15339           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15340             // FIXME: should only count parameters that are lowered to integers.
15341             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15342
15343         if (InRegCount > 2) {
15344           report_fatal_error("Nest register in use - reduce number of inreg"
15345                              " parameters!");
15346         }
15347       }
15348       break;
15349     }
15350     case CallingConv::X86_FastCall:
15351     case CallingConv::X86_ThisCall:
15352     case CallingConv::Fast:
15353       // Pass 'nest' parameter in EAX.
15354       // Must be kept in sync with X86CallingConv.td
15355       NestReg = X86::EAX;
15356       break;
15357     }
15358
15359     SDValue OutChains[4];
15360     SDValue Addr, Disp;
15361
15362     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15363                        DAG.getConstant(10, MVT::i32));
15364     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15365
15366     // This is storing the opcode for MOV32ri.
15367     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15368     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15369     OutChains[0] = DAG.getStore(Root, dl,
15370                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15371                                 Trmp, MachinePointerInfo(TrmpAddr),
15372                                 false, false, 0);
15373
15374     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15375                        DAG.getConstant(1, MVT::i32));
15376     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15377                                 MachinePointerInfo(TrmpAddr, 1),
15378                                 false, false, 1);
15379
15380     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15381     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15382                        DAG.getConstant(5, MVT::i32));
15383     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15384                                 MachinePointerInfo(TrmpAddr, 5),
15385                                 false, false, 1);
15386
15387     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15388                        DAG.getConstant(6, MVT::i32));
15389     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15390                                 MachinePointerInfo(TrmpAddr, 6),
15391                                 false, false, 1);
15392
15393     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15394   }
15395 }
15396
15397 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15398                                             SelectionDAG &DAG) const {
15399   /*
15400    The rounding mode is in bits 11:10 of FPSR, and has the following
15401    settings:
15402      00 Round to nearest
15403      01 Round to -inf
15404      10 Round to +inf
15405      11 Round to 0
15406
15407   FLT_ROUNDS, on the other hand, expects the following:
15408     -1 Undefined
15409      0 Round to 0
15410      1 Round to nearest
15411      2 Round to +inf
15412      3 Round to -inf
15413
15414   To perform the conversion, we do:
15415     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15416   */
15417
15418   MachineFunction &MF = DAG.getMachineFunction();
15419   const TargetMachine &TM = MF.getTarget();
15420   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15421   unsigned StackAlignment = TFI.getStackAlignment();
15422   MVT VT = Op.getSimpleValueType();
15423   SDLoc DL(Op);
15424
15425   // Save FP Control Word to stack slot
15426   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15427   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15428
15429   MachineMemOperand *MMO =
15430    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15431                            MachineMemOperand::MOStore, 2, 2);
15432
15433   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15434   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15435                                           DAG.getVTList(MVT::Other),
15436                                           Ops, MVT::i16, MMO);
15437
15438   // Load FP Control Word from stack slot
15439   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15440                             MachinePointerInfo(), false, false, false, 0);
15441
15442   // Transform as necessary
15443   SDValue CWD1 =
15444     DAG.getNode(ISD::SRL, DL, MVT::i16,
15445                 DAG.getNode(ISD::AND, DL, MVT::i16,
15446                             CWD, DAG.getConstant(0x800, MVT::i16)),
15447                 DAG.getConstant(11, MVT::i8));
15448   SDValue CWD2 =
15449     DAG.getNode(ISD::SRL, DL, MVT::i16,
15450                 DAG.getNode(ISD::AND, DL, MVT::i16,
15451                             CWD, DAG.getConstant(0x400, MVT::i16)),
15452                 DAG.getConstant(9, MVT::i8));
15453
15454   SDValue RetVal =
15455     DAG.getNode(ISD::AND, DL, MVT::i16,
15456                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15457                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15458                             DAG.getConstant(1, MVT::i16)),
15459                 DAG.getConstant(3, MVT::i16));
15460
15461   return DAG.getNode((VT.getSizeInBits() < 16 ?
15462                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15463 }
15464
15465 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15466   MVT VT = Op.getSimpleValueType();
15467   EVT OpVT = VT;
15468   unsigned NumBits = VT.getSizeInBits();
15469   SDLoc dl(Op);
15470
15471   Op = Op.getOperand(0);
15472   if (VT == MVT::i8) {
15473     // Zero extend to i32 since there is not an i8 bsr.
15474     OpVT = MVT::i32;
15475     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15476   }
15477
15478   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15479   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15480   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15481
15482   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15483   SDValue Ops[] = {
15484     Op,
15485     DAG.getConstant(NumBits+NumBits-1, OpVT),
15486     DAG.getConstant(X86::COND_E, MVT::i8),
15487     Op.getValue(1)
15488   };
15489   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15490
15491   // Finally xor with NumBits-1.
15492   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15493
15494   if (VT == MVT::i8)
15495     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15496   return Op;
15497 }
15498
15499 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15500   MVT VT = Op.getSimpleValueType();
15501   EVT OpVT = VT;
15502   unsigned NumBits = VT.getSizeInBits();
15503   SDLoc dl(Op);
15504
15505   Op = Op.getOperand(0);
15506   if (VT == MVT::i8) {
15507     // Zero extend to i32 since there is not an i8 bsr.
15508     OpVT = MVT::i32;
15509     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15510   }
15511
15512   // Issue a bsr (scan bits in reverse).
15513   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15514   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15515
15516   // And xor with NumBits-1.
15517   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15518
15519   if (VT == MVT::i8)
15520     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15521   return Op;
15522 }
15523
15524 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15525   MVT VT = Op.getSimpleValueType();
15526   unsigned NumBits = VT.getSizeInBits();
15527   SDLoc dl(Op);
15528   Op = Op.getOperand(0);
15529
15530   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15531   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15532   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15533
15534   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15535   SDValue Ops[] = {
15536     Op,
15537     DAG.getConstant(NumBits, VT),
15538     DAG.getConstant(X86::COND_E, MVT::i8),
15539     Op.getValue(1)
15540   };
15541   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15542 }
15543
15544 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15545 // ones, and then concatenate the result back.
15546 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15547   MVT VT = Op.getSimpleValueType();
15548
15549   assert(VT.is256BitVector() && VT.isInteger() &&
15550          "Unsupported value type for operation");
15551
15552   unsigned NumElems = VT.getVectorNumElements();
15553   SDLoc dl(Op);
15554
15555   // Extract the LHS vectors
15556   SDValue LHS = Op.getOperand(0);
15557   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15558   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15559
15560   // Extract the RHS vectors
15561   SDValue RHS = Op.getOperand(1);
15562   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15563   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15564
15565   MVT EltVT = VT.getVectorElementType();
15566   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15567
15568   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15569                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15570                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15571 }
15572
15573 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15574   assert(Op.getSimpleValueType().is256BitVector() &&
15575          Op.getSimpleValueType().isInteger() &&
15576          "Only handle AVX 256-bit vector integer operation");
15577   return Lower256IntArith(Op, DAG);
15578 }
15579
15580 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15581   assert(Op.getSimpleValueType().is256BitVector() &&
15582          Op.getSimpleValueType().isInteger() &&
15583          "Only handle AVX 256-bit vector integer operation");
15584   return Lower256IntArith(Op, DAG);
15585 }
15586
15587 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15588                         SelectionDAG &DAG) {
15589   SDLoc dl(Op);
15590   MVT VT = Op.getSimpleValueType();
15591
15592   // Decompose 256-bit ops into smaller 128-bit ops.
15593   if (VT.is256BitVector() && !Subtarget->hasInt256())
15594     return Lower256IntArith(Op, DAG);
15595
15596   SDValue A = Op.getOperand(0);
15597   SDValue B = Op.getOperand(1);
15598
15599   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15600   if (VT == MVT::v4i32) {
15601     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15602            "Should not custom lower when pmuldq is available!");
15603
15604     // Extract the odd parts.
15605     static const int UnpackMask[] = { 1, -1, 3, -1 };
15606     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15607     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15608
15609     // Multiply the even parts.
15610     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15611     // Now multiply odd parts.
15612     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15613
15614     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15615     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15616
15617     // Merge the two vectors back together with a shuffle. This expands into 2
15618     // shuffles.
15619     static const int ShufMask[] = { 0, 4, 2, 6 };
15620     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15621   }
15622
15623   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15624          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15625
15626   //  Ahi = psrlqi(a, 32);
15627   //  Bhi = psrlqi(b, 32);
15628   //
15629   //  AloBlo = pmuludq(a, b);
15630   //  AloBhi = pmuludq(a, Bhi);
15631   //  AhiBlo = pmuludq(Ahi, b);
15632
15633   //  AloBhi = psllqi(AloBhi, 32);
15634   //  AhiBlo = psllqi(AhiBlo, 32);
15635   //  return AloBlo + AloBhi + AhiBlo;
15636
15637   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15638   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15639
15640   // Bit cast to 32-bit vectors for MULUDQ
15641   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15642                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15643   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15644   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15645   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15646   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15647
15648   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15649   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15650   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15651
15652   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15653   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15654
15655   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15656   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15657 }
15658
15659 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15660   assert(Subtarget->isTargetWin64() && "Unexpected target");
15661   EVT VT = Op.getValueType();
15662   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15663          "Unexpected return type for lowering");
15664
15665   RTLIB::Libcall LC;
15666   bool isSigned;
15667   switch (Op->getOpcode()) {
15668   default: llvm_unreachable("Unexpected request for libcall!");
15669   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15670   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15671   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15672   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15673   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15674   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15675   }
15676
15677   SDLoc dl(Op);
15678   SDValue InChain = DAG.getEntryNode();
15679
15680   TargetLowering::ArgListTy Args;
15681   TargetLowering::ArgListEntry Entry;
15682   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15683     EVT ArgVT = Op->getOperand(i).getValueType();
15684     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15685            "Unexpected argument type for lowering");
15686     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15687     Entry.Node = StackPtr;
15688     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15689                            false, false, 16);
15690     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15691     Entry.Ty = PointerType::get(ArgTy,0);
15692     Entry.isSExt = false;
15693     Entry.isZExt = false;
15694     Args.push_back(Entry);
15695   }
15696
15697   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15698                                          getPointerTy());
15699
15700   TargetLowering::CallLoweringInfo CLI(DAG);
15701   CLI.setDebugLoc(dl).setChain(InChain)
15702     .setCallee(getLibcallCallingConv(LC),
15703                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15704                Callee, std::move(Args), 0)
15705     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15706
15707   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15708   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15709 }
15710
15711 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15712                              SelectionDAG &DAG) {
15713   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15714   EVT VT = Op0.getValueType();
15715   SDLoc dl(Op);
15716
15717   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15718          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15719
15720   // PMULxD operations multiply each even value (starting at 0) of LHS with
15721   // the related value of RHS and produce a widen result.
15722   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15723   // => <2 x i64> <ae|cg>
15724   //
15725   // In other word, to have all the results, we need to perform two PMULxD:
15726   // 1. one with the even values.
15727   // 2. one with the odd values.
15728   // To achieve #2, with need to place the odd values at an even position.
15729   //
15730   // Place the odd value at an even position (basically, shift all values 1
15731   // step to the left):
15732   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15733   // <a|b|c|d> => <b|undef|d|undef>
15734   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15735   // <e|f|g|h> => <f|undef|h|undef>
15736   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15737
15738   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15739   // ints.
15740   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15741   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15742   unsigned Opcode =
15743       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15744   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15745   // => <2 x i64> <ae|cg>
15746   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15747                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15748   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15749   // => <2 x i64> <bf|dh>
15750   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15751                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15752
15753   // Shuffle it back into the right order.
15754   SDValue Highs, Lows;
15755   if (VT == MVT::v8i32) {
15756     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15757     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15758     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15759     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15760   } else {
15761     const int HighMask[] = {1, 5, 3, 7};
15762     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15763     const int LowMask[] = {1, 4, 2, 6};
15764     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15765   }
15766
15767   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15768   // unsigned multiply.
15769   if (IsSigned && !Subtarget->hasSSE41()) {
15770     SDValue ShAmt =
15771         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15772     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15773                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15774     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15775                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15776
15777     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15778     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15779   }
15780
15781   // The first result of MUL_LOHI is actually the low value, followed by the
15782   // high value.
15783   SDValue Ops[] = {Lows, Highs};
15784   return DAG.getMergeValues(Ops, dl);
15785 }
15786
15787 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15788                                          const X86Subtarget *Subtarget) {
15789   MVT VT = Op.getSimpleValueType();
15790   SDLoc dl(Op);
15791   SDValue R = Op.getOperand(0);
15792   SDValue Amt = Op.getOperand(1);
15793
15794   // Optimize shl/srl/sra with constant shift amount.
15795   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15796     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15797       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15798
15799       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15800           (Subtarget->hasInt256() &&
15801            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15802           (Subtarget->hasAVX512() &&
15803            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15804         if (Op.getOpcode() == ISD::SHL)
15805           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15806                                             DAG);
15807         if (Op.getOpcode() == ISD::SRL)
15808           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15809                                             DAG);
15810         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15811           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15812                                             DAG);
15813       }
15814
15815       if (VT == MVT::v16i8) {
15816         if (Op.getOpcode() == ISD::SHL) {
15817           // Make a large shift.
15818           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15819                                                    MVT::v8i16, R, ShiftAmt,
15820                                                    DAG);
15821           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15822           // Zero out the rightmost bits.
15823           SmallVector<SDValue, 16> V(16,
15824                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15825                                                      MVT::i8));
15826           return DAG.getNode(ISD::AND, dl, VT, SHL,
15827                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15828         }
15829         if (Op.getOpcode() == ISD::SRL) {
15830           // Make a large shift.
15831           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15832                                                    MVT::v8i16, R, ShiftAmt,
15833                                                    DAG);
15834           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15835           // Zero out the leftmost bits.
15836           SmallVector<SDValue, 16> V(16,
15837                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15838                                                      MVT::i8));
15839           return DAG.getNode(ISD::AND, dl, VT, SRL,
15840                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15841         }
15842         if (Op.getOpcode() == ISD::SRA) {
15843           if (ShiftAmt == 7) {
15844             // R s>> 7  ===  R s< 0
15845             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15846             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15847           }
15848
15849           // R s>> a === ((R u>> a) ^ m) - m
15850           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15851           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15852                                                          MVT::i8));
15853           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15854           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15855           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15856           return Res;
15857         }
15858         llvm_unreachable("Unknown shift opcode.");
15859       }
15860
15861       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15862         if (Op.getOpcode() == ISD::SHL) {
15863           // Make a large shift.
15864           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15865                                                    MVT::v16i16, R, ShiftAmt,
15866                                                    DAG);
15867           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15868           // Zero out the rightmost bits.
15869           SmallVector<SDValue, 32> V(32,
15870                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15871                                                      MVT::i8));
15872           return DAG.getNode(ISD::AND, dl, VT, SHL,
15873                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15874         }
15875         if (Op.getOpcode() == ISD::SRL) {
15876           // Make a large shift.
15877           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15878                                                    MVT::v16i16, R, ShiftAmt,
15879                                                    DAG);
15880           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15881           // Zero out the leftmost bits.
15882           SmallVector<SDValue, 32> V(32,
15883                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15884                                                      MVT::i8));
15885           return DAG.getNode(ISD::AND, dl, VT, SRL,
15886                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15887         }
15888         if (Op.getOpcode() == ISD::SRA) {
15889           if (ShiftAmt == 7) {
15890             // R s>> 7  ===  R s< 0
15891             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15892             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15893           }
15894
15895           // R s>> a === ((R u>> a) ^ m) - m
15896           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15897           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15898                                                          MVT::i8));
15899           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15900           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15901           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15902           return Res;
15903         }
15904         llvm_unreachable("Unknown shift opcode.");
15905       }
15906     }
15907   }
15908
15909   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15910   if (!Subtarget->is64Bit() &&
15911       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15912       Amt.getOpcode() == ISD::BITCAST &&
15913       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15914     Amt = Amt.getOperand(0);
15915     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15916                      VT.getVectorNumElements();
15917     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15918     uint64_t ShiftAmt = 0;
15919     for (unsigned i = 0; i != Ratio; ++i) {
15920       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15921       if (!C)
15922         return SDValue();
15923       // 6 == Log2(64)
15924       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15925     }
15926     // Check remaining shift amounts.
15927     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15928       uint64_t ShAmt = 0;
15929       for (unsigned j = 0; j != Ratio; ++j) {
15930         ConstantSDNode *C =
15931           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15932         if (!C)
15933           return SDValue();
15934         // 6 == Log2(64)
15935         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15936       }
15937       if (ShAmt != ShiftAmt)
15938         return SDValue();
15939     }
15940     switch (Op.getOpcode()) {
15941     default:
15942       llvm_unreachable("Unknown shift opcode!");
15943     case ISD::SHL:
15944       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15945                                         DAG);
15946     case ISD::SRL:
15947       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15948                                         DAG);
15949     case ISD::SRA:
15950       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15951                                         DAG);
15952     }
15953   }
15954
15955   return SDValue();
15956 }
15957
15958 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15959                                         const X86Subtarget* Subtarget) {
15960   MVT VT = Op.getSimpleValueType();
15961   SDLoc dl(Op);
15962   SDValue R = Op.getOperand(0);
15963   SDValue Amt = Op.getOperand(1);
15964
15965   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15966       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15967       (Subtarget->hasInt256() &&
15968        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15969         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15970        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15971     SDValue BaseShAmt;
15972     EVT EltVT = VT.getVectorElementType();
15973
15974     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15975       unsigned NumElts = VT.getVectorNumElements();
15976       unsigned i, j;
15977       for (i = 0; i != NumElts; ++i) {
15978         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15979           continue;
15980         break;
15981       }
15982       for (j = i; j != NumElts; ++j) {
15983         SDValue Arg = Amt.getOperand(j);
15984         if (Arg.getOpcode() == ISD::UNDEF) continue;
15985         if (Arg != Amt.getOperand(i))
15986           break;
15987       }
15988       if (i != NumElts && j == NumElts)
15989         BaseShAmt = Amt.getOperand(i);
15990     } else {
15991       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15992         Amt = Amt.getOperand(0);
15993       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15994                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15995         SDValue InVec = Amt.getOperand(0);
15996         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15997           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15998           unsigned i = 0;
15999           for (; i != NumElts; ++i) {
16000             SDValue Arg = InVec.getOperand(i);
16001             if (Arg.getOpcode() == ISD::UNDEF) continue;
16002             BaseShAmt = Arg;
16003             break;
16004           }
16005         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16006            if (ConstantSDNode *C =
16007                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16008              unsigned SplatIdx =
16009                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16010              if (C->getZExtValue() == SplatIdx)
16011                BaseShAmt = InVec.getOperand(1);
16012            }
16013         }
16014         if (!BaseShAmt.getNode())
16015           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16016                                   DAG.getIntPtrConstant(0));
16017       }
16018     }
16019
16020     if (BaseShAmt.getNode()) {
16021       if (EltVT.bitsGT(MVT::i32))
16022         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16023       else if (EltVT.bitsLT(MVT::i32))
16024         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16025
16026       switch (Op.getOpcode()) {
16027       default:
16028         llvm_unreachable("Unknown shift opcode!");
16029       case ISD::SHL:
16030         switch (VT.SimpleTy) {
16031         default: return SDValue();
16032         case MVT::v2i64:
16033         case MVT::v4i32:
16034         case MVT::v8i16:
16035         case MVT::v4i64:
16036         case MVT::v8i32:
16037         case MVT::v16i16:
16038         case MVT::v16i32:
16039         case MVT::v8i64:
16040           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16041         }
16042       case ISD::SRA:
16043         switch (VT.SimpleTy) {
16044         default: return SDValue();
16045         case MVT::v4i32:
16046         case MVT::v8i16:
16047         case MVT::v8i32:
16048         case MVT::v16i16:
16049         case MVT::v16i32:
16050         case MVT::v8i64:
16051           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16052         }
16053       case ISD::SRL:
16054         switch (VT.SimpleTy) {
16055         default: return SDValue();
16056         case MVT::v2i64:
16057         case MVT::v4i32:
16058         case MVT::v8i16:
16059         case MVT::v4i64:
16060         case MVT::v8i32:
16061         case MVT::v16i16:
16062         case MVT::v16i32:
16063         case MVT::v8i64:
16064           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16065         }
16066       }
16067     }
16068   }
16069
16070   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16071   if (!Subtarget->is64Bit() &&
16072       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16073       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16074       Amt.getOpcode() == ISD::BITCAST &&
16075       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16076     Amt = Amt.getOperand(0);
16077     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16078                      VT.getVectorNumElements();
16079     std::vector<SDValue> Vals(Ratio);
16080     for (unsigned i = 0; i != Ratio; ++i)
16081       Vals[i] = Amt.getOperand(i);
16082     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16083       for (unsigned j = 0; j != Ratio; ++j)
16084         if (Vals[j] != Amt.getOperand(i + j))
16085           return SDValue();
16086     }
16087     switch (Op.getOpcode()) {
16088     default:
16089       llvm_unreachable("Unknown shift opcode!");
16090     case ISD::SHL:
16091       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16092     case ISD::SRL:
16093       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16094     case ISD::SRA:
16095       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16096     }
16097   }
16098
16099   return SDValue();
16100 }
16101
16102 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16103                           SelectionDAG &DAG) {
16104   MVT VT = Op.getSimpleValueType();
16105   SDLoc dl(Op);
16106   SDValue R = Op.getOperand(0);
16107   SDValue Amt = Op.getOperand(1);
16108   SDValue V;
16109
16110   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16111   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16112
16113   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16114   if (V.getNode())
16115     return V;
16116
16117   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16118   if (V.getNode())
16119       return V;
16120
16121   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16122     return Op;
16123   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16124   if (Subtarget->hasInt256()) {
16125     if (Op.getOpcode() == ISD::SRL &&
16126         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16127          VT == MVT::v4i64 || VT == MVT::v8i32))
16128       return Op;
16129     if (Op.getOpcode() == ISD::SHL &&
16130         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16131          VT == MVT::v4i64 || VT == MVT::v8i32))
16132       return Op;
16133     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16134       return Op;
16135   }
16136
16137   // If possible, lower this packed shift into a vector multiply instead of
16138   // expanding it into a sequence of scalar shifts.
16139   // Do this only if the vector shift count is a constant build_vector.
16140   if (Op.getOpcode() == ISD::SHL && 
16141       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16142        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16143       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16144     SmallVector<SDValue, 8> Elts;
16145     EVT SVT = VT.getScalarType();
16146     unsigned SVTBits = SVT.getSizeInBits();
16147     const APInt &One = APInt(SVTBits, 1);
16148     unsigned NumElems = VT.getVectorNumElements();
16149
16150     for (unsigned i=0; i !=NumElems; ++i) {
16151       SDValue Op = Amt->getOperand(i);
16152       if (Op->getOpcode() == ISD::UNDEF) {
16153         Elts.push_back(Op);
16154         continue;
16155       }
16156
16157       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16158       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16159       uint64_t ShAmt = C.getZExtValue();
16160       if (ShAmt >= SVTBits) {
16161         Elts.push_back(DAG.getUNDEF(SVT));
16162         continue;
16163       }
16164       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16165     }
16166     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16167     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16168   }
16169
16170   // Lower SHL with variable shift amount.
16171   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16172     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16173
16174     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16175     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16176     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16177     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16178   }
16179
16180   // If possible, lower this shift as a sequence of two shifts by
16181   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16182   // Example:
16183   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16184   //
16185   // Could be rewritten as:
16186   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16187   //
16188   // The advantage is that the two shifts from the example would be
16189   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16190   // the vector shift into four scalar shifts plus four pairs of vector
16191   // insert/extract.
16192   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16193       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16194     unsigned TargetOpcode = X86ISD::MOVSS;
16195     bool CanBeSimplified;
16196     // The splat value for the first packed shift (the 'X' from the example).
16197     SDValue Amt1 = Amt->getOperand(0);
16198     // The splat value for the second packed shift (the 'Y' from the example).
16199     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16200                                         Amt->getOperand(2);
16201
16202     // See if it is possible to replace this node with a sequence of
16203     // two shifts followed by a MOVSS/MOVSD
16204     if (VT == MVT::v4i32) {
16205       // Check if it is legal to use a MOVSS.
16206       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16207                         Amt2 == Amt->getOperand(3);
16208       if (!CanBeSimplified) {
16209         // Otherwise, check if we can still simplify this node using a MOVSD.
16210         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16211                           Amt->getOperand(2) == Amt->getOperand(3);
16212         TargetOpcode = X86ISD::MOVSD;
16213         Amt2 = Amt->getOperand(2);
16214       }
16215     } else {
16216       // Do similar checks for the case where the machine value type
16217       // is MVT::v8i16.
16218       CanBeSimplified = Amt1 == Amt->getOperand(1);
16219       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16220         CanBeSimplified = Amt2 == Amt->getOperand(i);
16221
16222       if (!CanBeSimplified) {
16223         TargetOpcode = X86ISD::MOVSD;
16224         CanBeSimplified = true;
16225         Amt2 = Amt->getOperand(4);
16226         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16227           CanBeSimplified = Amt1 == Amt->getOperand(i);
16228         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16229           CanBeSimplified = Amt2 == Amt->getOperand(j);
16230       }
16231     }
16232     
16233     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16234         isa<ConstantSDNode>(Amt2)) {
16235       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16236       EVT CastVT = MVT::v4i32;
16237       SDValue Splat1 = 
16238         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16239       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16240       SDValue Splat2 = 
16241         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16242       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16243       if (TargetOpcode == X86ISD::MOVSD)
16244         CastVT = MVT::v2i64;
16245       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16246       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16247       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16248                                             BitCast1, DAG);
16249       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16250     }
16251   }
16252
16253   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16254     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16255
16256     // a = a << 5;
16257     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16258     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16259
16260     // Turn 'a' into a mask suitable for VSELECT
16261     SDValue VSelM = DAG.getConstant(0x80, VT);
16262     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16263     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16264
16265     SDValue CM1 = DAG.getConstant(0x0f, VT);
16266     SDValue CM2 = DAG.getConstant(0x3f, VT);
16267
16268     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16269     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16270     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16271     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16272     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16273
16274     // a += a
16275     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16276     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16277     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16278
16279     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16280     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16281     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16282     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16283     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16284
16285     // a += a
16286     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16287     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16288     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16289
16290     // return VSELECT(r, r+r, a);
16291     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16292                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16293     return R;
16294   }
16295
16296   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16297   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16298   // solution better.
16299   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16300     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16301     unsigned ExtOpc =
16302         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16303     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16304     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16305     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16306                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16307     }
16308
16309   // Decompose 256-bit shifts into smaller 128-bit shifts.
16310   if (VT.is256BitVector()) {
16311     unsigned NumElems = VT.getVectorNumElements();
16312     MVT EltVT = VT.getVectorElementType();
16313     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16314
16315     // Extract the two vectors
16316     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16317     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16318
16319     // Recreate the shift amount vectors
16320     SDValue Amt1, Amt2;
16321     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16322       // Constant shift amount
16323       SmallVector<SDValue, 4> Amt1Csts;
16324       SmallVector<SDValue, 4> Amt2Csts;
16325       for (unsigned i = 0; i != NumElems/2; ++i)
16326         Amt1Csts.push_back(Amt->getOperand(i));
16327       for (unsigned i = NumElems/2; i != NumElems; ++i)
16328         Amt2Csts.push_back(Amt->getOperand(i));
16329
16330       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16331       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16332     } else {
16333       // Variable shift amount
16334       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16335       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16336     }
16337
16338     // Issue new vector shifts for the smaller types
16339     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16340     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16341
16342     // Concatenate the result back
16343     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16344   }
16345
16346   return SDValue();
16347 }
16348
16349 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16350   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16351   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16352   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16353   // has only one use.
16354   SDNode *N = Op.getNode();
16355   SDValue LHS = N->getOperand(0);
16356   SDValue RHS = N->getOperand(1);
16357   unsigned BaseOp = 0;
16358   unsigned Cond = 0;
16359   SDLoc DL(Op);
16360   switch (Op.getOpcode()) {
16361   default: llvm_unreachable("Unknown ovf instruction!");
16362   case ISD::SADDO:
16363     // A subtract of one will be selected as a INC. Note that INC doesn't
16364     // set CF, so we can't do this for UADDO.
16365     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16366       if (C->isOne()) {
16367         BaseOp = X86ISD::INC;
16368         Cond = X86::COND_O;
16369         break;
16370       }
16371     BaseOp = X86ISD::ADD;
16372     Cond = X86::COND_O;
16373     break;
16374   case ISD::UADDO:
16375     BaseOp = X86ISD::ADD;
16376     Cond = X86::COND_B;
16377     break;
16378   case ISD::SSUBO:
16379     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16380     // set CF, so we can't do this for USUBO.
16381     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16382       if (C->isOne()) {
16383         BaseOp = X86ISD::DEC;
16384         Cond = X86::COND_O;
16385         break;
16386       }
16387     BaseOp = X86ISD::SUB;
16388     Cond = X86::COND_O;
16389     break;
16390   case ISD::USUBO:
16391     BaseOp = X86ISD::SUB;
16392     Cond = X86::COND_B;
16393     break;
16394   case ISD::SMULO:
16395     BaseOp = X86ISD::SMUL;
16396     Cond = X86::COND_O;
16397     break;
16398   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16399     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16400                                  MVT::i32);
16401     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16402
16403     SDValue SetCC =
16404       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16405                   DAG.getConstant(X86::COND_O, MVT::i32),
16406                   SDValue(Sum.getNode(), 2));
16407
16408     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16409   }
16410   }
16411
16412   // Also sets EFLAGS.
16413   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16414   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16415
16416   SDValue SetCC =
16417     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16418                 DAG.getConstant(Cond, MVT::i32),
16419                 SDValue(Sum.getNode(), 1));
16420
16421   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16422 }
16423
16424 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16425                                                   SelectionDAG &DAG) const {
16426   SDLoc dl(Op);
16427   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16428   MVT VT = Op.getSimpleValueType();
16429
16430   if (!Subtarget->hasSSE2() || !VT.isVector())
16431     return SDValue();
16432
16433   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16434                       ExtraVT.getScalarType().getSizeInBits();
16435
16436   switch (VT.SimpleTy) {
16437     default: return SDValue();
16438     case MVT::v8i32:
16439     case MVT::v16i16:
16440       if (!Subtarget->hasFp256())
16441         return SDValue();
16442       if (!Subtarget->hasInt256()) {
16443         // needs to be split
16444         unsigned NumElems = VT.getVectorNumElements();
16445
16446         // Extract the LHS vectors
16447         SDValue LHS = Op.getOperand(0);
16448         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16449         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16450
16451         MVT EltVT = VT.getVectorElementType();
16452         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16453
16454         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16455         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16456         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16457                                    ExtraNumElems/2);
16458         SDValue Extra = DAG.getValueType(ExtraVT);
16459
16460         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16461         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16462
16463         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16464       }
16465       // fall through
16466     case MVT::v4i32:
16467     case MVT::v8i16: {
16468       SDValue Op0 = Op.getOperand(0);
16469       SDValue Op00 = Op0.getOperand(0);
16470       SDValue Tmp1;
16471       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16472       if (Op0.getOpcode() == ISD::BITCAST &&
16473           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16474         // (sext (vzext x)) -> (vsext x)
16475         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16476         if (Tmp1.getNode()) {
16477           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16478           // This folding is only valid when the in-reg type is a vector of i8,
16479           // i16, or i32.
16480           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16481               ExtraEltVT == MVT::i32) {
16482             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16483             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16484                    "This optimization is invalid without a VZEXT.");
16485             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16486           }
16487           Op0 = Tmp1;
16488         }
16489       }
16490
16491       // If the above didn't work, then just use Shift-Left + Shift-Right.
16492       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16493                                         DAG);
16494       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16495                                         DAG);
16496     }
16497   }
16498 }
16499
16500 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16501                                  SelectionDAG &DAG) {
16502   SDLoc dl(Op);
16503   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16504     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16505   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16506     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16507
16508   // The only fence that needs an instruction is a sequentially-consistent
16509   // cross-thread fence.
16510   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16511     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16512     // no-sse2). There isn't any reason to disable it if the target processor
16513     // supports it.
16514     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16515       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16516
16517     SDValue Chain = Op.getOperand(0);
16518     SDValue Zero = DAG.getConstant(0, MVT::i32);
16519     SDValue Ops[] = {
16520       DAG.getRegister(X86::ESP, MVT::i32), // Base
16521       DAG.getTargetConstant(1, MVT::i8),   // Scale
16522       DAG.getRegister(0, MVT::i32),        // Index
16523       DAG.getTargetConstant(0, MVT::i32),  // Disp
16524       DAG.getRegister(0, MVT::i32),        // Segment.
16525       Zero,
16526       Chain
16527     };
16528     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16529     return SDValue(Res, 0);
16530   }
16531
16532   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16533   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16534 }
16535
16536 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16537                              SelectionDAG &DAG) {
16538   MVT T = Op.getSimpleValueType();
16539   SDLoc DL(Op);
16540   unsigned Reg = 0;
16541   unsigned size = 0;
16542   switch(T.SimpleTy) {
16543   default: llvm_unreachable("Invalid value type!");
16544   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16545   case MVT::i16: Reg = X86::AX;  size = 2; break;
16546   case MVT::i32: Reg = X86::EAX; size = 4; break;
16547   case MVT::i64:
16548     assert(Subtarget->is64Bit() && "Node not type legal!");
16549     Reg = X86::RAX; size = 8;
16550     break;
16551   }
16552   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16553                                   Op.getOperand(2), SDValue());
16554   SDValue Ops[] = { cpIn.getValue(0),
16555                     Op.getOperand(1),
16556                     Op.getOperand(3),
16557                     DAG.getTargetConstant(size, MVT::i8),
16558                     cpIn.getValue(1) };
16559   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16560   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16561   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16562                                            Ops, T, MMO);
16563
16564   SDValue cpOut =
16565     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16566   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16567                                       MVT::i32, cpOut.getValue(2));
16568   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16569                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16570
16571   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16572   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16573   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16574   return SDValue();
16575 }
16576
16577 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16578                             SelectionDAG &DAG) {
16579   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16580   MVT DstVT = Op.getSimpleValueType();
16581
16582   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16583     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16584     if (DstVT != MVT::f64)
16585       // This conversion needs to be expanded.
16586       return SDValue();
16587
16588     SDValue InVec = Op->getOperand(0);
16589     SDLoc dl(Op);
16590     unsigned NumElts = SrcVT.getVectorNumElements();
16591     EVT SVT = SrcVT.getVectorElementType();
16592
16593     // Widen the vector in input in the case of MVT::v2i32.
16594     // Example: from MVT::v2i32 to MVT::v4i32.
16595     SmallVector<SDValue, 16> Elts;
16596     for (unsigned i = 0, e = NumElts; i != e; ++i)
16597       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16598                                  DAG.getIntPtrConstant(i)));
16599
16600     // Explicitly mark the extra elements as Undef.
16601     SDValue Undef = DAG.getUNDEF(SVT);
16602     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16603       Elts.push_back(Undef);
16604
16605     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16606     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16607     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16608     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16609                        DAG.getIntPtrConstant(0));
16610   }
16611
16612   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16613          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16614   assert((DstVT == MVT::i64 ||
16615           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16616          "Unexpected custom BITCAST");
16617   // i64 <=> MMX conversions are Legal.
16618   if (SrcVT==MVT::i64 && DstVT.isVector())
16619     return Op;
16620   if (DstVT==MVT::i64 && SrcVT.isVector())
16621     return Op;
16622   // MMX <=> MMX conversions are Legal.
16623   if (SrcVT.isVector() && DstVT.isVector())
16624     return Op;
16625   // All other conversions need to be expanded.
16626   return SDValue();
16627 }
16628
16629 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16630   SDNode *Node = Op.getNode();
16631   SDLoc dl(Node);
16632   EVT T = Node->getValueType(0);
16633   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16634                               DAG.getConstant(0, T), Node->getOperand(2));
16635   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16636                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16637                        Node->getOperand(0),
16638                        Node->getOperand(1), negOp,
16639                        cast<AtomicSDNode>(Node)->getMemOperand(),
16640                        cast<AtomicSDNode>(Node)->getOrdering(),
16641                        cast<AtomicSDNode>(Node)->getSynchScope());
16642 }
16643
16644 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16645   SDNode *Node = Op.getNode();
16646   SDLoc dl(Node);
16647   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16648
16649   // Convert seq_cst store -> xchg
16650   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16651   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16652   //        (The only way to get a 16-byte store is cmpxchg16b)
16653   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16654   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16655       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16656     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16657                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16658                                  Node->getOperand(0),
16659                                  Node->getOperand(1), Node->getOperand(2),
16660                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16661                                  cast<AtomicSDNode>(Node)->getOrdering(),
16662                                  cast<AtomicSDNode>(Node)->getSynchScope());
16663     return Swap.getValue(1);
16664   }
16665   // Other atomic stores have a simple pattern.
16666   return Op;
16667 }
16668
16669 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16670   EVT VT = Op.getNode()->getSimpleValueType(0);
16671
16672   // Let legalize expand this if it isn't a legal type yet.
16673   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16674     return SDValue();
16675
16676   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16677
16678   unsigned Opc;
16679   bool ExtraOp = false;
16680   switch (Op.getOpcode()) {
16681   default: llvm_unreachable("Invalid code");
16682   case ISD::ADDC: Opc = X86ISD::ADD; break;
16683   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16684   case ISD::SUBC: Opc = X86ISD::SUB; break;
16685   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16686   }
16687
16688   if (!ExtraOp)
16689     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16690                        Op.getOperand(1));
16691   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16692                      Op.getOperand(1), Op.getOperand(2));
16693 }
16694
16695 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16696                             SelectionDAG &DAG) {
16697   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16698
16699   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16700   // which returns the values as { float, float } (in XMM0) or
16701   // { double, double } (which is returned in XMM0, XMM1).
16702   SDLoc dl(Op);
16703   SDValue Arg = Op.getOperand(0);
16704   EVT ArgVT = Arg.getValueType();
16705   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16706
16707   TargetLowering::ArgListTy Args;
16708   TargetLowering::ArgListEntry Entry;
16709
16710   Entry.Node = Arg;
16711   Entry.Ty = ArgTy;
16712   Entry.isSExt = false;
16713   Entry.isZExt = false;
16714   Args.push_back(Entry);
16715
16716   bool isF64 = ArgVT == MVT::f64;
16717   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16718   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16719   // the results are returned via SRet in memory.
16720   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16721   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16722   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16723
16724   Type *RetTy = isF64
16725     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16726     : (Type*)VectorType::get(ArgTy, 4);
16727
16728   TargetLowering::CallLoweringInfo CLI(DAG);
16729   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16730     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16731
16732   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16733
16734   if (isF64)
16735     // Returned in xmm0 and xmm1.
16736     return CallResult.first;
16737
16738   // Returned in bits 0:31 and 32:64 xmm0.
16739   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16740                                CallResult.first, DAG.getIntPtrConstant(0));
16741   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16742                                CallResult.first, DAG.getIntPtrConstant(1));
16743   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16744   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16745 }
16746
16747 /// LowerOperation - Provide custom lowering hooks for some operations.
16748 ///
16749 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16750   switch (Op.getOpcode()) {
16751   default: llvm_unreachable("Should not custom lower this!");
16752   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16753   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16754   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16755     return LowerCMP_SWAP(Op, Subtarget, DAG);
16756   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16757   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16758   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16759   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16760   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16761   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16762   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16763   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16764   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16765   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16766   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16767   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16768   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16769   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16770   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16771   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16772   case ISD::SHL_PARTS:
16773   case ISD::SRA_PARTS:
16774   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16775   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16776   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16777   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16778   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16779   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16780   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16781   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16782   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16783   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16784   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16785   case ISD::FABS:               return LowerFABS(Op, DAG);
16786   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16787   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16788   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16789   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16790   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16791   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16792   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16793   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16794   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16795   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16796   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16797   case ISD::INTRINSIC_VOID:
16798   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16799   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16800   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16801   case ISD::FRAME_TO_ARGS_OFFSET:
16802                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16803   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16804   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16805   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16806   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16807   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16808   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16809   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16810   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16811   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16812   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16813   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16814   case ISD::UMUL_LOHI:
16815   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16816   case ISD::SRA:
16817   case ISD::SRL:
16818   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16819   case ISD::SADDO:
16820   case ISD::UADDO:
16821   case ISD::SSUBO:
16822   case ISD::USUBO:
16823   case ISD::SMULO:
16824   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16825   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16826   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16827   case ISD::ADDC:
16828   case ISD::ADDE:
16829   case ISD::SUBC:
16830   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16831   case ISD::ADD:                return LowerADD(Op, DAG);
16832   case ISD::SUB:                return LowerSUB(Op, DAG);
16833   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16834   }
16835 }
16836
16837 static void ReplaceATOMIC_LOAD(SDNode *Node,
16838                                SmallVectorImpl<SDValue> &Results,
16839                                SelectionDAG &DAG) {
16840   SDLoc dl(Node);
16841   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16842
16843   // Convert wide load -> cmpxchg8b/cmpxchg16b
16844   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16845   //        (The only way to get a 16-byte load is cmpxchg16b)
16846   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16847   SDValue Zero = DAG.getConstant(0, VT);
16848   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16849   SDValue Swap =
16850       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16851                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16852                            cast<AtomicSDNode>(Node)->getMemOperand(),
16853                            cast<AtomicSDNode>(Node)->getOrdering(),
16854                            cast<AtomicSDNode>(Node)->getOrdering(),
16855                            cast<AtomicSDNode>(Node)->getSynchScope());
16856   Results.push_back(Swap.getValue(0));
16857   Results.push_back(Swap.getValue(2));
16858 }
16859
16860 /// ReplaceNodeResults - Replace a node with an illegal result type
16861 /// with a new node built out of custom code.
16862 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16863                                            SmallVectorImpl<SDValue>&Results,
16864                                            SelectionDAG &DAG) const {
16865   SDLoc dl(N);
16866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16867   switch (N->getOpcode()) {
16868   default:
16869     llvm_unreachable("Do not know how to custom type legalize this operation!");
16870   case ISD::SIGN_EXTEND_INREG:
16871   case ISD::ADDC:
16872   case ISD::ADDE:
16873   case ISD::SUBC:
16874   case ISD::SUBE:
16875     // We don't want to expand or promote these.
16876     return;
16877   case ISD::SDIV:
16878   case ISD::UDIV:
16879   case ISD::SREM:
16880   case ISD::UREM:
16881   case ISD::SDIVREM:
16882   case ISD::UDIVREM: {
16883     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16884     Results.push_back(V);
16885     return;
16886   }
16887   case ISD::FP_TO_SINT:
16888   case ISD::FP_TO_UINT: {
16889     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16890
16891     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16892       return;
16893
16894     std::pair<SDValue,SDValue> Vals =
16895         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16896     SDValue FIST = Vals.first, StackSlot = Vals.second;
16897     if (FIST.getNode()) {
16898       EVT VT = N->getValueType(0);
16899       // Return a load from the stack slot.
16900       if (StackSlot.getNode())
16901         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16902                                       MachinePointerInfo(),
16903                                       false, false, false, 0));
16904       else
16905         Results.push_back(FIST);
16906     }
16907     return;
16908   }
16909   case ISD::UINT_TO_FP: {
16910     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16911     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16912         N->getValueType(0) != MVT::v2f32)
16913       return;
16914     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16915                                  N->getOperand(0));
16916     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16917                                      MVT::f64);
16918     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16919     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16920                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16921     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16922     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16923     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16924     return;
16925   }
16926   case ISD::FP_ROUND: {
16927     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16928         return;
16929     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16930     Results.push_back(V);
16931     return;
16932   }
16933   case ISD::INTRINSIC_W_CHAIN: {
16934     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16935     switch (IntNo) {
16936     default : llvm_unreachable("Do not know how to custom type "
16937                                "legalize this intrinsic operation!");
16938     case Intrinsic::x86_rdtsc:
16939       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16940                                      Results);
16941     case Intrinsic::x86_rdtscp:
16942       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16943                                      Results);
16944     case Intrinsic::x86_rdpmc:
16945       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16946     }
16947   }
16948   case ISD::READCYCLECOUNTER: {
16949     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16950                                    Results);
16951   }
16952   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16953     EVT T = N->getValueType(0);
16954     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16955     bool Regs64bit = T == MVT::i128;
16956     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16957     SDValue cpInL, cpInH;
16958     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16959                         DAG.getConstant(0, HalfT));
16960     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16961                         DAG.getConstant(1, HalfT));
16962     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16963                              Regs64bit ? X86::RAX : X86::EAX,
16964                              cpInL, SDValue());
16965     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16966                              Regs64bit ? X86::RDX : X86::EDX,
16967                              cpInH, cpInL.getValue(1));
16968     SDValue swapInL, swapInH;
16969     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16970                           DAG.getConstant(0, HalfT));
16971     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16972                           DAG.getConstant(1, HalfT));
16973     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16974                                Regs64bit ? X86::RBX : X86::EBX,
16975                                swapInL, cpInH.getValue(1));
16976     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16977                                Regs64bit ? X86::RCX : X86::ECX,
16978                                swapInH, swapInL.getValue(1));
16979     SDValue Ops[] = { swapInH.getValue(0),
16980                       N->getOperand(1),
16981                       swapInH.getValue(1) };
16982     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16983     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16984     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16985                                   X86ISD::LCMPXCHG8_DAG;
16986     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16987     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16988                                         Regs64bit ? X86::RAX : X86::EAX,
16989                                         HalfT, Result.getValue(1));
16990     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16991                                         Regs64bit ? X86::RDX : X86::EDX,
16992                                         HalfT, cpOutL.getValue(2));
16993     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16994
16995     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16996                                         MVT::i32, cpOutH.getValue(2));
16997     SDValue Success =
16998         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16999                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17000     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17001
17002     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17003     Results.push_back(Success);
17004     Results.push_back(EFLAGS.getValue(1));
17005     return;
17006   }
17007   case ISD::ATOMIC_SWAP:
17008   case ISD::ATOMIC_LOAD_ADD:
17009   case ISD::ATOMIC_LOAD_SUB:
17010   case ISD::ATOMIC_LOAD_AND:
17011   case ISD::ATOMIC_LOAD_OR:
17012   case ISD::ATOMIC_LOAD_XOR:
17013   case ISD::ATOMIC_LOAD_NAND:
17014   case ISD::ATOMIC_LOAD_MIN:
17015   case ISD::ATOMIC_LOAD_MAX:
17016   case ISD::ATOMIC_LOAD_UMIN:
17017   case ISD::ATOMIC_LOAD_UMAX:
17018     // Delegate to generic TypeLegalization. Situations we can really handle
17019     // should have already been dealt with by X86AtomicExpandPass.cpp.
17020     break;
17021   case ISD::ATOMIC_LOAD: {
17022     ReplaceATOMIC_LOAD(N, Results, DAG);
17023     return;
17024   }
17025   case ISD::BITCAST: {
17026     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17027     EVT DstVT = N->getValueType(0);
17028     EVT SrcVT = N->getOperand(0)->getValueType(0);
17029
17030     if (SrcVT != MVT::f64 ||
17031         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17032       return;
17033
17034     unsigned NumElts = DstVT.getVectorNumElements();
17035     EVT SVT = DstVT.getVectorElementType();
17036     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17037     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17038                                    MVT::v2f64, N->getOperand(0));
17039     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17040
17041     if (ExperimentalVectorWideningLegalization) {
17042       // If we are legalizing vectors by widening, we already have the desired
17043       // legal vector type, just return it.
17044       Results.push_back(ToVecInt);
17045       return;
17046     }
17047
17048     SmallVector<SDValue, 8> Elts;
17049     for (unsigned i = 0, e = NumElts; i != e; ++i)
17050       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17051                                    ToVecInt, DAG.getIntPtrConstant(i)));
17052
17053     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17054   }
17055   }
17056 }
17057
17058 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17059   switch (Opcode) {
17060   default: return nullptr;
17061   case X86ISD::BSF:                return "X86ISD::BSF";
17062   case X86ISD::BSR:                return "X86ISD::BSR";
17063   case X86ISD::SHLD:               return "X86ISD::SHLD";
17064   case X86ISD::SHRD:               return "X86ISD::SHRD";
17065   case X86ISD::FAND:               return "X86ISD::FAND";
17066   case X86ISD::FANDN:              return "X86ISD::FANDN";
17067   case X86ISD::FOR:                return "X86ISD::FOR";
17068   case X86ISD::FXOR:               return "X86ISD::FXOR";
17069   case X86ISD::FSRL:               return "X86ISD::FSRL";
17070   case X86ISD::FILD:               return "X86ISD::FILD";
17071   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17072   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17073   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17074   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17075   case X86ISD::FLD:                return "X86ISD::FLD";
17076   case X86ISD::FST:                return "X86ISD::FST";
17077   case X86ISD::CALL:               return "X86ISD::CALL";
17078   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17079   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17080   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17081   case X86ISD::BT:                 return "X86ISD::BT";
17082   case X86ISD::CMP:                return "X86ISD::CMP";
17083   case X86ISD::COMI:               return "X86ISD::COMI";
17084   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17085   case X86ISD::CMPM:               return "X86ISD::CMPM";
17086   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17087   case X86ISD::SETCC:              return "X86ISD::SETCC";
17088   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17089   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17090   case X86ISD::CMOV:               return "X86ISD::CMOV";
17091   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17092   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17093   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17094   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17095   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17096   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17097   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17098   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17099   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17100   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17101   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17102   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17103   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17104   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17105   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17106   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17107   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17108   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17109   case X86ISD::HADD:               return "X86ISD::HADD";
17110   case X86ISD::HSUB:               return "X86ISD::HSUB";
17111   case X86ISD::FHADD:              return "X86ISD::FHADD";
17112   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17113   case X86ISD::UMAX:               return "X86ISD::UMAX";
17114   case X86ISD::UMIN:               return "X86ISD::UMIN";
17115   case X86ISD::SMAX:               return "X86ISD::SMAX";
17116   case X86ISD::SMIN:               return "X86ISD::SMIN";
17117   case X86ISD::FMAX:               return "X86ISD::FMAX";
17118   case X86ISD::FMIN:               return "X86ISD::FMIN";
17119   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17120   case X86ISD::FMINC:              return "X86ISD::FMINC";
17121   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17122   case X86ISD::FRCP:               return "X86ISD::FRCP";
17123   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17124   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17125   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17126   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17127   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17128   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17129   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17130   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17131   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17132   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17133   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17134   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17135   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17136   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17137   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17138   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17139   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17140   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17141   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17142   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17143   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17144   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17145   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17146   case X86ISD::VSHL:               return "X86ISD::VSHL";
17147   case X86ISD::VSRL:               return "X86ISD::VSRL";
17148   case X86ISD::VSRA:               return "X86ISD::VSRA";
17149   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17150   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17151   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17152   case X86ISD::CMPP:               return "X86ISD::CMPP";
17153   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17154   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17155   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17156   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17157   case X86ISD::ADD:                return "X86ISD::ADD";
17158   case X86ISD::SUB:                return "X86ISD::SUB";
17159   case X86ISD::ADC:                return "X86ISD::ADC";
17160   case X86ISD::SBB:                return "X86ISD::SBB";
17161   case X86ISD::SMUL:               return "X86ISD::SMUL";
17162   case X86ISD::UMUL:               return "X86ISD::UMUL";
17163   case X86ISD::INC:                return "X86ISD::INC";
17164   case X86ISD::DEC:                return "X86ISD::DEC";
17165   case X86ISD::OR:                 return "X86ISD::OR";
17166   case X86ISD::XOR:                return "X86ISD::XOR";
17167   case X86ISD::AND:                return "X86ISD::AND";
17168   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17169   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17170   case X86ISD::PTEST:              return "X86ISD::PTEST";
17171   case X86ISD::TESTP:              return "X86ISD::TESTP";
17172   case X86ISD::TESTM:              return "X86ISD::TESTM";
17173   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17174   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17175   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17176   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17177   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17178   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17179   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17180   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17181   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17182   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17183   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17184   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17185   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17186   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17187   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17188   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17189   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17190   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17191   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17192   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17193   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17194   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17195   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17196   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17197   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17198   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17199   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17200   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17201   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17202   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17203   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17204   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17205   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17206   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17207   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17208   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17209   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17210   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17211   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17212   case X86ISD::SAHF:               return "X86ISD::SAHF";
17213   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17214   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17215   case X86ISD::FMADD:              return "X86ISD::FMADD";
17216   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17217   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17218   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17219   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17220   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17221   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17222   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17223   case X86ISD::XTEST:              return "X86ISD::XTEST";
17224   }
17225 }
17226
17227 // isLegalAddressingMode - Return true if the addressing mode represented
17228 // by AM is legal for this target, for a load/store of the specified type.
17229 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17230                                               Type *Ty) const {
17231   // X86 supports extremely general addressing modes.
17232   CodeModel::Model M = getTargetMachine().getCodeModel();
17233   Reloc::Model R = getTargetMachine().getRelocationModel();
17234
17235   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17236   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17237     return false;
17238
17239   if (AM.BaseGV) {
17240     unsigned GVFlags =
17241       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17242
17243     // If a reference to this global requires an extra load, we can't fold it.
17244     if (isGlobalStubReference(GVFlags))
17245       return false;
17246
17247     // If BaseGV requires a register for the PIC base, we cannot also have a
17248     // BaseReg specified.
17249     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17250       return false;
17251
17252     // If lower 4G is not available, then we must use rip-relative addressing.
17253     if ((M != CodeModel::Small || R != Reloc::Static) &&
17254         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17255       return false;
17256   }
17257
17258   switch (AM.Scale) {
17259   case 0:
17260   case 1:
17261   case 2:
17262   case 4:
17263   case 8:
17264     // These scales always work.
17265     break;
17266   case 3:
17267   case 5:
17268   case 9:
17269     // These scales are formed with basereg+scalereg.  Only accept if there is
17270     // no basereg yet.
17271     if (AM.HasBaseReg)
17272       return false;
17273     break;
17274   default:  // Other stuff never works.
17275     return false;
17276   }
17277
17278   return true;
17279 }
17280
17281 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17282   unsigned Bits = Ty->getScalarSizeInBits();
17283
17284   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17285   // particularly cheaper than those without.
17286   if (Bits == 8)
17287     return false;
17288
17289   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17290   // variable shifts just as cheap as scalar ones.
17291   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17292     return false;
17293
17294   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17295   // fully general vector.
17296   return true;
17297 }
17298
17299 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17300   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17301     return false;
17302   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17303   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17304   return NumBits1 > NumBits2;
17305 }
17306
17307 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17308   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17309     return false;
17310
17311   if (!isTypeLegal(EVT::getEVT(Ty1)))
17312     return false;
17313
17314   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17315
17316   // Assuming the caller doesn't have a zeroext or signext return parameter,
17317   // truncation all the way down to i1 is valid.
17318   return true;
17319 }
17320
17321 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17322   return isInt<32>(Imm);
17323 }
17324
17325 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17326   // Can also use sub to handle negated immediates.
17327   return isInt<32>(Imm);
17328 }
17329
17330 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17331   if (!VT1.isInteger() || !VT2.isInteger())
17332     return false;
17333   unsigned NumBits1 = VT1.getSizeInBits();
17334   unsigned NumBits2 = VT2.getSizeInBits();
17335   return NumBits1 > NumBits2;
17336 }
17337
17338 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17339   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17340   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17341 }
17342
17343 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17344   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17345   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17346 }
17347
17348 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17349   EVT VT1 = Val.getValueType();
17350   if (isZExtFree(VT1, VT2))
17351     return true;
17352
17353   if (Val.getOpcode() != ISD::LOAD)
17354     return false;
17355
17356   if (!VT1.isSimple() || !VT1.isInteger() ||
17357       !VT2.isSimple() || !VT2.isInteger())
17358     return false;
17359
17360   switch (VT1.getSimpleVT().SimpleTy) {
17361   default: break;
17362   case MVT::i8:
17363   case MVT::i16:
17364   case MVT::i32:
17365     // X86 has 8, 16, and 32-bit zero-extending loads.
17366     return true;
17367   }
17368
17369   return false;
17370 }
17371
17372 bool
17373 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17374   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17375     return false;
17376
17377   VT = VT.getScalarType();
17378
17379   if (!VT.isSimple())
17380     return false;
17381
17382   switch (VT.getSimpleVT().SimpleTy) {
17383   case MVT::f32:
17384   case MVT::f64:
17385     return true;
17386   default:
17387     break;
17388   }
17389
17390   return false;
17391 }
17392
17393 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17394   // i16 instructions are longer (0x66 prefix) and potentially slower.
17395   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17396 }
17397
17398 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17399 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17400 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17401 /// are assumed to be legal.
17402 bool
17403 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17404                                       EVT VT) const {
17405   if (!VT.isSimple())
17406     return false;
17407
17408   MVT SVT = VT.getSimpleVT();
17409
17410   // Very little shuffling can be done for 64-bit vectors right now.
17411   if (VT.getSizeInBits() == 64)
17412     return false;
17413
17414   // If this is a single-input shuffle with no 128 bit lane crossings we can
17415   // lower it into pshufb.
17416   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17417       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17418     bool isLegal = true;
17419     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17420       if (M[I] >= (int)SVT.getVectorNumElements() ||
17421           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17422         isLegal = false;
17423         break;
17424       }
17425     }
17426     if (isLegal)
17427       return true;
17428   }
17429
17430   // FIXME: blends, shifts.
17431   return (SVT.getVectorNumElements() == 2 ||
17432           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17433           isMOVLMask(M, SVT) ||
17434           isMOVHLPSMask(M, SVT) ||
17435           isSHUFPMask(M, SVT) ||
17436           isPSHUFDMask(M, SVT) ||
17437           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17438           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17439           isPALIGNRMask(M, SVT, Subtarget) ||
17440           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17441           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17442           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17443           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17444           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17445 }
17446
17447 bool
17448 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17449                                           EVT VT) const {
17450   if (!VT.isSimple())
17451     return false;
17452
17453   MVT SVT = VT.getSimpleVT();
17454   unsigned NumElts = SVT.getVectorNumElements();
17455   // FIXME: This collection of masks seems suspect.
17456   if (NumElts == 2)
17457     return true;
17458   if (NumElts == 4 && SVT.is128BitVector()) {
17459     return (isMOVLMask(Mask, SVT)  ||
17460             isCommutedMOVLMask(Mask, SVT, true) ||
17461             isSHUFPMask(Mask, SVT) ||
17462             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17463   }
17464   return false;
17465 }
17466
17467 //===----------------------------------------------------------------------===//
17468 //                           X86 Scheduler Hooks
17469 //===----------------------------------------------------------------------===//
17470
17471 /// Utility function to emit xbegin specifying the start of an RTM region.
17472 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17473                                      const TargetInstrInfo *TII) {
17474   DebugLoc DL = MI->getDebugLoc();
17475
17476   const BasicBlock *BB = MBB->getBasicBlock();
17477   MachineFunction::iterator I = MBB;
17478   ++I;
17479
17480   // For the v = xbegin(), we generate
17481   //
17482   // thisMBB:
17483   //  xbegin sinkMBB
17484   //
17485   // mainMBB:
17486   //  eax = -1
17487   //
17488   // sinkMBB:
17489   //  v = eax
17490
17491   MachineBasicBlock *thisMBB = MBB;
17492   MachineFunction *MF = MBB->getParent();
17493   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17494   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17495   MF->insert(I, mainMBB);
17496   MF->insert(I, sinkMBB);
17497
17498   // Transfer the remainder of BB and its successor edges to sinkMBB.
17499   sinkMBB->splice(sinkMBB->begin(), MBB,
17500                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17501   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17502
17503   // thisMBB:
17504   //  xbegin sinkMBB
17505   //  # fallthrough to mainMBB
17506   //  # abortion to sinkMBB
17507   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17508   thisMBB->addSuccessor(mainMBB);
17509   thisMBB->addSuccessor(sinkMBB);
17510
17511   // mainMBB:
17512   //  EAX = -1
17513   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17514   mainMBB->addSuccessor(sinkMBB);
17515
17516   // sinkMBB:
17517   // EAX is live into the sinkMBB
17518   sinkMBB->addLiveIn(X86::EAX);
17519   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17520           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17521     .addReg(X86::EAX);
17522
17523   MI->eraseFromParent();
17524   return sinkMBB;
17525 }
17526
17527 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17528 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17529 // in the .td file.
17530 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17531                                        const TargetInstrInfo *TII) {
17532   unsigned Opc;
17533   switch (MI->getOpcode()) {
17534   default: llvm_unreachable("illegal opcode!");
17535   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17536   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17537   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17538   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17539   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17540   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17541   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17542   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17543   }
17544
17545   DebugLoc dl = MI->getDebugLoc();
17546   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17547
17548   unsigned NumArgs = MI->getNumOperands();
17549   for (unsigned i = 1; i < NumArgs; ++i) {
17550     MachineOperand &Op = MI->getOperand(i);
17551     if (!(Op.isReg() && Op.isImplicit()))
17552       MIB.addOperand(Op);
17553   }
17554   if (MI->hasOneMemOperand())
17555     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17556
17557   BuildMI(*BB, MI, dl,
17558     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17559     .addReg(X86::XMM0);
17560
17561   MI->eraseFromParent();
17562   return BB;
17563 }
17564
17565 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17566 // defs in an instruction pattern
17567 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17568                                        const TargetInstrInfo *TII) {
17569   unsigned Opc;
17570   switch (MI->getOpcode()) {
17571   default: llvm_unreachable("illegal opcode!");
17572   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17573   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17574   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17575   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17576   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17577   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17578   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17579   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17580   }
17581
17582   DebugLoc dl = MI->getDebugLoc();
17583   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17584
17585   unsigned NumArgs = MI->getNumOperands(); // remove the results
17586   for (unsigned i = 1; i < NumArgs; ++i) {
17587     MachineOperand &Op = MI->getOperand(i);
17588     if (!(Op.isReg() && Op.isImplicit()))
17589       MIB.addOperand(Op);
17590   }
17591   if (MI->hasOneMemOperand())
17592     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17593
17594   BuildMI(*BB, MI, dl,
17595     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17596     .addReg(X86::ECX);
17597
17598   MI->eraseFromParent();
17599   return BB;
17600 }
17601
17602 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17603                                        const TargetInstrInfo *TII,
17604                                        const X86Subtarget* Subtarget) {
17605   DebugLoc dl = MI->getDebugLoc();
17606
17607   // Address into RAX/EAX, other two args into ECX, EDX.
17608   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17609   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17610   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17611   for (int i = 0; i < X86::AddrNumOperands; ++i)
17612     MIB.addOperand(MI->getOperand(i));
17613
17614   unsigned ValOps = X86::AddrNumOperands;
17615   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17616     .addReg(MI->getOperand(ValOps).getReg());
17617   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17618     .addReg(MI->getOperand(ValOps+1).getReg());
17619
17620   // The instruction doesn't actually take any operands though.
17621   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17622
17623   MI->eraseFromParent(); // The pseudo is gone now.
17624   return BB;
17625 }
17626
17627 MachineBasicBlock *
17628 X86TargetLowering::EmitVAARG64WithCustomInserter(
17629                    MachineInstr *MI,
17630                    MachineBasicBlock *MBB) const {
17631   // Emit va_arg instruction on X86-64.
17632
17633   // Operands to this pseudo-instruction:
17634   // 0  ) Output        : destination address (reg)
17635   // 1-5) Input         : va_list address (addr, i64mem)
17636   // 6  ) ArgSize       : Size (in bytes) of vararg type
17637   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17638   // 8  ) Align         : Alignment of type
17639   // 9  ) EFLAGS (implicit-def)
17640
17641   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17642   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17643
17644   unsigned DestReg = MI->getOperand(0).getReg();
17645   MachineOperand &Base = MI->getOperand(1);
17646   MachineOperand &Scale = MI->getOperand(2);
17647   MachineOperand &Index = MI->getOperand(3);
17648   MachineOperand &Disp = MI->getOperand(4);
17649   MachineOperand &Segment = MI->getOperand(5);
17650   unsigned ArgSize = MI->getOperand(6).getImm();
17651   unsigned ArgMode = MI->getOperand(7).getImm();
17652   unsigned Align = MI->getOperand(8).getImm();
17653
17654   // Memory Reference
17655   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17656   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17657   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17658
17659   // Machine Information
17660   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17661   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17662   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17663   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17664   DebugLoc DL = MI->getDebugLoc();
17665
17666   // struct va_list {
17667   //   i32   gp_offset
17668   //   i32   fp_offset
17669   //   i64   overflow_area (address)
17670   //   i64   reg_save_area (address)
17671   // }
17672   // sizeof(va_list) = 24
17673   // alignment(va_list) = 8
17674
17675   unsigned TotalNumIntRegs = 6;
17676   unsigned TotalNumXMMRegs = 8;
17677   bool UseGPOffset = (ArgMode == 1);
17678   bool UseFPOffset = (ArgMode == 2);
17679   unsigned MaxOffset = TotalNumIntRegs * 8 +
17680                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17681
17682   /* Align ArgSize to a multiple of 8 */
17683   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17684   bool NeedsAlign = (Align > 8);
17685
17686   MachineBasicBlock *thisMBB = MBB;
17687   MachineBasicBlock *overflowMBB;
17688   MachineBasicBlock *offsetMBB;
17689   MachineBasicBlock *endMBB;
17690
17691   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17692   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17693   unsigned OffsetReg = 0;
17694
17695   if (!UseGPOffset && !UseFPOffset) {
17696     // If we only pull from the overflow region, we don't create a branch.
17697     // We don't need to alter control flow.
17698     OffsetDestReg = 0; // unused
17699     OverflowDestReg = DestReg;
17700
17701     offsetMBB = nullptr;
17702     overflowMBB = thisMBB;
17703     endMBB = thisMBB;
17704   } else {
17705     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17706     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17707     // If not, pull from overflow_area. (branch to overflowMBB)
17708     //
17709     //       thisMBB
17710     //         |     .
17711     //         |        .
17712     //     offsetMBB   overflowMBB
17713     //         |        .
17714     //         |     .
17715     //        endMBB
17716
17717     // Registers for the PHI in endMBB
17718     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17719     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17720
17721     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17722     MachineFunction *MF = MBB->getParent();
17723     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17724     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17725     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17726
17727     MachineFunction::iterator MBBIter = MBB;
17728     ++MBBIter;
17729
17730     // Insert the new basic blocks
17731     MF->insert(MBBIter, offsetMBB);
17732     MF->insert(MBBIter, overflowMBB);
17733     MF->insert(MBBIter, endMBB);
17734
17735     // Transfer the remainder of MBB and its successor edges to endMBB.
17736     endMBB->splice(endMBB->begin(), thisMBB,
17737                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17738     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17739
17740     // Make offsetMBB and overflowMBB successors of thisMBB
17741     thisMBB->addSuccessor(offsetMBB);
17742     thisMBB->addSuccessor(overflowMBB);
17743
17744     // endMBB is a successor of both offsetMBB and overflowMBB
17745     offsetMBB->addSuccessor(endMBB);
17746     overflowMBB->addSuccessor(endMBB);
17747
17748     // Load the offset value into a register
17749     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17750     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17751       .addOperand(Base)
17752       .addOperand(Scale)
17753       .addOperand(Index)
17754       .addDisp(Disp, UseFPOffset ? 4 : 0)
17755       .addOperand(Segment)
17756       .setMemRefs(MMOBegin, MMOEnd);
17757
17758     // Check if there is enough room left to pull this argument.
17759     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17760       .addReg(OffsetReg)
17761       .addImm(MaxOffset + 8 - ArgSizeA8);
17762
17763     // Branch to "overflowMBB" if offset >= max
17764     // Fall through to "offsetMBB" otherwise
17765     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17766       .addMBB(overflowMBB);
17767   }
17768
17769   // In offsetMBB, emit code to use the reg_save_area.
17770   if (offsetMBB) {
17771     assert(OffsetReg != 0);
17772
17773     // Read the reg_save_area address.
17774     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17775     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17776       .addOperand(Base)
17777       .addOperand(Scale)
17778       .addOperand(Index)
17779       .addDisp(Disp, 16)
17780       .addOperand(Segment)
17781       .setMemRefs(MMOBegin, MMOEnd);
17782
17783     // Zero-extend the offset
17784     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17785       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17786         .addImm(0)
17787         .addReg(OffsetReg)
17788         .addImm(X86::sub_32bit);
17789
17790     // Add the offset to the reg_save_area to get the final address.
17791     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17792       .addReg(OffsetReg64)
17793       .addReg(RegSaveReg);
17794
17795     // Compute the offset for the next argument
17796     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17797     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17798       .addReg(OffsetReg)
17799       .addImm(UseFPOffset ? 16 : 8);
17800
17801     // Store it back into the va_list.
17802     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17803       .addOperand(Base)
17804       .addOperand(Scale)
17805       .addOperand(Index)
17806       .addDisp(Disp, UseFPOffset ? 4 : 0)
17807       .addOperand(Segment)
17808       .addReg(NextOffsetReg)
17809       .setMemRefs(MMOBegin, MMOEnd);
17810
17811     // Jump to endMBB
17812     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17813       .addMBB(endMBB);
17814   }
17815
17816   //
17817   // Emit code to use overflow area
17818   //
17819
17820   // Load the overflow_area address into a register.
17821   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17822   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17823     .addOperand(Base)
17824     .addOperand(Scale)
17825     .addOperand(Index)
17826     .addDisp(Disp, 8)
17827     .addOperand(Segment)
17828     .setMemRefs(MMOBegin, MMOEnd);
17829
17830   // If we need to align it, do so. Otherwise, just copy the address
17831   // to OverflowDestReg.
17832   if (NeedsAlign) {
17833     // Align the overflow address
17834     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17835     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17836
17837     // aligned_addr = (addr + (align-1)) & ~(align-1)
17838     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17839       .addReg(OverflowAddrReg)
17840       .addImm(Align-1);
17841
17842     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17843       .addReg(TmpReg)
17844       .addImm(~(uint64_t)(Align-1));
17845   } else {
17846     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17847       .addReg(OverflowAddrReg);
17848   }
17849
17850   // Compute the next overflow address after this argument.
17851   // (the overflow address should be kept 8-byte aligned)
17852   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17853   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17854     .addReg(OverflowDestReg)
17855     .addImm(ArgSizeA8);
17856
17857   // Store the new overflow address.
17858   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17859     .addOperand(Base)
17860     .addOperand(Scale)
17861     .addOperand(Index)
17862     .addDisp(Disp, 8)
17863     .addOperand(Segment)
17864     .addReg(NextAddrReg)
17865     .setMemRefs(MMOBegin, MMOEnd);
17866
17867   // If we branched, emit the PHI to the front of endMBB.
17868   if (offsetMBB) {
17869     BuildMI(*endMBB, endMBB->begin(), DL,
17870             TII->get(X86::PHI), DestReg)
17871       .addReg(OffsetDestReg).addMBB(offsetMBB)
17872       .addReg(OverflowDestReg).addMBB(overflowMBB);
17873   }
17874
17875   // Erase the pseudo instruction
17876   MI->eraseFromParent();
17877
17878   return endMBB;
17879 }
17880
17881 MachineBasicBlock *
17882 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17883                                                  MachineInstr *MI,
17884                                                  MachineBasicBlock *MBB) const {
17885   // Emit code to save XMM registers to the stack. The ABI says that the
17886   // number of registers to save is given in %al, so it's theoretically
17887   // possible to do an indirect jump trick to avoid saving all of them,
17888   // however this code takes a simpler approach and just executes all
17889   // of the stores if %al is non-zero. It's less code, and it's probably
17890   // easier on the hardware branch predictor, and stores aren't all that
17891   // expensive anyway.
17892
17893   // Create the new basic blocks. One block contains all the XMM stores,
17894   // and one block is the final destination regardless of whether any
17895   // stores were performed.
17896   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17897   MachineFunction *F = MBB->getParent();
17898   MachineFunction::iterator MBBIter = MBB;
17899   ++MBBIter;
17900   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17901   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17902   F->insert(MBBIter, XMMSaveMBB);
17903   F->insert(MBBIter, EndMBB);
17904
17905   // Transfer the remainder of MBB and its successor edges to EndMBB.
17906   EndMBB->splice(EndMBB->begin(), MBB,
17907                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17908   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17909
17910   // The original block will now fall through to the XMM save block.
17911   MBB->addSuccessor(XMMSaveMBB);
17912   // The XMMSaveMBB will fall through to the end block.
17913   XMMSaveMBB->addSuccessor(EndMBB);
17914
17915   // Now add the instructions.
17916   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17917   DebugLoc DL = MI->getDebugLoc();
17918
17919   unsigned CountReg = MI->getOperand(0).getReg();
17920   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17921   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17922
17923   if (!Subtarget->isTargetWin64()) {
17924     // If %al is 0, branch around the XMM save block.
17925     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17926     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17927     MBB->addSuccessor(EndMBB);
17928   }
17929
17930   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17931   // that was just emitted, but clearly shouldn't be "saved".
17932   assert((MI->getNumOperands() <= 3 ||
17933           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17934           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17935          && "Expected last argument to be EFLAGS");
17936   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17937   // In the XMM save block, save all the XMM argument registers.
17938   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17939     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17940     MachineMemOperand *MMO =
17941       F->getMachineMemOperand(
17942           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17943         MachineMemOperand::MOStore,
17944         /*Size=*/16, /*Align=*/16);
17945     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17946       .addFrameIndex(RegSaveFrameIndex)
17947       .addImm(/*Scale=*/1)
17948       .addReg(/*IndexReg=*/0)
17949       .addImm(/*Disp=*/Offset)
17950       .addReg(/*Segment=*/0)
17951       .addReg(MI->getOperand(i).getReg())
17952       .addMemOperand(MMO);
17953   }
17954
17955   MI->eraseFromParent();   // The pseudo instruction is gone now.
17956
17957   return EndMBB;
17958 }
17959
17960 // The EFLAGS operand of SelectItr might be missing a kill marker
17961 // because there were multiple uses of EFLAGS, and ISel didn't know
17962 // which to mark. Figure out whether SelectItr should have had a
17963 // kill marker, and set it if it should. Returns the correct kill
17964 // marker value.
17965 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17966                                      MachineBasicBlock* BB,
17967                                      const TargetRegisterInfo* TRI) {
17968   // Scan forward through BB for a use/def of EFLAGS.
17969   MachineBasicBlock::iterator miI(std::next(SelectItr));
17970   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17971     const MachineInstr& mi = *miI;
17972     if (mi.readsRegister(X86::EFLAGS))
17973       return false;
17974     if (mi.definesRegister(X86::EFLAGS))
17975       break; // Should have kill-flag - update below.
17976   }
17977
17978   // If we hit the end of the block, check whether EFLAGS is live into a
17979   // successor.
17980   if (miI == BB->end()) {
17981     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17982                                           sEnd = BB->succ_end();
17983          sItr != sEnd; ++sItr) {
17984       MachineBasicBlock* succ = *sItr;
17985       if (succ->isLiveIn(X86::EFLAGS))
17986         return false;
17987     }
17988   }
17989
17990   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17991   // out. SelectMI should have a kill flag on EFLAGS.
17992   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17993   return true;
17994 }
17995
17996 MachineBasicBlock *
17997 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17998                                      MachineBasicBlock *BB) const {
17999   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18000   DebugLoc DL = MI->getDebugLoc();
18001
18002   // To "insert" a SELECT_CC instruction, we actually have to insert the
18003   // diamond control-flow pattern.  The incoming instruction knows the
18004   // destination vreg to set, the condition code register to branch on, the
18005   // true/false values to select between, and a branch opcode to use.
18006   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18007   MachineFunction::iterator It = BB;
18008   ++It;
18009
18010   //  thisMBB:
18011   //  ...
18012   //   TrueVal = ...
18013   //   cmpTY ccX, r1, r2
18014   //   bCC copy1MBB
18015   //   fallthrough --> copy0MBB
18016   MachineBasicBlock *thisMBB = BB;
18017   MachineFunction *F = BB->getParent();
18018   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18019   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18020   F->insert(It, copy0MBB);
18021   F->insert(It, sinkMBB);
18022
18023   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18024   // live into the sink and copy blocks.
18025   const TargetRegisterInfo *TRI =
18026       BB->getParent()->getSubtarget().getRegisterInfo();
18027   if (!MI->killsRegister(X86::EFLAGS) &&
18028       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18029     copy0MBB->addLiveIn(X86::EFLAGS);
18030     sinkMBB->addLiveIn(X86::EFLAGS);
18031   }
18032
18033   // Transfer the remainder of BB and its successor edges to sinkMBB.
18034   sinkMBB->splice(sinkMBB->begin(), BB,
18035                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18036   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18037
18038   // Add the true and fallthrough blocks as its successors.
18039   BB->addSuccessor(copy0MBB);
18040   BB->addSuccessor(sinkMBB);
18041
18042   // Create the conditional branch instruction.
18043   unsigned Opc =
18044     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18045   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18046
18047   //  copy0MBB:
18048   //   %FalseValue = ...
18049   //   # fallthrough to sinkMBB
18050   copy0MBB->addSuccessor(sinkMBB);
18051
18052   //  sinkMBB:
18053   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18054   //  ...
18055   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18056           TII->get(X86::PHI), MI->getOperand(0).getReg())
18057     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18058     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18059
18060   MI->eraseFromParent();   // The pseudo instruction is gone now.
18061   return sinkMBB;
18062 }
18063
18064 MachineBasicBlock *
18065 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18066                                         bool Is64Bit) const {
18067   MachineFunction *MF = BB->getParent();
18068   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18069   DebugLoc DL = MI->getDebugLoc();
18070   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18071
18072   assert(MF->shouldSplitStack());
18073
18074   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18075   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18076
18077   // BB:
18078   //  ... [Till the alloca]
18079   // If stacklet is not large enough, jump to mallocMBB
18080   //
18081   // bumpMBB:
18082   //  Allocate by subtracting from RSP
18083   //  Jump to continueMBB
18084   //
18085   // mallocMBB:
18086   //  Allocate by call to runtime
18087   //
18088   // continueMBB:
18089   //  ...
18090   //  [rest of original BB]
18091   //
18092
18093   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18094   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18095   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18096
18097   MachineRegisterInfo &MRI = MF->getRegInfo();
18098   const TargetRegisterClass *AddrRegClass =
18099     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18100
18101   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18102     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18103     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18104     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18105     sizeVReg = MI->getOperand(1).getReg(),
18106     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18107
18108   MachineFunction::iterator MBBIter = BB;
18109   ++MBBIter;
18110
18111   MF->insert(MBBIter, bumpMBB);
18112   MF->insert(MBBIter, mallocMBB);
18113   MF->insert(MBBIter, continueMBB);
18114
18115   continueMBB->splice(continueMBB->begin(), BB,
18116                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18117   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18118
18119   // Add code to the main basic block to check if the stack limit has been hit,
18120   // and if so, jump to mallocMBB otherwise to bumpMBB.
18121   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18122   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18123     .addReg(tmpSPVReg).addReg(sizeVReg);
18124   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18125     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18126     .addReg(SPLimitVReg);
18127   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18128
18129   // bumpMBB simply decreases the stack pointer, since we know the current
18130   // stacklet has enough space.
18131   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18132     .addReg(SPLimitVReg);
18133   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18134     .addReg(SPLimitVReg);
18135   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18136
18137   // Calls into a routine in libgcc to allocate more space from the heap.
18138   const uint32_t *RegMask = MF->getTarget()
18139                                 .getSubtargetImpl()
18140                                 ->getRegisterInfo()
18141                                 ->getCallPreservedMask(CallingConv::C);
18142   if (Is64Bit) {
18143     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18144       .addReg(sizeVReg);
18145     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18146       .addExternalSymbol("__morestack_allocate_stack_space")
18147       .addRegMask(RegMask)
18148       .addReg(X86::RDI, RegState::Implicit)
18149       .addReg(X86::RAX, RegState::ImplicitDefine);
18150   } else {
18151     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18152       .addImm(12);
18153     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18154     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18155       .addExternalSymbol("__morestack_allocate_stack_space")
18156       .addRegMask(RegMask)
18157       .addReg(X86::EAX, RegState::ImplicitDefine);
18158   }
18159
18160   if (!Is64Bit)
18161     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18162       .addImm(16);
18163
18164   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18165     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18166   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18167
18168   // Set up the CFG correctly.
18169   BB->addSuccessor(bumpMBB);
18170   BB->addSuccessor(mallocMBB);
18171   mallocMBB->addSuccessor(continueMBB);
18172   bumpMBB->addSuccessor(continueMBB);
18173
18174   // Take care of the PHI nodes.
18175   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18176           MI->getOperand(0).getReg())
18177     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18178     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18179
18180   // Delete the original pseudo instruction.
18181   MI->eraseFromParent();
18182
18183   // And we're done.
18184   return continueMBB;
18185 }
18186
18187 MachineBasicBlock *
18188 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18189                                         MachineBasicBlock *BB) const {
18190   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18191   DebugLoc DL = MI->getDebugLoc();
18192
18193   assert(!Subtarget->isTargetMacho());
18194
18195   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18196   // non-trivial part is impdef of ESP.
18197
18198   if (Subtarget->isTargetWin64()) {
18199     if (Subtarget->isTargetCygMing()) {
18200       // ___chkstk(Mingw64):
18201       // Clobbers R10, R11, RAX and EFLAGS.
18202       // Updates RSP.
18203       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18204         .addExternalSymbol("___chkstk")
18205         .addReg(X86::RAX, RegState::Implicit)
18206         .addReg(X86::RSP, RegState::Implicit)
18207         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18208         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18209         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18210     } else {
18211       // __chkstk(MSVCRT): does not update stack pointer.
18212       // Clobbers R10, R11 and EFLAGS.
18213       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18214         .addExternalSymbol("__chkstk")
18215         .addReg(X86::RAX, RegState::Implicit)
18216         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18217       // RAX has the offset to be subtracted from RSP.
18218       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18219         .addReg(X86::RSP)
18220         .addReg(X86::RAX);
18221     }
18222   } else {
18223     const char *StackProbeSymbol =
18224       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18225
18226     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18227       .addExternalSymbol(StackProbeSymbol)
18228       .addReg(X86::EAX, RegState::Implicit)
18229       .addReg(X86::ESP, RegState::Implicit)
18230       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18231       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18232       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18233   }
18234
18235   MI->eraseFromParent();   // The pseudo instruction is gone now.
18236   return BB;
18237 }
18238
18239 MachineBasicBlock *
18240 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18241                                       MachineBasicBlock *BB) const {
18242   // This is pretty easy.  We're taking the value that we received from
18243   // our load from the relocation, sticking it in either RDI (x86-64)
18244   // or EAX and doing an indirect call.  The return value will then
18245   // be in the normal return register.
18246   MachineFunction *F = BB->getParent();
18247   const X86InstrInfo *TII =
18248       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18249   DebugLoc DL = MI->getDebugLoc();
18250
18251   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18252   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18253
18254   // Get a register mask for the lowered call.
18255   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18256   // proper register mask.
18257   const uint32_t *RegMask = F->getTarget()
18258                                 .getSubtargetImpl()
18259                                 ->getRegisterInfo()
18260                                 ->getCallPreservedMask(CallingConv::C);
18261   if (Subtarget->is64Bit()) {
18262     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18263                                       TII->get(X86::MOV64rm), X86::RDI)
18264     .addReg(X86::RIP)
18265     .addImm(0).addReg(0)
18266     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18267                       MI->getOperand(3).getTargetFlags())
18268     .addReg(0);
18269     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18270     addDirectMem(MIB, X86::RDI);
18271     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18272   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18273     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18274                                       TII->get(X86::MOV32rm), X86::EAX)
18275     .addReg(0)
18276     .addImm(0).addReg(0)
18277     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18278                       MI->getOperand(3).getTargetFlags())
18279     .addReg(0);
18280     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18281     addDirectMem(MIB, X86::EAX);
18282     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18283   } else {
18284     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18285                                       TII->get(X86::MOV32rm), X86::EAX)
18286     .addReg(TII->getGlobalBaseReg(F))
18287     .addImm(0).addReg(0)
18288     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18289                       MI->getOperand(3).getTargetFlags())
18290     .addReg(0);
18291     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18292     addDirectMem(MIB, X86::EAX);
18293     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18294   }
18295
18296   MI->eraseFromParent(); // The pseudo instruction is gone now.
18297   return BB;
18298 }
18299
18300 MachineBasicBlock *
18301 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18302                                     MachineBasicBlock *MBB) const {
18303   DebugLoc DL = MI->getDebugLoc();
18304   MachineFunction *MF = MBB->getParent();
18305   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18306   MachineRegisterInfo &MRI = MF->getRegInfo();
18307
18308   const BasicBlock *BB = MBB->getBasicBlock();
18309   MachineFunction::iterator I = MBB;
18310   ++I;
18311
18312   // Memory Reference
18313   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18314   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18315
18316   unsigned DstReg;
18317   unsigned MemOpndSlot = 0;
18318
18319   unsigned CurOp = 0;
18320
18321   DstReg = MI->getOperand(CurOp++).getReg();
18322   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18323   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18324   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18325   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18326
18327   MemOpndSlot = CurOp;
18328
18329   MVT PVT = getPointerTy();
18330   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18331          "Invalid Pointer Size!");
18332
18333   // For v = setjmp(buf), we generate
18334   //
18335   // thisMBB:
18336   //  buf[LabelOffset] = restoreMBB
18337   //  SjLjSetup restoreMBB
18338   //
18339   // mainMBB:
18340   //  v_main = 0
18341   //
18342   // sinkMBB:
18343   //  v = phi(main, restore)
18344   //
18345   // restoreMBB:
18346   //  v_restore = 1
18347
18348   MachineBasicBlock *thisMBB = MBB;
18349   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18350   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18351   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18352   MF->insert(I, mainMBB);
18353   MF->insert(I, sinkMBB);
18354   MF->push_back(restoreMBB);
18355
18356   MachineInstrBuilder MIB;
18357
18358   // Transfer the remainder of BB and its successor edges to sinkMBB.
18359   sinkMBB->splice(sinkMBB->begin(), MBB,
18360                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18361   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18362
18363   // thisMBB:
18364   unsigned PtrStoreOpc = 0;
18365   unsigned LabelReg = 0;
18366   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18367   Reloc::Model RM = MF->getTarget().getRelocationModel();
18368   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18369                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18370
18371   // Prepare IP either in reg or imm.
18372   if (!UseImmLabel) {
18373     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18374     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18375     LabelReg = MRI.createVirtualRegister(PtrRC);
18376     if (Subtarget->is64Bit()) {
18377       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18378               .addReg(X86::RIP)
18379               .addImm(0)
18380               .addReg(0)
18381               .addMBB(restoreMBB)
18382               .addReg(0);
18383     } else {
18384       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18385       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18386               .addReg(XII->getGlobalBaseReg(MF))
18387               .addImm(0)
18388               .addReg(0)
18389               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18390               .addReg(0);
18391     }
18392   } else
18393     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18394   // Store IP
18395   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18396   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18397     if (i == X86::AddrDisp)
18398       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18399     else
18400       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18401   }
18402   if (!UseImmLabel)
18403     MIB.addReg(LabelReg);
18404   else
18405     MIB.addMBB(restoreMBB);
18406   MIB.setMemRefs(MMOBegin, MMOEnd);
18407   // Setup
18408   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18409           .addMBB(restoreMBB);
18410
18411   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18412       MF->getSubtarget().getRegisterInfo());
18413   MIB.addRegMask(RegInfo->getNoPreservedMask());
18414   thisMBB->addSuccessor(mainMBB);
18415   thisMBB->addSuccessor(restoreMBB);
18416
18417   // mainMBB:
18418   //  EAX = 0
18419   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18420   mainMBB->addSuccessor(sinkMBB);
18421
18422   // sinkMBB:
18423   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18424           TII->get(X86::PHI), DstReg)
18425     .addReg(mainDstReg).addMBB(mainMBB)
18426     .addReg(restoreDstReg).addMBB(restoreMBB);
18427
18428   // restoreMBB:
18429   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18430   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18431   restoreMBB->addSuccessor(sinkMBB);
18432
18433   MI->eraseFromParent();
18434   return sinkMBB;
18435 }
18436
18437 MachineBasicBlock *
18438 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18439                                      MachineBasicBlock *MBB) const {
18440   DebugLoc DL = MI->getDebugLoc();
18441   MachineFunction *MF = MBB->getParent();
18442   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18443   MachineRegisterInfo &MRI = MF->getRegInfo();
18444
18445   // Memory Reference
18446   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18447   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18448
18449   MVT PVT = getPointerTy();
18450   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18451          "Invalid Pointer Size!");
18452
18453   const TargetRegisterClass *RC =
18454     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18455   unsigned Tmp = MRI.createVirtualRegister(RC);
18456   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18457   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18458       MF->getSubtarget().getRegisterInfo());
18459   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18460   unsigned SP = RegInfo->getStackRegister();
18461
18462   MachineInstrBuilder MIB;
18463
18464   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18465   const int64_t SPOffset = 2 * PVT.getStoreSize();
18466
18467   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18468   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18469
18470   // Reload FP
18471   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18472   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18473     MIB.addOperand(MI->getOperand(i));
18474   MIB.setMemRefs(MMOBegin, MMOEnd);
18475   // Reload IP
18476   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18477   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18478     if (i == X86::AddrDisp)
18479       MIB.addDisp(MI->getOperand(i), LabelOffset);
18480     else
18481       MIB.addOperand(MI->getOperand(i));
18482   }
18483   MIB.setMemRefs(MMOBegin, MMOEnd);
18484   // Reload SP
18485   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18486   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18487     if (i == X86::AddrDisp)
18488       MIB.addDisp(MI->getOperand(i), SPOffset);
18489     else
18490       MIB.addOperand(MI->getOperand(i));
18491   }
18492   MIB.setMemRefs(MMOBegin, MMOEnd);
18493   // Jump
18494   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18495
18496   MI->eraseFromParent();
18497   return MBB;
18498 }
18499
18500 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18501 // accumulator loops. Writing back to the accumulator allows the coalescer
18502 // to remove extra copies in the loop.   
18503 MachineBasicBlock *
18504 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18505                                  MachineBasicBlock *MBB) const {
18506   MachineOperand &AddendOp = MI->getOperand(3);
18507
18508   // Bail out early if the addend isn't a register - we can't switch these.
18509   if (!AddendOp.isReg())
18510     return MBB;
18511
18512   MachineFunction &MF = *MBB->getParent();
18513   MachineRegisterInfo &MRI = MF.getRegInfo();
18514
18515   // Check whether the addend is defined by a PHI:
18516   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18517   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18518   if (!AddendDef.isPHI())
18519     return MBB;
18520
18521   // Look for the following pattern:
18522   // loop:
18523   //   %addend = phi [%entry, 0], [%loop, %result]
18524   //   ...
18525   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18526
18527   // Replace with:
18528   //   loop:
18529   //   %addend = phi [%entry, 0], [%loop, %result]
18530   //   ...
18531   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18532
18533   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18534     assert(AddendDef.getOperand(i).isReg());
18535     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18536     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18537     if (&PHISrcInst == MI) {
18538       // Found a matching instruction.
18539       unsigned NewFMAOpc = 0;
18540       switch (MI->getOpcode()) {
18541         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18542         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18543         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18544         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18545         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18546         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18547         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18548         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18549         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18550         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18551         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18552         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18553         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18554         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18555         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18556         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18557         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18558         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18559         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18560         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18561         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18562         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18563         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18564         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18565         default: llvm_unreachable("Unrecognized FMA variant.");
18566       }
18567
18568       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18569       MachineInstrBuilder MIB =
18570         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18571         .addOperand(MI->getOperand(0))
18572         .addOperand(MI->getOperand(3))
18573         .addOperand(MI->getOperand(2))
18574         .addOperand(MI->getOperand(1));
18575       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18576       MI->eraseFromParent();
18577     }
18578   }
18579
18580   return MBB;
18581 }
18582
18583 MachineBasicBlock *
18584 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18585                                                MachineBasicBlock *BB) const {
18586   switch (MI->getOpcode()) {
18587   default: llvm_unreachable("Unexpected instr type to insert");
18588   case X86::TAILJMPd64:
18589   case X86::TAILJMPr64:
18590   case X86::TAILJMPm64:
18591     llvm_unreachable("TAILJMP64 would not be touched here.");
18592   case X86::TCRETURNdi64:
18593   case X86::TCRETURNri64:
18594   case X86::TCRETURNmi64:
18595     return BB;
18596   case X86::WIN_ALLOCA:
18597     return EmitLoweredWinAlloca(MI, BB);
18598   case X86::SEG_ALLOCA_32:
18599     return EmitLoweredSegAlloca(MI, BB, false);
18600   case X86::SEG_ALLOCA_64:
18601     return EmitLoweredSegAlloca(MI, BB, true);
18602   case X86::TLSCall_32:
18603   case X86::TLSCall_64:
18604     return EmitLoweredTLSCall(MI, BB);
18605   case X86::CMOV_GR8:
18606   case X86::CMOV_FR32:
18607   case X86::CMOV_FR64:
18608   case X86::CMOV_V4F32:
18609   case X86::CMOV_V2F64:
18610   case X86::CMOV_V2I64:
18611   case X86::CMOV_V8F32:
18612   case X86::CMOV_V4F64:
18613   case X86::CMOV_V4I64:
18614   case X86::CMOV_V16F32:
18615   case X86::CMOV_V8F64:
18616   case X86::CMOV_V8I64:
18617   case X86::CMOV_GR16:
18618   case X86::CMOV_GR32:
18619   case X86::CMOV_RFP32:
18620   case X86::CMOV_RFP64:
18621   case X86::CMOV_RFP80:
18622     return EmitLoweredSelect(MI, BB);
18623
18624   case X86::FP32_TO_INT16_IN_MEM:
18625   case X86::FP32_TO_INT32_IN_MEM:
18626   case X86::FP32_TO_INT64_IN_MEM:
18627   case X86::FP64_TO_INT16_IN_MEM:
18628   case X86::FP64_TO_INT32_IN_MEM:
18629   case X86::FP64_TO_INT64_IN_MEM:
18630   case X86::FP80_TO_INT16_IN_MEM:
18631   case X86::FP80_TO_INT32_IN_MEM:
18632   case X86::FP80_TO_INT64_IN_MEM: {
18633     MachineFunction *F = BB->getParent();
18634     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18635     DebugLoc DL = MI->getDebugLoc();
18636
18637     // Change the floating point control register to use "round towards zero"
18638     // mode when truncating to an integer value.
18639     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18640     addFrameReference(BuildMI(*BB, MI, DL,
18641                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18642
18643     // Load the old value of the high byte of the control word...
18644     unsigned OldCW =
18645       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18646     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18647                       CWFrameIdx);
18648
18649     // Set the high part to be round to zero...
18650     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18651       .addImm(0xC7F);
18652
18653     // Reload the modified control word now...
18654     addFrameReference(BuildMI(*BB, MI, DL,
18655                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18656
18657     // Restore the memory image of control word to original value
18658     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18659       .addReg(OldCW);
18660
18661     // Get the X86 opcode to use.
18662     unsigned Opc;
18663     switch (MI->getOpcode()) {
18664     default: llvm_unreachable("illegal opcode!");
18665     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18666     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18667     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18668     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18669     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18670     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18671     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18672     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18673     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18674     }
18675
18676     X86AddressMode AM;
18677     MachineOperand &Op = MI->getOperand(0);
18678     if (Op.isReg()) {
18679       AM.BaseType = X86AddressMode::RegBase;
18680       AM.Base.Reg = Op.getReg();
18681     } else {
18682       AM.BaseType = X86AddressMode::FrameIndexBase;
18683       AM.Base.FrameIndex = Op.getIndex();
18684     }
18685     Op = MI->getOperand(1);
18686     if (Op.isImm())
18687       AM.Scale = Op.getImm();
18688     Op = MI->getOperand(2);
18689     if (Op.isImm())
18690       AM.IndexReg = Op.getImm();
18691     Op = MI->getOperand(3);
18692     if (Op.isGlobal()) {
18693       AM.GV = Op.getGlobal();
18694     } else {
18695       AM.Disp = Op.getImm();
18696     }
18697     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18698                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18699
18700     // Reload the original control word now.
18701     addFrameReference(BuildMI(*BB, MI, DL,
18702                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18703
18704     MI->eraseFromParent();   // The pseudo instruction is gone now.
18705     return BB;
18706   }
18707     // String/text processing lowering.
18708   case X86::PCMPISTRM128REG:
18709   case X86::VPCMPISTRM128REG:
18710   case X86::PCMPISTRM128MEM:
18711   case X86::VPCMPISTRM128MEM:
18712   case X86::PCMPESTRM128REG:
18713   case X86::VPCMPESTRM128REG:
18714   case X86::PCMPESTRM128MEM:
18715   case X86::VPCMPESTRM128MEM:
18716     assert(Subtarget->hasSSE42() &&
18717            "Target must have SSE4.2 or AVX features enabled");
18718     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18719
18720   // String/text processing lowering.
18721   case X86::PCMPISTRIREG:
18722   case X86::VPCMPISTRIREG:
18723   case X86::PCMPISTRIMEM:
18724   case X86::VPCMPISTRIMEM:
18725   case X86::PCMPESTRIREG:
18726   case X86::VPCMPESTRIREG:
18727   case X86::PCMPESTRIMEM:
18728   case X86::VPCMPESTRIMEM:
18729     assert(Subtarget->hasSSE42() &&
18730            "Target must have SSE4.2 or AVX features enabled");
18731     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18732
18733   // Thread synchronization.
18734   case X86::MONITOR:
18735     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18736                        Subtarget);
18737
18738   // xbegin
18739   case X86::XBEGIN:
18740     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18741
18742   case X86::VASTART_SAVE_XMM_REGS:
18743     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18744
18745   case X86::VAARG_64:
18746     return EmitVAARG64WithCustomInserter(MI, BB);
18747
18748   case X86::EH_SjLj_SetJmp32:
18749   case X86::EH_SjLj_SetJmp64:
18750     return emitEHSjLjSetJmp(MI, BB);
18751
18752   case X86::EH_SjLj_LongJmp32:
18753   case X86::EH_SjLj_LongJmp64:
18754     return emitEHSjLjLongJmp(MI, BB);
18755
18756   case TargetOpcode::STACKMAP:
18757   case TargetOpcode::PATCHPOINT:
18758     return emitPatchPoint(MI, BB);
18759
18760   case X86::VFMADDPDr213r:
18761   case X86::VFMADDPSr213r:
18762   case X86::VFMADDSDr213r:
18763   case X86::VFMADDSSr213r:
18764   case X86::VFMSUBPDr213r:
18765   case X86::VFMSUBPSr213r:
18766   case X86::VFMSUBSDr213r:
18767   case X86::VFMSUBSSr213r:
18768   case X86::VFNMADDPDr213r:
18769   case X86::VFNMADDPSr213r:
18770   case X86::VFNMADDSDr213r:
18771   case X86::VFNMADDSSr213r:
18772   case X86::VFNMSUBPDr213r:
18773   case X86::VFNMSUBPSr213r:
18774   case X86::VFNMSUBSDr213r:
18775   case X86::VFNMSUBSSr213r:
18776   case X86::VFMADDPDr213rY:
18777   case X86::VFMADDPSr213rY:
18778   case X86::VFMSUBPDr213rY:
18779   case X86::VFMSUBPSr213rY:
18780   case X86::VFNMADDPDr213rY:
18781   case X86::VFNMADDPSr213rY:
18782   case X86::VFNMSUBPDr213rY:
18783   case X86::VFNMSUBPSr213rY:
18784     return emitFMA3Instr(MI, BB);
18785   }
18786 }
18787
18788 //===----------------------------------------------------------------------===//
18789 //                           X86 Optimization Hooks
18790 //===----------------------------------------------------------------------===//
18791
18792 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18793                                                       APInt &KnownZero,
18794                                                       APInt &KnownOne,
18795                                                       const SelectionDAG &DAG,
18796                                                       unsigned Depth) const {
18797   unsigned BitWidth = KnownZero.getBitWidth();
18798   unsigned Opc = Op.getOpcode();
18799   assert((Opc >= ISD::BUILTIN_OP_END ||
18800           Opc == ISD::INTRINSIC_WO_CHAIN ||
18801           Opc == ISD::INTRINSIC_W_CHAIN ||
18802           Opc == ISD::INTRINSIC_VOID) &&
18803          "Should use MaskedValueIsZero if you don't know whether Op"
18804          " is a target node!");
18805
18806   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18807   switch (Opc) {
18808   default: break;
18809   case X86ISD::ADD:
18810   case X86ISD::SUB:
18811   case X86ISD::ADC:
18812   case X86ISD::SBB:
18813   case X86ISD::SMUL:
18814   case X86ISD::UMUL:
18815   case X86ISD::INC:
18816   case X86ISD::DEC:
18817   case X86ISD::OR:
18818   case X86ISD::XOR:
18819   case X86ISD::AND:
18820     // These nodes' second result is a boolean.
18821     if (Op.getResNo() == 0)
18822       break;
18823     // Fallthrough
18824   case X86ISD::SETCC:
18825     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18826     break;
18827   case ISD::INTRINSIC_WO_CHAIN: {
18828     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18829     unsigned NumLoBits = 0;
18830     switch (IntId) {
18831     default: break;
18832     case Intrinsic::x86_sse_movmsk_ps:
18833     case Intrinsic::x86_avx_movmsk_ps_256:
18834     case Intrinsic::x86_sse2_movmsk_pd:
18835     case Intrinsic::x86_avx_movmsk_pd_256:
18836     case Intrinsic::x86_mmx_pmovmskb:
18837     case Intrinsic::x86_sse2_pmovmskb_128:
18838     case Intrinsic::x86_avx2_pmovmskb: {
18839       // High bits of movmskp{s|d}, pmovmskb are known zero.
18840       switch (IntId) {
18841         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18842         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18843         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18844         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18845         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18846         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18847         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18848         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18849       }
18850       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18851       break;
18852     }
18853     }
18854     break;
18855   }
18856   }
18857 }
18858
18859 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18860   SDValue Op,
18861   const SelectionDAG &,
18862   unsigned Depth) const {
18863   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18864   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18865     return Op.getValueType().getScalarType().getSizeInBits();
18866
18867   // Fallback case.
18868   return 1;
18869 }
18870
18871 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18872 /// node is a GlobalAddress + offset.
18873 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18874                                        const GlobalValue* &GA,
18875                                        int64_t &Offset) const {
18876   if (N->getOpcode() == X86ISD::Wrapper) {
18877     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18878       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18879       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18880       return true;
18881     }
18882   }
18883   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18884 }
18885
18886 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18887 /// same as extracting the high 128-bit part of 256-bit vector and then
18888 /// inserting the result into the low part of a new 256-bit vector
18889 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18890   EVT VT = SVOp->getValueType(0);
18891   unsigned NumElems = VT.getVectorNumElements();
18892
18893   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18894   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18895     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18896         SVOp->getMaskElt(j) >= 0)
18897       return false;
18898
18899   return true;
18900 }
18901
18902 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18903 /// same as extracting the low 128-bit part of 256-bit vector and then
18904 /// inserting the result into the high part of a new 256-bit vector
18905 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18906   EVT VT = SVOp->getValueType(0);
18907   unsigned NumElems = VT.getVectorNumElements();
18908
18909   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18910   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18911     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18912         SVOp->getMaskElt(j) >= 0)
18913       return false;
18914
18915   return true;
18916 }
18917
18918 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18919 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18920                                         TargetLowering::DAGCombinerInfo &DCI,
18921                                         const X86Subtarget* Subtarget) {
18922   SDLoc dl(N);
18923   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18924   SDValue V1 = SVOp->getOperand(0);
18925   SDValue V2 = SVOp->getOperand(1);
18926   EVT VT = SVOp->getValueType(0);
18927   unsigned NumElems = VT.getVectorNumElements();
18928
18929   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18930       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18931     //
18932     //                   0,0,0,...
18933     //                      |
18934     //    V      UNDEF    BUILD_VECTOR    UNDEF
18935     //     \      /           \           /
18936     //  CONCAT_VECTOR         CONCAT_VECTOR
18937     //         \                  /
18938     //          \                /
18939     //          RESULT: V + zero extended
18940     //
18941     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18942         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18943         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18944       return SDValue();
18945
18946     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18947       return SDValue();
18948
18949     // To match the shuffle mask, the first half of the mask should
18950     // be exactly the first vector, and all the rest a splat with the
18951     // first element of the second one.
18952     for (unsigned i = 0; i != NumElems/2; ++i)
18953       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18954           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18955         return SDValue();
18956
18957     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18958     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18959       if (Ld->hasNUsesOfValue(1, 0)) {
18960         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18961         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18962         SDValue ResNode =
18963           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18964                                   Ld->getMemoryVT(),
18965                                   Ld->getPointerInfo(),
18966                                   Ld->getAlignment(),
18967                                   false/*isVolatile*/, true/*ReadMem*/,
18968                                   false/*WriteMem*/);
18969
18970         // Make sure the newly-created LOAD is in the same position as Ld in
18971         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18972         // and update uses of Ld's output chain to use the TokenFactor.
18973         if (Ld->hasAnyUseOfValue(1)) {
18974           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18975                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18976           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18977           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18978                                  SDValue(ResNode.getNode(), 1));
18979         }
18980
18981         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18982       }
18983     }
18984
18985     // Emit a zeroed vector and insert the desired subvector on its
18986     // first half.
18987     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18988     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18989     return DCI.CombineTo(N, InsV);
18990   }
18991
18992   //===--------------------------------------------------------------------===//
18993   // Combine some shuffles into subvector extracts and inserts:
18994   //
18995
18996   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18997   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18998     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18999     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19000     return DCI.CombineTo(N, InsV);
19001   }
19002
19003   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19004   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19005     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19006     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19007     return DCI.CombineTo(N, InsV);
19008   }
19009
19010   return SDValue();
19011 }
19012
19013 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19014 /// possible.
19015 ///
19016 /// This is the leaf of the recursive combinine below. When we have found some
19017 /// chain of single-use x86 shuffle instructions and accumulated the combined
19018 /// shuffle mask represented by them, this will try to pattern match that mask
19019 /// into either a single instruction if there is a special purpose instruction
19020 /// for this operation, or into a PSHUFB instruction which is a fully general
19021 /// instruction but should only be used to replace chains over a certain depth.
19022 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19023                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19024                                    TargetLowering::DAGCombinerInfo &DCI,
19025                                    const X86Subtarget *Subtarget) {
19026   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19027
19028   // Find the operand that enters the chain. Note that multiple uses are OK
19029   // here, we're not going to remove the operand we find.
19030   SDValue Input = Op.getOperand(0);
19031   while (Input.getOpcode() == ISD::BITCAST)
19032     Input = Input.getOperand(0);
19033
19034   MVT VT = Input.getSimpleValueType();
19035   MVT RootVT = Root.getSimpleValueType();
19036   SDLoc DL(Root);
19037
19038   // Just remove no-op shuffle masks.
19039   if (Mask.size() == 1) {
19040     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19041                   /*AddTo*/ true);
19042     return true;
19043   }
19044
19045   // Use the float domain if the operand type is a floating point type.
19046   bool FloatDomain = VT.isFloatingPoint();
19047
19048   // If we don't have access to VEX encodings, the generic PSHUF instructions
19049   // are preferable to some of the specialized forms despite requiring one more
19050   // byte to encode because they can implicitly copy.
19051   //
19052   // IF we *do* have VEX encodings, than we can use shorter, more specific
19053   // shuffle instructions freely as they can copy due to the extra register
19054   // operand.
19055   if (Subtarget->hasAVX()) {
19056     // We have both floating point and integer variants of shuffles that dup
19057     // either the low or high half of the vector.
19058     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19059       bool Lo = Mask.equals(0, 0);
19060       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19061                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19062       if (Depth == 1 && Root->getOpcode() == Shuffle)
19063         return false; // Nothing to do!
19064       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19065       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19066       DCI.AddToWorklist(Op.getNode());
19067       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19068       DCI.AddToWorklist(Op.getNode());
19069       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19070                     /*AddTo*/ true);
19071       return true;
19072     }
19073
19074     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19075
19076     // For the integer domain we have specialized instructions for duplicating
19077     // any element size from the low or high half.
19078     if (!FloatDomain &&
19079         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19080          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19081          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19082          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19083          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19084                      15))) {
19085       bool Lo = Mask[0] == 0;
19086       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19087       if (Depth == 1 && Root->getOpcode() == Shuffle)
19088         return false; // Nothing to do!
19089       MVT ShuffleVT;
19090       switch (Mask.size()) {
19091       case 4: ShuffleVT = MVT::v4i32; break;
19092       case 8: ShuffleVT = MVT::v8i16; break;
19093       case 16: ShuffleVT = MVT::v16i8; break;
19094       };
19095       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19096       DCI.AddToWorklist(Op.getNode());
19097       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19098       DCI.AddToWorklist(Op.getNode());
19099       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19100                     /*AddTo*/ true);
19101       return true;
19102     }
19103   }
19104
19105   // Don't try to re-form single instruction chains under any circumstances now
19106   // that we've done encoding canonicalization for them.
19107   if (Depth < 2)
19108     return false;
19109
19110   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19111   // can replace them with a single PSHUFB instruction profitably. Intel's
19112   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19113   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19114   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19115     SmallVector<SDValue, 16> PSHUFBMask;
19116     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19117     int Ratio = 16 / Mask.size();
19118     for (unsigned i = 0; i < 16; ++i) {
19119       int M = Ratio * Mask[i / Ratio] + i % Ratio;
19120       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19121     }
19122     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19123     DCI.AddToWorklist(Op.getNode());
19124     SDValue PSHUFBMaskOp =
19125         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19126     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19127     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19128     DCI.AddToWorklist(Op.getNode());
19129     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19130                   /*AddTo*/ true);
19131     return true;
19132   }
19133
19134   // Failed to find any combines.
19135   return false;
19136 }
19137
19138 /// \brief Fully generic combining of x86 shuffle instructions.
19139 ///
19140 /// This should be the last combine run over the x86 shuffle instructions. Once
19141 /// they have been fully optimized, this will recursively consdier all chains
19142 /// of single-use shuffle instructions, build a generic model of the cumulative
19143 /// shuffle operation, and check for simpler instructions which implement this
19144 /// operation. We use this primarily for two purposes:
19145 ///
19146 /// 1) Collapse generic shuffles to specialized single instructions when
19147 ///    equivalent. In most cases, this is just an encoding size win, but
19148 ///    sometimes we will collapse multiple generic shuffles into a single
19149 ///    special-purpose shuffle.
19150 /// 2) Look for sequences of shuffle instructions with 3 or more total
19151 ///    instructions, and replace them with the slightly more expensive SSSE3
19152 ///    PSHUFB instruction if available. We do this as the last combining step
19153 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19154 ///    a suitable short sequence of other instructions. The PHUFB will either
19155 ///    use a register or have to read from memory and so is slightly (but only
19156 ///    slightly) more expensive than the other shuffle instructions.
19157 ///
19158 /// Because this is inherently a quadratic operation (for each shuffle in
19159 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19160 /// This should never be an issue in practice as the shuffle lowering doesn't
19161 /// produce sequences of more than 8 instructions.
19162 ///
19163 /// FIXME: We will currently miss some cases where the redundant shuffling
19164 /// would simplify under the threshold for PSHUFB formation because of
19165 /// combine-ordering. To fix this, we should do the redundant instruction
19166 /// combining in this recursive walk.
19167 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19168                                           ArrayRef<int> IncomingMask, int Depth,
19169                                           bool HasPSHUFB, SelectionDAG &DAG,
19170                                           TargetLowering::DAGCombinerInfo &DCI,
19171                                           const X86Subtarget *Subtarget) {
19172   // Bound the depth of our recursive combine because this is ultimately
19173   // quadratic in nature.
19174   if (Depth > 8)
19175     return false;
19176
19177   // Directly rip through bitcasts to find the underlying operand.
19178   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19179     Op = Op.getOperand(0);
19180
19181   MVT VT = Op.getSimpleValueType();
19182   if (!VT.isVector())
19183     return false; // Bail if we hit a non-vector.
19184   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19185   // version should be added.
19186   if (VT.getSizeInBits() != 128)
19187     return false;
19188
19189   assert(Root.getSimpleValueType().isVector() &&
19190          "Shuffles operate on vector types!");
19191   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19192          "Can only combine shuffles of the same vector register size.");
19193
19194   if (!isTargetShuffle(Op.getOpcode()))
19195     return false;
19196   SmallVector<int, 16> OpMask;
19197   bool IsUnary;
19198   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19199   // We only can combine unary shuffles which we can decode the mask for.
19200   if (!HaveMask || !IsUnary)
19201     return false;
19202
19203   assert(VT.getVectorNumElements() == OpMask.size() &&
19204          "Different mask size from vector size!");
19205
19206   SmallVector<int, 16> Mask;
19207   Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
19208
19209   // Merge this shuffle operation's mask into our accumulated mask. This is
19210   // a bit tricky as the shuffle may have a different size from the root.
19211   if (OpMask.size() == IncomingMask.size()) {
19212     for (int M : IncomingMask)
19213       Mask.push_back(OpMask[M]);
19214   } else if (OpMask.size() < IncomingMask.size()) {
19215     assert(IncomingMask.size() % OpMask.size() == 0 &&
19216            "The smaller number of elements must divide the larger.");
19217     int Ratio = IncomingMask.size() / OpMask.size();
19218     for (int M : IncomingMask)
19219       Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
19220   } else {
19221     assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
19222     assert(OpMask.size() % IncomingMask.size() == 0 &&
19223            "The smaller number of elements must divide the larger.");
19224     int Ratio = OpMask.size() / IncomingMask.size();
19225     for (int i = 0, e = OpMask.size(); i < e; ++i)
19226       Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
19227   }
19228
19229   // See if we can recurse into the operand to combine more things.
19230   switch (Op.getOpcode()) {
19231     case X86ISD::PSHUFB:
19232       HasPSHUFB = true;
19233     case X86ISD::PSHUFD:
19234     case X86ISD::PSHUFHW:
19235     case X86ISD::PSHUFLW:
19236       if (Op.getOperand(0).hasOneUse() &&
19237           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19238                                         HasPSHUFB, DAG, DCI, Subtarget))
19239         return true;
19240       break;
19241
19242     case X86ISD::UNPCKL:
19243     case X86ISD::UNPCKH:
19244       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19245       // We can't check for single use, we have to check that this shuffle is the only user.
19246       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19247           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19248                                         HasPSHUFB, DAG, DCI, Subtarget))
19249           return true;
19250       break;
19251   }
19252
19253   // Minor canonicalization of the accumulated shuffle mask to make it easier
19254   // to match below. All this does is detect masks with squential pairs of
19255   // elements, and shrink them to the half-width mask. It does this in a loop
19256   // so it will reduce the size of the mask to the minimal width mask which
19257   // performs an equivalent shuffle.
19258   while (Mask.size() > 1) {
19259     SmallVector<int, 16> NewMask;
19260     for (int i = 0, e = Mask.size()/2; i < e; ++i) {
19261       if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
19262         NewMask.clear();
19263         break;
19264       }
19265       NewMask.push_back(Mask[2*i] / 2);
19266     }
19267     if (NewMask.empty())
19268       break;
19269     Mask.swap(NewMask);
19270   }
19271
19272   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19273                                 Subtarget);
19274 }
19275
19276 /// \brief Get the PSHUF-style mask from PSHUF node.
19277 ///
19278 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19279 /// PSHUF-style masks that can be reused with such instructions.
19280 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19281   SmallVector<int, 4> Mask;
19282   bool IsUnary;
19283   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19284   (void)HaveMask;
19285   assert(HaveMask);
19286
19287   switch (N.getOpcode()) {
19288   case X86ISD::PSHUFD:
19289     return Mask;
19290   case X86ISD::PSHUFLW:
19291     Mask.resize(4);
19292     return Mask;
19293   case X86ISD::PSHUFHW:
19294     Mask.erase(Mask.begin(), Mask.begin() + 4);
19295     for (int &M : Mask)
19296       M -= 4;
19297     return Mask;
19298   default:
19299     llvm_unreachable("No valid shuffle instruction found!");
19300   }
19301 }
19302
19303 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19304 ///
19305 /// We walk up the chain and look for a combinable shuffle, skipping over
19306 /// shuffles that we could hoist this shuffle's transformation past without
19307 /// altering anything.
19308 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19309                                          SelectionDAG &DAG,
19310                                          TargetLowering::DAGCombinerInfo &DCI) {
19311   assert(N.getOpcode() == X86ISD::PSHUFD &&
19312          "Called with something other than an x86 128-bit half shuffle!");
19313   SDLoc DL(N);
19314
19315   // Walk up a single-use chain looking for a combinable shuffle.
19316   SDValue V = N.getOperand(0);
19317   for (; V.hasOneUse(); V = V.getOperand(0)) {
19318     switch (V.getOpcode()) {
19319     default:
19320       return false; // Nothing combined!
19321
19322     case ISD::BITCAST:
19323       // Skip bitcasts as we always know the type for the target specific
19324       // instructions.
19325       continue;
19326
19327     case X86ISD::PSHUFD:
19328       // Found another dword shuffle.
19329       break;
19330
19331     case X86ISD::PSHUFLW:
19332       // Check that the low words (being shuffled) are the identity in the
19333       // dword shuffle, and the high words are self-contained.
19334       if (Mask[0] != 0 || Mask[1] != 1 ||
19335           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19336         return false;
19337
19338       continue;
19339
19340     case X86ISD::PSHUFHW:
19341       // Check that the high words (being shuffled) are the identity in the
19342       // dword shuffle, and the low words are self-contained.
19343       if (Mask[2] != 2 || Mask[3] != 3 ||
19344           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19345         return false;
19346
19347       continue;
19348
19349     case X86ISD::UNPCKL:
19350     case X86ISD::UNPCKH:
19351       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19352       // shuffle into a preceding word shuffle.
19353       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19354         return false;
19355
19356       // Search for a half-shuffle which we can combine with.
19357       unsigned CombineOp =
19358           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19359       if (V.getOperand(0) != V.getOperand(1) ||
19360           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19361         return false;
19362       V = V.getOperand(0);
19363       do {
19364         switch (V.getOpcode()) {
19365         default:
19366           return false; // Nothing to combine.
19367
19368         case X86ISD::PSHUFLW:
19369         case X86ISD::PSHUFHW:
19370           if (V.getOpcode() == CombineOp)
19371             break;
19372
19373           // Fallthrough!
19374         case ISD::BITCAST:
19375           V = V.getOperand(0);
19376           continue;
19377         }
19378         break;
19379       } while (V.hasOneUse());
19380       break;
19381     }
19382     // Break out of the loop if we break out of the switch.
19383     break;
19384   }
19385
19386   if (!V.hasOneUse())
19387     // We fell out of the loop without finding a viable combining instruction.
19388     return false;
19389
19390   // Record the old value to use in RAUW-ing.
19391   SDValue Old = V;
19392
19393   // Merge this node's mask and our incoming mask.
19394   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19395   for (int &M : Mask)
19396     M = VMask[M];
19397   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19398                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19399
19400   // It is possible that one of the combinable shuffles was completely absorbed
19401   // by the other, just replace it and revisit all users in that case.
19402   if (Old.getNode() == V.getNode()) {
19403     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19404     return true;
19405   }
19406
19407   // Replace N with its operand as we're going to combine that shuffle away.
19408   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19409
19410   // Replace the combinable shuffle with the combined one, updating all users
19411   // so that we re-evaluate the chain here.
19412   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19413   return true;
19414 }
19415
19416 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19417 ///
19418 /// We walk up the chain, skipping shuffles of the other half and looking
19419 /// through shuffles which switch halves trying to find a shuffle of the same
19420 /// pair of dwords.
19421 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19422                                         SelectionDAG &DAG,
19423                                         TargetLowering::DAGCombinerInfo &DCI) {
19424   assert(
19425       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19426       "Called with something other than an x86 128-bit half shuffle!");
19427   SDLoc DL(N);
19428   unsigned CombineOpcode = N.getOpcode();
19429
19430   // Walk up a single-use chain looking for a combinable shuffle.
19431   SDValue V = N.getOperand(0);
19432   for (; V.hasOneUse(); V = V.getOperand(0)) {
19433     switch (V.getOpcode()) {
19434     default:
19435       return false; // Nothing combined!
19436
19437     case ISD::BITCAST:
19438       // Skip bitcasts as we always know the type for the target specific
19439       // instructions.
19440       continue;
19441
19442     case X86ISD::PSHUFLW:
19443     case X86ISD::PSHUFHW:
19444       if (V.getOpcode() == CombineOpcode)
19445         break;
19446
19447       // Other-half shuffles are no-ops.
19448       continue;
19449     }
19450     // Break out of the loop if we break out of the switch.
19451     break;
19452   }
19453
19454   if (!V.hasOneUse())
19455     // We fell out of the loop without finding a viable combining instruction.
19456     return false;
19457
19458   // Combine away the bottom node as its shuffle will be accumulated into
19459   // a preceding shuffle.
19460   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19461
19462   // Record the old value.
19463   SDValue Old = V;
19464
19465   // Merge this node's mask and our incoming mask (adjusted to account for all
19466   // the pshufd instructions encountered).
19467   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19468   for (int &M : Mask)
19469     M = VMask[M];
19470   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19471                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19472
19473   // Check that the shuffles didn't cancel each other out. If not, we need to
19474   // combine to the new one.
19475   if (Old != V)
19476     // Replace the combinable shuffle with the combined one, updating all users
19477     // so that we re-evaluate the chain here.
19478     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19479
19480   return true;
19481 }
19482
19483 /// \brief Try to combine x86 target specific shuffles.
19484 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19485                                            TargetLowering::DAGCombinerInfo &DCI,
19486                                            const X86Subtarget *Subtarget) {
19487   SDLoc DL(N);
19488   MVT VT = N.getSimpleValueType();
19489   SmallVector<int, 4> Mask;
19490
19491   switch (N.getOpcode()) {
19492   case X86ISD::PSHUFD:
19493   case X86ISD::PSHUFLW:
19494   case X86ISD::PSHUFHW:
19495     Mask = getPSHUFShuffleMask(N);
19496     assert(Mask.size() == 4);
19497     break;
19498   default:
19499     return SDValue();
19500   }
19501
19502   // Nuke no-op shuffles that show up after combining.
19503   if (isNoopShuffleMask(Mask))
19504     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19505
19506   // Look for simplifications involving one or two shuffle instructions.
19507   SDValue V = N.getOperand(0);
19508   switch (N.getOpcode()) {
19509   default:
19510     break;
19511   case X86ISD::PSHUFLW:
19512   case X86ISD::PSHUFHW:
19513     assert(VT == MVT::v8i16);
19514     (void)VT;
19515
19516     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19517       return SDValue(); // We combined away this shuffle, so we're done.
19518
19519     // See if this reduces to a PSHUFD which is no more expensive and can
19520     // combine with more operations.
19521     if (canWidenShuffleElements(Mask)) {
19522       int DMask[] = {-1, -1, -1, -1};
19523       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19524       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19525       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19526       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19527       DCI.AddToWorklist(V.getNode());
19528       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19529                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19530       DCI.AddToWorklist(V.getNode());
19531       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19532     }
19533
19534     // Look for shuffle patterns which can be implemented as a single unpack.
19535     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19536     // only works when we have a PSHUFD followed by two half-shuffles.
19537     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19538         (V.getOpcode() == X86ISD::PSHUFLW ||
19539          V.getOpcode() == X86ISD::PSHUFHW) &&
19540         V.getOpcode() != N.getOpcode() &&
19541         V.hasOneUse()) {
19542       SDValue D = V.getOperand(0);
19543       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19544         D = D.getOperand(0);
19545       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19546         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19547         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19548         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19549         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19550         int WordMask[8];
19551         for (int i = 0; i < 4; ++i) {
19552           WordMask[i + NOffset] = Mask[i] + NOffset;
19553           WordMask[i + VOffset] = VMask[i] + VOffset;
19554         }
19555         // Map the word mask through the DWord mask.
19556         int MappedMask[8];
19557         for (int i = 0; i < 8; ++i)
19558           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19559         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19560         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19561         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19562                        std::begin(UnpackLoMask)) ||
19563             std::equal(std::begin(MappedMask), std::end(MappedMask),
19564                        std::begin(UnpackHiMask))) {
19565           // We can replace all three shuffles with an unpack.
19566           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19567           DCI.AddToWorklist(V.getNode());
19568           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19569                                                 : X86ISD::UNPCKH,
19570                              DL, MVT::v8i16, V, V);
19571         }
19572       }
19573     }
19574
19575     break;
19576
19577   case X86ISD::PSHUFD:
19578     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19579       return SDValue(); // We combined away this shuffle.
19580
19581     break;
19582   }
19583
19584   return SDValue();
19585 }
19586
19587 /// PerformShuffleCombine - Performs several different shuffle combines.
19588 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19589                                      TargetLowering::DAGCombinerInfo &DCI,
19590                                      const X86Subtarget *Subtarget) {
19591   SDLoc dl(N);
19592   SDValue N0 = N->getOperand(0);
19593   SDValue N1 = N->getOperand(1);
19594   EVT VT = N->getValueType(0);
19595
19596   // Don't create instructions with illegal types after legalize types has run.
19597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19598   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19599     return SDValue();
19600
19601   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19602   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19603       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19604     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19605
19606   // During Type Legalization, when promoting illegal vector types,
19607   // the backend might introduce new shuffle dag nodes and bitcasts.
19608   //
19609   // This code performs the following transformation:
19610   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19611   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19612   //
19613   // We do this only if both the bitcast and the BINOP dag nodes have
19614   // one use. Also, perform this transformation only if the new binary
19615   // operation is legal. This is to avoid introducing dag nodes that
19616   // potentially need to be further expanded (or custom lowered) into a
19617   // less optimal sequence of dag nodes.
19618   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19619       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19620       N0.getOpcode() == ISD::BITCAST) {
19621     SDValue BC0 = N0.getOperand(0);
19622     EVT SVT = BC0.getValueType();
19623     unsigned Opcode = BC0.getOpcode();
19624     unsigned NumElts = VT.getVectorNumElements();
19625     
19626     if (BC0.hasOneUse() && SVT.isVector() &&
19627         SVT.getVectorNumElements() * 2 == NumElts &&
19628         TLI.isOperationLegal(Opcode, VT)) {
19629       bool CanFold = false;
19630       switch (Opcode) {
19631       default : break;
19632       case ISD::ADD :
19633       case ISD::FADD :
19634       case ISD::SUB :
19635       case ISD::FSUB :
19636       case ISD::MUL :
19637       case ISD::FMUL :
19638         CanFold = true;
19639       }
19640
19641       unsigned SVTNumElts = SVT.getVectorNumElements();
19642       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19643       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19644         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19645       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19646         CanFold = SVOp->getMaskElt(i) < 0;
19647
19648       if (CanFold) {
19649         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19650         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19651         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19652         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19653       }
19654     }
19655   }
19656
19657   // Only handle 128 wide vector from here on.
19658   if (!VT.is128BitVector())
19659     return SDValue();
19660
19661   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19662   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19663   // consecutive, non-overlapping, and in the right order.
19664   SmallVector<SDValue, 16> Elts;
19665   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19666     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19667
19668   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19669   if (LD.getNode())
19670     return LD;
19671
19672   if (isTargetShuffle(N->getOpcode())) {
19673     SDValue Shuffle =
19674         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19675     if (Shuffle.getNode())
19676       return Shuffle;
19677
19678     // Try recursively combining arbitrary sequences of x86 shuffle
19679     // instructions into higher-order shuffles. We do this after combining
19680     // specific PSHUF instruction sequences into their minimal form so that we
19681     // can evaluate how many specialized shuffle instructions are involved in
19682     // a particular chain.
19683     SmallVector<int, 1> NonceMask; // Just a placeholder.
19684     NonceMask.push_back(0);
19685     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19686                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19687                                       DCI, Subtarget))
19688       return SDValue(); // This routine will use CombineTo to replace N.
19689   }
19690
19691   return SDValue();
19692 }
19693
19694 /// PerformTruncateCombine - Converts truncate operation to
19695 /// a sequence of vector shuffle operations.
19696 /// It is possible when we truncate 256-bit vector to 128-bit vector
19697 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19698                                       TargetLowering::DAGCombinerInfo &DCI,
19699                                       const X86Subtarget *Subtarget)  {
19700   return SDValue();
19701 }
19702
19703 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19704 /// specific shuffle of a load can be folded into a single element load.
19705 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19706 /// shuffles have been customed lowered so we need to handle those here.
19707 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19708                                          TargetLowering::DAGCombinerInfo &DCI) {
19709   if (DCI.isBeforeLegalizeOps())
19710     return SDValue();
19711
19712   SDValue InVec = N->getOperand(0);
19713   SDValue EltNo = N->getOperand(1);
19714
19715   if (!isa<ConstantSDNode>(EltNo))
19716     return SDValue();
19717
19718   EVT VT = InVec.getValueType();
19719
19720   bool HasShuffleIntoBitcast = false;
19721   if (InVec.getOpcode() == ISD::BITCAST) {
19722     // Don't duplicate a load with other uses.
19723     if (!InVec.hasOneUse())
19724       return SDValue();
19725     EVT BCVT = InVec.getOperand(0).getValueType();
19726     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19727       return SDValue();
19728     InVec = InVec.getOperand(0);
19729     HasShuffleIntoBitcast = true;
19730   }
19731
19732   if (!isTargetShuffle(InVec.getOpcode()))
19733     return SDValue();
19734
19735   // Don't duplicate a load with other uses.
19736   if (!InVec.hasOneUse())
19737     return SDValue();
19738
19739   SmallVector<int, 16> ShuffleMask;
19740   bool UnaryShuffle;
19741   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19742                             UnaryShuffle))
19743     return SDValue();
19744
19745   // Select the input vector, guarding against out of range extract vector.
19746   unsigned NumElems = VT.getVectorNumElements();
19747   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19748   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19749   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19750                                          : InVec.getOperand(1);
19751
19752   // If inputs to shuffle are the same for both ops, then allow 2 uses
19753   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19754
19755   if (LdNode.getOpcode() == ISD::BITCAST) {
19756     // Don't duplicate a load with other uses.
19757     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19758       return SDValue();
19759
19760     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19761     LdNode = LdNode.getOperand(0);
19762   }
19763
19764   if (!ISD::isNormalLoad(LdNode.getNode()))
19765     return SDValue();
19766
19767   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19768
19769   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19770     return SDValue();
19771
19772   if (HasShuffleIntoBitcast) {
19773     // If there's a bitcast before the shuffle, check if the load type and
19774     // alignment is valid.
19775     unsigned Align = LN0->getAlignment();
19776     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19777     unsigned NewAlign = TLI.getDataLayout()->
19778       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19779
19780     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19781       return SDValue();
19782   }
19783
19784   // All checks match so transform back to vector_shuffle so that DAG combiner
19785   // can finish the job
19786   SDLoc dl(N);
19787
19788   // Create shuffle node taking into account the case that its a unary shuffle
19789   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19790   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19791                                  InVec.getOperand(0), Shuffle,
19792                                  &ShuffleMask[0]);
19793   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19794   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19795                      EltNo);
19796 }
19797
19798 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19799 /// generation and convert it from being a bunch of shuffles and extracts
19800 /// to a simple store and scalar loads to extract the elements.
19801 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19802                                          TargetLowering::DAGCombinerInfo &DCI) {
19803   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19804   if (NewOp.getNode())
19805     return NewOp;
19806
19807   SDValue InputVector = N->getOperand(0);
19808
19809   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19810   // from mmx to v2i32 has a single usage.
19811   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19812       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19813       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19814     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19815                        N->getValueType(0),
19816                        InputVector.getNode()->getOperand(0));
19817
19818   // Only operate on vectors of 4 elements, where the alternative shuffling
19819   // gets to be more expensive.
19820   if (InputVector.getValueType() != MVT::v4i32)
19821     return SDValue();
19822
19823   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19824   // single use which is a sign-extend or zero-extend, and all elements are
19825   // used.
19826   SmallVector<SDNode *, 4> Uses;
19827   unsigned ExtractedElements = 0;
19828   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19829        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19830     if (UI.getUse().getResNo() != InputVector.getResNo())
19831       return SDValue();
19832
19833     SDNode *Extract = *UI;
19834     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19835       return SDValue();
19836
19837     if (Extract->getValueType(0) != MVT::i32)
19838       return SDValue();
19839     if (!Extract->hasOneUse())
19840       return SDValue();
19841     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19842         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19843       return SDValue();
19844     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19845       return SDValue();
19846
19847     // Record which element was extracted.
19848     ExtractedElements |=
19849       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19850
19851     Uses.push_back(Extract);
19852   }
19853
19854   // If not all the elements were used, this may not be worthwhile.
19855   if (ExtractedElements != 15)
19856     return SDValue();
19857
19858   // Ok, we've now decided to do the transformation.
19859   SDLoc dl(InputVector);
19860
19861   // Store the value to a temporary stack slot.
19862   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19863   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19864                             MachinePointerInfo(), false, false, 0);
19865
19866   // Replace each use (extract) with a load of the appropriate element.
19867   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19868        UE = Uses.end(); UI != UE; ++UI) {
19869     SDNode *Extract = *UI;
19870
19871     // cOMpute the element's address.
19872     SDValue Idx = Extract->getOperand(1);
19873     unsigned EltSize =
19874         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19875     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19876     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19877     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19878
19879     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19880                                      StackPtr, OffsetVal);
19881
19882     // Load the scalar.
19883     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19884                                      ScalarAddr, MachinePointerInfo(),
19885                                      false, false, false, 0);
19886
19887     // Replace the exact with the load.
19888     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19889   }
19890
19891   // The replacement was made in place; don't return anything.
19892   return SDValue();
19893 }
19894
19895 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19896 static std::pair<unsigned, bool>
19897 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19898                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19899   if (!VT.isVector())
19900     return std::make_pair(0, false);
19901
19902   bool NeedSplit = false;
19903   switch (VT.getSimpleVT().SimpleTy) {
19904   default: return std::make_pair(0, false);
19905   case MVT::v32i8:
19906   case MVT::v16i16:
19907   case MVT::v8i32:
19908     if (!Subtarget->hasAVX2())
19909       NeedSplit = true;
19910     if (!Subtarget->hasAVX())
19911       return std::make_pair(0, false);
19912     break;
19913   case MVT::v16i8:
19914   case MVT::v8i16:
19915   case MVT::v4i32:
19916     if (!Subtarget->hasSSE2())
19917       return std::make_pair(0, false);
19918   }
19919
19920   // SSE2 has only a small subset of the operations.
19921   bool hasUnsigned = Subtarget->hasSSE41() ||
19922                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19923   bool hasSigned = Subtarget->hasSSE41() ||
19924                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19925
19926   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19927
19928   unsigned Opc = 0;
19929   // Check for x CC y ? x : y.
19930   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19931       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19932     switch (CC) {
19933     default: break;
19934     case ISD::SETULT:
19935     case ISD::SETULE:
19936       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19937     case ISD::SETUGT:
19938     case ISD::SETUGE:
19939       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19940     case ISD::SETLT:
19941     case ISD::SETLE:
19942       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19943     case ISD::SETGT:
19944     case ISD::SETGE:
19945       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19946     }
19947   // Check for x CC y ? y : x -- a min/max with reversed arms.
19948   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19949              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19950     switch (CC) {
19951     default: break;
19952     case ISD::SETULT:
19953     case ISD::SETULE:
19954       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19955     case ISD::SETUGT:
19956     case ISD::SETUGE:
19957       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19958     case ISD::SETLT:
19959     case ISD::SETLE:
19960       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19961     case ISD::SETGT:
19962     case ISD::SETGE:
19963       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19964     }
19965   }
19966
19967   return std::make_pair(Opc, NeedSplit);
19968 }
19969
19970 static SDValue
19971 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19972                                       const X86Subtarget *Subtarget) {
19973   SDLoc dl(N);
19974   SDValue Cond = N->getOperand(0);
19975   SDValue LHS = N->getOperand(1);
19976   SDValue RHS = N->getOperand(2);
19977
19978   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19979     SDValue CondSrc = Cond->getOperand(0);
19980     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19981       Cond = CondSrc->getOperand(0);
19982   }
19983
19984   MVT VT = N->getSimpleValueType(0);
19985   MVT EltVT = VT.getVectorElementType();
19986   unsigned NumElems = VT.getVectorNumElements();
19987   // There is no blend with immediate in AVX-512.
19988   if (VT.is512BitVector())
19989     return SDValue();
19990
19991   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19992     return SDValue();
19993   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19994     return SDValue();
19995
19996   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19997     return SDValue();
19998
19999   unsigned MaskValue = 0;
20000   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20001     return SDValue();
20002
20003   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20004   for (unsigned i = 0; i < NumElems; ++i) {
20005     // Be sure we emit undef where we can.
20006     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20007       ShuffleMask[i] = -1;
20008     else
20009       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20010   }
20011
20012   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20013 }
20014
20015 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20016 /// nodes.
20017 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20018                                     TargetLowering::DAGCombinerInfo &DCI,
20019                                     const X86Subtarget *Subtarget) {
20020   SDLoc DL(N);
20021   SDValue Cond = N->getOperand(0);
20022   // Get the LHS/RHS of the select.
20023   SDValue LHS = N->getOperand(1);
20024   SDValue RHS = N->getOperand(2);
20025   EVT VT = LHS.getValueType();
20026   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20027
20028   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20029   // instructions match the semantics of the common C idiom x<y?x:y but not
20030   // x<=y?x:y, because of how they handle negative zero (which can be
20031   // ignored in unsafe-math mode).
20032   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20033       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20034       (Subtarget->hasSSE2() ||
20035        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20036     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20037
20038     unsigned Opcode = 0;
20039     // Check for x CC y ? x : y.
20040     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20041         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20042       switch (CC) {
20043       default: break;
20044       case ISD::SETULT:
20045         // Converting this to a min would handle NaNs incorrectly, and swapping
20046         // the operands would cause it to handle comparisons between positive
20047         // and negative zero incorrectly.
20048         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20049           if (!DAG.getTarget().Options.UnsafeFPMath &&
20050               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20051             break;
20052           std::swap(LHS, RHS);
20053         }
20054         Opcode = X86ISD::FMIN;
20055         break;
20056       case ISD::SETOLE:
20057         // Converting this to a min would handle comparisons between positive
20058         // and negative zero incorrectly.
20059         if (!DAG.getTarget().Options.UnsafeFPMath &&
20060             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20061           break;
20062         Opcode = X86ISD::FMIN;
20063         break;
20064       case ISD::SETULE:
20065         // Converting this to a min would handle both negative zeros and NaNs
20066         // incorrectly, but we can swap the operands to fix both.
20067         std::swap(LHS, RHS);
20068       case ISD::SETOLT:
20069       case ISD::SETLT:
20070       case ISD::SETLE:
20071         Opcode = X86ISD::FMIN;
20072         break;
20073
20074       case ISD::SETOGE:
20075         // Converting this to a max would handle comparisons between positive
20076         // and negative zero incorrectly.
20077         if (!DAG.getTarget().Options.UnsafeFPMath &&
20078             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20079           break;
20080         Opcode = X86ISD::FMAX;
20081         break;
20082       case ISD::SETUGT:
20083         // Converting this to a max would handle NaNs incorrectly, and swapping
20084         // the operands would cause it to handle comparisons between positive
20085         // and negative zero incorrectly.
20086         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20087           if (!DAG.getTarget().Options.UnsafeFPMath &&
20088               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20089             break;
20090           std::swap(LHS, RHS);
20091         }
20092         Opcode = X86ISD::FMAX;
20093         break;
20094       case ISD::SETUGE:
20095         // Converting this to a max would handle both negative zeros and NaNs
20096         // incorrectly, but we can swap the operands to fix both.
20097         std::swap(LHS, RHS);
20098       case ISD::SETOGT:
20099       case ISD::SETGT:
20100       case ISD::SETGE:
20101         Opcode = X86ISD::FMAX;
20102         break;
20103       }
20104     // Check for x CC y ? y : x -- a min/max with reversed arms.
20105     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20106                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20107       switch (CC) {
20108       default: break;
20109       case ISD::SETOGE:
20110         // Converting this to a min would handle comparisons between positive
20111         // and negative zero incorrectly, and swapping the operands would
20112         // cause it to handle NaNs incorrectly.
20113         if (!DAG.getTarget().Options.UnsafeFPMath &&
20114             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20115           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20116             break;
20117           std::swap(LHS, RHS);
20118         }
20119         Opcode = X86ISD::FMIN;
20120         break;
20121       case ISD::SETUGT:
20122         // Converting this to a min would handle NaNs incorrectly.
20123         if (!DAG.getTarget().Options.UnsafeFPMath &&
20124             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20125           break;
20126         Opcode = X86ISD::FMIN;
20127         break;
20128       case ISD::SETUGE:
20129         // Converting this to a min would handle both negative zeros and NaNs
20130         // incorrectly, but we can swap the operands to fix both.
20131         std::swap(LHS, RHS);
20132       case ISD::SETOGT:
20133       case ISD::SETGT:
20134       case ISD::SETGE:
20135         Opcode = X86ISD::FMIN;
20136         break;
20137
20138       case ISD::SETULT:
20139         // Converting this to a max would handle NaNs incorrectly.
20140         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20141           break;
20142         Opcode = X86ISD::FMAX;
20143         break;
20144       case ISD::SETOLE:
20145         // Converting this to a max would handle comparisons between positive
20146         // and negative zero incorrectly, and swapping the operands would
20147         // cause it to handle NaNs incorrectly.
20148         if (!DAG.getTarget().Options.UnsafeFPMath &&
20149             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20150           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20151             break;
20152           std::swap(LHS, RHS);
20153         }
20154         Opcode = X86ISD::FMAX;
20155         break;
20156       case ISD::SETULE:
20157         // Converting this to a max would handle both negative zeros and NaNs
20158         // incorrectly, but we can swap the operands to fix both.
20159         std::swap(LHS, RHS);
20160       case ISD::SETOLT:
20161       case ISD::SETLT:
20162       case ISD::SETLE:
20163         Opcode = X86ISD::FMAX;
20164         break;
20165       }
20166     }
20167
20168     if (Opcode)
20169       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20170   }
20171
20172   EVT CondVT = Cond.getValueType();
20173   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20174       CondVT.getVectorElementType() == MVT::i1) {
20175     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20176     // lowering on AVX-512. In this case we convert it to
20177     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20178     // The same situation for all 128 and 256-bit vectors of i8 and i16
20179     EVT OpVT = LHS.getValueType();
20180     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20181         (OpVT.getVectorElementType() == MVT::i8 ||
20182          OpVT.getVectorElementType() == MVT::i16)) {
20183       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20184       DCI.AddToWorklist(Cond.getNode());
20185       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20186     }
20187   }
20188   // If this is a select between two integer constants, try to do some
20189   // optimizations.
20190   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20191     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20192       // Don't do this for crazy integer types.
20193       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20194         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20195         // so that TrueC (the true value) is larger than FalseC.
20196         bool NeedsCondInvert = false;
20197
20198         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20199             // Efficiently invertible.
20200             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20201              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20202               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20203           NeedsCondInvert = true;
20204           std::swap(TrueC, FalseC);
20205         }
20206
20207         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20208         if (FalseC->getAPIntValue() == 0 &&
20209             TrueC->getAPIntValue().isPowerOf2()) {
20210           if (NeedsCondInvert) // Invert the condition if needed.
20211             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20212                                DAG.getConstant(1, Cond.getValueType()));
20213
20214           // Zero extend the condition if needed.
20215           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20216
20217           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20218           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20219                              DAG.getConstant(ShAmt, MVT::i8));
20220         }
20221
20222         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20223         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20224           if (NeedsCondInvert) // Invert the condition if needed.
20225             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20226                                DAG.getConstant(1, Cond.getValueType()));
20227
20228           // Zero extend the condition if needed.
20229           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20230                              FalseC->getValueType(0), Cond);
20231           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20232                              SDValue(FalseC, 0));
20233         }
20234
20235         // Optimize cases that will turn into an LEA instruction.  This requires
20236         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20237         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20238           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20239           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20240
20241           bool isFastMultiplier = false;
20242           if (Diff < 10) {
20243             switch ((unsigned char)Diff) {
20244               default: break;
20245               case 1:  // result = add base, cond
20246               case 2:  // result = lea base(    , cond*2)
20247               case 3:  // result = lea base(cond, cond*2)
20248               case 4:  // result = lea base(    , cond*4)
20249               case 5:  // result = lea base(cond, cond*4)
20250               case 8:  // result = lea base(    , cond*8)
20251               case 9:  // result = lea base(cond, cond*8)
20252                 isFastMultiplier = true;
20253                 break;
20254             }
20255           }
20256
20257           if (isFastMultiplier) {
20258             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20259             if (NeedsCondInvert) // Invert the condition if needed.
20260               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20261                                  DAG.getConstant(1, Cond.getValueType()));
20262
20263             // Zero extend the condition if needed.
20264             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20265                                Cond);
20266             // Scale the condition by the difference.
20267             if (Diff != 1)
20268               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20269                                  DAG.getConstant(Diff, Cond.getValueType()));
20270
20271             // Add the base if non-zero.
20272             if (FalseC->getAPIntValue() != 0)
20273               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20274                                  SDValue(FalseC, 0));
20275             return Cond;
20276           }
20277         }
20278       }
20279   }
20280
20281   // Canonicalize max and min:
20282   // (x > y) ? x : y -> (x >= y) ? x : y
20283   // (x < y) ? x : y -> (x <= y) ? x : y
20284   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20285   // the need for an extra compare
20286   // against zero. e.g.
20287   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20288   // subl   %esi, %edi
20289   // testl  %edi, %edi
20290   // movl   $0, %eax
20291   // cmovgl %edi, %eax
20292   // =>
20293   // xorl   %eax, %eax
20294   // subl   %esi, $edi
20295   // cmovsl %eax, %edi
20296   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20297       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20298       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20299     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20300     switch (CC) {
20301     default: break;
20302     case ISD::SETLT:
20303     case ISD::SETGT: {
20304       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20305       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20306                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20307       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20308     }
20309     }
20310   }
20311
20312   // Early exit check
20313   if (!TLI.isTypeLegal(VT))
20314     return SDValue();
20315
20316   // Match VSELECTs into subs with unsigned saturation.
20317   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20318       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20319       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20320        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20321     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20322
20323     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20324     // left side invert the predicate to simplify logic below.
20325     SDValue Other;
20326     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20327       Other = RHS;
20328       CC = ISD::getSetCCInverse(CC, true);
20329     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20330       Other = LHS;
20331     }
20332
20333     if (Other.getNode() && Other->getNumOperands() == 2 &&
20334         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20335       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20336       SDValue CondRHS = Cond->getOperand(1);
20337
20338       // Look for a general sub with unsigned saturation first.
20339       // x >= y ? x-y : 0 --> subus x, y
20340       // x >  y ? x-y : 0 --> subus x, y
20341       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20342           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20343         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20344
20345       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20346         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20347           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20348             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20349               // If the RHS is a constant we have to reverse the const
20350               // canonicalization.
20351               // x > C-1 ? x+-C : 0 --> subus x, C
20352               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20353                   CondRHSConst->getAPIntValue() ==
20354                       (-OpRHSConst->getAPIntValue() - 1))
20355                 return DAG.getNode(
20356                     X86ISD::SUBUS, DL, VT, OpLHS,
20357                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20358
20359           // Another special case: If C was a sign bit, the sub has been
20360           // canonicalized into a xor.
20361           // FIXME: Would it be better to use computeKnownBits to determine
20362           //        whether it's safe to decanonicalize the xor?
20363           // x s< 0 ? x^C : 0 --> subus x, C
20364           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20365               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20366               OpRHSConst->getAPIntValue().isSignBit())
20367             // Note that we have to rebuild the RHS constant here to ensure we
20368             // don't rely on particular values of undef lanes.
20369             return DAG.getNode(
20370                 X86ISD::SUBUS, DL, VT, OpLHS,
20371                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20372         }
20373     }
20374   }
20375
20376   // Try to match a min/max vector operation.
20377   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20378     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20379     unsigned Opc = ret.first;
20380     bool NeedSplit = ret.second;
20381
20382     if (Opc && NeedSplit) {
20383       unsigned NumElems = VT.getVectorNumElements();
20384       // Extract the LHS vectors
20385       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20386       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20387
20388       // Extract the RHS vectors
20389       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20390       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20391
20392       // Create min/max for each subvector
20393       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20394       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20395
20396       // Merge the result
20397       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20398     } else if (Opc)
20399       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20400   }
20401
20402   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20403   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20404       // Check if SETCC has already been promoted
20405       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20406       // Check that condition value type matches vselect operand type
20407       CondVT == VT) { 
20408
20409     assert(Cond.getValueType().isVector() &&
20410            "vector select expects a vector selector!");
20411
20412     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20413     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20414
20415     if (!TValIsAllOnes && !FValIsAllZeros) {
20416       // Try invert the condition if true value is not all 1s and false value
20417       // is not all 0s.
20418       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20419       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20420
20421       if (TValIsAllZeros || FValIsAllOnes) {
20422         SDValue CC = Cond.getOperand(2);
20423         ISD::CondCode NewCC =
20424           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20425                                Cond.getOperand(0).getValueType().isInteger());
20426         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20427         std::swap(LHS, RHS);
20428         TValIsAllOnes = FValIsAllOnes;
20429         FValIsAllZeros = TValIsAllZeros;
20430       }
20431     }
20432
20433     if (TValIsAllOnes || FValIsAllZeros) {
20434       SDValue Ret;
20435
20436       if (TValIsAllOnes && FValIsAllZeros)
20437         Ret = Cond;
20438       else if (TValIsAllOnes)
20439         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20440                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20441       else if (FValIsAllZeros)
20442         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20443                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20444
20445       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20446     }
20447   }
20448
20449   // Try to fold this VSELECT into a MOVSS/MOVSD
20450   if (N->getOpcode() == ISD::VSELECT &&
20451       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20452     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20453         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20454       bool CanFold = false;
20455       unsigned NumElems = Cond.getNumOperands();
20456       SDValue A = LHS;
20457       SDValue B = RHS;
20458       
20459       if (isZero(Cond.getOperand(0))) {
20460         CanFold = true;
20461
20462         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20463         // fold (vselect <0,-1> -> (movsd A, B)
20464         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20465           CanFold = isAllOnes(Cond.getOperand(i));
20466       } else if (isAllOnes(Cond.getOperand(0))) {
20467         CanFold = true;
20468         std::swap(A, B);
20469
20470         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20471         // fold (vselect <-1,0> -> (movsd B, A)
20472         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20473           CanFold = isZero(Cond.getOperand(i));
20474       }
20475
20476       if (CanFold) {
20477         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20478           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20479         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20480       }
20481
20482       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20483         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20484         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20485         //                             (v2i64 (bitcast B)))))
20486         //
20487         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20488         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20489         //                             (v2f64 (bitcast B)))))
20490         //
20491         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20492         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20493         //                             (v2i64 (bitcast A)))))
20494         //
20495         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20496         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20497         //                             (v2f64 (bitcast A)))))
20498
20499         CanFold = (isZero(Cond.getOperand(0)) &&
20500                    isZero(Cond.getOperand(1)) &&
20501                    isAllOnes(Cond.getOperand(2)) &&
20502                    isAllOnes(Cond.getOperand(3)));
20503
20504         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20505             isAllOnes(Cond.getOperand(1)) &&
20506             isZero(Cond.getOperand(2)) &&
20507             isZero(Cond.getOperand(3))) {
20508           CanFold = true;
20509           std::swap(LHS, RHS);
20510         }
20511
20512         if (CanFold) {
20513           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20514           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20515           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20516           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20517                                                 NewB, DAG);
20518           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20519         }
20520       }
20521     }
20522   }
20523
20524   // If we know that this node is legal then we know that it is going to be
20525   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20526   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20527   // to simplify previous instructions.
20528   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20529       !DCI.isBeforeLegalize() &&
20530       // We explicitly check against v8i16 and v16i16 because, although
20531       // they're marked as Custom, they might only be legal when Cond is a
20532       // build_vector of constants. This will be taken care in a later
20533       // condition.
20534       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20535        VT != MVT::v8i16)) {
20536     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20537
20538     // Don't optimize vector selects that map to mask-registers.
20539     if (BitWidth == 1)
20540       return SDValue();
20541
20542     // Check all uses of that condition operand to check whether it will be
20543     // consumed by non-BLEND instructions, which may depend on all bits are set
20544     // properly.
20545     for (SDNode::use_iterator I = Cond->use_begin(),
20546                               E = Cond->use_end(); I != E; ++I)
20547       if (I->getOpcode() != ISD::VSELECT)
20548         // TODO: Add other opcodes eventually lowered into BLEND.
20549         return SDValue();
20550
20551     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20552     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20553
20554     APInt KnownZero, KnownOne;
20555     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20556                                           DCI.isBeforeLegalizeOps());
20557     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20558         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20559       DCI.CommitTargetLoweringOpt(TLO);
20560   }
20561
20562   // We should generate an X86ISD::BLENDI from a vselect if its argument
20563   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20564   // constants. This specific pattern gets generated when we split a
20565   // selector for a 512 bit vector in a machine without AVX512 (but with
20566   // 256-bit vectors), during legalization:
20567   //
20568   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20569   //
20570   // Iff we find this pattern and the build_vectors are built from
20571   // constants, we translate the vselect into a shuffle_vector that we
20572   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20573   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20574     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20575     if (Shuffle.getNode())
20576       return Shuffle;
20577   }
20578
20579   return SDValue();
20580 }
20581
20582 // Check whether a boolean test is testing a boolean value generated by
20583 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20584 // code.
20585 //
20586 // Simplify the following patterns:
20587 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20588 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20589 // to (Op EFLAGS Cond)
20590 //
20591 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20592 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20593 // to (Op EFLAGS !Cond)
20594 //
20595 // where Op could be BRCOND or CMOV.
20596 //
20597 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20598   // Quit if not CMP and SUB with its value result used.
20599   if (Cmp.getOpcode() != X86ISD::CMP &&
20600       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20601       return SDValue();
20602
20603   // Quit if not used as a boolean value.
20604   if (CC != X86::COND_E && CC != X86::COND_NE)
20605     return SDValue();
20606
20607   // Check CMP operands. One of them should be 0 or 1 and the other should be
20608   // an SetCC or extended from it.
20609   SDValue Op1 = Cmp.getOperand(0);
20610   SDValue Op2 = Cmp.getOperand(1);
20611
20612   SDValue SetCC;
20613   const ConstantSDNode* C = nullptr;
20614   bool needOppositeCond = (CC == X86::COND_E);
20615   bool checkAgainstTrue = false; // Is it a comparison against 1?
20616
20617   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20618     SetCC = Op2;
20619   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20620     SetCC = Op1;
20621   else // Quit if all operands are not constants.
20622     return SDValue();
20623
20624   if (C->getZExtValue() == 1) {
20625     needOppositeCond = !needOppositeCond;
20626     checkAgainstTrue = true;
20627   } else if (C->getZExtValue() != 0)
20628     // Quit if the constant is neither 0 or 1.
20629     return SDValue();
20630
20631   bool truncatedToBoolWithAnd = false;
20632   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20633   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20634          SetCC.getOpcode() == ISD::TRUNCATE ||
20635          SetCC.getOpcode() == ISD::AND) {
20636     if (SetCC.getOpcode() == ISD::AND) {
20637       int OpIdx = -1;
20638       ConstantSDNode *CS;
20639       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20640           CS->getZExtValue() == 1)
20641         OpIdx = 1;
20642       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20643           CS->getZExtValue() == 1)
20644         OpIdx = 0;
20645       if (OpIdx == -1)
20646         break;
20647       SetCC = SetCC.getOperand(OpIdx);
20648       truncatedToBoolWithAnd = true;
20649     } else
20650       SetCC = SetCC.getOperand(0);
20651   }
20652
20653   switch (SetCC.getOpcode()) {
20654   case X86ISD::SETCC_CARRY:
20655     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20656     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20657     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20658     // truncated to i1 using 'and'.
20659     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20660       break;
20661     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20662            "Invalid use of SETCC_CARRY!");
20663     // FALL THROUGH
20664   case X86ISD::SETCC:
20665     // Set the condition code or opposite one if necessary.
20666     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20667     if (needOppositeCond)
20668       CC = X86::GetOppositeBranchCondition(CC);
20669     return SetCC.getOperand(1);
20670   case X86ISD::CMOV: {
20671     // Check whether false/true value has canonical one, i.e. 0 or 1.
20672     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20673     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20674     // Quit if true value is not a constant.
20675     if (!TVal)
20676       return SDValue();
20677     // Quit if false value is not a constant.
20678     if (!FVal) {
20679       SDValue Op = SetCC.getOperand(0);
20680       // Skip 'zext' or 'trunc' node.
20681       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20682           Op.getOpcode() == ISD::TRUNCATE)
20683         Op = Op.getOperand(0);
20684       // A special case for rdrand/rdseed, where 0 is set if false cond is
20685       // found.
20686       if ((Op.getOpcode() != X86ISD::RDRAND &&
20687            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20688         return SDValue();
20689     }
20690     // Quit if false value is not the constant 0 or 1.
20691     bool FValIsFalse = true;
20692     if (FVal && FVal->getZExtValue() != 0) {
20693       if (FVal->getZExtValue() != 1)
20694         return SDValue();
20695       // If FVal is 1, opposite cond is needed.
20696       needOppositeCond = !needOppositeCond;
20697       FValIsFalse = false;
20698     }
20699     // Quit if TVal is not the constant opposite of FVal.
20700     if (FValIsFalse && TVal->getZExtValue() != 1)
20701       return SDValue();
20702     if (!FValIsFalse && TVal->getZExtValue() != 0)
20703       return SDValue();
20704     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20705     if (needOppositeCond)
20706       CC = X86::GetOppositeBranchCondition(CC);
20707     return SetCC.getOperand(3);
20708   }
20709   }
20710
20711   return SDValue();
20712 }
20713
20714 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20715 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20716                                   TargetLowering::DAGCombinerInfo &DCI,
20717                                   const X86Subtarget *Subtarget) {
20718   SDLoc DL(N);
20719
20720   // If the flag operand isn't dead, don't touch this CMOV.
20721   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20722     return SDValue();
20723
20724   SDValue FalseOp = N->getOperand(0);
20725   SDValue TrueOp = N->getOperand(1);
20726   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20727   SDValue Cond = N->getOperand(3);
20728
20729   if (CC == X86::COND_E || CC == X86::COND_NE) {
20730     switch (Cond.getOpcode()) {
20731     default: break;
20732     case X86ISD::BSR:
20733     case X86ISD::BSF:
20734       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20735       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20736         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20737     }
20738   }
20739
20740   SDValue Flags;
20741
20742   Flags = checkBoolTestSetCCCombine(Cond, CC);
20743   if (Flags.getNode() &&
20744       // Extra check as FCMOV only supports a subset of X86 cond.
20745       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20746     SDValue Ops[] = { FalseOp, TrueOp,
20747                       DAG.getConstant(CC, MVT::i8), Flags };
20748     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20749   }
20750
20751   // If this is a select between two integer constants, try to do some
20752   // optimizations.  Note that the operands are ordered the opposite of SELECT
20753   // operands.
20754   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20755     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20756       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20757       // larger than FalseC (the false value).
20758       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20759         CC = X86::GetOppositeBranchCondition(CC);
20760         std::swap(TrueC, FalseC);
20761         std::swap(TrueOp, FalseOp);
20762       }
20763
20764       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20765       // This is efficient for any integer data type (including i8/i16) and
20766       // shift amount.
20767       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20768         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20769                            DAG.getConstant(CC, MVT::i8), Cond);
20770
20771         // Zero extend the condition if needed.
20772         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20773
20774         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20775         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20776                            DAG.getConstant(ShAmt, MVT::i8));
20777         if (N->getNumValues() == 2)  // Dead flag value?
20778           return DCI.CombineTo(N, Cond, SDValue());
20779         return Cond;
20780       }
20781
20782       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20783       // for any integer data type, including i8/i16.
20784       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20785         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20786                            DAG.getConstant(CC, MVT::i8), Cond);
20787
20788         // Zero extend the condition if needed.
20789         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20790                            FalseC->getValueType(0), Cond);
20791         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20792                            SDValue(FalseC, 0));
20793
20794         if (N->getNumValues() == 2)  // Dead flag value?
20795           return DCI.CombineTo(N, Cond, SDValue());
20796         return Cond;
20797       }
20798
20799       // Optimize cases that will turn into an LEA instruction.  This requires
20800       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20801       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20802         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20803         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20804
20805         bool isFastMultiplier = false;
20806         if (Diff < 10) {
20807           switch ((unsigned char)Diff) {
20808           default: break;
20809           case 1:  // result = add base, cond
20810           case 2:  // result = lea base(    , cond*2)
20811           case 3:  // result = lea base(cond, cond*2)
20812           case 4:  // result = lea base(    , cond*4)
20813           case 5:  // result = lea base(cond, cond*4)
20814           case 8:  // result = lea base(    , cond*8)
20815           case 9:  // result = lea base(cond, cond*8)
20816             isFastMultiplier = true;
20817             break;
20818           }
20819         }
20820
20821         if (isFastMultiplier) {
20822           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20823           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20824                              DAG.getConstant(CC, MVT::i8), Cond);
20825           // Zero extend the condition if needed.
20826           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20827                              Cond);
20828           // Scale the condition by the difference.
20829           if (Diff != 1)
20830             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20831                                DAG.getConstant(Diff, Cond.getValueType()));
20832
20833           // Add the base if non-zero.
20834           if (FalseC->getAPIntValue() != 0)
20835             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20836                                SDValue(FalseC, 0));
20837           if (N->getNumValues() == 2)  // Dead flag value?
20838             return DCI.CombineTo(N, Cond, SDValue());
20839           return Cond;
20840         }
20841       }
20842     }
20843   }
20844
20845   // Handle these cases:
20846   //   (select (x != c), e, c) -> select (x != c), e, x),
20847   //   (select (x == c), c, e) -> select (x == c), x, e)
20848   // where the c is an integer constant, and the "select" is the combination
20849   // of CMOV and CMP.
20850   //
20851   // The rationale for this change is that the conditional-move from a constant
20852   // needs two instructions, however, conditional-move from a register needs
20853   // only one instruction.
20854   //
20855   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20856   //  some instruction-combining opportunities. This opt needs to be
20857   //  postponed as late as possible.
20858   //
20859   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20860     // the DCI.xxxx conditions are provided to postpone the optimization as
20861     // late as possible.
20862
20863     ConstantSDNode *CmpAgainst = nullptr;
20864     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20865         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20866         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20867
20868       if (CC == X86::COND_NE &&
20869           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20870         CC = X86::GetOppositeBranchCondition(CC);
20871         std::swap(TrueOp, FalseOp);
20872       }
20873
20874       if (CC == X86::COND_E &&
20875           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20876         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20877                           DAG.getConstant(CC, MVT::i8), Cond };
20878         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20879       }
20880     }
20881   }
20882
20883   return SDValue();
20884 }
20885
20886 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20887                                                 const X86Subtarget *Subtarget) {
20888   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20889   switch (IntNo) {
20890   default: return SDValue();
20891   // SSE/AVX/AVX2 blend intrinsics.
20892   case Intrinsic::x86_avx2_pblendvb:
20893   case Intrinsic::x86_avx2_pblendw:
20894   case Intrinsic::x86_avx2_pblendd_128:
20895   case Intrinsic::x86_avx2_pblendd_256:
20896     // Don't try to simplify this intrinsic if we don't have AVX2.
20897     if (!Subtarget->hasAVX2())
20898       return SDValue();
20899     // FALL-THROUGH
20900   case Intrinsic::x86_avx_blend_pd_256:
20901   case Intrinsic::x86_avx_blend_ps_256:
20902   case Intrinsic::x86_avx_blendv_pd_256:
20903   case Intrinsic::x86_avx_blendv_ps_256:
20904     // Don't try to simplify this intrinsic if we don't have AVX.
20905     if (!Subtarget->hasAVX())
20906       return SDValue();
20907     // FALL-THROUGH
20908   case Intrinsic::x86_sse41_pblendw:
20909   case Intrinsic::x86_sse41_blendpd:
20910   case Intrinsic::x86_sse41_blendps:
20911   case Intrinsic::x86_sse41_blendvps:
20912   case Intrinsic::x86_sse41_blendvpd:
20913   case Intrinsic::x86_sse41_pblendvb: {
20914     SDValue Op0 = N->getOperand(1);
20915     SDValue Op1 = N->getOperand(2);
20916     SDValue Mask = N->getOperand(3);
20917
20918     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20919     if (!Subtarget->hasSSE41())
20920       return SDValue();
20921
20922     // fold (blend A, A, Mask) -> A
20923     if (Op0 == Op1)
20924       return Op0;
20925     // fold (blend A, B, allZeros) -> A
20926     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20927       return Op0;
20928     // fold (blend A, B, allOnes) -> B
20929     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20930       return Op1;
20931     
20932     // Simplify the case where the mask is a constant i32 value.
20933     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20934       if (C->isNullValue())
20935         return Op0;
20936       if (C->isAllOnesValue())
20937         return Op1;
20938     }
20939
20940     return SDValue();
20941   }
20942
20943   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20944   case Intrinsic::x86_sse2_psrai_w:
20945   case Intrinsic::x86_sse2_psrai_d:
20946   case Intrinsic::x86_avx2_psrai_w:
20947   case Intrinsic::x86_avx2_psrai_d:
20948   case Intrinsic::x86_sse2_psra_w:
20949   case Intrinsic::x86_sse2_psra_d:
20950   case Intrinsic::x86_avx2_psra_w:
20951   case Intrinsic::x86_avx2_psra_d: {
20952     SDValue Op0 = N->getOperand(1);
20953     SDValue Op1 = N->getOperand(2);
20954     EVT VT = Op0.getValueType();
20955     assert(VT.isVector() && "Expected a vector type!");
20956
20957     if (isa<BuildVectorSDNode>(Op1))
20958       Op1 = Op1.getOperand(0);
20959
20960     if (!isa<ConstantSDNode>(Op1))
20961       return SDValue();
20962
20963     EVT SVT = VT.getVectorElementType();
20964     unsigned SVTBits = SVT.getSizeInBits();
20965
20966     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20967     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20968     uint64_t ShAmt = C.getZExtValue();
20969
20970     // Don't try to convert this shift into a ISD::SRA if the shift
20971     // count is bigger than or equal to the element size.
20972     if (ShAmt >= SVTBits)
20973       return SDValue();
20974
20975     // Trivial case: if the shift count is zero, then fold this
20976     // into the first operand.
20977     if (ShAmt == 0)
20978       return Op0;
20979
20980     // Replace this packed shift intrinsic with a target independent
20981     // shift dag node.
20982     SDValue Splat = DAG.getConstant(C, VT);
20983     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20984   }
20985   }
20986 }
20987
20988 /// PerformMulCombine - Optimize a single multiply with constant into two
20989 /// in order to implement it with two cheaper instructions, e.g.
20990 /// LEA + SHL, LEA + LEA.
20991 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20992                                  TargetLowering::DAGCombinerInfo &DCI) {
20993   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20994     return SDValue();
20995
20996   EVT VT = N->getValueType(0);
20997   if (VT != MVT::i64)
20998     return SDValue();
20999
21000   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21001   if (!C)
21002     return SDValue();
21003   uint64_t MulAmt = C->getZExtValue();
21004   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21005     return SDValue();
21006
21007   uint64_t MulAmt1 = 0;
21008   uint64_t MulAmt2 = 0;
21009   if ((MulAmt % 9) == 0) {
21010     MulAmt1 = 9;
21011     MulAmt2 = MulAmt / 9;
21012   } else if ((MulAmt % 5) == 0) {
21013     MulAmt1 = 5;
21014     MulAmt2 = MulAmt / 5;
21015   } else if ((MulAmt % 3) == 0) {
21016     MulAmt1 = 3;
21017     MulAmt2 = MulAmt / 3;
21018   }
21019   if (MulAmt2 &&
21020       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21021     SDLoc DL(N);
21022
21023     if (isPowerOf2_64(MulAmt2) &&
21024         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21025       // If second multiplifer is pow2, issue it first. We want the multiply by
21026       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21027       // is an add.
21028       std::swap(MulAmt1, MulAmt2);
21029
21030     SDValue NewMul;
21031     if (isPowerOf2_64(MulAmt1))
21032       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21033                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21034     else
21035       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21036                            DAG.getConstant(MulAmt1, VT));
21037
21038     if (isPowerOf2_64(MulAmt2))
21039       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21040                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21041     else
21042       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21043                            DAG.getConstant(MulAmt2, VT));
21044
21045     // Do not add new nodes to DAG combiner worklist.
21046     DCI.CombineTo(N, NewMul, false);
21047   }
21048   return SDValue();
21049 }
21050
21051 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21052   SDValue N0 = N->getOperand(0);
21053   SDValue N1 = N->getOperand(1);
21054   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21055   EVT VT = N0.getValueType();
21056
21057   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21058   // since the result of setcc_c is all zero's or all ones.
21059   if (VT.isInteger() && !VT.isVector() &&
21060       N1C && N0.getOpcode() == ISD::AND &&
21061       N0.getOperand(1).getOpcode() == ISD::Constant) {
21062     SDValue N00 = N0.getOperand(0);
21063     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21064         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21065           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21066          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21067       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21068       APInt ShAmt = N1C->getAPIntValue();
21069       Mask = Mask.shl(ShAmt);
21070       if (Mask != 0)
21071         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21072                            N00, DAG.getConstant(Mask, VT));
21073     }
21074   }
21075
21076   // Hardware support for vector shifts is sparse which makes us scalarize the
21077   // vector operations in many cases. Also, on sandybridge ADD is faster than
21078   // shl.
21079   // (shl V, 1) -> add V,V
21080   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21081     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21082       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21083       // We shift all of the values by one. In many cases we do not have
21084       // hardware support for this operation. This is better expressed as an ADD
21085       // of two values.
21086       if (N1SplatC->getZExtValue() == 1)
21087         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21088     }
21089
21090   return SDValue();
21091 }
21092
21093 /// \brief Returns a vector of 0s if the node in input is a vector logical
21094 /// shift by a constant amount which is known to be bigger than or equal
21095 /// to the vector element size in bits.
21096 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21097                                       const X86Subtarget *Subtarget) {
21098   EVT VT = N->getValueType(0);
21099
21100   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21101       (!Subtarget->hasInt256() ||
21102        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21103     return SDValue();
21104
21105   SDValue Amt = N->getOperand(1);
21106   SDLoc DL(N);
21107   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21108     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21109       APInt ShiftAmt = AmtSplat->getAPIntValue();
21110       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21111
21112       // SSE2/AVX2 logical shifts always return a vector of 0s
21113       // if the shift amount is bigger than or equal to
21114       // the element size. The constant shift amount will be
21115       // encoded as a 8-bit immediate.
21116       if (ShiftAmt.trunc(8).uge(MaxAmount))
21117         return getZeroVector(VT, Subtarget, DAG, DL);
21118     }
21119
21120   return SDValue();
21121 }
21122
21123 /// PerformShiftCombine - Combine shifts.
21124 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21125                                    TargetLowering::DAGCombinerInfo &DCI,
21126                                    const X86Subtarget *Subtarget) {
21127   if (N->getOpcode() == ISD::SHL) {
21128     SDValue V = PerformSHLCombine(N, DAG);
21129     if (V.getNode()) return V;
21130   }
21131
21132   if (N->getOpcode() != ISD::SRA) {
21133     // Try to fold this logical shift into a zero vector.
21134     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21135     if (V.getNode()) return V;
21136   }
21137
21138   return SDValue();
21139 }
21140
21141 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21142 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21143 // and friends.  Likewise for OR -> CMPNEQSS.
21144 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21145                             TargetLowering::DAGCombinerInfo &DCI,
21146                             const X86Subtarget *Subtarget) {
21147   unsigned opcode;
21148
21149   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21150   // we're requiring SSE2 for both.
21151   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21152     SDValue N0 = N->getOperand(0);
21153     SDValue N1 = N->getOperand(1);
21154     SDValue CMP0 = N0->getOperand(1);
21155     SDValue CMP1 = N1->getOperand(1);
21156     SDLoc DL(N);
21157
21158     // The SETCCs should both refer to the same CMP.
21159     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21160       return SDValue();
21161
21162     SDValue CMP00 = CMP0->getOperand(0);
21163     SDValue CMP01 = CMP0->getOperand(1);
21164     EVT     VT    = CMP00.getValueType();
21165
21166     if (VT == MVT::f32 || VT == MVT::f64) {
21167       bool ExpectingFlags = false;
21168       // Check for any users that want flags:
21169       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21170            !ExpectingFlags && UI != UE; ++UI)
21171         switch (UI->getOpcode()) {
21172         default:
21173         case ISD::BR_CC:
21174         case ISD::BRCOND:
21175         case ISD::SELECT:
21176           ExpectingFlags = true;
21177           break;
21178         case ISD::CopyToReg:
21179         case ISD::SIGN_EXTEND:
21180         case ISD::ZERO_EXTEND:
21181         case ISD::ANY_EXTEND:
21182           break;
21183         }
21184
21185       if (!ExpectingFlags) {
21186         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21187         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21188
21189         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21190           X86::CondCode tmp = cc0;
21191           cc0 = cc1;
21192           cc1 = tmp;
21193         }
21194
21195         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21196             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21197           // FIXME: need symbolic constants for these magic numbers.
21198           // See X86ATTInstPrinter.cpp:printSSECC().
21199           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21200           if (Subtarget->hasAVX512()) {
21201             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21202                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21203             if (N->getValueType(0) != MVT::i1)
21204               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21205                                  FSetCC);
21206             return FSetCC;
21207           }
21208           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21209                                               CMP00.getValueType(), CMP00, CMP01,
21210                                               DAG.getConstant(x86cc, MVT::i8));
21211
21212           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21213           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21214
21215           if (is64BitFP && !Subtarget->is64Bit()) {
21216             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21217             // 64-bit integer, since that's not a legal type. Since
21218             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21219             // bits, but can do this little dance to extract the lowest 32 bits
21220             // and work with those going forward.
21221             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21222                                            OnesOrZeroesF);
21223             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21224                                            Vector64);
21225             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21226                                         Vector32, DAG.getIntPtrConstant(0));
21227             IntVT = MVT::i32;
21228           }
21229
21230           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21231           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21232                                       DAG.getConstant(1, IntVT));
21233           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21234           return OneBitOfTruth;
21235         }
21236       }
21237     }
21238   }
21239   return SDValue();
21240 }
21241
21242 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21243 /// so it can be folded inside ANDNP.
21244 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21245   EVT VT = N->getValueType(0);
21246
21247   // Match direct AllOnes for 128 and 256-bit vectors
21248   if (ISD::isBuildVectorAllOnes(N))
21249     return true;
21250
21251   // Look through a bit convert.
21252   if (N->getOpcode() == ISD::BITCAST)
21253     N = N->getOperand(0).getNode();
21254
21255   // Sometimes the operand may come from a insert_subvector building a 256-bit
21256   // allones vector
21257   if (VT.is256BitVector() &&
21258       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21259     SDValue V1 = N->getOperand(0);
21260     SDValue V2 = N->getOperand(1);
21261
21262     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21263         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21264         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21265         ISD::isBuildVectorAllOnes(V2.getNode()))
21266       return true;
21267   }
21268
21269   return false;
21270 }
21271
21272 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21273 // register. In most cases we actually compare or select YMM-sized registers
21274 // and mixing the two types creates horrible code. This method optimizes
21275 // some of the transition sequences.
21276 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21277                                  TargetLowering::DAGCombinerInfo &DCI,
21278                                  const X86Subtarget *Subtarget) {
21279   EVT VT = N->getValueType(0);
21280   if (!VT.is256BitVector())
21281     return SDValue();
21282
21283   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21284           N->getOpcode() == ISD::ZERO_EXTEND ||
21285           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21286
21287   SDValue Narrow = N->getOperand(0);
21288   EVT NarrowVT = Narrow->getValueType(0);
21289   if (!NarrowVT.is128BitVector())
21290     return SDValue();
21291
21292   if (Narrow->getOpcode() != ISD::XOR &&
21293       Narrow->getOpcode() != ISD::AND &&
21294       Narrow->getOpcode() != ISD::OR)
21295     return SDValue();
21296
21297   SDValue N0  = Narrow->getOperand(0);
21298   SDValue N1  = Narrow->getOperand(1);
21299   SDLoc DL(Narrow);
21300
21301   // The Left side has to be a trunc.
21302   if (N0.getOpcode() != ISD::TRUNCATE)
21303     return SDValue();
21304
21305   // The type of the truncated inputs.
21306   EVT WideVT = N0->getOperand(0)->getValueType(0);
21307   if (WideVT != VT)
21308     return SDValue();
21309
21310   // The right side has to be a 'trunc' or a constant vector.
21311   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21312   ConstantSDNode *RHSConstSplat = nullptr;
21313   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21314     RHSConstSplat = RHSBV->getConstantSplatNode();
21315   if (!RHSTrunc && !RHSConstSplat)
21316     return SDValue();
21317
21318   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21319
21320   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21321     return SDValue();
21322
21323   // Set N0 and N1 to hold the inputs to the new wide operation.
21324   N0 = N0->getOperand(0);
21325   if (RHSConstSplat) {
21326     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21327                      SDValue(RHSConstSplat, 0));
21328     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21329     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21330   } else if (RHSTrunc) {
21331     N1 = N1->getOperand(0);
21332   }
21333
21334   // Generate the wide operation.
21335   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21336   unsigned Opcode = N->getOpcode();
21337   switch (Opcode) {
21338   case ISD::ANY_EXTEND:
21339     return Op;
21340   case ISD::ZERO_EXTEND: {
21341     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21342     APInt Mask = APInt::getAllOnesValue(InBits);
21343     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21344     return DAG.getNode(ISD::AND, DL, VT,
21345                        Op, DAG.getConstant(Mask, VT));
21346   }
21347   case ISD::SIGN_EXTEND:
21348     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21349                        Op, DAG.getValueType(NarrowVT));
21350   default:
21351     llvm_unreachable("Unexpected opcode");
21352   }
21353 }
21354
21355 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21356                                  TargetLowering::DAGCombinerInfo &DCI,
21357                                  const X86Subtarget *Subtarget) {
21358   EVT VT = N->getValueType(0);
21359   if (DCI.isBeforeLegalizeOps())
21360     return SDValue();
21361
21362   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21363   if (R.getNode())
21364     return R;
21365
21366   // Create BEXTR instructions
21367   // BEXTR is ((X >> imm) & (2**size-1))
21368   if (VT == MVT::i32 || VT == MVT::i64) {
21369     SDValue N0 = N->getOperand(0);
21370     SDValue N1 = N->getOperand(1);
21371     SDLoc DL(N);
21372
21373     // Check for BEXTR.
21374     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21375         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21376       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21377       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21378       if (MaskNode && ShiftNode) {
21379         uint64_t Mask = MaskNode->getZExtValue();
21380         uint64_t Shift = ShiftNode->getZExtValue();
21381         if (isMask_64(Mask)) {
21382           uint64_t MaskSize = CountPopulation_64(Mask);
21383           if (Shift + MaskSize <= VT.getSizeInBits())
21384             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21385                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21386         }
21387       }
21388     } // BEXTR
21389
21390     return SDValue();
21391   }
21392
21393   // Want to form ANDNP nodes:
21394   // 1) In the hopes of then easily combining them with OR and AND nodes
21395   //    to form PBLEND/PSIGN.
21396   // 2) To match ANDN packed intrinsics
21397   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21398     return SDValue();
21399
21400   SDValue N0 = N->getOperand(0);
21401   SDValue N1 = N->getOperand(1);
21402   SDLoc DL(N);
21403
21404   // Check LHS for vnot
21405   if (N0.getOpcode() == ISD::XOR &&
21406       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21407       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21408     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21409
21410   // Check RHS for vnot
21411   if (N1.getOpcode() == ISD::XOR &&
21412       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21413       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21414     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21415
21416   return SDValue();
21417 }
21418
21419 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21420                                 TargetLowering::DAGCombinerInfo &DCI,
21421                                 const X86Subtarget *Subtarget) {
21422   if (DCI.isBeforeLegalizeOps())
21423     return SDValue();
21424
21425   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21426   if (R.getNode())
21427     return R;
21428
21429   SDValue N0 = N->getOperand(0);
21430   SDValue N1 = N->getOperand(1);
21431   EVT VT = N->getValueType(0);
21432
21433   // look for psign/blend
21434   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21435     if (!Subtarget->hasSSSE3() ||
21436         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21437       return SDValue();
21438
21439     // Canonicalize pandn to RHS
21440     if (N0.getOpcode() == X86ISD::ANDNP)
21441       std::swap(N0, N1);
21442     // or (and (m, y), (pandn m, x))
21443     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21444       SDValue Mask = N1.getOperand(0);
21445       SDValue X    = N1.getOperand(1);
21446       SDValue Y;
21447       if (N0.getOperand(0) == Mask)
21448         Y = N0.getOperand(1);
21449       if (N0.getOperand(1) == Mask)
21450         Y = N0.getOperand(0);
21451
21452       // Check to see if the mask appeared in both the AND and ANDNP and
21453       if (!Y.getNode())
21454         return SDValue();
21455
21456       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21457       // Look through mask bitcast.
21458       if (Mask.getOpcode() == ISD::BITCAST)
21459         Mask = Mask.getOperand(0);
21460       if (X.getOpcode() == ISD::BITCAST)
21461         X = X.getOperand(0);
21462       if (Y.getOpcode() == ISD::BITCAST)
21463         Y = Y.getOperand(0);
21464
21465       EVT MaskVT = Mask.getValueType();
21466
21467       // Validate that the Mask operand is a vector sra node.
21468       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21469       // there is no psrai.b
21470       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21471       unsigned SraAmt = ~0;
21472       if (Mask.getOpcode() == ISD::SRA) {
21473         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21474           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21475             SraAmt = AmtConst->getZExtValue();
21476       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21477         SDValue SraC = Mask.getOperand(1);
21478         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21479       }
21480       if ((SraAmt + 1) != EltBits)
21481         return SDValue();
21482
21483       SDLoc DL(N);
21484
21485       // Now we know we at least have a plendvb with the mask val.  See if
21486       // we can form a psignb/w/d.
21487       // psign = x.type == y.type == mask.type && y = sub(0, x);
21488       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21489           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21490           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21491         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21492                "Unsupported VT for PSIGN");
21493         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21494         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21495       }
21496       // PBLENDVB only available on SSE 4.1
21497       if (!Subtarget->hasSSE41())
21498         return SDValue();
21499
21500       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21501
21502       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21503       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21504       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21505       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21506       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21507     }
21508   }
21509
21510   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21511     return SDValue();
21512
21513   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21514   MachineFunction &MF = DAG.getMachineFunction();
21515   bool OptForSize = MF.getFunction()->getAttributes().
21516     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21517
21518   // SHLD/SHRD instructions have lower register pressure, but on some
21519   // platforms they have higher latency than the equivalent
21520   // series of shifts/or that would otherwise be generated.
21521   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21522   // have higher latencies and we are not optimizing for size.
21523   if (!OptForSize && Subtarget->isSHLDSlow())
21524     return SDValue();
21525
21526   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21527     std::swap(N0, N1);
21528   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21529     return SDValue();
21530   if (!N0.hasOneUse() || !N1.hasOneUse())
21531     return SDValue();
21532
21533   SDValue ShAmt0 = N0.getOperand(1);
21534   if (ShAmt0.getValueType() != MVT::i8)
21535     return SDValue();
21536   SDValue ShAmt1 = N1.getOperand(1);
21537   if (ShAmt1.getValueType() != MVT::i8)
21538     return SDValue();
21539   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21540     ShAmt0 = ShAmt0.getOperand(0);
21541   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21542     ShAmt1 = ShAmt1.getOperand(0);
21543
21544   SDLoc DL(N);
21545   unsigned Opc = X86ISD::SHLD;
21546   SDValue Op0 = N0.getOperand(0);
21547   SDValue Op1 = N1.getOperand(0);
21548   if (ShAmt0.getOpcode() == ISD::SUB) {
21549     Opc = X86ISD::SHRD;
21550     std::swap(Op0, Op1);
21551     std::swap(ShAmt0, ShAmt1);
21552   }
21553
21554   unsigned Bits = VT.getSizeInBits();
21555   if (ShAmt1.getOpcode() == ISD::SUB) {
21556     SDValue Sum = ShAmt1.getOperand(0);
21557     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21558       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21559       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21560         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21561       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21562         return DAG.getNode(Opc, DL, VT,
21563                            Op0, Op1,
21564                            DAG.getNode(ISD::TRUNCATE, DL,
21565                                        MVT::i8, ShAmt0));
21566     }
21567   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21568     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21569     if (ShAmt0C &&
21570         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21571       return DAG.getNode(Opc, DL, VT,
21572                          N0.getOperand(0), N1.getOperand(0),
21573                          DAG.getNode(ISD::TRUNCATE, DL,
21574                                        MVT::i8, ShAmt0));
21575   }
21576
21577   return SDValue();
21578 }
21579
21580 // Generate NEG and CMOV for integer abs.
21581 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21582   EVT VT = N->getValueType(0);
21583
21584   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21585   // 8-bit integer abs to NEG and CMOV.
21586   if (VT.isInteger() && VT.getSizeInBits() == 8)
21587     return SDValue();
21588
21589   SDValue N0 = N->getOperand(0);
21590   SDValue N1 = N->getOperand(1);
21591   SDLoc DL(N);
21592
21593   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21594   // and change it to SUB and CMOV.
21595   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21596       N0.getOpcode() == ISD::ADD &&
21597       N0.getOperand(1) == N1 &&
21598       N1.getOpcode() == ISD::SRA &&
21599       N1.getOperand(0) == N0.getOperand(0))
21600     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21601       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21602         // Generate SUB & CMOV.
21603         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21604                                   DAG.getConstant(0, VT), N0.getOperand(0));
21605
21606         SDValue Ops[] = { N0.getOperand(0), Neg,
21607                           DAG.getConstant(X86::COND_GE, MVT::i8),
21608                           SDValue(Neg.getNode(), 1) };
21609         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21610       }
21611   return SDValue();
21612 }
21613
21614 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21615 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21616                                  TargetLowering::DAGCombinerInfo &DCI,
21617                                  const X86Subtarget *Subtarget) {
21618   if (DCI.isBeforeLegalizeOps())
21619     return SDValue();
21620
21621   if (Subtarget->hasCMov()) {
21622     SDValue RV = performIntegerAbsCombine(N, DAG);
21623     if (RV.getNode())
21624       return RV;
21625   }
21626
21627   return SDValue();
21628 }
21629
21630 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21631 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21632                                   TargetLowering::DAGCombinerInfo &DCI,
21633                                   const X86Subtarget *Subtarget) {
21634   LoadSDNode *Ld = cast<LoadSDNode>(N);
21635   EVT RegVT = Ld->getValueType(0);
21636   EVT MemVT = Ld->getMemoryVT();
21637   SDLoc dl(Ld);
21638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21639
21640   // On Sandybridge unaligned 256bit loads are inefficient.
21641   ISD::LoadExtType Ext = Ld->getExtensionType();
21642   unsigned Alignment = Ld->getAlignment();
21643   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21644   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21645       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21646     unsigned NumElems = RegVT.getVectorNumElements();
21647     if (NumElems < 2)
21648       return SDValue();
21649
21650     SDValue Ptr = Ld->getBasePtr();
21651     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21652
21653     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21654                                   NumElems/2);
21655     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21656                                 Ld->getPointerInfo(), Ld->isVolatile(),
21657                                 Ld->isNonTemporal(), Ld->isInvariant(),
21658                                 Alignment);
21659     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21660     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21661                                 Ld->getPointerInfo(), Ld->isVolatile(),
21662                                 Ld->isNonTemporal(), Ld->isInvariant(),
21663                                 std::min(16U, Alignment));
21664     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21665                              Load1.getValue(1),
21666                              Load2.getValue(1));
21667
21668     SDValue NewVec = DAG.getUNDEF(RegVT);
21669     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21670     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21671     return DCI.CombineTo(N, NewVec, TF, true);
21672   }
21673
21674   return SDValue();
21675 }
21676
21677 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21678 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21679                                    const X86Subtarget *Subtarget) {
21680   StoreSDNode *St = cast<StoreSDNode>(N);
21681   EVT VT = St->getValue().getValueType();
21682   EVT StVT = St->getMemoryVT();
21683   SDLoc dl(St);
21684   SDValue StoredVal = St->getOperand(1);
21685   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21686
21687   // If we are saving a concatenation of two XMM registers, perform two stores.
21688   // On Sandy Bridge, 256-bit memory operations are executed by two
21689   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21690   // memory  operation.
21691   unsigned Alignment = St->getAlignment();
21692   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21693   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21694       StVT == VT && !IsAligned) {
21695     unsigned NumElems = VT.getVectorNumElements();
21696     if (NumElems < 2)
21697       return SDValue();
21698
21699     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21700     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21701
21702     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21703     SDValue Ptr0 = St->getBasePtr();
21704     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21705
21706     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21707                                 St->getPointerInfo(), St->isVolatile(),
21708                                 St->isNonTemporal(), Alignment);
21709     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21710                                 St->getPointerInfo(), St->isVolatile(),
21711                                 St->isNonTemporal(),
21712                                 std::min(16U, Alignment));
21713     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21714   }
21715
21716   // Optimize trunc store (of multiple scalars) to shuffle and store.
21717   // First, pack all of the elements in one place. Next, store to memory
21718   // in fewer chunks.
21719   if (St->isTruncatingStore() && VT.isVector()) {
21720     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21721     unsigned NumElems = VT.getVectorNumElements();
21722     assert(StVT != VT && "Cannot truncate to the same type");
21723     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21724     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21725
21726     // From, To sizes and ElemCount must be pow of two
21727     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21728     // We are going to use the original vector elt for storing.
21729     // Accumulated smaller vector elements must be a multiple of the store size.
21730     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21731
21732     unsigned SizeRatio  = FromSz / ToSz;
21733
21734     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21735
21736     // Create a type on which we perform the shuffle
21737     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21738             StVT.getScalarType(), NumElems*SizeRatio);
21739
21740     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21741
21742     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21743     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21744     for (unsigned i = 0; i != NumElems; ++i)
21745       ShuffleVec[i] = i * SizeRatio;
21746
21747     // Can't shuffle using an illegal type.
21748     if (!TLI.isTypeLegal(WideVecVT))
21749       return SDValue();
21750
21751     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21752                                          DAG.getUNDEF(WideVecVT),
21753                                          &ShuffleVec[0]);
21754     // At this point all of the data is stored at the bottom of the
21755     // register. We now need to save it to mem.
21756
21757     // Find the largest store unit
21758     MVT StoreType = MVT::i8;
21759     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21760          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21761       MVT Tp = (MVT::SimpleValueType)tp;
21762       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21763         StoreType = Tp;
21764     }
21765
21766     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21767     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21768         (64 <= NumElems * ToSz))
21769       StoreType = MVT::f64;
21770
21771     // Bitcast the original vector into a vector of store-size units
21772     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21773             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21774     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21775     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21776     SmallVector<SDValue, 8> Chains;
21777     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21778                                         TLI.getPointerTy());
21779     SDValue Ptr = St->getBasePtr();
21780
21781     // Perform one or more big stores into memory.
21782     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21783       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21784                                    StoreType, ShuffWide,
21785                                    DAG.getIntPtrConstant(i));
21786       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21787                                 St->getPointerInfo(), St->isVolatile(),
21788                                 St->isNonTemporal(), St->getAlignment());
21789       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21790       Chains.push_back(Ch);
21791     }
21792
21793     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21794   }
21795
21796   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21797   // the FP state in cases where an emms may be missing.
21798   // A preferable solution to the general problem is to figure out the right
21799   // places to insert EMMS.  This qualifies as a quick hack.
21800
21801   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21802   if (VT.getSizeInBits() != 64)
21803     return SDValue();
21804
21805   const Function *F = DAG.getMachineFunction().getFunction();
21806   bool NoImplicitFloatOps = F->getAttributes().
21807     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21808   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21809                      && Subtarget->hasSSE2();
21810   if ((VT.isVector() ||
21811        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21812       isa<LoadSDNode>(St->getValue()) &&
21813       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21814       St->getChain().hasOneUse() && !St->isVolatile()) {
21815     SDNode* LdVal = St->getValue().getNode();
21816     LoadSDNode *Ld = nullptr;
21817     int TokenFactorIndex = -1;
21818     SmallVector<SDValue, 8> Ops;
21819     SDNode* ChainVal = St->getChain().getNode();
21820     // Must be a store of a load.  We currently handle two cases:  the load
21821     // is a direct child, and it's under an intervening TokenFactor.  It is
21822     // possible to dig deeper under nested TokenFactors.
21823     if (ChainVal == LdVal)
21824       Ld = cast<LoadSDNode>(St->getChain());
21825     else if (St->getValue().hasOneUse() &&
21826              ChainVal->getOpcode() == ISD::TokenFactor) {
21827       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21828         if (ChainVal->getOperand(i).getNode() == LdVal) {
21829           TokenFactorIndex = i;
21830           Ld = cast<LoadSDNode>(St->getValue());
21831         } else
21832           Ops.push_back(ChainVal->getOperand(i));
21833       }
21834     }
21835
21836     if (!Ld || !ISD::isNormalLoad(Ld))
21837       return SDValue();
21838
21839     // If this is not the MMX case, i.e. we are just turning i64 load/store
21840     // into f64 load/store, avoid the transformation if there are multiple
21841     // uses of the loaded value.
21842     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21843       return SDValue();
21844
21845     SDLoc LdDL(Ld);
21846     SDLoc StDL(N);
21847     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21848     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21849     // pair instead.
21850     if (Subtarget->is64Bit() || F64IsLegal) {
21851       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21852       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21853                                   Ld->getPointerInfo(), Ld->isVolatile(),
21854                                   Ld->isNonTemporal(), Ld->isInvariant(),
21855                                   Ld->getAlignment());
21856       SDValue NewChain = NewLd.getValue(1);
21857       if (TokenFactorIndex != -1) {
21858         Ops.push_back(NewChain);
21859         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21860       }
21861       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21862                           St->getPointerInfo(),
21863                           St->isVolatile(), St->isNonTemporal(),
21864                           St->getAlignment());
21865     }
21866
21867     // Otherwise, lower to two pairs of 32-bit loads / stores.
21868     SDValue LoAddr = Ld->getBasePtr();
21869     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21870                                  DAG.getConstant(4, MVT::i32));
21871
21872     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21873                                Ld->getPointerInfo(),
21874                                Ld->isVolatile(), Ld->isNonTemporal(),
21875                                Ld->isInvariant(), Ld->getAlignment());
21876     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21877                                Ld->getPointerInfo().getWithOffset(4),
21878                                Ld->isVolatile(), Ld->isNonTemporal(),
21879                                Ld->isInvariant(),
21880                                MinAlign(Ld->getAlignment(), 4));
21881
21882     SDValue NewChain = LoLd.getValue(1);
21883     if (TokenFactorIndex != -1) {
21884       Ops.push_back(LoLd);
21885       Ops.push_back(HiLd);
21886       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21887     }
21888
21889     LoAddr = St->getBasePtr();
21890     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21891                          DAG.getConstant(4, MVT::i32));
21892
21893     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21894                                 St->getPointerInfo(),
21895                                 St->isVolatile(), St->isNonTemporal(),
21896                                 St->getAlignment());
21897     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21898                                 St->getPointerInfo().getWithOffset(4),
21899                                 St->isVolatile(),
21900                                 St->isNonTemporal(),
21901                                 MinAlign(St->getAlignment(), 4));
21902     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21903   }
21904   return SDValue();
21905 }
21906
21907 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21908 /// and return the operands for the horizontal operation in LHS and RHS.  A
21909 /// horizontal operation performs the binary operation on successive elements
21910 /// of its first operand, then on successive elements of its second operand,
21911 /// returning the resulting values in a vector.  For example, if
21912 ///   A = < float a0, float a1, float a2, float a3 >
21913 /// and
21914 ///   B = < float b0, float b1, float b2, float b3 >
21915 /// then the result of doing a horizontal operation on A and B is
21916 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21917 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21918 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21919 /// set to A, RHS to B, and the routine returns 'true'.
21920 /// Note that the binary operation should have the property that if one of the
21921 /// operands is UNDEF then the result is UNDEF.
21922 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21923   // Look for the following pattern: if
21924   //   A = < float a0, float a1, float a2, float a3 >
21925   //   B = < float b0, float b1, float b2, float b3 >
21926   // and
21927   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21928   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21929   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21930   // which is A horizontal-op B.
21931
21932   // At least one of the operands should be a vector shuffle.
21933   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21934       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21935     return false;
21936
21937   MVT VT = LHS.getSimpleValueType();
21938
21939   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21940          "Unsupported vector type for horizontal add/sub");
21941
21942   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21943   // operate independently on 128-bit lanes.
21944   unsigned NumElts = VT.getVectorNumElements();
21945   unsigned NumLanes = VT.getSizeInBits()/128;
21946   unsigned NumLaneElts = NumElts / NumLanes;
21947   assert((NumLaneElts % 2 == 0) &&
21948          "Vector type should have an even number of elements in each lane");
21949   unsigned HalfLaneElts = NumLaneElts/2;
21950
21951   // View LHS in the form
21952   //   LHS = VECTOR_SHUFFLE A, B, LMask
21953   // If LHS is not a shuffle then pretend it is the shuffle
21954   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21955   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21956   // type VT.
21957   SDValue A, B;
21958   SmallVector<int, 16> LMask(NumElts);
21959   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21960     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21961       A = LHS.getOperand(0);
21962     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21963       B = LHS.getOperand(1);
21964     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21965     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21966   } else {
21967     if (LHS.getOpcode() != ISD::UNDEF)
21968       A = LHS;
21969     for (unsigned i = 0; i != NumElts; ++i)
21970       LMask[i] = i;
21971   }
21972
21973   // Likewise, view RHS in the form
21974   //   RHS = VECTOR_SHUFFLE C, D, RMask
21975   SDValue C, D;
21976   SmallVector<int, 16> RMask(NumElts);
21977   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21978     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21979       C = RHS.getOperand(0);
21980     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21981       D = RHS.getOperand(1);
21982     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21983     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21984   } else {
21985     if (RHS.getOpcode() != ISD::UNDEF)
21986       C = RHS;
21987     for (unsigned i = 0; i != NumElts; ++i)
21988       RMask[i] = i;
21989   }
21990
21991   // Check that the shuffles are both shuffling the same vectors.
21992   if (!(A == C && B == D) && !(A == D && B == C))
21993     return false;
21994
21995   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21996   if (!A.getNode() && !B.getNode())
21997     return false;
21998
21999   // If A and B occur in reverse order in RHS, then "swap" them (which means
22000   // rewriting the mask).
22001   if (A != C)
22002     CommuteVectorShuffleMask(RMask, NumElts);
22003
22004   // At this point LHS and RHS are equivalent to
22005   //   LHS = VECTOR_SHUFFLE A, B, LMask
22006   //   RHS = VECTOR_SHUFFLE A, B, RMask
22007   // Check that the masks correspond to performing a horizontal operation.
22008   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22009     for (unsigned i = 0; i != NumLaneElts; ++i) {
22010       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22011
22012       // Ignore any UNDEF components.
22013       if (LIdx < 0 || RIdx < 0 ||
22014           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22015           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22016         continue;
22017
22018       // Check that successive elements are being operated on.  If not, this is
22019       // not a horizontal operation.
22020       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22021       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22022       if (!(LIdx == Index && RIdx == Index + 1) &&
22023           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22024         return false;
22025     }
22026   }
22027
22028   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22029   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22030   return true;
22031 }
22032
22033 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22034 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22035                                   const X86Subtarget *Subtarget) {
22036   EVT VT = N->getValueType(0);
22037   SDValue LHS = N->getOperand(0);
22038   SDValue RHS = N->getOperand(1);
22039
22040   // Try to synthesize horizontal adds from adds of shuffles.
22041   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22042        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22043       isHorizontalBinOp(LHS, RHS, true))
22044     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22045   return SDValue();
22046 }
22047
22048 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22049 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22050                                   const X86Subtarget *Subtarget) {
22051   EVT VT = N->getValueType(0);
22052   SDValue LHS = N->getOperand(0);
22053   SDValue RHS = N->getOperand(1);
22054
22055   // Try to synthesize horizontal subs from subs of shuffles.
22056   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22057        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22058       isHorizontalBinOp(LHS, RHS, false))
22059     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22060   return SDValue();
22061 }
22062
22063 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22064 /// X86ISD::FXOR nodes.
22065 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22066   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22067   // F[X]OR(0.0, x) -> x
22068   // F[X]OR(x, 0.0) -> x
22069   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22070     if (C->getValueAPF().isPosZero())
22071       return N->getOperand(1);
22072   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22073     if (C->getValueAPF().isPosZero())
22074       return N->getOperand(0);
22075   return SDValue();
22076 }
22077
22078 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22079 /// X86ISD::FMAX nodes.
22080 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22081   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22082
22083   // Only perform optimizations if UnsafeMath is used.
22084   if (!DAG.getTarget().Options.UnsafeFPMath)
22085     return SDValue();
22086
22087   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22088   // into FMINC and FMAXC, which are Commutative operations.
22089   unsigned NewOp = 0;
22090   switch (N->getOpcode()) {
22091     default: llvm_unreachable("unknown opcode");
22092     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22093     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22094   }
22095
22096   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22097                      N->getOperand(0), N->getOperand(1));
22098 }
22099
22100 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22101 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22102   // FAND(0.0, x) -> 0.0
22103   // FAND(x, 0.0) -> 0.0
22104   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22105     if (C->getValueAPF().isPosZero())
22106       return N->getOperand(0);
22107   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22108     if (C->getValueAPF().isPosZero())
22109       return N->getOperand(1);
22110   return SDValue();
22111 }
22112
22113 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22114 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22115   // FANDN(x, 0.0) -> 0.0
22116   // FANDN(0.0, x) -> x
22117   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22118     if (C->getValueAPF().isPosZero())
22119       return N->getOperand(1);
22120   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22121     if (C->getValueAPF().isPosZero())
22122       return N->getOperand(1);
22123   return SDValue();
22124 }
22125
22126 static SDValue PerformBTCombine(SDNode *N,
22127                                 SelectionDAG &DAG,
22128                                 TargetLowering::DAGCombinerInfo &DCI) {
22129   // BT ignores high bits in the bit index operand.
22130   SDValue Op1 = N->getOperand(1);
22131   if (Op1.hasOneUse()) {
22132     unsigned BitWidth = Op1.getValueSizeInBits();
22133     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22134     APInt KnownZero, KnownOne;
22135     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22136                                           !DCI.isBeforeLegalizeOps());
22137     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22138     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22139         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22140       DCI.CommitTargetLoweringOpt(TLO);
22141   }
22142   return SDValue();
22143 }
22144
22145 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22146   SDValue Op = N->getOperand(0);
22147   if (Op.getOpcode() == ISD::BITCAST)
22148     Op = Op.getOperand(0);
22149   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22150   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22151       VT.getVectorElementType().getSizeInBits() ==
22152       OpVT.getVectorElementType().getSizeInBits()) {
22153     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22154   }
22155   return SDValue();
22156 }
22157
22158 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22159                                                const X86Subtarget *Subtarget) {
22160   EVT VT = N->getValueType(0);
22161   if (!VT.isVector())
22162     return SDValue();
22163
22164   SDValue N0 = N->getOperand(0);
22165   SDValue N1 = N->getOperand(1);
22166   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22167   SDLoc dl(N);
22168
22169   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22170   // both SSE and AVX2 since there is no sign-extended shift right
22171   // operation on a vector with 64-bit elements.
22172   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22173   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22174   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22175       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22176     SDValue N00 = N0.getOperand(0);
22177
22178     // EXTLOAD has a better solution on AVX2,
22179     // it may be replaced with X86ISD::VSEXT node.
22180     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22181       if (!ISD::isNormalLoad(N00.getNode()))
22182         return SDValue();
22183
22184     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22185         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22186                                   N00, N1);
22187       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22188     }
22189   }
22190   return SDValue();
22191 }
22192
22193 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22194                                   TargetLowering::DAGCombinerInfo &DCI,
22195                                   const X86Subtarget *Subtarget) {
22196   if (!DCI.isBeforeLegalizeOps())
22197     return SDValue();
22198
22199   if (!Subtarget->hasFp256())
22200     return SDValue();
22201
22202   EVT VT = N->getValueType(0);
22203   if (VT.isVector() && VT.getSizeInBits() == 256) {
22204     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22205     if (R.getNode())
22206       return R;
22207   }
22208
22209   return SDValue();
22210 }
22211
22212 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22213                                  const X86Subtarget* Subtarget) {
22214   SDLoc dl(N);
22215   EVT VT = N->getValueType(0);
22216
22217   // Let legalize expand this if it isn't a legal type yet.
22218   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22219     return SDValue();
22220
22221   EVT ScalarVT = VT.getScalarType();
22222   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22223       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22224     return SDValue();
22225
22226   SDValue A = N->getOperand(0);
22227   SDValue B = N->getOperand(1);
22228   SDValue C = N->getOperand(2);
22229
22230   bool NegA = (A.getOpcode() == ISD::FNEG);
22231   bool NegB = (B.getOpcode() == ISD::FNEG);
22232   bool NegC = (C.getOpcode() == ISD::FNEG);
22233
22234   // Negative multiplication when NegA xor NegB
22235   bool NegMul = (NegA != NegB);
22236   if (NegA)
22237     A = A.getOperand(0);
22238   if (NegB)
22239     B = B.getOperand(0);
22240   if (NegC)
22241     C = C.getOperand(0);
22242
22243   unsigned Opcode;
22244   if (!NegMul)
22245     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22246   else
22247     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22248
22249   return DAG.getNode(Opcode, dl, VT, A, B, C);
22250 }
22251
22252 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22253                                   TargetLowering::DAGCombinerInfo &DCI,
22254                                   const X86Subtarget *Subtarget) {
22255   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22256   //           (and (i32 x86isd::setcc_carry), 1)
22257   // This eliminates the zext. This transformation is necessary because
22258   // ISD::SETCC is always legalized to i8.
22259   SDLoc dl(N);
22260   SDValue N0 = N->getOperand(0);
22261   EVT VT = N->getValueType(0);
22262
22263   if (N0.getOpcode() == ISD::AND &&
22264       N0.hasOneUse() &&
22265       N0.getOperand(0).hasOneUse()) {
22266     SDValue N00 = N0.getOperand(0);
22267     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22268       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22269       if (!C || C->getZExtValue() != 1)
22270         return SDValue();
22271       return DAG.getNode(ISD::AND, dl, VT,
22272                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22273                                      N00.getOperand(0), N00.getOperand(1)),
22274                          DAG.getConstant(1, VT));
22275     }
22276   }
22277
22278   if (N0.getOpcode() == ISD::TRUNCATE &&
22279       N0.hasOneUse() &&
22280       N0.getOperand(0).hasOneUse()) {
22281     SDValue N00 = N0.getOperand(0);
22282     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22283       return DAG.getNode(ISD::AND, dl, VT,
22284                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22285                                      N00.getOperand(0), N00.getOperand(1)),
22286                          DAG.getConstant(1, VT));
22287     }
22288   }
22289   if (VT.is256BitVector()) {
22290     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22291     if (R.getNode())
22292       return R;
22293   }
22294
22295   return SDValue();
22296 }
22297
22298 // Optimize x == -y --> x+y == 0
22299 //          x != -y --> x+y != 0
22300 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22301                                       const X86Subtarget* Subtarget) {
22302   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22303   SDValue LHS = N->getOperand(0);
22304   SDValue RHS = N->getOperand(1);
22305   EVT VT = N->getValueType(0);
22306   SDLoc DL(N);
22307
22308   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22309     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22310       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22311         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22312                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22313         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22314                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22315       }
22316   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22317     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22318       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22319         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22320                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22321         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22322                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22323       }
22324
22325   if (VT.getScalarType() == MVT::i1) {
22326     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22327       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22328     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22329     if (!IsSEXT0 && !IsVZero0)
22330       return SDValue();
22331     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22332       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22333     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22334
22335     if (!IsSEXT1 && !IsVZero1)
22336       return SDValue();
22337
22338     if (IsSEXT0 && IsVZero1) {
22339       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22340       if (CC == ISD::SETEQ)
22341         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22342       return LHS.getOperand(0);
22343     }
22344     if (IsSEXT1 && IsVZero0) {
22345       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22346       if (CC == ISD::SETEQ)
22347         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22348       return RHS.getOperand(0);
22349     }
22350   }
22351
22352   return SDValue();
22353 }
22354
22355 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22356                                       const X86Subtarget *Subtarget) {
22357   SDLoc dl(N);
22358   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22359   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22360          "X86insertps is only defined for v4x32");
22361
22362   SDValue Ld = N->getOperand(1);
22363   if (MayFoldLoad(Ld)) {
22364     // Extract the countS bits from the immediate so we can get the proper
22365     // address when narrowing the vector load to a specific element.
22366     // When the second source op is a memory address, interps doesn't use
22367     // countS and just gets an f32 from that address.
22368     unsigned DestIndex =
22369         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22370     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22371   } else
22372     return SDValue();
22373
22374   // Create this as a scalar to vector to match the instruction pattern.
22375   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22376   // countS bits are ignored when loading from memory on insertps, which
22377   // means we don't need to explicitly set them to 0.
22378   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22379                      LoadScalarToVector, N->getOperand(2));
22380 }
22381
22382 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22383 // as "sbb reg,reg", since it can be extended without zext and produces
22384 // an all-ones bit which is more useful than 0/1 in some cases.
22385 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22386                                MVT VT) {
22387   if (VT == MVT::i8)
22388     return DAG.getNode(ISD::AND, DL, VT,
22389                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22390                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22391                        DAG.getConstant(1, VT));
22392   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22393   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22394                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22395                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22396 }
22397
22398 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22399 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22400                                    TargetLowering::DAGCombinerInfo &DCI,
22401                                    const X86Subtarget *Subtarget) {
22402   SDLoc DL(N);
22403   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22404   SDValue EFLAGS = N->getOperand(1);
22405
22406   if (CC == X86::COND_A) {
22407     // Try to convert COND_A into COND_B in an attempt to facilitate
22408     // materializing "setb reg".
22409     //
22410     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22411     // cannot take an immediate as its first operand.
22412     //
22413     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22414         EFLAGS.getValueType().isInteger() &&
22415         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22416       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22417                                    EFLAGS.getNode()->getVTList(),
22418                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22419       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22420       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22421     }
22422   }
22423
22424   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22425   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22426   // cases.
22427   if (CC == X86::COND_B)
22428     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22429
22430   SDValue Flags;
22431
22432   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22433   if (Flags.getNode()) {
22434     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22435     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22436   }
22437
22438   return SDValue();
22439 }
22440
22441 // Optimize branch condition evaluation.
22442 //
22443 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22444                                     TargetLowering::DAGCombinerInfo &DCI,
22445                                     const X86Subtarget *Subtarget) {
22446   SDLoc DL(N);
22447   SDValue Chain = N->getOperand(0);
22448   SDValue Dest = N->getOperand(1);
22449   SDValue EFLAGS = N->getOperand(3);
22450   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22451
22452   SDValue Flags;
22453
22454   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22455   if (Flags.getNode()) {
22456     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22457     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22458                        Flags);
22459   }
22460
22461   return SDValue();
22462 }
22463
22464 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22465                                                          SelectionDAG &DAG) {
22466   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22467   // optimize away operation when it's from a constant.
22468   //
22469   // The general transformation is:
22470   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22471   //       AND(VECTOR_CMP(x,y), constant2)
22472   //    constant2 = UNARYOP(constant)
22473
22474   // Early exit if this isn't a vector operation, the operand of the
22475   // unary operation isn't a bitwise AND, or if the sizes of the operations
22476   // aren't the same.
22477   EVT VT = N->getValueType(0);
22478   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22479       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22480       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22481     return SDValue();
22482
22483   // Now check that the other operand of the AND is a constant. We could
22484   // make the transformation for non-constant splats as well, but it's unclear
22485   // that would be a benefit as it would not eliminate any operations, just
22486   // perform one more step in scalar code before moving to the vector unit.
22487   if (BuildVectorSDNode *BV =
22488           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22489     // Bail out if the vector isn't a constant.
22490     if (!BV->isConstant())
22491       return SDValue();
22492
22493     // Everything checks out. Build up the new and improved node.
22494     SDLoc DL(N);
22495     EVT IntVT = BV->getValueType(0);
22496     // Create a new constant of the appropriate type for the transformed
22497     // DAG.
22498     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22499     // The AND node needs bitcasts to/from an integer vector type around it.
22500     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22501     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22502                                  N->getOperand(0)->getOperand(0), MaskConst);
22503     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22504     return Res;
22505   }
22506
22507   return SDValue();
22508 }
22509
22510 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22511                                         const X86TargetLowering *XTLI) {
22512   // First try to optimize away the conversion entirely when it's
22513   // conditionally from a constant. Vectors only.
22514   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22515   if (Res != SDValue())
22516     return Res;
22517
22518   // Now move on to more general possibilities.
22519   SDValue Op0 = N->getOperand(0);
22520   EVT InVT = Op0->getValueType(0);
22521
22522   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22523   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22524     SDLoc dl(N);
22525     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22526     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22527     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22528   }
22529
22530   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22531   // a 32-bit target where SSE doesn't support i64->FP operations.
22532   if (Op0.getOpcode() == ISD::LOAD) {
22533     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22534     EVT VT = Ld->getValueType(0);
22535     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22536         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22537         !XTLI->getSubtarget()->is64Bit() &&
22538         VT == MVT::i64) {
22539       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22540                                           Ld->getChain(), Op0, DAG);
22541       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22542       return FILDChain;
22543     }
22544   }
22545   return SDValue();
22546 }
22547
22548 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22549 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22550                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22551   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22552   // the result is either zero or one (depending on the input carry bit).
22553   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22554   if (X86::isZeroNode(N->getOperand(0)) &&
22555       X86::isZeroNode(N->getOperand(1)) &&
22556       // We don't have a good way to replace an EFLAGS use, so only do this when
22557       // dead right now.
22558       SDValue(N, 1).use_empty()) {
22559     SDLoc DL(N);
22560     EVT VT = N->getValueType(0);
22561     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22562     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22563                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22564                                            DAG.getConstant(X86::COND_B,MVT::i8),
22565                                            N->getOperand(2)),
22566                                DAG.getConstant(1, VT));
22567     return DCI.CombineTo(N, Res1, CarryOut);
22568   }
22569
22570   return SDValue();
22571 }
22572
22573 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22574 //      (add Y, (setne X, 0)) -> sbb -1, Y
22575 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22576 //      (sub (setne X, 0), Y) -> adc -1, Y
22577 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22578   SDLoc DL(N);
22579
22580   // Look through ZExts.
22581   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22582   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22583     return SDValue();
22584
22585   SDValue SetCC = Ext.getOperand(0);
22586   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22587     return SDValue();
22588
22589   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22590   if (CC != X86::COND_E && CC != X86::COND_NE)
22591     return SDValue();
22592
22593   SDValue Cmp = SetCC.getOperand(1);
22594   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22595       !X86::isZeroNode(Cmp.getOperand(1)) ||
22596       !Cmp.getOperand(0).getValueType().isInteger())
22597     return SDValue();
22598
22599   SDValue CmpOp0 = Cmp.getOperand(0);
22600   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22601                                DAG.getConstant(1, CmpOp0.getValueType()));
22602
22603   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22604   if (CC == X86::COND_NE)
22605     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22606                        DL, OtherVal.getValueType(), OtherVal,
22607                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22608   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22609                      DL, OtherVal.getValueType(), OtherVal,
22610                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22611 }
22612
22613 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22614 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22615                                  const X86Subtarget *Subtarget) {
22616   EVT VT = N->getValueType(0);
22617   SDValue Op0 = N->getOperand(0);
22618   SDValue Op1 = N->getOperand(1);
22619
22620   // Try to synthesize horizontal adds from adds of shuffles.
22621   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22622        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22623       isHorizontalBinOp(Op0, Op1, true))
22624     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22625
22626   return OptimizeConditionalInDecrement(N, DAG);
22627 }
22628
22629 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22630                                  const X86Subtarget *Subtarget) {
22631   SDValue Op0 = N->getOperand(0);
22632   SDValue Op1 = N->getOperand(1);
22633
22634   // X86 can't encode an immediate LHS of a sub. See if we can push the
22635   // negation into a preceding instruction.
22636   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22637     // If the RHS of the sub is a XOR with one use and a constant, invert the
22638     // immediate. Then add one to the LHS of the sub so we can turn
22639     // X-Y -> X+~Y+1, saving one register.
22640     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22641         isa<ConstantSDNode>(Op1.getOperand(1))) {
22642       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22643       EVT VT = Op0.getValueType();
22644       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22645                                    Op1.getOperand(0),
22646                                    DAG.getConstant(~XorC, VT));
22647       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22648                          DAG.getConstant(C->getAPIntValue()+1, VT));
22649     }
22650   }
22651
22652   // Try to synthesize horizontal adds from adds of shuffles.
22653   EVT VT = N->getValueType(0);
22654   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22655        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22656       isHorizontalBinOp(Op0, Op1, true))
22657     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22658
22659   return OptimizeConditionalInDecrement(N, DAG);
22660 }
22661
22662 /// performVZEXTCombine - Performs build vector combines
22663 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22664                                         TargetLowering::DAGCombinerInfo &DCI,
22665                                         const X86Subtarget *Subtarget) {
22666   // (vzext (bitcast (vzext (x)) -> (vzext x)
22667   SDValue In = N->getOperand(0);
22668   while (In.getOpcode() == ISD::BITCAST)
22669     In = In.getOperand(0);
22670
22671   if (In.getOpcode() != X86ISD::VZEXT)
22672     return SDValue();
22673
22674   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22675                      In.getOperand(0));
22676 }
22677
22678 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22679                                              DAGCombinerInfo &DCI) const {
22680   SelectionDAG &DAG = DCI.DAG;
22681   switch (N->getOpcode()) {
22682   default: break;
22683   case ISD::EXTRACT_VECTOR_ELT:
22684     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22685   case ISD::VSELECT:
22686   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22687   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22688   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22689   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22690   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22691   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22692   case ISD::SHL:
22693   case ISD::SRA:
22694   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22695   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22696   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22697   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22698   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22699   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22700   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22701   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22702   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22703   case X86ISD::FXOR:
22704   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22705   case X86ISD::FMIN:
22706   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22707   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22708   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22709   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22710   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22711   case ISD::ANY_EXTEND:
22712   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22713   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22714   case ISD::SIGN_EXTEND_INREG:
22715     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22716   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22717   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22718   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22719   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22720   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22721   case X86ISD::SHUFP:       // Handle all target specific shuffles
22722   case X86ISD::PALIGNR:
22723   case X86ISD::UNPCKH:
22724   case X86ISD::UNPCKL:
22725   case X86ISD::MOVHLPS:
22726   case X86ISD::MOVLHPS:
22727   case X86ISD::PSHUFB:
22728   case X86ISD::PSHUFD:
22729   case X86ISD::PSHUFHW:
22730   case X86ISD::PSHUFLW:
22731   case X86ISD::MOVSS:
22732   case X86ISD::MOVSD:
22733   case X86ISD::VPERMILP:
22734   case X86ISD::VPERM2X128:
22735   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22736   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22737   case ISD::INTRINSIC_WO_CHAIN:
22738     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22739   case X86ISD::INSERTPS:
22740     return PerformINSERTPSCombine(N, DAG, Subtarget);
22741   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22742   }
22743
22744   return SDValue();
22745 }
22746
22747 /// isTypeDesirableForOp - Return true if the target has native support for
22748 /// the specified value type and it is 'desirable' to use the type for the
22749 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22750 /// instruction encodings are longer and some i16 instructions are slow.
22751 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22752   if (!isTypeLegal(VT))
22753     return false;
22754   if (VT != MVT::i16)
22755     return true;
22756
22757   switch (Opc) {
22758   default:
22759     return true;
22760   case ISD::LOAD:
22761   case ISD::SIGN_EXTEND:
22762   case ISD::ZERO_EXTEND:
22763   case ISD::ANY_EXTEND:
22764   case ISD::SHL:
22765   case ISD::SRL:
22766   case ISD::SUB:
22767   case ISD::ADD:
22768   case ISD::MUL:
22769   case ISD::AND:
22770   case ISD::OR:
22771   case ISD::XOR:
22772     return false;
22773   }
22774 }
22775
22776 /// IsDesirableToPromoteOp - This method query the target whether it is
22777 /// beneficial for dag combiner to promote the specified node. If true, it
22778 /// should return the desired promotion type by reference.
22779 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22780   EVT VT = Op.getValueType();
22781   if (VT != MVT::i16)
22782     return false;
22783
22784   bool Promote = false;
22785   bool Commute = false;
22786   switch (Op.getOpcode()) {
22787   default: break;
22788   case ISD::LOAD: {
22789     LoadSDNode *LD = cast<LoadSDNode>(Op);
22790     // If the non-extending load has a single use and it's not live out, then it
22791     // might be folded.
22792     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22793                                                      Op.hasOneUse()*/) {
22794       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22795              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22796         // The only case where we'd want to promote LOAD (rather then it being
22797         // promoted as an operand is when it's only use is liveout.
22798         if (UI->getOpcode() != ISD::CopyToReg)
22799           return false;
22800       }
22801     }
22802     Promote = true;
22803     break;
22804   }
22805   case ISD::SIGN_EXTEND:
22806   case ISD::ZERO_EXTEND:
22807   case ISD::ANY_EXTEND:
22808     Promote = true;
22809     break;
22810   case ISD::SHL:
22811   case ISD::SRL: {
22812     SDValue N0 = Op.getOperand(0);
22813     // Look out for (store (shl (load), x)).
22814     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22815       return false;
22816     Promote = true;
22817     break;
22818   }
22819   case ISD::ADD:
22820   case ISD::MUL:
22821   case ISD::AND:
22822   case ISD::OR:
22823   case ISD::XOR:
22824     Commute = true;
22825     // fallthrough
22826   case ISD::SUB: {
22827     SDValue N0 = Op.getOperand(0);
22828     SDValue N1 = Op.getOperand(1);
22829     if (!Commute && MayFoldLoad(N1))
22830       return false;
22831     // Avoid disabling potential load folding opportunities.
22832     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22833       return false;
22834     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22835       return false;
22836     Promote = true;
22837   }
22838   }
22839
22840   PVT = MVT::i32;
22841   return Promote;
22842 }
22843
22844 //===----------------------------------------------------------------------===//
22845 //                           X86 Inline Assembly Support
22846 //===----------------------------------------------------------------------===//
22847
22848 namespace {
22849   // Helper to match a string separated by whitespace.
22850   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22851     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22852
22853     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22854       StringRef piece(*args[i]);
22855       if (!s.startswith(piece)) // Check if the piece matches.
22856         return false;
22857
22858       s = s.substr(piece.size());
22859       StringRef::size_type pos = s.find_first_not_of(" \t");
22860       if (pos == 0) // We matched a prefix.
22861         return false;
22862
22863       s = s.substr(pos);
22864     }
22865
22866     return s.empty();
22867   }
22868   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22869 }
22870
22871 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22872
22873   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22874     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22875         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22876         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22877
22878       if (AsmPieces.size() == 3)
22879         return true;
22880       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22881         return true;
22882     }
22883   }
22884   return false;
22885 }
22886
22887 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22888   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22889
22890   std::string AsmStr = IA->getAsmString();
22891
22892   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22893   if (!Ty || Ty->getBitWidth() % 16 != 0)
22894     return false;
22895
22896   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22897   SmallVector<StringRef, 4> AsmPieces;
22898   SplitString(AsmStr, AsmPieces, ";\n");
22899
22900   switch (AsmPieces.size()) {
22901   default: return false;
22902   case 1:
22903     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22904     // we will turn this bswap into something that will be lowered to logical
22905     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22906     // lower so don't worry about this.
22907     // bswap $0
22908     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22909         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22910         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22911         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22912         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22913         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22914       // No need to check constraints, nothing other than the equivalent of
22915       // "=r,0" would be valid here.
22916       return IntrinsicLowering::LowerToByteSwap(CI);
22917     }
22918
22919     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22920     if (CI->getType()->isIntegerTy(16) &&
22921         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22922         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22923          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22924       AsmPieces.clear();
22925       const std::string &ConstraintsStr = IA->getConstraintString();
22926       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22927       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22928       if (clobbersFlagRegisters(AsmPieces))
22929         return IntrinsicLowering::LowerToByteSwap(CI);
22930     }
22931     break;
22932   case 3:
22933     if (CI->getType()->isIntegerTy(32) &&
22934         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22935         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22936         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22937         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22938       AsmPieces.clear();
22939       const std::string &ConstraintsStr = IA->getConstraintString();
22940       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22941       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22942       if (clobbersFlagRegisters(AsmPieces))
22943         return IntrinsicLowering::LowerToByteSwap(CI);
22944     }
22945
22946     if (CI->getType()->isIntegerTy(64)) {
22947       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22948       if (Constraints.size() >= 2 &&
22949           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22950           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22951         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22952         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22953             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22954             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22955           return IntrinsicLowering::LowerToByteSwap(CI);
22956       }
22957     }
22958     break;
22959   }
22960   return false;
22961 }
22962
22963 /// getConstraintType - Given a constraint letter, return the type of
22964 /// constraint it is for this target.
22965 X86TargetLowering::ConstraintType
22966 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22967   if (Constraint.size() == 1) {
22968     switch (Constraint[0]) {
22969     case 'R':
22970     case 'q':
22971     case 'Q':
22972     case 'f':
22973     case 't':
22974     case 'u':
22975     case 'y':
22976     case 'x':
22977     case 'Y':
22978     case 'l':
22979       return C_RegisterClass;
22980     case 'a':
22981     case 'b':
22982     case 'c':
22983     case 'd':
22984     case 'S':
22985     case 'D':
22986     case 'A':
22987       return C_Register;
22988     case 'I':
22989     case 'J':
22990     case 'K':
22991     case 'L':
22992     case 'M':
22993     case 'N':
22994     case 'G':
22995     case 'C':
22996     case 'e':
22997     case 'Z':
22998       return C_Other;
22999     default:
23000       break;
23001     }
23002   }
23003   return TargetLowering::getConstraintType(Constraint);
23004 }
23005
23006 /// Examine constraint type and operand type and determine a weight value.
23007 /// This object must already have been set up with the operand type
23008 /// and the current alternative constraint selected.
23009 TargetLowering::ConstraintWeight
23010   X86TargetLowering::getSingleConstraintMatchWeight(
23011     AsmOperandInfo &info, const char *constraint) const {
23012   ConstraintWeight weight = CW_Invalid;
23013   Value *CallOperandVal = info.CallOperandVal;
23014     // If we don't have a value, we can't do a match,
23015     // but allow it at the lowest weight.
23016   if (!CallOperandVal)
23017     return CW_Default;
23018   Type *type = CallOperandVal->getType();
23019   // Look at the constraint type.
23020   switch (*constraint) {
23021   default:
23022     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23023   case 'R':
23024   case 'q':
23025   case 'Q':
23026   case 'a':
23027   case 'b':
23028   case 'c':
23029   case 'd':
23030   case 'S':
23031   case 'D':
23032   case 'A':
23033     if (CallOperandVal->getType()->isIntegerTy())
23034       weight = CW_SpecificReg;
23035     break;
23036   case 'f':
23037   case 't':
23038   case 'u':
23039     if (type->isFloatingPointTy())
23040       weight = CW_SpecificReg;
23041     break;
23042   case 'y':
23043     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23044       weight = CW_SpecificReg;
23045     break;
23046   case 'x':
23047   case 'Y':
23048     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23049         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23050       weight = CW_Register;
23051     break;
23052   case 'I':
23053     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23054       if (C->getZExtValue() <= 31)
23055         weight = CW_Constant;
23056     }
23057     break;
23058   case 'J':
23059     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23060       if (C->getZExtValue() <= 63)
23061         weight = CW_Constant;
23062     }
23063     break;
23064   case 'K':
23065     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23066       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23067         weight = CW_Constant;
23068     }
23069     break;
23070   case 'L':
23071     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23072       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23073         weight = CW_Constant;
23074     }
23075     break;
23076   case 'M':
23077     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23078       if (C->getZExtValue() <= 3)
23079         weight = CW_Constant;
23080     }
23081     break;
23082   case 'N':
23083     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23084       if (C->getZExtValue() <= 0xff)
23085         weight = CW_Constant;
23086     }
23087     break;
23088   case 'G':
23089   case 'C':
23090     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23091       weight = CW_Constant;
23092     }
23093     break;
23094   case 'e':
23095     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23096       if ((C->getSExtValue() >= -0x80000000LL) &&
23097           (C->getSExtValue() <= 0x7fffffffLL))
23098         weight = CW_Constant;
23099     }
23100     break;
23101   case 'Z':
23102     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23103       if (C->getZExtValue() <= 0xffffffff)
23104         weight = CW_Constant;
23105     }
23106     break;
23107   }
23108   return weight;
23109 }
23110
23111 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23112 /// with another that has more specific requirements based on the type of the
23113 /// corresponding operand.
23114 const char *X86TargetLowering::
23115 LowerXConstraint(EVT ConstraintVT) const {
23116   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23117   // 'f' like normal targets.
23118   if (ConstraintVT.isFloatingPoint()) {
23119     if (Subtarget->hasSSE2())
23120       return "Y";
23121     if (Subtarget->hasSSE1())
23122       return "x";
23123   }
23124
23125   return TargetLowering::LowerXConstraint(ConstraintVT);
23126 }
23127
23128 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23129 /// vector.  If it is invalid, don't add anything to Ops.
23130 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23131                                                      std::string &Constraint,
23132                                                      std::vector<SDValue>&Ops,
23133                                                      SelectionDAG &DAG) const {
23134   SDValue Result;
23135
23136   // Only support length 1 constraints for now.
23137   if (Constraint.length() > 1) return;
23138
23139   char ConstraintLetter = Constraint[0];
23140   switch (ConstraintLetter) {
23141   default: break;
23142   case 'I':
23143     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23144       if (C->getZExtValue() <= 31) {
23145         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23146         break;
23147       }
23148     }
23149     return;
23150   case 'J':
23151     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23152       if (C->getZExtValue() <= 63) {
23153         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23154         break;
23155       }
23156     }
23157     return;
23158   case 'K':
23159     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23160       if (isInt<8>(C->getSExtValue())) {
23161         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23162         break;
23163       }
23164     }
23165     return;
23166   case 'N':
23167     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23168       if (C->getZExtValue() <= 255) {
23169         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23170         break;
23171       }
23172     }
23173     return;
23174   case 'e': {
23175     // 32-bit signed value
23176     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23177       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23178                                            C->getSExtValue())) {
23179         // Widen to 64 bits here to get it sign extended.
23180         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23181         break;
23182       }
23183     // FIXME gcc accepts some relocatable values here too, but only in certain
23184     // memory models; it's complicated.
23185     }
23186     return;
23187   }
23188   case 'Z': {
23189     // 32-bit unsigned value
23190     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23191       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23192                                            C->getZExtValue())) {
23193         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23194         break;
23195       }
23196     }
23197     // FIXME gcc accepts some relocatable values here too, but only in certain
23198     // memory models; it's complicated.
23199     return;
23200   }
23201   case 'i': {
23202     // Literal immediates are always ok.
23203     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23204       // Widen to 64 bits here to get it sign extended.
23205       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23206       break;
23207     }
23208
23209     // In any sort of PIC mode addresses need to be computed at runtime by
23210     // adding in a register or some sort of table lookup.  These can't
23211     // be used as immediates.
23212     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23213       return;
23214
23215     // If we are in non-pic codegen mode, we allow the address of a global (with
23216     // an optional displacement) to be used with 'i'.
23217     GlobalAddressSDNode *GA = nullptr;
23218     int64_t Offset = 0;
23219
23220     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23221     while (1) {
23222       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23223         Offset += GA->getOffset();
23224         break;
23225       } else if (Op.getOpcode() == ISD::ADD) {
23226         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23227           Offset += C->getZExtValue();
23228           Op = Op.getOperand(0);
23229           continue;
23230         }
23231       } else if (Op.getOpcode() == ISD::SUB) {
23232         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23233           Offset += -C->getZExtValue();
23234           Op = Op.getOperand(0);
23235           continue;
23236         }
23237       }
23238
23239       // Otherwise, this isn't something we can handle, reject it.
23240       return;
23241     }
23242
23243     const GlobalValue *GV = GA->getGlobal();
23244     // If we require an extra load to get this address, as in PIC mode, we
23245     // can't accept it.
23246     if (isGlobalStubReference(
23247             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23248       return;
23249
23250     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23251                                         GA->getValueType(0), Offset);
23252     break;
23253   }
23254   }
23255
23256   if (Result.getNode()) {
23257     Ops.push_back(Result);
23258     return;
23259   }
23260   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23261 }
23262
23263 std::pair<unsigned, const TargetRegisterClass*>
23264 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23265                                                 MVT VT) const {
23266   // First, see if this is a constraint that directly corresponds to an LLVM
23267   // register class.
23268   if (Constraint.size() == 1) {
23269     // GCC Constraint Letters
23270     switch (Constraint[0]) {
23271     default: break;
23272       // TODO: Slight differences here in allocation order and leaving
23273       // RIP in the class. Do they matter any more here than they do
23274       // in the normal allocation?
23275     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23276       if (Subtarget->is64Bit()) {
23277         if (VT == MVT::i32 || VT == MVT::f32)
23278           return std::make_pair(0U, &X86::GR32RegClass);
23279         if (VT == MVT::i16)
23280           return std::make_pair(0U, &X86::GR16RegClass);
23281         if (VT == MVT::i8 || VT == MVT::i1)
23282           return std::make_pair(0U, &X86::GR8RegClass);
23283         if (VT == MVT::i64 || VT == MVT::f64)
23284           return std::make_pair(0U, &X86::GR64RegClass);
23285         break;
23286       }
23287       // 32-bit fallthrough
23288     case 'Q':   // Q_REGS
23289       if (VT == MVT::i32 || VT == MVT::f32)
23290         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23291       if (VT == MVT::i16)
23292         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23293       if (VT == MVT::i8 || VT == MVT::i1)
23294         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23295       if (VT == MVT::i64)
23296         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23297       break;
23298     case 'r':   // GENERAL_REGS
23299     case 'l':   // INDEX_REGS
23300       if (VT == MVT::i8 || VT == MVT::i1)
23301         return std::make_pair(0U, &X86::GR8RegClass);
23302       if (VT == MVT::i16)
23303         return std::make_pair(0U, &X86::GR16RegClass);
23304       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23305         return std::make_pair(0U, &X86::GR32RegClass);
23306       return std::make_pair(0U, &X86::GR64RegClass);
23307     case 'R':   // LEGACY_REGS
23308       if (VT == MVT::i8 || VT == MVT::i1)
23309         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23310       if (VT == MVT::i16)
23311         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23312       if (VT == MVT::i32 || !Subtarget->is64Bit())
23313         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23314       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23315     case 'f':  // FP Stack registers.
23316       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23317       // value to the correct fpstack register class.
23318       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23319         return std::make_pair(0U, &X86::RFP32RegClass);
23320       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23321         return std::make_pair(0U, &X86::RFP64RegClass);
23322       return std::make_pair(0U, &X86::RFP80RegClass);
23323     case 'y':   // MMX_REGS if MMX allowed.
23324       if (!Subtarget->hasMMX()) break;
23325       return std::make_pair(0U, &X86::VR64RegClass);
23326     case 'Y':   // SSE_REGS if SSE2 allowed
23327       if (!Subtarget->hasSSE2()) break;
23328       // FALL THROUGH.
23329     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23330       if (!Subtarget->hasSSE1()) break;
23331
23332       switch (VT.SimpleTy) {
23333       default: break;
23334       // Scalar SSE types.
23335       case MVT::f32:
23336       case MVT::i32:
23337         return std::make_pair(0U, &X86::FR32RegClass);
23338       case MVT::f64:
23339       case MVT::i64:
23340         return std::make_pair(0U, &X86::FR64RegClass);
23341       // Vector types.
23342       case MVT::v16i8:
23343       case MVT::v8i16:
23344       case MVT::v4i32:
23345       case MVT::v2i64:
23346       case MVT::v4f32:
23347       case MVT::v2f64:
23348         return std::make_pair(0U, &X86::VR128RegClass);
23349       // AVX types.
23350       case MVT::v32i8:
23351       case MVT::v16i16:
23352       case MVT::v8i32:
23353       case MVT::v4i64:
23354       case MVT::v8f32:
23355       case MVT::v4f64:
23356         return std::make_pair(0U, &X86::VR256RegClass);
23357       case MVT::v8f64:
23358       case MVT::v16f32:
23359       case MVT::v16i32:
23360       case MVT::v8i64:
23361         return std::make_pair(0U, &X86::VR512RegClass);
23362       }
23363       break;
23364     }
23365   }
23366
23367   // Use the default implementation in TargetLowering to convert the register
23368   // constraint into a member of a register class.
23369   std::pair<unsigned, const TargetRegisterClass*> Res;
23370   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23371
23372   // Not found as a standard register?
23373   if (!Res.second) {
23374     // Map st(0) -> st(7) -> ST0
23375     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23376         tolower(Constraint[1]) == 's' &&
23377         tolower(Constraint[2]) == 't' &&
23378         Constraint[3] == '(' &&
23379         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23380         Constraint[5] == ')' &&
23381         Constraint[6] == '}') {
23382
23383       Res.first = X86::FP0+Constraint[4]-'0';
23384       Res.second = &X86::RFP80RegClass;
23385       return Res;
23386     }
23387
23388     // GCC allows "st(0)" to be called just plain "st".
23389     if (StringRef("{st}").equals_lower(Constraint)) {
23390       Res.first = X86::FP0;
23391       Res.second = &X86::RFP80RegClass;
23392       return Res;
23393     }
23394
23395     // flags -> EFLAGS
23396     if (StringRef("{flags}").equals_lower(Constraint)) {
23397       Res.first = X86::EFLAGS;
23398       Res.second = &X86::CCRRegClass;
23399       return Res;
23400     }
23401
23402     // 'A' means EAX + EDX.
23403     if (Constraint == "A") {
23404       Res.first = X86::EAX;
23405       Res.second = &X86::GR32_ADRegClass;
23406       return Res;
23407     }
23408     return Res;
23409   }
23410
23411   // Otherwise, check to see if this is a register class of the wrong value
23412   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23413   // turn into {ax},{dx}.
23414   if (Res.second->hasType(VT))
23415     return Res;   // Correct type already, nothing to do.
23416
23417   // All of the single-register GCC register classes map their values onto
23418   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23419   // really want an 8-bit or 32-bit register, map to the appropriate register
23420   // class and return the appropriate register.
23421   if (Res.second == &X86::GR16RegClass) {
23422     if (VT == MVT::i8 || VT == MVT::i1) {
23423       unsigned DestReg = 0;
23424       switch (Res.first) {
23425       default: break;
23426       case X86::AX: DestReg = X86::AL; break;
23427       case X86::DX: DestReg = X86::DL; break;
23428       case X86::CX: DestReg = X86::CL; break;
23429       case X86::BX: DestReg = X86::BL; break;
23430       }
23431       if (DestReg) {
23432         Res.first = DestReg;
23433         Res.second = &X86::GR8RegClass;
23434       }
23435     } else if (VT == MVT::i32 || VT == MVT::f32) {
23436       unsigned DestReg = 0;
23437       switch (Res.first) {
23438       default: break;
23439       case X86::AX: DestReg = X86::EAX; break;
23440       case X86::DX: DestReg = X86::EDX; break;
23441       case X86::CX: DestReg = X86::ECX; break;
23442       case X86::BX: DestReg = X86::EBX; break;
23443       case X86::SI: DestReg = X86::ESI; break;
23444       case X86::DI: DestReg = X86::EDI; break;
23445       case X86::BP: DestReg = X86::EBP; break;
23446       case X86::SP: DestReg = X86::ESP; break;
23447       }
23448       if (DestReg) {
23449         Res.first = DestReg;
23450         Res.second = &X86::GR32RegClass;
23451       }
23452     } else if (VT == MVT::i64 || VT == MVT::f64) {
23453       unsigned DestReg = 0;
23454       switch (Res.first) {
23455       default: break;
23456       case X86::AX: DestReg = X86::RAX; break;
23457       case X86::DX: DestReg = X86::RDX; break;
23458       case X86::CX: DestReg = X86::RCX; break;
23459       case X86::BX: DestReg = X86::RBX; break;
23460       case X86::SI: DestReg = X86::RSI; break;
23461       case X86::DI: DestReg = X86::RDI; break;
23462       case X86::BP: DestReg = X86::RBP; break;
23463       case X86::SP: DestReg = X86::RSP; break;
23464       }
23465       if (DestReg) {
23466         Res.first = DestReg;
23467         Res.second = &X86::GR64RegClass;
23468       }
23469     }
23470   } else if (Res.second == &X86::FR32RegClass ||
23471              Res.second == &X86::FR64RegClass ||
23472              Res.second == &X86::VR128RegClass ||
23473              Res.second == &X86::VR256RegClass ||
23474              Res.second == &X86::FR32XRegClass ||
23475              Res.second == &X86::FR64XRegClass ||
23476              Res.second == &X86::VR128XRegClass ||
23477              Res.second == &X86::VR256XRegClass ||
23478              Res.second == &X86::VR512RegClass) {
23479     // Handle references to XMM physical registers that got mapped into the
23480     // wrong class.  This can happen with constraints like {xmm0} where the
23481     // target independent register mapper will just pick the first match it can
23482     // find, ignoring the required type.
23483
23484     if (VT == MVT::f32 || VT == MVT::i32)
23485       Res.second = &X86::FR32RegClass;
23486     else if (VT == MVT::f64 || VT == MVT::i64)
23487       Res.second = &X86::FR64RegClass;
23488     else if (X86::VR128RegClass.hasType(VT))
23489       Res.second = &X86::VR128RegClass;
23490     else if (X86::VR256RegClass.hasType(VT))
23491       Res.second = &X86::VR256RegClass;
23492     else if (X86::VR512RegClass.hasType(VT))
23493       Res.second = &X86::VR512RegClass;
23494   }
23495
23496   return Res;
23497 }
23498
23499 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23500                                             Type *Ty) const {
23501   // Scaling factors are not free at all.
23502   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23503   // will take 2 allocations in the out of order engine instead of 1
23504   // for plain addressing mode, i.e. inst (reg1).
23505   // E.g.,
23506   // vaddps (%rsi,%drx), %ymm0, %ymm1
23507   // Requires two allocations (one for the load, one for the computation)
23508   // whereas:
23509   // vaddps (%rsi), %ymm0, %ymm1
23510   // Requires just 1 allocation, i.e., freeing allocations for other operations
23511   // and having less micro operations to execute.
23512   //
23513   // For some X86 architectures, this is even worse because for instance for
23514   // stores, the complex addressing mode forces the instruction to use the
23515   // "load" ports instead of the dedicated "store" port.
23516   // E.g., on Haswell:
23517   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23518   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23519   if (isLegalAddressingMode(AM, Ty))
23520     // Scale represents reg2 * scale, thus account for 1
23521     // as soon as we use a second register.
23522     return AM.Scale != 0;
23523   return -1;
23524 }
23525
23526 bool X86TargetLowering::isTargetFTOL() const {
23527   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23528 }