[DWARF parser] Fix nasty memory corruption in .dwo files handling.
[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 "X86IntrinsicsInfo.h"
53 #include <bitset>
54 #include <numeric>
55 #include <cctype>
56 using namespace llvm;
57
58 #define DEBUG_TYPE "x86-isel"
59
60 STATISTIC(NumTailCalls, "Number of tail calls");
61
62 static cl::opt<bool> ExperimentalVectorWideningLegalization(
63     "x86-experimental-vector-widening-legalization", cl::init(false),
64     cl::desc("Enable an experimental vector type legalization through widening "
65              "rather than promotion."),
66     cl::Hidden);
67
68 static cl::opt<bool> ExperimentalVectorShuffleLowering(
69     "x86-experimental-vector-shuffle-lowering", cl::init(false),
70     cl::desc("Enable an experimental vector shuffle lowering code path."),
71     cl::Hidden);
72
73 // Forward declarations.
74 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
75                        SDValue V2);
76
77 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
78                                 SelectionDAG &DAG, SDLoc dl,
79                                 unsigned vectorWidth) {
80   assert((vectorWidth == 128 || vectorWidth == 256) &&
81          "Unsupported vector width");
82   EVT VT = Vec.getValueType();
83   EVT ElVT = VT.getVectorElementType();
84   unsigned Factor = VT.getSizeInBits()/vectorWidth;
85   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
86                                   VT.getVectorNumElements()/Factor);
87
88   // Extract from UNDEF is UNDEF.
89   if (Vec.getOpcode() == ISD::UNDEF)
90     return DAG.getUNDEF(ResultVT);
91
92   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
93   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94
95   // This is the index of the first element of the vectorWidth-bit chunk
96   // we want.
97   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
98                                * ElemsPerChunk);
99
100   // If the input is a buildvector just emit a smaller one.
101   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
102     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
103                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
104                                     ElemsPerChunk));
105
106   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
107   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                VecIdx);
109
110   return Result;
111
112 }
113 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
114 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
115 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
116 /// instructions or a simple subregister reference. Idx is an index in the
117 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
118 /// lowering EXTRACT_VECTOR_ELT operations easier.
119 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
120                                    SelectionDAG &DAG, SDLoc dl) {
121   assert((Vec.getValueType().is256BitVector() ||
122           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
123   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
124 }
125
126 /// Generate a DAG to grab 256-bits from a 512-bit vector.
127 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
128                                    SelectionDAG &DAG, SDLoc dl) {
129   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
130   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
131 }
132
133 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
134                                unsigned IdxVal, SelectionDAG &DAG,
135                                SDLoc dl, unsigned vectorWidth) {
136   assert((vectorWidth == 128 || vectorWidth == 256) &&
137          "Unsupported vector width");
138   // Inserting UNDEF is Result
139   if (Vec.getOpcode() == ISD::UNDEF)
140     return Result;
141   EVT VT = Vec.getValueType();
142   EVT ElVT = VT.getVectorElementType();
143   EVT ResultVT = Result.getValueType();
144
145   // Insert the relevant vectorWidth bits.
146   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147
148   // This is the index of the first element of the vectorWidth-bit chunk
149   // we want.
150   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
151                                * ElemsPerChunk);
152
153   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
154   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                      VecIdx);
156 }
157 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
158 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
159 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
160 /// simple superregister reference.  Idx is an index in the 128 bits
161 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
162 /// lowering INSERT_VECTOR_ELT operations easier.
163 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
164                                   unsigned IdxVal, SelectionDAG &DAG,
165                                   SDLoc dl) {
166   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
167   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
168 }
169
170 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
171                                   unsigned IdxVal, SelectionDAG &DAG,
172                                   SDLoc dl) {
173   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
174   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
175 }
176
177 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
178 /// instructions. This is used because creating CONCAT_VECTOR nodes of
179 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
180 /// large BUILD_VECTORS.
181 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
182                                    unsigned NumElems, SelectionDAG &DAG,
183                                    SDLoc dl) {
184   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
186 }
187
188 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
189                                    unsigned NumElems, SelectionDAG &DAG,
190                                    SDLoc dl) {
191   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
192   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
193 }
194
195 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
196   if (TT.isOSBinFormatMachO()) {
197     if (TT.getArch() == Triple::x86_64)
198       return new X86_64MachoTargetObjectFile();
199     return new TargetLoweringObjectFileMachO();
200   }
201
202   if (TT.isOSLinux())
203     return new X86LinuxTargetObjectFile();
204   if (TT.isOSBinFormatELF())
205     return new TargetLoweringObjectFileELF();
206   if (TT.isKnownWindowsMSVCEnvironment())
207     return new X86WindowsTargetObjectFile();
208   if (TT.isOSBinFormatCOFF())
209     return new TargetLoweringObjectFileCOFF();
210   llvm_unreachable("unknown subtarget type");
211 }
212
213 // FIXME: This should stop caching the target machine as soon as
214 // we can remove resetOperationActions et al.
215 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
216   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
217   Subtarget = &TM.getSubtarget<X86Subtarget>();
218   X86ScalarSSEf64 = Subtarget->hasSSE2();
219   X86ScalarSSEf32 = Subtarget->hasSSE1();
220   TD = getDataLayout();
221
222   resetOperationActions();
223 }
224
225 void X86TargetLowering::resetOperationActions() {
226   const TargetMachine &TM = getTargetMachine();
227   static bool FirstTimeThrough = true;
228
229   // If none of the target options have changed, then we don't need to reset the
230   // operation actions.
231   if (!FirstTimeThrough && TO == TM.Options) return;
232
233   if (!FirstTimeThrough) {
234     // Reinitialize the actions.
235     initActions();
236     FirstTimeThrough = false;
237   }
238
239   TO = TM.Options;
240
241   // Set up the TargetLowering object.
242   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243
244   // X86 is weird, it always uses i8 for shift amounts and setcc results.
245   setBooleanContents(ZeroOrOneBooleanContent);
246   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
247   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248
249   // For 64-bit since we have so many registers use the ILP scheduler, for
250   // 32-bit code use the register pressure specific scheduling.
251   // For Atom, always use ILP scheduling.
252   if (Subtarget->isAtom())
253     setSchedulingPreference(Sched::ILP);
254   else if (Subtarget->is64Bit())
255     setSchedulingPreference(Sched::ILP);
256   else
257     setSchedulingPreference(Sched::RegPressure);
258   const X86RegisterInfo *RegInfo =
259       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
260   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261
262   // Bypass expensive divides on Atom when compiling with O2
263   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
264     addBypassSlowDiv(32, 8);
265     if (Subtarget->is64Bit())
266       addBypassSlowDiv(64, 16);
267   }
268
269   if (Subtarget->isTargetKnownWindowsMSVC()) {
270     // Setup Windows compiler runtime calls.
271     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
272     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
273     setLibcallName(RTLIB::SREM_I64, "_allrem");
274     setLibcallName(RTLIB::UREM_I64, "_aullrem");
275     setLibcallName(RTLIB::MUL_I64, "_allmul");
276     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
280     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281
282     // The _ftol2 runtime function has an unusual calling conv, which
283     // is modeled by a special pseudo-instruction.
284     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
287     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
288   }
289
290   if (Subtarget->isTargetDarwin()) {
291     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
292     setUseUnderscoreSetJmp(false);
293     setUseUnderscoreLongJmp(false);
294   } else if (Subtarget->isTargetWindowsGNU()) {
295     // MS runtime is weird: it exports _setjmp, but longjmp!
296     setUseUnderscoreSetJmp(true);
297     setUseUnderscoreLongJmp(false);
298   } else {
299     setUseUnderscoreSetJmp(true);
300     setUseUnderscoreLongJmp(true);
301   }
302
303   // Set up the register classes.
304   addRegisterClass(MVT::i8, &X86::GR8RegClass);
305   addRegisterClass(MVT::i16, &X86::GR16RegClass);
306   addRegisterClass(MVT::i32, &X86::GR32RegClass);
307   if (Subtarget->is64Bit())
308     addRegisterClass(MVT::i64, &X86::GR64RegClass);
309
310   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311
312   // We don't accept any truncstore of integer registers.
313   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
315   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
316   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
317   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
318   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
319
320   // SETOEQ and SETUNE require checking two conditions.
321   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
323   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
326   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327
328   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329   // operation.
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
332   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
333
334   if (Subtarget->is64Bit()) {
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
336     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
337   } else if (!TM.Options.UseSoftFloat) {
338     // We have an algorithm for SSE2->double, and we turn this into a
339     // 64-bit FILD followed by conditional FADD for other targets.
340     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
341     // We have an algorithm for SSE2, and we turn this into a 64-bit
342     // FILD for other targets.
343     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
344   }
345
346   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347   // this operation.
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
349   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
350
351   if (!TM.Options.UseSoftFloat) {
352     // SSE has no i16 to fp conversion, only i32
353     if (X86ScalarSSEf32) {
354       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
355       // f32 and f64 cases are Legal, f80 case is not
356       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
357     } else {
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
359       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
360     }
361   } else {
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
363     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
364   }
365
366   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
367   // are Legal, f80 is custom lowered.
368   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
369   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
370
371   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372   // this operation.
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
374   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
375
376   if (X86ScalarSSEf32) {
377     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
378     // f32 and f64 cases are Legal, f80 case is not
379     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
380   } else {
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
382     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
383   }
384
385   // Handle FP_TO_UINT by promoting the destination to a larger signed
386   // conversion.
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
389   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
390
391   if (Subtarget->is64Bit()) {
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
393     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
394   } else if (!TM.Options.UseSoftFloat) {
395     // Since AVX is a superset of SSE3, only check for SSE here.
396     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
397       // Expand FP_TO_UINT into a select.
398       // FIXME: We would like to use a Custom expander here eventually to do
399       // the optimal thing for SSE vs. the default expansion in the legalizer.
400       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
401     else
402       // With SSE3 we can use fisttpll to convert to a signed i64; without
403       // SSE, we're stuck with a fistpll.
404       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
405   }
406
407   if (isTargetFTOL()) {
408     // Use the _ftol2 runtime function, which has a pseudo-instruction
409     // to handle its weird calling convention.
410     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
411   }
412
413   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
414   if (!X86ScalarSSEf64) {
415     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
416     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
417     if (Subtarget->is64Bit()) {
418       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
419       // Without SSE, i64->f64 goes through memory.
420       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
421     }
422   }
423
424   // Scalar integer divide and remainder are lowered to use operations that
425   // produce two results, to match the available instructions. This exposes
426   // the two-result form to trivial CSE, which is able to combine x/y and x%y
427   // into a single instruction.
428   //
429   // Scalar integer multiply-high is also lowered to use two-result
430   // operations, to match the available instructions. However, plain multiply
431   // (low) operations are left as Legal, as there are single-result
432   // instructions for this in x86. Using the two-result multiply instructions
433   // when both high and low results are needed must be arranged by dagcombine.
434   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435     MVT VT = IntVTs[i];
436     setOperationAction(ISD::MULHS, VT, Expand);
437     setOperationAction(ISD::MULHU, VT, Expand);
438     setOperationAction(ISD::SDIV, VT, Expand);
439     setOperationAction(ISD::UDIV, VT, Expand);
440     setOperationAction(ISD::SREM, VT, Expand);
441     setOperationAction(ISD::UREM, VT, Expand);
442
443     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
444     setOperationAction(ISD::ADDC, VT, Custom);
445     setOperationAction(ISD::ADDE, VT, Custom);
446     setOperationAction(ISD::SUBC, VT, Custom);
447     setOperationAction(ISD::SUBE, VT, Custom);
448   }
449
450   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
451   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
452   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
458   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
465   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
466   if (Subtarget->is64Bit())
467     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
470   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
471   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
474   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
475   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
476
477   // Promote the i8 variants and force them on up to i32 which has a shorter
478   // encoding.
479   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
480   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
481   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
482   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
483   if (Subtarget->hasBMI()) {
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
485     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
486     if (Subtarget->is64Bit())
487       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488   } else {
489     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
490     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
491     if (Subtarget->is64Bit())
492       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
493   }
494
495   if (Subtarget->hasLZCNT()) {
496     // When promoting the i8 variants, force them to i32 for a shorter
497     // encoding.
498     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
499     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
500     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
501     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
504     if (Subtarget->is64Bit())
505       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506   } else {
507     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
509     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
512     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
513     if (Subtarget->is64Bit()) {
514       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
515       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
516     }
517   }
518
519   // Special handling for half-precision floating point conversions.
520   // If we don't have F16C support, then lower half float conversions
521   // into library calls.
522   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
523     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
524     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
525   }
526
527   // There's never any support for operations beyond MVT::f32.
528   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
529   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
531   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532
533   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
536   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
537
538   if (Subtarget->hasPOPCNT()) {
539     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
540   } else {
541     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
543     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
544     if (Subtarget->is64Bit())
545       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
546   }
547
548   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
549
550   if (!Subtarget->hasMOVBE())
551     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
552
553   // These should be promoted to a larger select which is supported.
554   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
555   // X86 wants to expand cmov itself.
556   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
561   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
567   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
568   if (Subtarget->is64Bit()) {
569     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
570     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
571   }
572   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
573   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
574   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
575   // support continuation, user-level threading, and etc.. As a result, no
576   // other SjLj exception interfaces are implemented and please don't build
577   // your own exception handling based on them.
578   // LLVM/Clang supports zero-cost DWARF exception handling.
579   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
580   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
581
582   // Darwin ABI issue.
583   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
584   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
586   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
587   if (Subtarget->is64Bit())
588     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
589   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
590   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
591   if (Subtarget->is64Bit()) {
592     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
593     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
594     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
595     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
596     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
597   }
598   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
599   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
601   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
602   if (Subtarget->is64Bit()) {
603     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
605     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
606   }
607
608   if (Subtarget->hasSSE1())
609     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
610
611   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
612
613   // Expand certain atomics
614   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
615     MVT VT = IntVTs[i];
616     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
617     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
618     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
619   }
620
621   if (Subtarget->hasCmpxchg16b()) {
622     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
623   }
624
625   // FIXME - use subtarget debug flags
626   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
627       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
628     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
629   }
630
631   if (Subtarget->is64Bit()) {
632     setExceptionPointerRegister(X86::RAX);
633     setExceptionSelectorRegister(X86::RDX);
634   } else {
635     setExceptionPointerRegister(X86::EAX);
636     setExceptionSelectorRegister(X86::EDX);
637   }
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
639   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
640
641   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
642   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
643
644   setOperationAction(ISD::TRAP, MVT::Other, Legal);
645   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
646
647   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
648   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
649   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
650   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
651     // TargetInfo::X86_64ABIBuiltinVaList
652     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
653     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
654   } else {
655     // TargetInfo::CharPtrBuiltinVaList
656     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
657     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
658   }
659
660   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
661   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
662
663   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), 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 mean 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     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1027
1028     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1029     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1030     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1031     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1032     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1033     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1034
1035     if (Subtarget->is64Bit()) {
1036       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1037       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1038     }
1039
1040     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1041     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1042       MVT VT = (MVT::SimpleValueType)i;
1043
1044       // Do not attempt to promote non-128-bit vectors
1045       if (!VT.is128BitVector())
1046         continue;
1047
1048       setOperationAction(ISD::AND,    VT, Promote);
1049       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1050       setOperationAction(ISD::OR,     VT, Promote);
1051       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1052       setOperationAction(ISD::XOR,    VT, Promote);
1053       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1054       setOperationAction(ISD::LOAD,   VT, Promote);
1055       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1056       setOperationAction(ISD::SELECT, VT, Promote);
1057       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1058     }
1059
1060     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1061
1062     // Custom lower v2i64 and v2f64 selects.
1063     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1064     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1065     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1066     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1067
1068     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1069     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1070
1071     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1073     // As there is no 64-bit GPR available, we need build a special custom
1074     // sequence to convert from v2i32 to v2f32.
1075     if (!Subtarget->is64Bit())
1076       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1077
1078     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1079     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1080
1081     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1082
1083     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1084     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1086   }
1087
1088   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1089     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1090     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1091     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1094     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1095     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1096     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1099
1100     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1101     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1102     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1105     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1106     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1107     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1110
1111     // FIXME: Do we need to handle scalar-to-vector here?
1112     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1113
1114     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1115     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1119     // There is no BLENDI for byte vectors. We don't need to custom lower
1120     // some vselects for now.
1121     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1122
1123     // SSE41 brings specific instructions for doing vector sign extend even in
1124     // cases where we don't have SRA.
1125     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1128
1129     // i8 and i16 vectors are custom because the source register and source
1130     // source memory operand types are not the same width.  f32 vectors are
1131     // custom since the immediate controlling the insert encodes additional
1132     // information.
1133     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1137
1138     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1142
1143     // FIXME: these should be Legal, but that's only for the case where
1144     // the index is constant.  For now custom expand to deal with that.
1145     if (Subtarget->is64Bit()) {
1146       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1147       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1148     }
1149   }
1150
1151   if (Subtarget->hasSSE2()) {
1152     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1153     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1154
1155     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1156     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1157
1158     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1159     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1160
1161     // In the customized shift lowering, the legal cases in AVX2 will be
1162     // recognized.
1163     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1164     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1165
1166     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1167     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1168
1169     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1170   }
1171
1172   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1173     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1174     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1175     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1179
1180     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1181     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1183
1184     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1185     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1189     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1190     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1195     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1196
1197     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1198     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1202     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1203     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1208     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1209
1210     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1211     // even though v8i16 is a legal type.
1212     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1213     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1215
1216     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1218     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1219
1220     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1222
1223     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1224
1225     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1226     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1227
1228     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1229     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1230
1231     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1232     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1233
1234     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1235     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1238
1239     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1240     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1242
1243     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1244     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1247
1248     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1251     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1254     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1257     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1260
1261     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1262       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1263       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1268     }
1269
1270     if (Subtarget->hasInt256()) {
1271       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1272       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1275
1276       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1277       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1280
1281       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1282       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1283       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1284       // Don't lower v32i8 because there is no 128-bit byte mul
1285
1286       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1287       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1289       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1290
1291       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1292       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1293     } else {
1294       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1295       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1298
1299       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1300       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1303
1304       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1305       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1307       // Don't lower v32i8 because there is no 128-bit byte mul
1308     }
1309
1310     // In the customized shift lowering, the legal cases in AVX2 will be
1311     // recognized.
1312     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1313     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1314
1315     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1316     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1317
1318     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1319
1320     // Custom lower several nodes for 256-bit types.
1321     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1322              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1323       MVT VT = (MVT::SimpleValueType)i;
1324
1325       // Extract subvector is special because the value type
1326       // (result) is 128-bit but the source is 256-bit wide.
1327       if (VT.is128BitVector())
1328         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1329
1330       // Do not attempt to custom lower other non-256-bit vectors
1331       if (!VT.is256BitVector())
1332         continue;
1333
1334       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1335       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1336       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1337       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1338       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1339       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1340       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1341     }
1342
1343     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1344     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1345       MVT VT = (MVT::SimpleValueType)i;
1346
1347       // Do not attempt to promote non-256-bit vectors
1348       if (!VT.is256BitVector())
1349         continue;
1350
1351       setOperationAction(ISD::AND,    VT, Promote);
1352       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1353       setOperationAction(ISD::OR,     VT, Promote);
1354       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1355       setOperationAction(ISD::XOR,    VT, Promote);
1356       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1357       setOperationAction(ISD::LOAD,   VT, Promote);
1358       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1359       setOperationAction(ISD::SELECT, VT, Promote);
1360       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1361     }
1362   }
1363
1364   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1365     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1366     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1369
1370     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1371     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1372     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1373
1374     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1375     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1376     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1377     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1378     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1379     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1380     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1385
1386     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1387     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1391     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1392
1393     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1394     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1398     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1399     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1400     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1401
1402     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1403     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1405     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1406     if (Subtarget->is64Bit()) {
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1408       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1411     }
1412     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1413     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1416     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1417     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1420     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1421     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1422
1423     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1424     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1429     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1431     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1436
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1443
1444     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1445     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1446
1447     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1448
1449     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1451     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1453     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1455     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1458
1459     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1461
1462     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1463     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1464
1465     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1468     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1469
1470     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1474     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1475
1476     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1477     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1478     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1480     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1481     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1482
1483     if (Subtarget->hasCDI()) {
1484       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1485       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1486     }
1487
1488     // Custom lower several nodes.
1489     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1490              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1491       MVT VT = (MVT::SimpleValueType)i;
1492
1493       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1494       // Extract subvector is special because the value type
1495       // (result) is 256/128-bit but the source is 512-bit wide.
1496       if (VT.is128BitVector() || VT.is256BitVector())
1497         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1498
1499       if (VT.getVectorElementType() == MVT::i1)
1500         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1501
1502       // Do not attempt to custom lower other non-512-bit vectors
1503       if (!VT.is512BitVector())
1504         continue;
1505
1506       if ( EltSize >= 32) {
1507         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1508         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1509         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1510         setOperationAction(ISD::VSELECT,             VT, Legal);
1511         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1512         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1513         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1514       }
1515     }
1516     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1517       MVT VT = (MVT::SimpleValueType)i;
1518
1519       // Do not attempt to promote non-256-bit vectors
1520       if (!VT.is512BitVector())
1521         continue;
1522
1523       setOperationAction(ISD::SELECT, VT, Promote);
1524       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1525     }
1526   }// has  AVX-512
1527
1528   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1529     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1530     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1531
1532     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1533     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1534
1535     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1536     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1537     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1538     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1539
1540     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1541       const MVT VT = (MVT::SimpleValueType)i;
1542
1543       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1544
1545       // Do not attempt to promote non-256-bit vectors
1546       if (!VT.is512BitVector())
1547         continue;
1548
1549       if ( EltSize < 32) {
1550         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1551         setOperationAction(ISD::VSELECT,             VT, Legal);
1552       }
1553     }
1554   }
1555
1556   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1557     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1558     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1559
1560     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1561     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1562   }
1563
1564   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1565   // of this type with custom code.
1566   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1567            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1568     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1569                        Custom);
1570   }
1571
1572   // We want to custom lower some of our intrinsics.
1573   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1574   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1575   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1576   if (!Subtarget->is64Bit())
1577     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1578
1579   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1580   // handle type legalization for these operations here.
1581   //
1582   // FIXME: We really should do custom legalization for addition and
1583   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1584   // than generic legalization for 64-bit multiplication-with-overflow, though.
1585   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1586     // Add/Sub/Mul with overflow operations are custom lowered.
1587     MVT VT = IntVTs[i];
1588     setOperationAction(ISD::SADDO, VT, Custom);
1589     setOperationAction(ISD::UADDO, VT, Custom);
1590     setOperationAction(ISD::SSUBO, VT, Custom);
1591     setOperationAction(ISD::USUBO, VT, Custom);
1592     setOperationAction(ISD::SMULO, VT, Custom);
1593     setOperationAction(ISD::UMULO, VT, Custom);
1594   }
1595
1596   // There are no 8-bit 3-address imul/mul instructions
1597   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1598   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1599
1600   if (!Subtarget->is64Bit()) {
1601     // These libcalls are not available in 32-bit.
1602     setLibcallName(RTLIB::SHL_I128, nullptr);
1603     setLibcallName(RTLIB::SRL_I128, nullptr);
1604     setLibcallName(RTLIB::SRA_I128, nullptr);
1605   }
1606
1607   // Combine sin / cos into one node or libcall if possible.
1608   if (Subtarget->hasSinCos()) {
1609     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1610     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1611     if (Subtarget->isTargetDarwin()) {
1612       // For MacOSX, we don't want to the normal expansion of a libcall to
1613       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1614       // traffic.
1615       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1616       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1617     }
1618   }
1619
1620   if (Subtarget->isTargetWin64()) {
1621     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1622     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1623     setOperationAction(ISD::SREM, MVT::i128, Custom);
1624     setOperationAction(ISD::UREM, MVT::i128, Custom);
1625     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1626     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1627   }
1628
1629   // We have target-specific dag combine patterns for the following nodes:
1630   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1631   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1632   setTargetDAGCombine(ISD::VSELECT);
1633   setTargetDAGCombine(ISD::SELECT);
1634   setTargetDAGCombine(ISD::SHL);
1635   setTargetDAGCombine(ISD::SRA);
1636   setTargetDAGCombine(ISD::SRL);
1637   setTargetDAGCombine(ISD::OR);
1638   setTargetDAGCombine(ISD::AND);
1639   setTargetDAGCombine(ISD::ADD);
1640   setTargetDAGCombine(ISD::FADD);
1641   setTargetDAGCombine(ISD::FSUB);
1642   setTargetDAGCombine(ISD::FMA);
1643   setTargetDAGCombine(ISD::SUB);
1644   setTargetDAGCombine(ISD::LOAD);
1645   setTargetDAGCombine(ISD::STORE);
1646   setTargetDAGCombine(ISD::ZERO_EXTEND);
1647   setTargetDAGCombine(ISD::ANY_EXTEND);
1648   setTargetDAGCombine(ISD::SIGN_EXTEND);
1649   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1650   setTargetDAGCombine(ISD::TRUNCATE);
1651   setTargetDAGCombine(ISD::SINT_TO_FP);
1652   setTargetDAGCombine(ISD::SETCC);
1653   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1654   setTargetDAGCombine(ISD::BUILD_VECTOR);
1655   if (Subtarget->is64Bit())
1656     setTargetDAGCombine(ISD::MUL);
1657   setTargetDAGCombine(ISD::XOR);
1658
1659   computeRegisterProperties();
1660
1661   // On Darwin, -Os means optimize for size without hurting performance,
1662   // do not reduce the limit.
1663   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1664   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1665   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1666   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1667   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1668   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1669   setPrefLoopAlignment(4); // 2^4 bytes.
1670
1671   // Predictable cmov don't hurt on atom because it's in-order.
1672   PredictableSelectIsExpensive = !Subtarget->isAtom();
1673
1674   setPrefFunctionAlignment(4); // 2^4 bytes.
1675
1676   verifyIntrinsicTables();
1677 }
1678
1679 // This has so far only been implemented for 64-bit MachO.
1680 bool X86TargetLowering::useLoadStackGuardNode() const {
1681   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1682          Subtarget->is64Bit();
1683 }
1684
1685 TargetLoweringBase::LegalizeTypeAction
1686 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1687   if (ExperimentalVectorWideningLegalization &&
1688       VT.getVectorNumElements() != 1 &&
1689       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1690     return TypeWidenVector;
1691
1692   return TargetLoweringBase::getPreferredVectorAction(VT);
1693 }
1694
1695 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1696   if (!VT.isVector())
1697     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1698
1699   const unsigned NumElts = VT.getVectorNumElements();
1700   const EVT EltVT = VT.getVectorElementType();
1701   if (VT.is512BitVector()) {
1702     if (Subtarget->hasAVX512())
1703       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1704           EltVT == MVT::f32 || EltVT == MVT::f64)
1705         switch(NumElts) {
1706         case  8: return MVT::v8i1;
1707         case 16: return MVT::v16i1;
1708       }
1709     if (Subtarget->hasBWI())
1710       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1711         switch(NumElts) {
1712         case 32: return MVT::v32i1;
1713         case 64: return MVT::v64i1;
1714       }
1715   }
1716
1717   if (VT.is256BitVector() || VT.is128BitVector()) {
1718     if (Subtarget->hasVLX())
1719       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1720           EltVT == MVT::f32 || EltVT == MVT::f64)
1721         switch(NumElts) {
1722         case 2: return MVT::v2i1;
1723         case 4: return MVT::v4i1;
1724         case 8: return MVT::v8i1;
1725       }
1726     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1727       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1728         switch(NumElts) {
1729         case  8: return MVT::v8i1;
1730         case 16: return MVT::v16i1;
1731         case 32: return MVT::v32i1;
1732       }
1733   }
1734
1735   return VT.changeVectorElementTypeToInteger();
1736 }
1737
1738 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1739 /// the desired ByVal argument alignment.
1740 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1741   if (MaxAlign == 16)
1742     return;
1743   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1744     if (VTy->getBitWidth() == 128)
1745       MaxAlign = 16;
1746   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1747     unsigned EltAlign = 0;
1748     getMaxByValAlign(ATy->getElementType(), EltAlign);
1749     if (EltAlign > MaxAlign)
1750       MaxAlign = EltAlign;
1751   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1752     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1753       unsigned EltAlign = 0;
1754       getMaxByValAlign(STy->getElementType(i), EltAlign);
1755       if (EltAlign > MaxAlign)
1756         MaxAlign = EltAlign;
1757       if (MaxAlign == 16)
1758         break;
1759     }
1760   }
1761 }
1762
1763 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1764 /// function arguments in the caller parameter area. For X86, aggregates
1765 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1766 /// are at 4-byte boundaries.
1767 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1768   if (Subtarget->is64Bit()) {
1769     // Max of 8 and alignment of type.
1770     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1771     if (TyAlign > 8)
1772       return TyAlign;
1773     return 8;
1774   }
1775
1776   unsigned Align = 4;
1777   if (Subtarget->hasSSE1())
1778     getMaxByValAlign(Ty, Align);
1779   return Align;
1780 }
1781
1782 /// getOptimalMemOpType - Returns the target specific optimal type for load
1783 /// and store operations as a result of memset, memcpy, and memmove
1784 /// lowering. If DstAlign is zero that means it's safe to destination
1785 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1786 /// means there isn't a need to check it against alignment requirement,
1787 /// probably because the source does not need to be loaded. If 'IsMemset' is
1788 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1789 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1790 /// source is constant so it does not need to be loaded.
1791 /// It returns EVT::Other if the type should be determined using generic
1792 /// target-independent logic.
1793 EVT
1794 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1795                                        unsigned DstAlign, unsigned SrcAlign,
1796                                        bool IsMemset, bool ZeroMemset,
1797                                        bool MemcpyStrSrc,
1798                                        MachineFunction &MF) const {
1799   const Function *F = MF.getFunction();
1800   if ((!IsMemset || ZeroMemset) &&
1801       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1802                                        Attribute::NoImplicitFloat)) {
1803     if (Size >= 16 &&
1804         (Subtarget->isUnalignedMemAccessFast() ||
1805          ((DstAlign == 0 || DstAlign >= 16) &&
1806           (SrcAlign == 0 || SrcAlign >= 16)))) {
1807       if (Size >= 32) {
1808         if (Subtarget->hasInt256())
1809           return MVT::v8i32;
1810         if (Subtarget->hasFp256())
1811           return MVT::v8f32;
1812       }
1813       if (Subtarget->hasSSE2())
1814         return MVT::v4i32;
1815       if (Subtarget->hasSSE1())
1816         return MVT::v4f32;
1817     } else if (!MemcpyStrSrc && Size >= 8 &&
1818                !Subtarget->is64Bit() &&
1819                Subtarget->hasSSE2()) {
1820       // Do not use f64 to lower memcpy if source is string constant. It's
1821       // better to use i32 to avoid the loads.
1822       return MVT::f64;
1823     }
1824   }
1825   if (Subtarget->is64Bit() && Size >= 8)
1826     return MVT::i64;
1827   return MVT::i32;
1828 }
1829
1830 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1831   if (VT == MVT::f32)
1832     return X86ScalarSSEf32;
1833   else if (VT == MVT::f64)
1834     return X86ScalarSSEf64;
1835   return true;
1836 }
1837
1838 bool
1839 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1840                                                   unsigned,
1841                                                   unsigned,
1842                                                   bool *Fast) const {
1843   if (Fast)
1844     *Fast = Subtarget->isUnalignedMemAccessFast();
1845   return true;
1846 }
1847
1848 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1849 /// current function.  The returned value is a member of the
1850 /// MachineJumpTableInfo::JTEntryKind enum.
1851 unsigned X86TargetLowering::getJumpTableEncoding() const {
1852   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1853   // symbol.
1854   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1855       Subtarget->isPICStyleGOT())
1856     return MachineJumpTableInfo::EK_Custom32;
1857
1858   // Otherwise, use the normal jump table encoding heuristics.
1859   return TargetLowering::getJumpTableEncoding();
1860 }
1861
1862 const MCExpr *
1863 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1864                                              const MachineBasicBlock *MBB,
1865                                              unsigned uid,MCContext &Ctx) const{
1866   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1867          Subtarget->isPICStyleGOT());
1868   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1869   // entries.
1870   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1871                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1872 }
1873
1874 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1875 /// jumptable.
1876 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1877                                                     SelectionDAG &DAG) const {
1878   if (!Subtarget->is64Bit())
1879     // This doesn't have SDLoc associated with it, but is not really the
1880     // same as a Register.
1881     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1882   return Table;
1883 }
1884
1885 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1886 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1887 /// MCExpr.
1888 const MCExpr *X86TargetLowering::
1889 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1890                              MCContext &Ctx) const {
1891   // X86-64 uses RIP relative addressing based on the jump table label.
1892   if (Subtarget->isPICStyleRIPRel())
1893     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1894
1895   // Otherwise, the reference is relative to the PIC base.
1896   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1897 }
1898
1899 // FIXME: Why this routine is here? Move to RegInfo!
1900 std::pair<const TargetRegisterClass*, uint8_t>
1901 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1902   const TargetRegisterClass *RRC = nullptr;
1903   uint8_t Cost = 1;
1904   switch (VT.SimpleTy) {
1905   default:
1906     return TargetLowering::findRepresentativeClass(VT);
1907   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1908     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1909     break;
1910   case MVT::x86mmx:
1911     RRC = &X86::VR64RegClass;
1912     break;
1913   case MVT::f32: case MVT::f64:
1914   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1915   case MVT::v4f32: case MVT::v2f64:
1916   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1917   case MVT::v4f64:
1918     RRC = &X86::VR128RegClass;
1919     break;
1920   }
1921   return std::make_pair(RRC, Cost);
1922 }
1923
1924 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1925                                                unsigned &Offset) const {
1926   if (!Subtarget->isTargetLinux())
1927     return false;
1928
1929   if (Subtarget->is64Bit()) {
1930     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1931     Offset = 0x28;
1932     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1933       AddressSpace = 256;
1934     else
1935       AddressSpace = 257;
1936   } else {
1937     // %gs:0x14 on i386
1938     Offset = 0x14;
1939     AddressSpace = 256;
1940   }
1941   return true;
1942 }
1943
1944 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1945                                             unsigned DestAS) const {
1946   assert(SrcAS != DestAS && "Expected different address spaces!");
1947
1948   return SrcAS < 256 && DestAS < 256;
1949 }
1950
1951 //===----------------------------------------------------------------------===//
1952 //               Return Value Calling Convention Implementation
1953 //===----------------------------------------------------------------------===//
1954
1955 #include "X86GenCallingConv.inc"
1956
1957 bool
1958 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1959                                   MachineFunction &MF, bool isVarArg,
1960                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1961                         LLVMContext &Context) const {
1962   SmallVector<CCValAssign, 16> RVLocs;
1963   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1964   return CCInfo.CheckReturn(Outs, RetCC_X86);
1965 }
1966
1967 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1968   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1969   return ScratchRegs;
1970 }
1971
1972 SDValue
1973 X86TargetLowering::LowerReturn(SDValue Chain,
1974                                CallingConv::ID CallConv, bool isVarArg,
1975                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1976                                const SmallVectorImpl<SDValue> &OutVals,
1977                                SDLoc dl, SelectionDAG &DAG) const {
1978   MachineFunction &MF = DAG.getMachineFunction();
1979   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1980
1981   SmallVector<CCValAssign, 16> RVLocs;
1982   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1983   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1984
1985   SDValue Flag;
1986   SmallVector<SDValue, 6> RetOps;
1987   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1988   // Operand #1 = Bytes To Pop
1989   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1990                    MVT::i16));
1991
1992   // Copy the result values into the output registers.
1993   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1994     CCValAssign &VA = RVLocs[i];
1995     assert(VA.isRegLoc() && "Can only return in registers!");
1996     SDValue ValToCopy = OutVals[i];
1997     EVT ValVT = ValToCopy.getValueType();
1998
1999     // Promote values to the appropriate types
2000     if (VA.getLocInfo() == CCValAssign::SExt)
2001       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2002     else if (VA.getLocInfo() == CCValAssign::ZExt)
2003       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2004     else if (VA.getLocInfo() == CCValAssign::AExt)
2005       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2006     else if (VA.getLocInfo() == CCValAssign::BCvt)
2007       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2008
2009     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2010            "Unexpected FP-extend for return value.");  
2011
2012     // If this is x86-64, and we disabled SSE, we can't return FP values,
2013     // or SSE or MMX vectors.
2014     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2015          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2016           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2017       report_fatal_error("SSE register return with SSE disabled");
2018     }
2019     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2020     // llvm-gcc has never done it right and no one has noticed, so this
2021     // should be OK for now.
2022     if (ValVT == MVT::f64 &&
2023         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2024       report_fatal_error("SSE2 register return with SSE2 disabled");
2025
2026     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2027     // the RET instruction and handled by the FP Stackifier.
2028     if (VA.getLocReg() == X86::FP0 ||
2029         VA.getLocReg() == X86::FP1) {
2030       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2031       // change the value to the FP stack register class.
2032       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2033         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2034       RetOps.push_back(ValToCopy);
2035       // Don't emit a copytoreg.
2036       continue;
2037     }
2038
2039     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2040     // which is returned in RAX / RDX.
2041     if (Subtarget->is64Bit()) {
2042       if (ValVT == MVT::x86mmx) {
2043         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2044           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2045           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2046                                   ValToCopy);
2047           // If we don't have SSE2 available, convert to v4f32 so the generated
2048           // register is legal.
2049           if (!Subtarget->hasSSE2())
2050             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2051         }
2052       }
2053     }
2054
2055     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2056     Flag = Chain.getValue(1);
2057     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2058   }
2059
2060   // The x86-64 ABIs require that for returning structs by value we copy
2061   // the sret argument into %rax/%eax (depending on ABI) for the return.
2062   // Win32 requires us to put the sret argument to %eax as well.
2063   // We saved the argument into a virtual register in the entry block,
2064   // so now we copy the value out and into %rax/%eax.
2065   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2066       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2067     MachineFunction &MF = DAG.getMachineFunction();
2068     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2069     unsigned Reg = FuncInfo->getSRetReturnReg();
2070     assert(Reg &&
2071            "SRetReturnReg should have been set in LowerFormalArguments().");
2072     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2073
2074     unsigned RetValReg
2075         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2076           X86::RAX : X86::EAX;
2077     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2078     Flag = Chain.getValue(1);
2079
2080     // RAX/EAX now acts like a return value.
2081     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2082   }
2083
2084   RetOps[0] = Chain;  // Update chain.
2085
2086   // Add the flag if we have it.
2087   if (Flag.getNode())
2088     RetOps.push_back(Flag);
2089
2090   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2091 }
2092
2093 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2094   if (N->getNumValues() != 1)
2095     return false;
2096   if (!N->hasNUsesOfValue(1, 0))
2097     return false;
2098
2099   SDValue TCChain = Chain;
2100   SDNode *Copy = *N->use_begin();
2101   if (Copy->getOpcode() == ISD::CopyToReg) {
2102     // If the copy has a glue operand, we conservatively assume it isn't safe to
2103     // perform a tail call.
2104     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2105       return false;
2106     TCChain = Copy->getOperand(0);
2107   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2108     return false;
2109
2110   bool HasRet = false;
2111   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2112        UI != UE; ++UI) {
2113     if (UI->getOpcode() != X86ISD::RET_FLAG)
2114       return false;
2115     // If we are returning more than one value, we can definitely
2116     // not make a tail call see PR19530
2117     if (UI->getNumOperands() > 4)
2118       return false;
2119     if (UI->getNumOperands() == 4 &&
2120         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2121       return false;
2122     HasRet = true;
2123   }
2124
2125   if (!HasRet)
2126     return false;
2127
2128   Chain = TCChain;
2129   return true;
2130 }
2131
2132 EVT
2133 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2134                                             ISD::NodeType ExtendKind) const {
2135   MVT ReturnMVT;
2136   // TODO: Is this also valid on 32-bit?
2137   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2138     ReturnMVT = MVT::i8;
2139   else
2140     ReturnMVT = MVT::i32;
2141
2142   EVT MinVT = getRegisterType(Context, ReturnMVT);
2143   return VT.bitsLT(MinVT) ? MinVT : VT;
2144 }
2145
2146 /// LowerCallResult - Lower the result values of a call into the
2147 /// appropriate copies out of appropriate physical registers.
2148 ///
2149 SDValue
2150 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2151                                    CallingConv::ID CallConv, bool isVarArg,
2152                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2153                                    SDLoc dl, SelectionDAG &DAG,
2154                                    SmallVectorImpl<SDValue> &InVals) const {
2155
2156   // Assign locations to each value returned by this call.
2157   SmallVector<CCValAssign, 16> RVLocs;
2158   bool Is64Bit = Subtarget->is64Bit();
2159   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2160                  *DAG.getContext());
2161   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2162
2163   // Copy all of the result registers out of their specified physreg.
2164   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2165     CCValAssign &VA = RVLocs[i];
2166     EVT CopyVT = VA.getValVT();
2167
2168     // If this is x86-64, and we disabled SSE, we can't return FP values
2169     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2170         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2171       report_fatal_error("SSE register return with SSE disabled");
2172     }
2173
2174     // If we prefer to use the value in xmm registers, copy it out as f80 and
2175     // use a truncate to move it from fp stack reg to xmm reg.
2176     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2177         isScalarFPTypeInSSEReg(VA.getValVT()))
2178       CopyVT = MVT::f80;
2179
2180     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2181                                CopyVT, InFlag).getValue(1);
2182     SDValue Val = Chain.getValue(0);
2183
2184     if (CopyVT != VA.getValVT())
2185       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2186                         // This truncation won't change the value.
2187                         DAG.getIntPtrConstant(1));
2188
2189     InFlag = Chain.getValue(2);
2190     InVals.push_back(Val);
2191   }
2192
2193   return Chain;
2194 }
2195
2196 //===----------------------------------------------------------------------===//
2197 //                C & StdCall & Fast Calling Convention implementation
2198 //===----------------------------------------------------------------------===//
2199 //  StdCall calling convention seems to be standard for many Windows' API
2200 //  routines and around. It differs from C calling convention just a little:
2201 //  callee should clean up the stack, not caller. Symbols should be also
2202 //  decorated in some fancy way :) It doesn't support any vector arguments.
2203 //  For info on fast calling convention see Fast Calling Convention (tail call)
2204 //  implementation LowerX86_32FastCCCallTo.
2205
2206 /// CallIsStructReturn - Determines whether a call uses struct return
2207 /// semantics.
2208 enum StructReturnType {
2209   NotStructReturn,
2210   RegStructReturn,
2211   StackStructReturn
2212 };
2213 static StructReturnType
2214 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2215   if (Outs.empty())
2216     return NotStructReturn;
2217
2218   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2219   if (!Flags.isSRet())
2220     return NotStructReturn;
2221   if (Flags.isInReg())
2222     return RegStructReturn;
2223   return StackStructReturn;
2224 }
2225
2226 /// ArgsAreStructReturn - Determines whether a function uses struct
2227 /// return semantics.
2228 static StructReturnType
2229 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2230   if (Ins.empty())
2231     return NotStructReturn;
2232
2233   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2234   if (!Flags.isSRet())
2235     return NotStructReturn;
2236   if (Flags.isInReg())
2237     return RegStructReturn;
2238   return StackStructReturn;
2239 }
2240
2241 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2242 /// by "Src" to address "Dst" with size and alignment information specified by
2243 /// the specific parameter attribute. The copy will be passed as a byval
2244 /// function parameter.
2245 static SDValue
2246 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2247                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2248                           SDLoc dl) {
2249   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2250
2251   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2252                        /*isVolatile*/false, /*AlwaysInline=*/true,
2253                        MachinePointerInfo(), MachinePointerInfo());
2254 }
2255
2256 /// IsTailCallConvention - Return true if the calling convention is one that
2257 /// supports tail call optimization.
2258 static bool IsTailCallConvention(CallingConv::ID CC) {
2259   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2260           CC == CallingConv::HiPE);
2261 }
2262
2263 /// \brief Return true if the calling convention is a C calling convention.
2264 static bool IsCCallConvention(CallingConv::ID CC) {
2265   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2266           CC == CallingConv::X86_64_SysV);
2267 }
2268
2269 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2270   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2271     return false;
2272
2273   CallSite CS(CI);
2274   CallingConv::ID CalleeCC = CS.getCallingConv();
2275   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2276     return false;
2277
2278   return true;
2279 }
2280
2281 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2282 /// a tailcall target by changing its ABI.
2283 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2284                                    bool GuaranteedTailCallOpt) {
2285   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2286 }
2287
2288 SDValue
2289 X86TargetLowering::LowerMemArgument(SDValue Chain,
2290                                     CallingConv::ID CallConv,
2291                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2292                                     SDLoc dl, SelectionDAG &DAG,
2293                                     const CCValAssign &VA,
2294                                     MachineFrameInfo *MFI,
2295                                     unsigned i) const {
2296   // Create the nodes corresponding to a load from this parameter slot.
2297   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2298   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2299       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2300   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2301   EVT ValVT;
2302
2303   // If value is passed by pointer we have address passed instead of the value
2304   // itself.
2305   if (VA.getLocInfo() == CCValAssign::Indirect)
2306     ValVT = VA.getLocVT();
2307   else
2308     ValVT = VA.getValVT();
2309
2310   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2311   // changed with more analysis.
2312   // In case of tail call optimization mark all arguments mutable. Since they
2313   // could be overwritten by lowering of arguments in case of a tail call.
2314   if (Flags.isByVal()) {
2315     unsigned Bytes = Flags.getByValSize();
2316     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2317     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2318     return DAG.getFrameIndex(FI, getPointerTy());
2319   } else {
2320     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2321                                     VA.getLocMemOffset(), isImmutable);
2322     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2323     return DAG.getLoad(ValVT, dl, Chain, FIN,
2324                        MachinePointerInfo::getFixedStack(FI),
2325                        false, false, false, 0);
2326   }
2327 }
2328
2329 // FIXME: Get this from tablegen.
2330 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2331                                                 const X86Subtarget *Subtarget) {
2332   assert(Subtarget->is64Bit());
2333
2334   if (Subtarget->isCallingConvWin64(CallConv)) {
2335     static const MCPhysReg GPR64ArgRegsWin64[] = {
2336       X86::RCX, X86::RDX, X86::R8,  X86::R9
2337     };
2338     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2339   }
2340
2341   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2342     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2343   };
2344   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2345 }
2346
2347 // FIXME: Get this from tablegen.
2348 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2349                                                 CallingConv::ID CallConv,
2350                                                 const X86Subtarget *Subtarget) {
2351   assert(Subtarget->is64Bit());
2352   if (Subtarget->isCallingConvWin64(CallConv)) {
2353     // The XMM registers which might contain var arg parameters are shadowed
2354     // in their paired GPR.  So we only need to save the GPR to their home
2355     // slots.
2356     // TODO: __vectorcall will change this.
2357     return None;
2358   }
2359
2360   const Function *Fn = MF.getFunction();
2361   bool NoImplicitFloatOps = Fn->getAttributes().
2362       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2363   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2364          "SSE register cannot be used when SSE is disabled!");
2365   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2366       !Subtarget->hasSSE1())
2367     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2368     // registers.
2369     return None;
2370
2371   static const MCPhysReg XMMArgRegs64Bit[] = {
2372     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2373     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2374   };
2375   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2376 }
2377
2378 SDValue
2379 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2380                                         CallingConv::ID CallConv,
2381                                         bool isVarArg,
2382                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2383                                         SDLoc dl,
2384                                         SelectionDAG &DAG,
2385                                         SmallVectorImpl<SDValue> &InVals)
2386                                           const {
2387   MachineFunction &MF = DAG.getMachineFunction();
2388   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2389
2390   const Function* Fn = MF.getFunction();
2391   if (Fn->hasExternalLinkage() &&
2392       Subtarget->isTargetCygMing() &&
2393       Fn->getName() == "main")
2394     FuncInfo->setForceFramePointer(true);
2395
2396   MachineFrameInfo *MFI = MF.getFrameInfo();
2397   bool Is64Bit = Subtarget->is64Bit();
2398   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2399
2400   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2401          "Var args not supported with calling convention fastcc, ghc or hipe");
2402
2403   // Assign locations to all of the incoming arguments.
2404   SmallVector<CCValAssign, 16> ArgLocs;
2405   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2406
2407   // Allocate shadow area for Win64
2408   if (IsWin64)
2409     CCInfo.AllocateStack(32, 8);
2410
2411   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2412
2413   unsigned LastVal = ~0U;
2414   SDValue ArgValue;
2415   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416     CCValAssign &VA = ArgLocs[i];
2417     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2418     // places.
2419     assert(VA.getValNo() != LastVal &&
2420            "Don't support value assigned to multiple locs yet");
2421     (void)LastVal;
2422     LastVal = VA.getValNo();
2423
2424     if (VA.isRegLoc()) {
2425       EVT RegVT = VA.getLocVT();
2426       const TargetRegisterClass *RC;
2427       if (RegVT == MVT::i32)
2428         RC = &X86::GR32RegClass;
2429       else if (Is64Bit && RegVT == MVT::i64)
2430         RC = &X86::GR64RegClass;
2431       else if (RegVT == MVT::f32)
2432         RC = &X86::FR32RegClass;
2433       else if (RegVT == MVT::f64)
2434         RC = &X86::FR64RegClass;
2435       else if (RegVT.is512BitVector())
2436         RC = &X86::VR512RegClass;
2437       else if (RegVT.is256BitVector())
2438         RC = &X86::VR256RegClass;
2439       else if (RegVT.is128BitVector())
2440         RC = &X86::VR128RegClass;
2441       else if (RegVT == MVT::x86mmx)
2442         RC = &X86::VR64RegClass;
2443       else if (RegVT == MVT::i1)
2444         RC = &X86::VK1RegClass;
2445       else if (RegVT == MVT::v8i1)
2446         RC = &X86::VK8RegClass;
2447       else if (RegVT == MVT::v16i1)
2448         RC = &X86::VK16RegClass;
2449       else if (RegVT == MVT::v32i1)
2450         RC = &X86::VK32RegClass;
2451       else if (RegVT == MVT::v64i1)
2452         RC = &X86::VK64RegClass;
2453       else
2454         llvm_unreachable("Unknown argument type!");
2455
2456       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2457       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2458
2459       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2460       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2461       // right size.
2462       if (VA.getLocInfo() == CCValAssign::SExt)
2463         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2464                                DAG.getValueType(VA.getValVT()));
2465       else if (VA.getLocInfo() == CCValAssign::ZExt)
2466         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2467                                DAG.getValueType(VA.getValVT()));
2468       else if (VA.getLocInfo() == CCValAssign::BCvt)
2469         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2470
2471       if (VA.isExtInLoc()) {
2472         // Handle MMX values passed in XMM regs.
2473         if (RegVT.isVector())
2474           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2475         else
2476           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2477       }
2478     } else {
2479       assert(VA.isMemLoc());
2480       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2481     }
2482
2483     // If value is passed via pointer - do a load.
2484     if (VA.getLocInfo() == CCValAssign::Indirect)
2485       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2486                              MachinePointerInfo(), false, false, false, 0);
2487
2488     InVals.push_back(ArgValue);
2489   }
2490
2491   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2492     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2493       // The x86-64 ABIs require that for returning structs by value we copy
2494       // the sret argument into %rax/%eax (depending on ABI) for the return.
2495       // Win32 requires us to put the sret argument to %eax as well.
2496       // Save the argument into a virtual register so that we can access it
2497       // from the return points.
2498       if (Ins[i].Flags.isSRet()) {
2499         unsigned Reg = FuncInfo->getSRetReturnReg();
2500         if (!Reg) {
2501           MVT PtrTy = getPointerTy();
2502           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2503           FuncInfo->setSRetReturnReg(Reg);
2504         }
2505         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2506         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2507         break;
2508       }
2509     }
2510   }
2511
2512   unsigned StackSize = CCInfo.getNextStackOffset();
2513   // Align stack specially for tail calls.
2514   if (FuncIsMadeTailCallSafe(CallConv,
2515                              MF.getTarget().Options.GuaranteedTailCallOpt))
2516     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2517
2518   // If the function takes variable number of arguments, make a frame index for
2519   // the start of the first vararg value... for expansion of llvm.va_start. We
2520   // can skip this if there are no va_start calls.
2521   if (MFI->hasVAStart() &&
2522       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2523                    CallConv != CallingConv::X86_ThisCall))) {
2524     FuncInfo->setVarArgsFrameIndex(
2525         MFI->CreateFixedObject(1, StackSize, true));
2526   }
2527
2528   // 64-bit calling conventions support varargs and register parameters, so we
2529   // have to do extra work to spill them in the prologue or forward them to
2530   // musttail calls.
2531   if (Is64Bit && isVarArg &&
2532       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2533     // Find the first unallocated argument registers.
2534     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2535     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2536     unsigned NumIntRegs =
2537         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2538     unsigned NumXMMRegs =
2539         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2540     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2541            "SSE register cannot be used when SSE is disabled!");
2542
2543     // Gather all the live in physical registers.
2544     SmallVector<SDValue, 6> LiveGPRs;
2545     SmallVector<SDValue, 8> LiveXMMRegs;
2546     SDValue ALVal;
2547     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2548       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2549       LiveGPRs.push_back(
2550           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2551     }
2552     if (!ArgXMMs.empty()) {
2553       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2554       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2555       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2556         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2557         LiveXMMRegs.push_back(
2558             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2559       }
2560     }
2561
2562     // Store them to the va_list returned by va_start.
2563     if (MFI->hasVAStart()) {
2564       if (IsWin64) {
2565         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2566         // Get to the caller-allocated home save location.  Add 8 to account
2567         // for the return address.
2568         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2569         FuncInfo->setRegSaveFrameIndex(
2570           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2571         // Fixup to set vararg frame on shadow area (4 x i64).
2572         if (NumIntRegs < 4)
2573           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2574       } else {
2575         // For X86-64, if there are vararg parameters that are passed via
2576         // registers, then we must store them to their spots on the stack so
2577         // they may be loaded by deferencing the result of va_next.
2578         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2579         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2580         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2581             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2582       }
2583
2584       // Store the integer parameter registers.
2585       SmallVector<SDValue, 8> MemOps;
2586       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2587                                         getPointerTy());
2588       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2589       for (SDValue Val : LiveGPRs) {
2590         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2591                                   DAG.getIntPtrConstant(Offset));
2592         SDValue Store =
2593           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2594                        MachinePointerInfo::getFixedStack(
2595                          FuncInfo->getRegSaveFrameIndex(), Offset),
2596                        false, false, 0);
2597         MemOps.push_back(Store);
2598         Offset += 8;
2599       }
2600
2601       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2602         // Now store the XMM (fp + vector) parameter registers.
2603         SmallVector<SDValue, 12> SaveXMMOps;
2604         SaveXMMOps.push_back(Chain);
2605         SaveXMMOps.push_back(ALVal);
2606         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2607                                FuncInfo->getRegSaveFrameIndex()));
2608         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2609                                FuncInfo->getVarArgsFPOffset()));
2610         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2611                           LiveXMMRegs.end());
2612         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2613                                      MVT::Other, SaveXMMOps));
2614       }
2615
2616       if (!MemOps.empty())
2617         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2618     } else {
2619       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2620       // to the liveout set on a musttail call.
2621       assert(MFI->hasMustTailInVarArgFunc());
2622       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2623       typedef X86MachineFunctionInfo::Forward Forward;
2624
2625       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2626         unsigned VReg =
2627             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2628         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2629         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2630       }
2631
2632       if (!ArgXMMs.empty()) {
2633         unsigned ALVReg =
2634             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2635         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2636         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2637
2638         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2639           unsigned VReg =
2640               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2641           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2642           Forwards.push_back(
2643               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2644         }
2645       }
2646     }
2647   }
2648
2649   // Some CCs need callee pop.
2650   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2651                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2652     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2653   } else {
2654     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2655     // If this is an sret function, the return should pop the hidden pointer.
2656     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2657         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2658         argsAreStructReturn(Ins) == StackStructReturn)
2659       FuncInfo->setBytesToPopOnReturn(4);
2660   }
2661
2662   if (!Is64Bit) {
2663     // RegSaveFrameIndex is X86-64 only.
2664     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2665     if (CallConv == CallingConv::X86_FastCall ||
2666         CallConv == CallingConv::X86_ThisCall)
2667       // fastcc functions can't have varargs.
2668       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2669   }
2670
2671   FuncInfo->setArgumentStackSize(StackSize);
2672
2673   return Chain;
2674 }
2675
2676 SDValue
2677 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2678                                     SDValue StackPtr, SDValue Arg,
2679                                     SDLoc dl, SelectionDAG &DAG,
2680                                     const CCValAssign &VA,
2681                                     ISD::ArgFlagsTy Flags) const {
2682   unsigned LocMemOffset = VA.getLocMemOffset();
2683   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2684   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2685   if (Flags.isByVal())
2686     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2687
2688   return DAG.getStore(Chain, dl, Arg, PtrOff,
2689                       MachinePointerInfo::getStack(LocMemOffset),
2690                       false, false, 0);
2691 }
2692
2693 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2694 /// optimization is performed and it is required.
2695 SDValue
2696 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2697                                            SDValue &OutRetAddr, SDValue Chain,
2698                                            bool IsTailCall, bool Is64Bit,
2699                                            int FPDiff, SDLoc dl) const {
2700   // Adjust the Return address stack slot.
2701   EVT VT = getPointerTy();
2702   OutRetAddr = getReturnAddressFrameIndex(DAG);
2703
2704   // Load the "old" Return address.
2705   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2706                            false, false, false, 0);
2707   return SDValue(OutRetAddr.getNode(), 1);
2708 }
2709
2710 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2711 /// optimization is performed and it is required (FPDiff!=0).
2712 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2713                                         SDValue Chain, SDValue RetAddrFrIdx,
2714                                         EVT PtrVT, unsigned SlotSize,
2715                                         int FPDiff, SDLoc dl) {
2716   // Store the return address to the appropriate stack slot.
2717   if (!FPDiff) return Chain;
2718   // Calculate the new stack slot for the return address.
2719   int NewReturnAddrFI =
2720     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2721                                          false);
2722   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2723   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2724                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2725                        false, false, 0);
2726   return Chain;
2727 }
2728
2729 SDValue
2730 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2731                              SmallVectorImpl<SDValue> &InVals) const {
2732   SelectionDAG &DAG                     = CLI.DAG;
2733   SDLoc &dl                             = CLI.DL;
2734   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2735   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2736   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2737   SDValue Chain                         = CLI.Chain;
2738   SDValue Callee                        = CLI.Callee;
2739   CallingConv::ID CallConv              = CLI.CallConv;
2740   bool &isTailCall                      = CLI.IsTailCall;
2741   bool isVarArg                         = CLI.IsVarArg;
2742
2743   MachineFunction &MF = DAG.getMachineFunction();
2744   bool Is64Bit        = Subtarget->is64Bit();
2745   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2746   StructReturnType SR = callIsStructReturn(Outs);
2747   bool IsSibcall      = false;
2748   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2749
2750   if (MF.getTarget().Options.DisableTailCalls)
2751     isTailCall = false;
2752
2753   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2754   if (IsMustTail) {
2755     // Force this to be a tail call.  The verifier rules are enough to ensure
2756     // that we can lower this successfully without moving the return address
2757     // around.
2758     isTailCall = true;
2759   } else if (isTailCall) {
2760     // Check if it's really possible to do a tail call.
2761     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2762                     isVarArg, SR != NotStructReturn,
2763                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2764                     Outs, OutVals, Ins, DAG);
2765
2766     // Sibcalls are automatically detected tailcalls which do not require
2767     // ABI changes.
2768     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2769       IsSibcall = true;
2770
2771     if (isTailCall)
2772       ++NumTailCalls;
2773   }
2774
2775   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2776          "Var args not supported with calling convention fastcc, ghc or hipe");
2777
2778   // Analyze operands of the call, assigning locations to each operand.
2779   SmallVector<CCValAssign, 16> ArgLocs;
2780   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2781
2782   // Allocate shadow area for Win64
2783   if (IsWin64)
2784     CCInfo.AllocateStack(32, 8);
2785
2786   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2787
2788   // Get a count of how many bytes are to be pushed on the stack.
2789   unsigned NumBytes = CCInfo.getNextStackOffset();
2790   if (IsSibcall)
2791     // This is a sibcall. The memory operands are available in caller's
2792     // own caller's stack.
2793     NumBytes = 0;
2794   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2795            IsTailCallConvention(CallConv))
2796     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2797
2798   int FPDiff = 0;
2799   if (isTailCall && !IsSibcall && !IsMustTail) {
2800     // Lower arguments at fp - stackoffset + fpdiff.
2801     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2802
2803     FPDiff = NumBytesCallerPushed - NumBytes;
2804
2805     // Set the delta of movement of the returnaddr stackslot.
2806     // But only set if delta is greater than previous delta.
2807     if (FPDiff < X86Info->getTCReturnAddrDelta())
2808       X86Info->setTCReturnAddrDelta(FPDiff);
2809   }
2810
2811   unsigned NumBytesToPush = NumBytes;
2812   unsigned NumBytesToPop = NumBytes;
2813
2814   // If we have an inalloca argument, all stack space has already been allocated
2815   // for us and be right at the top of the stack.  We don't support multiple
2816   // arguments passed in memory when using inalloca.
2817   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2818     NumBytesToPush = 0;
2819     if (!ArgLocs.back().isMemLoc())
2820       report_fatal_error("cannot use inalloca attribute on a register "
2821                          "parameter");
2822     if (ArgLocs.back().getLocMemOffset() != 0)
2823       report_fatal_error("any parameter with the inalloca attribute must be "
2824                          "the only memory argument");
2825   }
2826
2827   if (!IsSibcall)
2828     Chain = DAG.getCALLSEQ_START(
2829         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2830
2831   SDValue RetAddrFrIdx;
2832   // Load return address for tail calls.
2833   if (isTailCall && FPDiff)
2834     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2835                                     Is64Bit, FPDiff, dl);
2836
2837   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2838   SmallVector<SDValue, 8> MemOpChains;
2839   SDValue StackPtr;
2840
2841   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2842   // of tail call optimization arguments are handle later.
2843   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2844       DAG.getSubtarget().getRegisterInfo());
2845   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2846     // Skip inalloca arguments, they have already been written.
2847     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2848     if (Flags.isInAlloca())
2849       continue;
2850
2851     CCValAssign &VA = ArgLocs[i];
2852     EVT RegVT = VA.getLocVT();
2853     SDValue Arg = OutVals[i];
2854     bool isByVal = Flags.isByVal();
2855
2856     // Promote the value if needed.
2857     switch (VA.getLocInfo()) {
2858     default: llvm_unreachable("Unknown loc info!");
2859     case CCValAssign::Full: break;
2860     case CCValAssign::SExt:
2861       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2862       break;
2863     case CCValAssign::ZExt:
2864       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2865       break;
2866     case CCValAssign::AExt:
2867       if (RegVT.is128BitVector()) {
2868         // Special case: passing MMX values in XMM registers.
2869         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2870         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2871         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2872       } else
2873         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2874       break;
2875     case CCValAssign::BCvt:
2876       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2877       break;
2878     case CCValAssign::Indirect: {
2879       // Store the argument.
2880       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2881       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2882       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2883                            MachinePointerInfo::getFixedStack(FI),
2884                            false, false, 0);
2885       Arg = SpillSlot;
2886       break;
2887     }
2888     }
2889
2890     if (VA.isRegLoc()) {
2891       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2892       if (isVarArg && IsWin64) {
2893         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2894         // shadow reg if callee is a varargs function.
2895         unsigned ShadowReg = 0;
2896         switch (VA.getLocReg()) {
2897         case X86::XMM0: ShadowReg = X86::RCX; break;
2898         case X86::XMM1: ShadowReg = X86::RDX; break;
2899         case X86::XMM2: ShadowReg = X86::R8; break;
2900         case X86::XMM3: ShadowReg = X86::R9; break;
2901         }
2902         if (ShadowReg)
2903           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2904       }
2905     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2906       assert(VA.isMemLoc());
2907       if (!StackPtr.getNode())
2908         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2909                                       getPointerTy());
2910       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2911                                              dl, DAG, VA, Flags));
2912     }
2913   }
2914
2915   if (!MemOpChains.empty())
2916     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2917
2918   if (Subtarget->isPICStyleGOT()) {
2919     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2920     // GOT pointer.
2921     if (!isTailCall) {
2922       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2923                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2924     } else {
2925       // If we are tail calling and generating PIC/GOT style code load the
2926       // address of the callee into ECX. The value in ecx is used as target of
2927       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2928       // for tail calls on PIC/GOT architectures. Normally we would just put the
2929       // address of GOT into ebx and then call target@PLT. But for tail calls
2930       // ebx would be restored (since ebx is callee saved) before jumping to the
2931       // target@PLT.
2932
2933       // Note: The actual moving to ECX is done further down.
2934       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2935       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2936           !G->getGlobal()->hasProtectedVisibility())
2937         Callee = LowerGlobalAddress(Callee, DAG);
2938       else if (isa<ExternalSymbolSDNode>(Callee))
2939         Callee = LowerExternalSymbol(Callee, DAG);
2940     }
2941   }
2942
2943   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2944     // From AMD64 ABI document:
2945     // For calls that may call functions that use varargs or stdargs
2946     // (prototype-less calls or calls to functions containing ellipsis (...) in
2947     // the declaration) %al is used as hidden argument to specify the number
2948     // of SSE registers used. The contents of %al do not need to match exactly
2949     // the number of registers, but must be an ubound on the number of SSE
2950     // registers used and is in the range 0 - 8 inclusive.
2951
2952     // Count the number of XMM registers allocated.
2953     static const MCPhysReg XMMArgRegs[] = {
2954       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2955       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2956     };
2957     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2958     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2959            && "SSE registers cannot be used when SSE is disabled");
2960
2961     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2962                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2963   }
2964
2965   if (Is64Bit && isVarArg && IsMustTail) {
2966     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2967     for (const auto &F : Forwards) {
2968       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2969       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2970     }
2971   }
2972
2973   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2974   // don't need this because the eligibility check rejects calls that require
2975   // shuffling arguments passed in memory.
2976   if (!IsSibcall && isTailCall) {
2977     // Force all the incoming stack arguments to be loaded from the stack
2978     // before any new outgoing arguments are stored to the stack, because the
2979     // outgoing stack slots may alias the incoming argument stack slots, and
2980     // the alias isn't otherwise explicit. This is slightly more conservative
2981     // than necessary, because it means that each store effectively depends
2982     // on every argument instead of just those arguments it would clobber.
2983     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2984
2985     SmallVector<SDValue, 8> MemOpChains2;
2986     SDValue FIN;
2987     int FI = 0;
2988     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2989       CCValAssign &VA = ArgLocs[i];
2990       if (VA.isRegLoc())
2991         continue;
2992       assert(VA.isMemLoc());
2993       SDValue Arg = OutVals[i];
2994       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2995       // Skip inalloca arguments.  They don't require any work.
2996       if (Flags.isInAlloca())
2997         continue;
2998       // Create frame index.
2999       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3000       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3001       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3002       FIN = DAG.getFrameIndex(FI, getPointerTy());
3003
3004       if (Flags.isByVal()) {
3005         // Copy relative to framepointer.
3006         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3007         if (!StackPtr.getNode())
3008           StackPtr = DAG.getCopyFromReg(Chain, dl,
3009                                         RegInfo->getStackRegister(),
3010                                         getPointerTy());
3011         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3012
3013         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3014                                                          ArgChain,
3015                                                          Flags, DAG, dl));
3016       } else {
3017         // Store relative to framepointer.
3018         MemOpChains2.push_back(
3019           DAG.getStore(ArgChain, dl, Arg, FIN,
3020                        MachinePointerInfo::getFixedStack(FI),
3021                        false, false, 0));
3022       }
3023     }
3024
3025     if (!MemOpChains2.empty())
3026       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3027
3028     // Store the return address to the appropriate stack slot.
3029     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3030                                      getPointerTy(), RegInfo->getSlotSize(),
3031                                      FPDiff, dl);
3032   }
3033
3034   // Build a sequence of copy-to-reg nodes chained together with token chain
3035   // and flag operands which copy the outgoing args into registers.
3036   SDValue InFlag;
3037   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3038     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3039                              RegsToPass[i].second, InFlag);
3040     InFlag = Chain.getValue(1);
3041   }
3042
3043   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3044     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3045     // In the 64-bit large code model, we have to make all calls
3046     // through a register, since the call instruction's 32-bit
3047     // pc-relative offset may not be large enough to hold the whole
3048     // address.
3049   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3050     // If the callee is a GlobalAddress node (quite common, every direct call
3051     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3052     // it.
3053
3054     // We should use extra load for direct calls to dllimported functions in
3055     // non-JIT mode.
3056     const GlobalValue *GV = G->getGlobal();
3057     if (!GV->hasDLLImportStorageClass()) {
3058       unsigned char OpFlags = 0;
3059       bool ExtraLoad = false;
3060       unsigned WrapperKind = ISD::DELETED_NODE;
3061
3062       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3063       // external symbols most go through the PLT in PIC mode.  If the symbol
3064       // has hidden or protected visibility, or if it is static or local, then
3065       // we don't need to use the PLT - we can directly call it.
3066       if (Subtarget->isTargetELF() &&
3067           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3068           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3069         OpFlags = X86II::MO_PLT;
3070       } else if (Subtarget->isPICStyleStubAny() &&
3071                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3072                  (!Subtarget->getTargetTriple().isMacOSX() ||
3073                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3074         // PC-relative references to external symbols should go through $stub,
3075         // unless we're building with the leopard linker or later, which
3076         // automatically synthesizes these stubs.
3077         OpFlags = X86II::MO_DARWIN_STUB;
3078       } else if (Subtarget->isPICStyleRIPRel() &&
3079                  isa<Function>(GV) &&
3080                  cast<Function>(GV)->getAttributes().
3081                    hasAttribute(AttributeSet::FunctionIndex,
3082                                 Attribute::NonLazyBind)) {
3083         // If the function is marked as non-lazy, generate an indirect call
3084         // which loads from the GOT directly. This avoids runtime overhead
3085         // at the cost of eager binding (and one extra byte of encoding).
3086         OpFlags = X86II::MO_GOTPCREL;
3087         WrapperKind = X86ISD::WrapperRIP;
3088         ExtraLoad = true;
3089       }
3090
3091       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3092                                           G->getOffset(), OpFlags);
3093
3094       // Add a wrapper if needed.
3095       if (WrapperKind != ISD::DELETED_NODE)
3096         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3097       // Add extra indirection if needed.
3098       if (ExtraLoad)
3099         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3100                              MachinePointerInfo::getGOT(),
3101                              false, false, false, 0);
3102     }
3103   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3104     unsigned char OpFlags = 0;
3105
3106     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3107     // external symbols should go through the PLT.
3108     if (Subtarget->isTargetELF() &&
3109         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3110       OpFlags = X86II::MO_PLT;
3111     } else if (Subtarget->isPICStyleStubAny() &&
3112                (!Subtarget->getTargetTriple().isMacOSX() ||
3113                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3114       // PC-relative references to external symbols should go through $stub,
3115       // unless we're building with the leopard linker or later, which
3116       // automatically synthesizes these stubs.
3117       OpFlags = X86II::MO_DARWIN_STUB;
3118     }
3119
3120     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3121                                          OpFlags);
3122   }
3123
3124   // Returns a chain & a flag for retval copy to use.
3125   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3126   SmallVector<SDValue, 8> Ops;
3127
3128   if (!IsSibcall && isTailCall) {
3129     Chain = DAG.getCALLSEQ_END(Chain,
3130                                DAG.getIntPtrConstant(NumBytesToPop, true),
3131                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3132     InFlag = Chain.getValue(1);
3133   }
3134
3135   Ops.push_back(Chain);
3136   Ops.push_back(Callee);
3137
3138   if (isTailCall)
3139     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3140
3141   // Add argument registers to the end of the list so that they are known live
3142   // into the call.
3143   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3144     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3145                                   RegsToPass[i].second.getValueType()));
3146
3147   // Add a register mask operand representing the call-preserved registers.
3148   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3149   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3150   assert(Mask && "Missing call preserved mask for calling convention");
3151   Ops.push_back(DAG.getRegisterMask(Mask));
3152
3153   if (InFlag.getNode())
3154     Ops.push_back(InFlag);
3155
3156   if (isTailCall) {
3157     // We used to do:
3158     //// If this is the first return lowered for this function, add the regs
3159     //// to the liveout set for the function.
3160     // This isn't right, although it's probably harmless on x86; liveouts
3161     // should be computed from returns not tail calls.  Consider a void
3162     // function making a tail call to a function returning int.
3163     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3164   }
3165
3166   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3167   InFlag = Chain.getValue(1);
3168
3169   // Create the CALLSEQ_END node.
3170   unsigned NumBytesForCalleeToPop;
3171   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3172                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3173     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3174   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3175            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3176            SR == StackStructReturn)
3177     // If this is a call to a struct-return function, the callee
3178     // pops the hidden struct pointer, so we have to push it back.
3179     // This is common for Darwin/X86, Linux & Mingw32 targets.
3180     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3181     NumBytesForCalleeToPop = 4;
3182   else
3183     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3184
3185   // Returns a flag for retval copy to use.
3186   if (!IsSibcall) {
3187     Chain = DAG.getCALLSEQ_END(Chain,
3188                                DAG.getIntPtrConstant(NumBytesToPop, true),
3189                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3190                                                      true),
3191                                InFlag, dl);
3192     InFlag = Chain.getValue(1);
3193   }
3194
3195   // Handle result values, copying them out of physregs into vregs that we
3196   // return.
3197   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3198                          Ins, dl, DAG, InVals);
3199 }
3200
3201 //===----------------------------------------------------------------------===//
3202 //                Fast Calling Convention (tail call) implementation
3203 //===----------------------------------------------------------------------===//
3204
3205 //  Like std call, callee cleans arguments, convention except that ECX is
3206 //  reserved for storing the tail called function address. Only 2 registers are
3207 //  free for argument passing (inreg). Tail call optimization is performed
3208 //  provided:
3209 //                * tailcallopt is enabled
3210 //                * caller/callee are fastcc
3211 //  On X86_64 architecture with GOT-style position independent code only local
3212 //  (within module) calls are supported at the moment.
3213 //  To keep the stack aligned according to platform abi the function
3214 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3215 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3216 //  If a tail called function callee has more arguments than the caller the
3217 //  caller needs to make sure that there is room to move the RETADDR to. This is
3218 //  achieved by reserving an area the size of the argument delta right after the
3219 //  original RETADDR, but before the saved framepointer or the spilled registers
3220 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3221 //  stack layout:
3222 //    arg1
3223 //    arg2
3224 //    RETADDR
3225 //    [ new RETADDR
3226 //      move area ]
3227 //    (possible EBP)
3228 //    ESI
3229 //    EDI
3230 //    local1 ..
3231
3232 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3233 /// for a 16 byte align requirement.
3234 unsigned
3235 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3236                                                SelectionDAG& DAG) const {
3237   MachineFunction &MF = DAG.getMachineFunction();
3238   const TargetMachine &TM = MF.getTarget();
3239   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3240       TM.getSubtargetImpl()->getRegisterInfo());
3241   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3242   unsigned StackAlignment = TFI.getStackAlignment();
3243   uint64_t AlignMask = StackAlignment - 1;
3244   int64_t Offset = StackSize;
3245   unsigned SlotSize = RegInfo->getSlotSize();
3246   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3247     // Number smaller than 12 so just add the difference.
3248     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3249   } else {
3250     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3251     Offset = ((~AlignMask) & Offset) + StackAlignment +
3252       (StackAlignment-SlotSize);
3253   }
3254   return Offset;
3255 }
3256
3257 /// MatchingStackOffset - Return true if the given stack call argument is
3258 /// already available in the same position (relatively) of the caller's
3259 /// incoming argument stack.
3260 static
3261 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3262                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3263                          const X86InstrInfo *TII) {
3264   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3265   int FI = INT_MAX;
3266   if (Arg.getOpcode() == ISD::CopyFromReg) {
3267     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3268     if (!TargetRegisterInfo::isVirtualRegister(VR))
3269       return false;
3270     MachineInstr *Def = MRI->getVRegDef(VR);
3271     if (!Def)
3272       return false;
3273     if (!Flags.isByVal()) {
3274       if (!TII->isLoadFromStackSlot(Def, FI))
3275         return false;
3276     } else {
3277       unsigned Opcode = Def->getOpcode();
3278       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3279           Def->getOperand(1).isFI()) {
3280         FI = Def->getOperand(1).getIndex();
3281         Bytes = Flags.getByValSize();
3282       } else
3283         return false;
3284     }
3285   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3286     if (Flags.isByVal())
3287       // ByVal argument is passed in as a pointer but it's now being
3288       // dereferenced. e.g.
3289       // define @foo(%struct.X* %A) {
3290       //   tail call @bar(%struct.X* byval %A)
3291       // }
3292       return false;
3293     SDValue Ptr = Ld->getBasePtr();
3294     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3295     if (!FINode)
3296       return false;
3297     FI = FINode->getIndex();
3298   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3299     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3300     FI = FINode->getIndex();
3301     Bytes = Flags.getByValSize();
3302   } else
3303     return false;
3304
3305   assert(FI != INT_MAX);
3306   if (!MFI->isFixedObjectIndex(FI))
3307     return false;
3308   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3309 }
3310
3311 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3312 /// for tail call optimization. Targets which want to do tail call
3313 /// optimization should implement this function.
3314 bool
3315 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3316                                                      CallingConv::ID CalleeCC,
3317                                                      bool isVarArg,
3318                                                      bool isCalleeStructRet,
3319                                                      bool isCallerStructRet,
3320                                                      Type *RetTy,
3321                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3322                                     const SmallVectorImpl<SDValue> &OutVals,
3323                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3324                                                      SelectionDAG &DAG) const {
3325   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3326     return false;
3327
3328   // If -tailcallopt is specified, make fastcc functions tail-callable.
3329   const MachineFunction &MF = DAG.getMachineFunction();
3330   const Function *CallerF = MF.getFunction();
3331
3332   // If the function return type is x86_fp80 and the callee return type is not,
3333   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3334   // perform a tailcall optimization here.
3335   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3336     return false;
3337
3338   CallingConv::ID CallerCC = CallerF->getCallingConv();
3339   bool CCMatch = CallerCC == CalleeCC;
3340   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3341   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3342
3343   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3344     if (IsTailCallConvention(CalleeCC) && CCMatch)
3345       return true;
3346     return false;
3347   }
3348
3349   // Look for obvious safe cases to perform tail call optimization that do not
3350   // require ABI changes. This is what gcc calls sibcall.
3351
3352   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3353   // emit a special epilogue.
3354   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3355       DAG.getSubtarget().getRegisterInfo());
3356   if (RegInfo->needsStackRealignment(MF))
3357     return false;
3358
3359   // Also avoid sibcall optimization if either caller or callee uses struct
3360   // return semantics.
3361   if (isCalleeStructRet || isCallerStructRet)
3362     return false;
3363
3364   // An stdcall/thiscall caller is expected to clean up its arguments; the
3365   // callee isn't going to do that.
3366   // FIXME: this is more restrictive than needed. We could produce a tailcall
3367   // when the stack adjustment matches. For example, with a thiscall that takes
3368   // only one argument.
3369   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3370                    CallerCC == CallingConv::X86_ThisCall))
3371     return false;
3372
3373   // Do not sibcall optimize vararg calls unless all arguments are passed via
3374   // registers.
3375   if (isVarArg && !Outs.empty()) {
3376
3377     // Optimizing for varargs on Win64 is unlikely to be safe without
3378     // additional testing.
3379     if (IsCalleeWin64 || IsCallerWin64)
3380       return false;
3381
3382     SmallVector<CCValAssign, 16> ArgLocs;
3383     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3384                    *DAG.getContext());
3385
3386     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3387     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3388       if (!ArgLocs[i].isRegLoc())
3389         return false;
3390   }
3391
3392   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3393   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3394   // this into a sibcall.
3395   bool Unused = false;
3396   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3397     if (!Ins[i].Used) {
3398       Unused = true;
3399       break;
3400     }
3401   }
3402   if (Unused) {
3403     SmallVector<CCValAssign, 16> RVLocs;
3404     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3405                    *DAG.getContext());
3406     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3407     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3408       CCValAssign &VA = RVLocs[i];
3409       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3410         return false;
3411     }
3412   }
3413
3414   // If the calling conventions do not match, then we'd better make sure the
3415   // results are returned in the same way as what the caller expects.
3416   if (!CCMatch) {
3417     SmallVector<CCValAssign, 16> RVLocs1;
3418     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3419                     *DAG.getContext());
3420     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3421
3422     SmallVector<CCValAssign, 16> RVLocs2;
3423     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3424                     *DAG.getContext());
3425     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3426
3427     if (RVLocs1.size() != RVLocs2.size())
3428       return false;
3429     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3430       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3431         return false;
3432       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3433         return false;
3434       if (RVLocs1[i].isRegLoc()) {
3435         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3436           return false;
3437       } else {
3438         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3439           return false;
3440       }
3441     }
3442   }
3443
3444   // If the callee takes no arguments then go on to check the results of the
3445   // call.
3446   if (!Outs.empty()) {
3447     // Check if stack adjustment is needed. For now, do not do this if any
3448     // argument is passed on the stack.
3449     SmallVector<CCValAssign, 16> ArgLocs;
3450     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3451                    *DAG.getContext());
3452
3453     // Allocate shadow area for Win64
3454     if (IsCalleeWin64)
3455       CCInfo.AllocateStack(32, 8);
3456
3457     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3458     if (CCInfo.getNextStackOffset()) {
3459       MachineFunction &MF = DAG.getMachineFunction();
3460       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3461         return false;
3462
3463       // Check if the arguments are already laid out in the right way as
3464       // the caller's fixed stack objects.
3465       MachineFrameInfo *MFI = MF.getFrameInfo();
3466       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3467       const X86InstrInfo *TII =
3468           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3469       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3470         CCValAssign &VA = ArgLocs[i];
3471         SDValue Arg = OutVals[i];
3472         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3473         if (VA.getLocInfo() == CCValAssign::Indirect)
3474           return false;
3475         if (!VA.isRegLoc()) {
3476           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3477                                    MFI, MRI, TII))
3478             return false;
3479         }
3480       }
3481     }
3482
3483     // If the tailcall address may be in a register, then make sure it's
3484     // possible to register allocate for it. In 32-bit, the call address can
3485     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3486     // callee-saved registers are restored. These happen to be the same
3487     // registers used to pass 'inreg' arguments so watch out for those.
3488     if (!Subtarget->is64Bit() &&
3489         ((!isa<GlobalAddressSDNode>(Callee) &&
3490           !isa<ExternalSymbolSDNode>(Callee)) ||
3491          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3492       unsigned NumInRegs = 0;
3493       // In PIC we need an extra register to formulate the address computation
3494       // for the callee.
3495       unsigned MaxInRegs =
3496         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3497
3498       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3499         CCValAssign &VA = ArgLocs[i];
3500         if (!VA.isRegLoc())
3501           continue;
3502         unsigned Reg = VA.getLocReg();
3503         switch (Reg) {
3504         default: break;
3505         case X86::EAX: case X86::EDX: case X86::ECX:
3506           if (++NumInRegs == MaxInRegs)
3507             return false;
3508           break;
3509         }
3510       }
3511     }
3512   }
3513
3514   return true;
3515 }
3516
3517 FastISel *
3518 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3519                                   const TargetLibraryInfo *libInfo) const {
3520   return X86::createFastISel(funcInfo, libInfo);
3521 }
3522
3523 //===----------------------------------------------------------------------===//
3524 //                           Other Lowering Hooks
3525 //===----------------------------------------------------------------------===//
3526
3527 static bool MayFoldLoad(SDValue Op) {
3528   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3529 }
3530
3531 static bool MayFoldIntoStore(SDValue Op) {
3532   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3533 }
3534
3535 static bool isTargetShuffle(unsigned Opcode) {
3536   switch(Opcode) {
3537   default: return false;
3538   case X86ISD::PSHUFB:
3539   case X86ISD::PSHUFD:
3540   case X86ISD::PSHUFHW:
3541   case X86ISD::PSHUFLW:
3542   case X86ISD::SHUFP:
3543   case X86ISD::PALIGNR:
3544   case X86ISD::MOVLHPS:
3545   case X86ISD::MOVLHPD:
3546   case X86ISD::MOVHLPS:
3547   case X86ISD::MOVLPS:
3548   case X86ISD::MOVLPD:
3549   case X86ISD::MOVSHDUP:
3550   case X86ISD::MOVSLDUP:
3551   case X86ISD::MOVDDUP:
3552   case X86ISD::MOVSS:
3553   case X86ISD::MOVSD:
3554   case X86ISD::UNPCKL:
3555   case X86ISD::UNPCKH:
3556   case X86ISD::VPERMILP:
3557   case X86ISD::VPERM2X128:
3558   case X86ISD::VPERMI:
3559     return true;
3560   }
3561 }
3562
3563 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3564                                     SDValue V1, SelectionDAG &DAG) {
3565   switch(Opc) {
3566   default: llvm_unreachable("Unknown x86 shuffle node");
3567   case X86ISD::MOVSHDUP:
3568   case X86ISD::MOVSLDUP:
3569   case X86ISD::MOVDDUP:
3570     return DAG.getNode(Opc, dl, VT, V1);
3571   }
3572 }
3573
3574 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3575                                     SDValue V1, unsigned TargetMask,
3576                                     SelectionDAG &DAG) {
3577   switch(Opc) {
3578   default: llvm_unreachable("Unknown x86 shuffle node");
3579   case X86ISD::PSHUFD:
3580   case X86ISD::PSHUFHW:
3581   case X86ISD::PSHUFLW:
3582   case X86ISD::VPERMILP:
3583   case X86ISD::VPERMI:
3584     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3585   }
3586 }
3587
3588 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3589                                     SDValue V1, SDValue V2, unsigned TargetMask,
3590                                     SelectionDAG &DAG) {
3591   switch(Opc) {
3592   default: llvm_unreachable("Unknown x86 shuffle node");
3593   case X86ISD::PALIGNR:
3594   case X86ISD::VALIGN:
3595   case X86ISD::SHUFP:
3596   case X86ISD::VPERM2X128:
3597     return DAG.getNode(Opc, dl, VT, V1, V2,
3598                        DAG.getConstant(TargetMask, MVT::i8));
3599   }
3600 }
3601
3602 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3603                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3604   switch(Opc) {
3605   default: llvm_unreachable("Unknown x86 shuffle node");
3606   case X86ISD::MOVLHPS:
3607   case X86ISD::MOVLHPD:
3608   case X86ISD::MOVHLPS:
3609   case X86ISD::MOVLPS:
3610   case X86ISD::MOVLPD:
3611   case X86ISD::MOVSS:
3612   case X86ISD::MOVSD:
3613   case X86ISD::UNPCKL:
3614   case X86ISD::UNPCKH:
3615     return DAG.getNode(Opc, dl, VT, V1, V2);
3616   }
3617 }
3618
3619 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3620   MachineFunction &MF = DAG.getMachineFunction();
3621   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3622       DAG.getSubtarget().getRegisterInfo());
3623   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3624   int ReturnAddrIndex = FuncInfo->getRAIndex();
3625
3626   if (ReturnAddrIndex == 0) {
3627     // Set up a frame object for the return address.
3628     unsigned SlotSize = RegInfo->getSlotSize();
3629     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3630                                                            -(int64_t)SlotSize,
3631                                                            false);
3632     FuncInfo->setRAIndex(ReturnAddrIndex);
3633   }
3634
3635   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3636 }
3637
3638 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3639                                        bool hasSymbolicDisplacement) {
3640   // Offset should fit into 32 bit immediate field.
3641   if (!isInt<32>(Offset))
3642     return false;
3643
3644   // If we don't have a symbolic displacement - we don't have any extra
3645   // restrictions.
3646   if (!hasSymbolicDisplacement)
3647     return true;
3648
3649   // FIXME: Some tweaks might be needed for medium code model.
3650   if (M != CodeModel::Small && M != CodeModel::Kernel)
3651     return false;
3652
3653   // For small code model we assume that latest object is 16MB before end of 31
3654   // bits boundary. We may also accept pretty large negative constants knowing
3655   // that all objects are in the positive half of address space.
3656   if (M == CodeModel::Small && Offset < 16*1024*1024)
3657     return true;
3658
3659   // For kernel code model we know that all object resist in the negative half
3660   // of 32bits address space. We may not accept negative offsets, since they may
3661   // be just off and we may accept pretty large positive ones.
3662   if (M == CodeModel::Kernel && Offset > 0)
3663     return true;
3664
3665   return false;
3666 }
3667
3668 /// isCalleePop - Determines whether the callee is required to pop its
3669 /// own arguments. Callee pop is necessary to support tail calls.
3670 bool X86::isCalleePop(CallingConv::ID CallingConv,
3671                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3672   switch (CallingConv) {
3673   default:
3674     return false;
3675   case CallingConv::X86_StdCall:
3676   case CallingConv::X86_FastCall:
3677   case CallingConv::X86_ThisCall:
3678     return !is64Bit;
3679   case CallingConv::Fast:
3680   case CallingConv::GHC:
3681   case CallingConv::HiPE:
3682     if (IsVarArg)
3683       return false;
3684     return TailCallOpt;
3685   }
3686 }
3687
3688 /// \brief Return true if the condition is an unsigned comparison operation.
3689 static bool isX86CCUnsigned(unsigned X86CC) {
3690   switch (X86CC) {
3691   default: llvm_unreachable("Invalid integer condition!");
3692   case X86::COND_E:     return true;
3693   case X86::COND_G:     return false;
3694   case X86::COND_GE:    return false;
3695   case X86::COND_L:     return false;
3696   case X86::COND_LE:    return false;
3697   case X86::COND_NE:    return true;
3698   case X86::COND_B:     return true;
3699   case X86::COND_A:     return true;
3700   case X86::COND_BE:    return true;
3701   case X86::COND_AE:    return true;
3702   }
3703   llvm_unreachable("covered switch fell through?!");
3704 }
3705
3706 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3707 /// specific condition code, returning the condition code and the LHS/RHS of the
3708 /// comparison to make.
3709 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3710                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3711   if (!isFP) {
3712     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3713       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3714         // X > -1   -> X == 0, jump !sign.
3715         RHS = DAG.getConstant(0, RHS.getValueType());
3716         return X86::COND_NS;
3717       }
3718       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3719         // X < 0   -> X == 0, jump on sign.
3720         return X86::COND_S;
3721       }
3722       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3723         // X < 1   -> X <= 0
3724         RHS = DAG.getConstant(0, RHS.getValueType());
3725         return X86::COND_LE;
3726       }
3727     }
3728
3729     switch (SetCCOpcode) {
3730     default: llvm_unreachable("Invalid integer condition!");
3731     case ISD::SETEQ:  return X86::COND_E;
3732     case ISD::SETGT:  return X86::COND_G;
3733     case ISD::SETGE:  return X86::COND_GE;
3734     case ISD::SETLT:  return X86::COND_L;
3735     case ISD::SETLE:  return X86::COND_LE;
3736     case ISD::SETNE:  return X86::COND_NE;
3737     case ISD::SETULT: return X86::COND_B;
3738     case ISD::SETUGT: return X86::COND_A;
3739     case ISD::SETULE: return X86::COND_BE;
3740     case ISD::SETUGE: return X86::COND_AE;
3741     }
3742   }
3743
3744   // First determine if it is required or is profitable to flip the operands.
3745
3746   // If LHS is a foldable load, but RHS is not, flip the condition.
3747   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3748       !ISD::isNON_EXTLoad(RHS.getNode())) {
3749     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3750     std::swap(LHS, RHS);
3751   }
3752
3753   switch (SetCCOpcode) {
3754   default: break;
3755   case ISD::SETOLT:
3756   case ISD::SETOLE:
3757   case ISD::SETUGT:
3758   case ISD::SETUGE:
3759     std::swap(LHS, RHS);
3760     break;
3761   }
3762
3763   // On a floating point condition, the flags are set as follows:
3764   // ZF  PF  CF   op
3765   //  0 | 0 | 0 | X > Y
3766   //  0 | 0 | 1 | X < Y
3767   //  1 | 0 | 0 | X == Y
3768   //  1 | 1 | 1 | unordered
3769   switch (SetCCOpcode) {
3770   default: llvm_unreachable("Condcode should be pre-legalized away");
3771   case ISD::SETUEQ:
3772   case ISD::SETEQ:   return X86::COND_E;
3773   case ISD::SETOLT:              // flipped
3774   case ISD::SETOGT:
3775   case ISD::SETGT:   return X86::COND_A;
3776   case ISD::SETOLE:              // flipped
3777   case ISD::SETOGE:
3778   case ISD::SETGE:   return X86::COND_AE;
3779   case ISD::SETUGT:              // flipped
3780   case ISD::SETULT:
3781   case ISD::SETLT:   return X86::COND_B;
3782   case ISD::SETUGE:              // flipped
3783   case ISD::SETULE:
3784   case ISD::SETLE:   return X86::COND_BE;
3785   case ISD::SETONE:
3786   case ISD::SETNE:   return X86::COND_NE;
3787   case ISD::SETUO:   return X86::COND_P;
3788   case ISD::SETO:    return X86::COND_NP;
3789   case ISD::SETOEQ:
3790   case ISD::SETUNE:  return X86::COND_INVALID;
3791   }
3792 }
3793
3794 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3795 /// code. Current x86 isa includes the following FP cmov instructions:
3796 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3797 static bool hasFPCMov(unsigned X86CC) {
3798   switch (X86CC) {
3799   default:
3800     return false;
3801   case X86::COND_B:
3802   case X86::COND_BE:
3803   case X86::COND_E:
3804   case X86::COND_P:
3805   case X86::COND_A:
3806   case X86::COND_AE:
3807   case X86::COND_NE:
3808   case X86::COND_NP:
3809     return true;
3810   }
3811 }
3812
3813 /// isFPImmLegal - Returns true if the target can instruction select the
3814 /// specified FP immediate natively. If false, the legalizer will
3815 /// materialize the FP immediate as a load from a constant pool.
3816 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3817   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3818     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3819       return true;
3820   }
3821   return false;
3822 }
3823
3824 /// \brief Returns true if it is beneficial to convert a load of a constant
3825 /// to just the constant itself.
3826 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3827                                                           Type *Ty) const {
3828   assert(Ty->isIntegerTy());
3829
3830   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3831   if (BitSize == 0 || BitSize > 64)
3832     return false;
3833   return true;
3834 }
3835
3836 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3837 /// the specified range (L, H].
3838 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3839   return (Val < 0) || (Val >= Low && Val < Hi);
3840 }
3841
3842 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3843 /// specified value.
3844 static bool isUndefOrEqual(int Val, int CmpVal) {
3845   return (Val < 0 || Val == CmpVal);
3846 }
3847
3848 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3849 /// from position Pos and ending in Pos+Size, falls within the specified
3850 /// sequential range (L, L+Pos]. or is undef.
3851 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3852                                        unsigned Pos, unsigned Size, int Low) {
3853   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3854     if (!isUndefOrEqual(Mask[i], Low))
3855       return false;
3856   return true;
3857 }
3858
3859 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3860 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3861 /// the second operand.
3862 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3863   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3864     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3865   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3866     return (Mask[0] < 2 && Mask[1] < 2);
3867   return false;
3868 }
3869
3870 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3871 /// is suitable for input to PSHUFHW.
3872 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3873   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3874     return false;
3875
3876   // Lower quadword copied in order or undef.
3877   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3878     return false;
3879
3880   // Upper quadword shuffled.
3881   for (unsigned i = 4; i != 8; ++i)
3882     if (!isUndefOrInRange(Mask[i], 4, 8))
3883       return false;
3884
3885   if (VT == MVT::v16i16) {
3886     // Lower quadword copied in order or undef.
3887     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3888       return false;
3889
3890     // Upper quadword shuffled.
3891     for (unsigned i = 12; i != 16; ++i)
3892       if (!isUndefOrInRange(Mask[i], 12, 16))
3893         return false;
3894   }
3895
3896   return true;
3897 }
3898
3899 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3900 /// is suitable for input to PSHUFLW.
3901 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3902   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3903     return false;
3904
3905   // Upper quadword copied in order.
3906   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3907     return false;
3908
3909   // Lower quadword shuffled.
3910   for (unsigned i = 0; i != 4; ++i)
3911     if (!isUndefOrInRange(Mask[i], 0, 4))
3912       return false;
3913
3914   if (VT == MVT::v16i16) {
3915     // Upper quadword copied in order.
3916     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3917       return false;
3918
3919     // Lower quadword shuffled.
3920     for (unsigned i = 8; i != 12; ++i)
3921       if (!isUndefOrInRange(Mask[i], 8, 12))
3922         return false;
3923   }
3924
3925   return true;
3926 }
3927
3928 /// \brief Return true if the mask specifies a shuffle of elements that is
3929 /// suitable for input to intralane (palignr) or interlane (valign) vector
3930 /// right-shift.
3931 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3932   unsigned NumElts = VT.getVectorNumElements();
3933   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3934   unsigned NumLaneElts = NumElts/NumLanes;
3935
3936   // Do not handle 64-bit element shuffles with palignr.
3937   if (NumLaneElts == 2)
3938     return false;
3939
3940   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3941     unsigned i;
3942     for (i = 0; i != NumLaneElts; ++i) {
3943       if (Mask[i+l] >= 0)
3944         break;
3945     }
3946
3947     // Lane is all undef, go to next lane
3948     if (i == NumLaneElts)
3949       continue;
3950
3951     int Start = Mask[i+l];
3952
3953     // Make sure its in this lane in one of the sources
3954     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3955         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3956       return false;
3957
3958     // If not lane 0, then we must match lane 0
3959     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3960       return false;
3961
3962     // Correct second source to be contiguous with first source
3963     if (Start >= (int)NumElts)
3964       Start -= NumElts - NumLaneElts;
3965
3966     // Make sure we're shifting in the right direction.
3967     if (Start <= (int)(i+l))
3968       return false;
3969
3970     Start -= i;
3971
3972     // Check the rest of the elements to see if they are consecutive.
3973     for (++i; i != NumLaneElts; ++i) {
3974       int Idx = Mask[i+l];
3975
3976       // Make sure its in this lane
3977       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3978           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3979         return false;
3980
3981       // If not lane 0, then we must match lane 0
3982       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3983         return false;
3984
3985       if (Idx >= (int)NumElts)
3986         Idx -= NumElts - NumLaneElts;
3987
3988       if (!isUndefOrEqual(Idx, Start+i))
3989         return false;
3990
3991     }
3992   }
3993
3994   return true;
3995 }
3996
3997 /// \brief Return true if the node specifies a shuffle of elements that is
3998 /// suitable for input to PALIGNR.
3999 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4000                           const X86Subtarget *Subtarget) {
4001   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4002       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4003       VT.is512BitVector())
4004     // FIXME: Add AVX512BW.
4005     return false;
4006
4007   return isAlignrMask(Mask, VT, false);
4008 }
4009
4010 /// \brief Return true if the node specifies a shuffle of elements that is
4011 /// suitable for input to VALIGN.
4012 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4013                           const X86Subtarget *Subtarget) {
4014   // FIXME: Add AVX512VL.
4015   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4016     return false;
4017   return isAlignrMask(Mask, VT, true);
4018 }
4019
4020 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4021 /// the two vector operands have swapped position.
4022 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4023                                      unsigned NumElems) {
4024   for (unsigned i = 0; i != NumElems; ++i) {
4025     int idx = Mask[i];
4026     if (idx < 0)
4027       continue;
4028     else if (idx < (int)NumElems)
4029       Mask[i] = idx + NumElems;
4030     else
4031       Mask[i] = idx - NumElems;
4032   }
4033 }
4034
4035 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4037 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4038 /// reverse of what x86 shuffles want.
4039 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4040
4041   unsigned NumElems = VT.getVectorNumElements();
4042   unsigned NumLanes = VT.getSizeInBits()/128;
4043   unsigned NumLaneElems = NumElems/NumLanes;
4044
4045   if (NumLaneElems != 2 && NumLaneElems != 4)
4046     return false;
4047
4048   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4049   bool symetricMaskRequired =
4050     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4051
4052   // VSHUFPSY divides the resulting vector into 4 chunks.
4053   // The sources are also splitted into 4 chunks, and each destination
4054   // chunk must come from a different source chunk.
4055   //
4056   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4057   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4058   //
4059   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4060   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4061   //
4062   // VSHUFPDY divides the resulting vector into 4 chunks.
4063   // The sources are also splitted into 4 chunks, and each destination
4064   // chunk must come from a different source chunk.
4065   //
4066   //  SRC1 =>      X3       X2       X1       X0
4067   //  SRC2 =>      Y3       Y2       Y1       Y0
4068   //
4069   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4070   //
4071   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4072   unsigned HalfLaneElems = NumLaneElems/2;
4073   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4074     for (unsigned i = 0; i != NumLaneElems; ++i) {
4075       int Idx = Mask[i+l];
4076       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4077       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4078         return false;
4079       // For VSHUFPSY, the mask of the second half must be the same as the
4080       // first but with the appropriate offsets. This works in the same way as
4081       // VPERMILPS works with masks.
4082       if (!symetricMaskRequired || Idx < 0)
4083         continue;
4084       if (MaskVal[i] < 0) {
4085         MaskVal[i] = Idx - l;
4086         continue;
4087       }
4088       if ((signed)(Idx - l) != MaskVal[i])
4089         return false;
4090     }
4091   }
4092
4093   return true;
4094 }
4095
4096 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4097 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4098 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4099   if (!VT.is128BitVector())
4100     return false;
4101
4102   unsigned NumElems = VT.getVectorNumElements();
4103
4104   if (NumElems != 4)
4105     return false;
4106
4107   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4108   return isUndefOrEqual(Mask[0], 6) &&
4109          isUndefOrEqual(Mask[1], 7) &&
4110          isUndefOrEqual(Mask[2], 2) &&
4111          isUndefOrEqual(Mask[3], 3);
4112 }
4113
4114 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4115 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4116 /// <2, 3, 2, 3>
4117 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4118   if (!VT.is128BitVector())
4119     return false;
4120
4121   unsigned NumElems = VT.getVectorNumElements();
4122
4123   if (NumElems != 4)
4124     return false;
4125
4126   return isUndefOrEqual(Mask[0], 2) &&
4127          isUndefOrEqual(Mask[1], 3) &&
4128          isUndefOrEqual(Mask[2], 2) &&
4129          isUndefOrEqual(Mask[3], 3);
4130 }
4131
4132 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4133 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4134 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4135   if (!VT.is128BitVector())
4136     return false;
4137
4138   unsigned NumElems = VT.getVectorNumElements();
4139
4140   if (NumElems != 2 && NumElems != 4)
4141     return false;
4142
4143   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4144     if (!isUndefOrEqual(Mask[i], i + NumElems))
4145       return false;
4146
4147   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4148     if (!isUndefOrEqual(Mask[i], i))
4149       return false;
4150
4151   return true;
4152 }
4153
4154 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4155 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4156 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4157   if (!VT.is128BitVector())
4158     return false;
4159
4160   unsigned NumElems = VT.getVectorNumElements();
4161
4162   if (NumElems != 2 && NumElems != 4)
4163     return false;
4164
4165   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4166     if (!isUndefOrEqual(Mask[i], i))
4167       return false;
4168
4169   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4170     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4171       return false;
4172
4173   return true;
4174 }
4175
4176 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4177 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4178 /// i. e: If all but one element come from the same vector.
4179 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4180   // TODO: Deal with AVX's VINSERTPS
4181   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4182     return false;
4183
4184   unsigned CorrectPosV1 = 0;
4185   unsigned CorrectPosV2 = 0;
4186   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4187     if (Mask[i] == -1) {
4188       ++CorrectPosV1;
4189       ++CorrectPosV2;
4190       continue;
4191     }
4192
4193     if (Mask[i] == i)
4194       ++CorrectPosV1;
4195     else if (Mask[i] == i + 4)
4196       ++CorrectPosV2;
4197   }
4198
4199   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4200     // We have 3 elements (undefs count as elements from any vector) from one
4201     // vector, and one from another.
4202     return true;
4203
4204   return false;
4205 }
4206
4207 //
4208 // Some special combinations that can be optimized.
4209 //
4210 static
4211 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4212                                SelectionDAG &DAG) {
4213   MVT VT = SVOp->getSimpleValueType(0);
4214   SDLoc dl(SVOp);
4215
4216   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4217     return SDValue();
4218
4219   ArrayRef<int> Mask = SVOp->getMask();
4220
4221   // These are the special masks that may be optimized.
4222   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4223   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4224   bool MatchEvenMask = true;
4225   bool MatchOddMask  = true;
4226   for (int i=0; i<8; ++i) {
4227     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4228       MatchEvenMask = false;
4229     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4230       MatchOddMask = false;
4231   }
4232
4233   if (!MatchEvenMask && !MatchOddMask)
4234     return SDValue();
4235
4236   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4237
4238   SDValue Op0 = SVOp->getOperand(0);
4239   SDValue Op1 = SVOp->getOperand(1);
4240
4241   if (MatchEvenMask) {
4242     // Shift the second operand right to 32 bits.
4243     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4244     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4245   } else {
4246     // Shift the first operand left to 32 bits.
4247     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4248     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4249   }
4250   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4251   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4252 }
4253
4254 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4255 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4256 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4257                          bool HasInt256, bool V2IsSplat = false) {
4258
4259   assert(VT.getSizeInBits() >= 128 &&
4260          "Unsupported vector type for unpckl");
4261
4262   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4263   unsigned NumLanes;
4264   unsigned NumOf256BitLanes;
4265   unsigned NumElts = VT.getVectorNumElements();
4266   if (VT.is256BitVector()) {
4267     if (NumElts != 4 && NumElts != 8 &&
4268         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4269     return false;
4270     NumLanes = 2;
4271     NumOf256BitLanes = 1;
4272   } else if (VT.is512BitVector()) {
4273     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4274            "Unsupported vector type for unpckh");
4275     NumLanes = 2;
4276     NumOf256BitLanes = 2;
4277   } else {
4278     NumLanes = 1;
4279     NumOf256BitLanes = 1;
4280   }
4281
4282   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4283   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4284
4285   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4286     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4287       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4288         int BitI  = Mask[l256*NumEltsInStride+l+i];
4289         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4290         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4291           return false;
4292         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4293           return false;
4294         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4295           return false;
4296       }
4297     }
4298   }
4299   return true;
4300 }
4301
4302 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4303 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4304 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4305                          bool HasInt256, bool V2IsSplat = false) {
4306   assert(VT.getSizeInBits() >= 128 &&
4307          "Unsupported vector type for unpckh");
4308
4309   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4310   unsigned NumLanes;
4311   unsigned NumOf256BitLanes;
4312   unsigned NumElts = VT.getVectorNumElements();
4313   if (VT.is256BitVector()) {
4314     if (NumElts != 4 && NumElts != 8 &&
4315         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4316     return false;
4317     NumLanes = 2;
4318     NumOf256BitLanes = 1;
4319   } else if (VT.is512BitVector()) {
4320     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4321            "Unsupported vector type for unpckh");
4322     NumLanes = 2;
4323     NumOf256BitLanes = 2;
4324   } else {
4325     NumLanes = 1;
4326     NumOf256BitLanes = 1;
4327   }
4328
4329   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4330   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4331
4332   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4333     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4334       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4335         int BitI  = Mask[l256*NumEltsInStride+l+i];
4336         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4337         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4338           return false;
4339         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4340           return false;
4341         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4342           return false;
4343       }
4344     }
4345   }
4346   return true;
4347 }
4348
4349 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4350 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4351 /// <0, 0, 1, 1>
4352 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4353   unsigned NumElts = VT.getVectorNumElements();
4354   bool Is256BitVec = VT.is256BitVector();
4355
4356   if (VT.is512BitVector())
4357     return false;
4358   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4359          "Unsupported vector type for unpckh");
4360
4361   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4362       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4363     return false;
4364
4365   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4366   // FIXME: Need a better way to get rid of this, there's no latency difference
4367   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4368   // the former later. We should also remove the "_undef" special mask.
4369   if (NumElts == 4 && Is256BitVec)
4370     return false;
4371
4372   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4373   // independently on 128-bit lanes.
4374   unsigned NumLanes = VT.getSizeInBits()/128;
4375   unsigned NumLaneElts = NumElts/NumLanes;
4376
4377   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4378     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4379       int BitI  = Mask[l+i];
4380       int BitI1 = Mask[l+i+1];
4381
4382       if (!isUndefOrEqual(BitI, j))
4383         return false;
4384       if (!isUndefOrEqual(BitI1, j))
4385         return false;
4386     }
4387   }
4388
4389   return true;
4390 }
4391
4392 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4393 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4394 /// <2, 2, 3, 3>
4395 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4396   unsigned NumElts = VT.getVectorNumElements();
4397
4398   if (VT.is512BitVector())
4399     return false;
4400
4401   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4402          "Unsupported vector type for unpckh");
4403
4404   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4405       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4406     return false;
4407
4408   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4409   // independently on 128-bit lanes.
4410   unsigned NumLanes = VT.getSizeInBits()/128;
4411   unsigned NumLaneElts = NumElts/NumLanes;
4412
4413   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4414     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4415       int BitI  = Mask[l+i];
4416       int BitI1 = Mask[l+i+1];
4417       if (!isUndefOrEqual(BitI, j))
4418         return false;
4419       if (!isUndefOrEqual(BitI1, j))
4420         return false;
4421     }
4422   }
4423   return true;
4424 }
4425
4426 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4427 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4428 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4429   if (!VT.is512BitVector())
4430     return false;
4431
4432   unsigned NumElts = VT.getVectorNumElements();
4433   unsigned HalfSize = NumElts/2;
4434   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4435     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4436       *Imm = 1;
4437       return true;
4438     }
4439   }
4440   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4441     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4442       *Imm = 0;
4443       return true;
4444     }
4445   }
4446   return false;
4447 }
4448
4449 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4450 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4451 /// MOVSD, and MOVD, i.e. setting the lowest element.
4452 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4453   if (VT.getVectorElementType().getSizeInBits() < 32)
4454     return false;
4455   if (!VT.is128BitVector())
4456     return false;
4457
4458   unsigned NumElts = VT.getVectorNumElements();
4459
4460   if (!isUndefOrEqual(Mask[0], NumElts))
4461     return false;
4462
4463   for (unsigned i = 1; i != NumElts; ++i)
4464     if (!isUndefOrEqual(Mask[i], i))
4465       return false;
4466
4467   return true;
4468 }
4469
4470 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4471 /// as permutations between 128-bit chunks or halves. As an example: this
4472 /// shuffle bellow:
4473 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4474 /// The first half comes from the second half of V1 and the second half from the
4475 /// the second half of V2.
4476 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4477   if (!HasFp256 || !VT.is256BitVector())
4478     return false;
4479
4480   // The shuffle result is divided into half A and half B. In total the two
4481   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4482   // B must come from C, D, E or F.
4483   unsigned HalfSize = VT.getVectorNumElements()/2;
4484   bool MatchA = false, MatchB = false;
4485
4486   // Check if A comes from one of C, D, E, F.
4487   for (unsigned Half = 0; Half != 4; ++Half) {
4488     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4489       MatchA = true;
4490       break;
4491     }
4492   }
4493
4494   // Check if B comes from one of C, D, E, F.
4495   for (unsigned Half = 0; Half != 4; ++Half) {
4496     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4497       MatchB = true;
4498       break;
4499     }
4500   }
4501
4502   return MatchA && MatchB;
4503 }
4504
4505 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4506 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4507 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4508   MVT VT = SVOp->getSimpleValueType(0);
4509
4510   unsigned HalfSize = VT.getVectorNumElements()/2;
4511
4512   unsigned FstHalf = 0, SndHalf = 0;
4513   for (unsigned i = 0; i < HalfSize; ++i) {
4514     if (SVOp->getMaskElt(i) > 0) {
4515       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4516       break;
4517     }
4518   }
4519   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4520     if (SVOp->getMaskElt(i) > 0) {
4521       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4522       break;
4523     }
4524   }
4525
4526   return (FstHalf | (SndHalf << 4));
4527 }
4528
4529 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4530 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4531   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4532   if (EltSize < 32)
4533     return false;
4534
4535   unsigned NumElts = VT.getVectorNumElements();
4536   Imm8 = 0;
4537   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4538     for (unsigned i = 0; i != NumElts; ++i) {
4539       if (Mask[i] < 0)
4540         continue;
4541       Imm8 |= Mask[i] << (i*2);
4542     }
4543     return true;
4544   }
4545
4546   unsigned LaneSize = 4;
4547   SmallVector<int, 4> MaskVal(LaneSize, -1);
4548
4549   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4550     for (unsigned i = 0; i != LaneSize; ++i) {
4551       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4552         return false;
4553       if (Mask[i+l] < 0)
4554         continue;
4555       if (MaskVal[i] < 0) {
4556         MaskVal[i] = Mask[i+l] - l;
4557         Imm8 |= MaskVal[i] << (i*2);
4558         continue;
4559       }
4560       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4561         return false;
4562     }
4563   }
4564   return true;
4565 }
4566
4567 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4568 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4569 /// Note that VPERMIL mask matching is different depending whether theunderlying
4570 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4571 /// to the same elements of the low, but to the higher half of the source.
4572 /// In VPERMILPD the two lanes could be shuffled independently of each other
4573 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4574 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4575   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4576   if (VT.getSizeInBits() < 256 || EltSize < 32)
4577     return false;
4578   bool symetricMaskRequired = (EltSize == 32);
4579   unsigned NumElts = VT.getVectorNumElements();
4580
4581   unsigned NumLanes = VT.getSizeInBits()/128;
4582   unsigned LaneSize = NumElts/NumLanes;
4583   // 2 or 4 elements in one lane
4584
4585   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4586   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4587     for (unsigned i = 0; i != LaneSize; ++i) {
4588       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4589         return false;
4590       if (symetricMaskRequired) {
4591         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4592           ExpectedMaskVal[i] = Mask[i+l] - l;
4593           continue;
4594         }
4595         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4596           return false;
4597       }
4598     }
4599   }
4600   return true;
4601 }
4602
4603 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4604 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4605 /// element of vector 2 and the other elements to come from vector 1 in order.
4606 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4607                                bool V2IsSplat = false, bool V2IsUndef = false) {
4608   if (!VT.is128BitVector())
4609     return false;
4610
4611   unsigned NumOps = VT.getVectorNumElements();
4612   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4613     return false;
4614
4615   if (!isUndefOrEqual(Mask[0], 0))
4616     return false;
4617
4618   for (unsigned i = 1; i != NumOps; ++i)
4619     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4620           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4621           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4622       return false;
4623
4624   return true;
4625 }
4626
4627 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4628 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4629 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4630 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4631                            const X86Subtarget *Subtarget) {
4632   if (!Subtarget->hasSSE3())
4633     return false;
4634
4635   unsigned NumElems = VT.getVectorNumElements();
4636
4637   if ((VT.is128BitVector() && NumElems != 4) ||
4638       (VT.is256BitVector() && NumElems != 8) ||
4639       (VT.is512BitVector() && NumElems != 16))
4640     return false;
4641
4642   // "i+1" is the value the indexed mask element must have
4643   for (unsigned i = 0; i != NumElems; i += 2)
4644     if (!isUndefOrEqual(Mask[i], i+1) ||
4645         !isUndefOrEqual(Mask[i+1], i+1))
4646       return false;
4647
4648   return true;
4649 }
4650
4651 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4652 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4653 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4654 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4655                            const X86Subtarget *Subtarget) {
4656   if (!Subtarget->hasSSE3())
4657     return false;
4658
4659   unsigned NumElems = VT.getVectorNumElements();
4660
4661   if ((VT.is128BitVector() && NumElems != 4) ||
4662       (VT.is256BitVector() && NumElems != 8) ||
4663       (VT.is512BitVector() && NumElems != 16))
4664     return false;
4665
4666   // "i" is the value the indexed mask element must have
4667   for (unsigned i = 0; i != NumElems; i += 2)
4668     if (!isUndefOrEqual(Mask[i], i) ||
4669         !isUndefOrEqual(Mask[i+1], i))
4670       return false;
4671
4672   return true;
4673 }
4674
4675 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4676 /// specifies a shuffle of elements that is suitable for input to 256-bit
4677 /// version of MOVDDUP.
4678 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4679   if (!HasFp256 || !VT.is256BitVector())
4680     return false;
4681
4682   unsigned NumElts = VT.getVectorNumElements();
4683   if (NumElts != 4)
4684     return false;
4685
4686   for (unsigned i = 0; i != NumElts/2; ++i)
4687     if (!isUndefOrEqual(Mask[i], 0))
4688       return false;
4689   for (unsigned i = NumElts/2; i != NumElts; ++i)
4690     if (!isUndefOrEqual(Mask[i], NumElts/2))
4691       return false;
4692   return true;
4693 }
4694
4695 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4696 /// specifies a shuffle of elements that is suitable for input to 128-bit
4697 /// version of MOVDDUP.
4698 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4699   if (!VT.is128BitVector())
4700     return false;
4701
4702   unsigned e = VT.getVectorNumElements() / 2;
4703   for (unsigned i = 0; i != e; ++i)
4704     if (!isUndefOrEqual(Mask[i], i))
4705       return false;
4706   for (unsigned i = 0; i != e; ++i)
4707     if (!isUndefOrEqual(Mask[e+i], i))
4708       return false;
4709   return true;
4710 }
4711
4712 /// isVEXTRACTIndex - Return true if the specified
4713 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4714 /// suitable for instruction that extract 128 or 256 bit vectors
4715 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4716   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4717   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4718     return false;
4719
4720   // The index should be aligned on a vecWidth-bit boundary.
4721   uint64_t Index =
4722     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4723
4724   MVT VT = N->getSimpleValueType(0);
4725   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4726   bool Result = (Index * ElSize) % vecWidth == 0;
4727
4728   return Result;
4729 }
4730
4731 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4732 /// operand specifies a subvector insert that is suitable for input to
4733 /// insertion of 128 or 256-bit subvectors
4734 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4735   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4736   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4737     return false;
4738   // The index should be aligned on a vecWidth-bit boundary.
4739   uint64_t Index =
4740     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4741
4742   MVT VT = N->getSimpleValueType(0);
4743   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4744   bool Result = (Index * ElSize) % vecWidth == 0;
4745
4746   return Result;
4747 }
4748
4749 bool X86::isVINSERT128Index(SDNode *N) {
4750   return isVINSERTIndex(N, 128);
4751 }
4752
4753 bool X86::isVINSERT256Index(SDNode *N) {
4754   return isVINSERTIndex(N, 256);
4755 }
4756
4757 bool X86::isVEXTRACT128Index(SDNode *N) {
4758   return isVEXTRACTIndex(N, 128);
4759 }
4760
4761 bool X86::isVEXTRACT256Index(SDNode *N) {
4762   return isVEXTRACTIndex(N, 256);
4763 }
4764
4765 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4766 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4767 /// Handles 128-bit and 256-bit.
4768 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4769   MVT VT = N->getSimpleValueType(0);
4770
4771   assert((VT.getSizeInBits() >= 128) &&
4772          "Unsupported vector type for PSHUF/SHUFP");
4773
4774   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4775   // independently on 128-bit lanes.
4776   unsigned NumElts = VT.getVectorNumElements();
4777   unsigned NumLanes = VT.getSizeInBits()/128;
4778   unsigned NumLaneElts = NumElts/NumLanes;
4779
4780   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4781          "Only supports 2, 4 or 8 elements per lane");
4782
4783   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4784   unsigned Mask = 0;
4785   for (unsigned i = 0; i != NumElts; ++i) {
4786     int Elt = N->getMaskElt(i);
4787     if (Elt < 0) continue;
4788     Elt &= NumLaneElts - 1;
4789     unsigned ShAmt = (i << Shift) % 8;
4790     Mask |= Elt << ShAmt;
4791   }
4792
4793   return Mask;
4794 }
4795
4796 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4797 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4798 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4799   MVT VT = N->getSimpleValueType(0);
4800
4801   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4802          "Unsupported vector type for PSHUFHW");
4803
4804   unsigned NumElts = VT.getVectorNumElements();
4805
4806   unsigned Mask = 0;
4807   for (unsigned l = 0; l != NumElts; l += 8) {
4808     // 8 nodes per lane, but we only care about the last 4.
4809     for (unsigned i = 0; i < 4; ++i) {
4810       int Elt = N->getMaskElt(l+i+4);
4811       if (Elt < 0) continue;
4812       Elt &= 0x3; // only 2-bits.
4813       Mask |= Elt << (i * 2);
4814     }
4815   }
4816
4817   return Mask;
4818 }
4819
4820 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4821 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4822 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4823   MVT VT = N->getSimpleValueType(0);
4824
4825   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4826          "Unsupported vector type for PSHUFHW");
4827
4828   unsigned NumElts = VT.getVectorNumElements();
4829
4830   unsigned Mask = 0;
4831   for (unsigned l = 0; l != NumElts; l += 8) {
4832     // 8 nodes per lane, but we only care about the first 4.
4833     for (unsigned i = 0; i < 4; ++i) {
4834       int Elt = N->getMaskElt(l+i);
4835       if (Elt < 0) continue;
4836       Elt &= 0x3; // only 2-bits
4837       Mask |= Elt << (i * 2);
4838     }
4839   }
4840
4841   return Mask;
4842 }
4843
4844 /// \brief Return the appropriate immediate to shuffle the specified
4845 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4846 /// VALIGN (if Interlane is true) instructions.
4847 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4848                                            bool InterLane) {
4849   MVT VT = SVOp->getSimpleValueType(0);
4850   unsigned EltSize = InterLane ? 1 :
4851     VT.getVectorElementType().getSizeInBits() >> 3;
4852
4853   unsigned NumElts = VT.getVectorNumElements();
4854   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4855   unsigned NumLaneElts = NumElts/NumLanes;
4856
4857   int Val = 0;
4858   unsigned i;
4859   for (i = 0; i != NumElts; ++i) {
4860     Val = SVOp->getMaskElt(i);
4861     if (Val >= 0)
4862       break;
4863   }
4864   if (Val >= (int)NumElts)
4865     Val -= NumElts - NumLaneElts;
4866
4867   assert(Val - i > 0 && "PALIGNR imm should be positive");
4868   return (Val - i) * EltSize;
4869 }
4870
4871 /// \brief Return the appropriate immediate to shuffle the specified
4872 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4873 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4874   return getShuffleAlignrImmediate(SVOp, false);
4875 }
4876
4877 /// \brief Return the appropriate immediate to shuffle the specified
4878 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4879 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4880   return getShuffleAlignrImmediate(SVOp, true);
4881 }
4882
4883
4884 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4885   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4886   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4887     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4888
4889   uint64_t Index =
4890     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4891
4892   MVT VecVT = N->getOperand(0).getSimpleValueType();
4893   MVT ElVT = VecVT.getVectorElementType();
4894
4895   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4896   return Index / NumElemsPerChunk;
4897 }
4898
4899 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4900   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4901   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4902     llvm_unreachable("Illegal insert subvector for VINSERT");
4903
4904   uint64_t Index =
4905     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4906
4907   MVT VecVT = N->getSimpleValueType(0);
4908   MVT ElVT = VecVT.getVectorElementType();
4909
4910   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4911   return Index / NumElemsPerChunk;
4912 }
4913
4914 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4915 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4916 /// and VINSERTI128 instructions.
4917 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4918   return getExtractVEXTRACTImmediate(N, 128);
4919 }
4920
4921 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4922 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4923 /// and VINSERTI64x4 instructions.
4924 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4925   return getExtractVEXTRACTImmediate(N, 256);
4926 }
4927
4928 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4929 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4930 /// and VINSERTI128 instructions.
4931 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4932   return getInsertVINSERTImmediate(N, 128);
4933 }
4934
4935 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4936 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4937 /// and VINSERTI64x4 instructions.
4938 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4939   return getInsertVINSERTImmediate(N, 256);
4940 }
4941
4942 /// isZero - Returns true if Elt is a constant integer zero
4943 static bool isZero(SDValue V) {
4944   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4945   return C && C->isNullValue();
4946 }
4947
4948 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4949 /// constant +0.0.
4950 bool X86::isZeroNode(SDValue Elt) {
4951   if (isZero(Elt))
4952     return true;
4953   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4954     return CFP->getValueAPF().isPosZero();
4955   return false;
4956 }
4957
4958 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4959 /// match movhlps. The lower half elements should come from upper half of
4960 /// V1 (and in order), and the upper half elements should come from the upper
4961 /// half of V2 (and in order).
4962 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4963   if (!VT.is128BitVector())
4964     return false;
4965   if (VT.getVectorNumElements() != 4)
4966     return false;
4967   for (unsigned i = 0, e = 2; i != e; ++i)
4968     if (!isUndefOrEqual(Mask[i], i+2))
4969       return false;
4970   for (unsigned i = 2; i != 4; ++i)
4971     if (!isUndefOrEqual(Mask[i], i+4))
4972       return false;
4973   return true;
4974 }
4975
4976 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4977 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4978 /// required.
4979 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4980   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4981     return false;
4982   N = N->getOperand(0).getNode();
4983   if (!ISD::isNON_EXTLoad(N))
4984     return false;
4985   if (LD)
4986     *LD = cast<LoadSDNode>(N);
4987   return true;
4988 }
4989
4990 // Test whether the given value is a vector value which will be legalized
4991 // into a load.
4992 static bool WillBeConstantPoolLoad(SDNode *N) {
4993   if (N->getOpcode() != ISD::BUILD_VECTOR)
4994     return false;
4995
4996   // Check for any non-constant elements.
4997   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4998     switch (N->getOperand(i).getNode()->getOpcode()) {
4999     case ISD::UNDEF:
5000     case ISD::ConstantFP:
5001     case ISD::Constant:
5002       break;
5003     default:
5004       return false;
5005     }
5006
5007   // Vectors of all-zeros and all-ones are materialized with special
5008   // instructions rather than being loaded.
5009   return !ISD::isBuildVectorAllZeros(N) &&
5010          !ISD::isBuildVectorAllOnes(N);
5011 }
5012
5013 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5014 /// match movlp{s|d}. The lower half elements should come from lower half of
5015 /// V1 (and in order), and the upper half elements should come from the upper
5016 /// half of V2 (and in order). And since V1 will become the source of the
5017 /// MOVLP, it must be either a vector load or a scalar load to vector.
5018 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5019                                ArrayRef<int> Mask, MVT VT) {
5020   if (!VT.is128BitVector())
5021     return false;
5022
5023   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5024     return false;
5025   // Is V2 is a vector load, don't do this transformation. We will try to use
5026   // load folding shufps op.
5027   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5028     return false;
5029
5030   unsigned NumElems = VT.getVectorNumElements();
5031
5032   if (NumElems != 2 && NumElems != 4)
5033     return false;
5034   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5035     if (!isUndefOrEqual(Mask[i], i))
5036       return false;
5037   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5038     if (!isUndefOrEqual(Mask[i], i+NumElems))
5039       return false;
5040   return true;
5041 }
5042
5043 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5044 /// to an zero vector.
5045 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5046 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5047   SDValue V1 = N->getOperand(0);
5048   SDValue V2 = N->getOperand(1);
5049   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5050   for (unsigned i = 0; i != NumElems; ++i) {
5051     int Idx = N->getMaskElt(i);
5052     if (Idx >= (int)NumElems) {
5053       unsigned Opc = V2.getOpcode();
5054       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5055         continue;
5056       if (Opc != ISD::BUILD_VECTOR ||
5057           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5058         return false;
5059     } else if (Idx >= 0) {
5060       unsigned Opc = V1.getOpcode();
5061       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5062         continue;
5063       if (Opc != ISD::BUILD_VECTOR ||
5064           !X86::isZeroNode(V1.getOperand(Idx)))
5065         return false;
5066     }
5067   }
5068   return true;
5069 }
5070
5071 /// getZeroVector - Returns a vector of specified type with all zero elements.
5072 ///
5073 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5074                              SelectionDAG &DAG, SDLoc dl) {
5075   assert(VT.isVector() && "Expected a vector type");
5076
5077   // Always build SSE zero vectors as <4 x i32> bitcasted
5078   // to their dest type. This ensures they get CSE'd.
5079   SDValue Vec;
5080   if (VT.is128BitVector()) {  // SSE
5081     if (Subtarget->hasSSE2()) {  // SSE2
5082       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5083       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5084     } else { // SSE1
5085       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5086       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5087     }
5088   } else if (VT.is256BitVector()) { // AVX
5089     if (Subtarget->hasInt256()) { // AVX2
5090       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5091       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5092       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5093     } else {
5094       // 256-bit logic and arithmetic instructions in AVX are all
5095       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5096       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5097       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5098       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5099     }
5100   } else if (VT.is512BitVector()) { // AVX-512
5101       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5102       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5103                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5104       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5105   } else if (VT.getScalarType() == MVT::i1) {
5106     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5107     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5108     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5109     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5110   } else
5111     llvm_unreachable("Unexpected vector type");
5112
5113   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5114 }
5115
5116 /// getOnesVector - Returns a vector of specified type with all bits set.
5117 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5118 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5119 /// Then bitcast to their original type, ensuring they get CSE'd.
5120 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5121                              SDLoc dl) {
5122   assert(VT.isVector() && "Expected a vector type");
5123
5124   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5125   SDValue Vec;
5126   if (VT.is256BitVector()) {
5127     if (HasInt256) { // AVX2
5128       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5129       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5130     } else { // AVX
5131       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5132       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5133     }
5134   } else if (VT.is128BitVector()) {
5135     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5136   } else
5137     llvm_unreachable("Unexpected vector type");
5138
5139   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5140 }
5141
5142 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5143 /// that point to V2 points to its first element.
5144 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5145   for (unsigned i = 0; i != NumElems; ++i) {
5146     if (Mask[i] > (int)NumElems) {
5147       Mask[i] = NumElems;
5148     }
5149   }
5150 }
5151
5152 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5153 /// operation of specified width.
5154 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5155                        SDValue V2) {
5156   unsigned NumElems = VT.getVectorNumElements();
5157   SmallVector<int, 8> Mask;
5158   Mask.push_back(NumElems);
5159   for (unsigned i = 1; i != NumElems; ++i)
5160     Mask.push_back(i);
5161   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5162 }
5163
5164 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5165 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5166                           SDValue V2) {
5167   unsigned NumElems = VT.getVectorNumElements();
5168   SmallVector<int, 8> Mask;
5169   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5170     Mask.push_back(i);
5171     Mask.push_back(i + NumElems);
5172   }
5173   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5174 }
5175
5176 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5177 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5178                           SDValue V2) {
5179   unsigned NumElems = VT.getVectorNumElements();
5180   SmallVector<int, 8> Mask;
5181   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5182     Mask.push_back(i + Half);
5183     Mask.push_back(i + NumElems + Half);
5184   }
5185   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5186 }
5187
5188 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5189 // a generic shuffle instruction because the target has no such instructions.
5190 // Generate shuffles which repeat i16 and i8 several times until they can be
5191 // represented by v4f32 and then be manipulated by target suported shuffles.
5192 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5193   MVT VT = V.getSimpleValueType();
5194   int NumElems = VT.getVectorNumElements();
5195   SDLoc dl(V);
5196
5197   while (NumElems > 4) {
5198     if (EltNo < NumElems/2) {
5199       V = getUnpackl(DAG, dl, VT, V, V);
5200     } else {
5201       V = getUnpackh(DAG, dl, VT, V, V);
5202       EltNo -= NumElems/2;
5203     }
5204     NumElems >>= 1;
5205   }
5206   return V;
5207 }
5208
5209 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5210 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5211   MVT VT = V.getSimpleValueType();
5212   SDLoc dl(V);
5213
5214   if (VT.is128BitVector()) {
5215     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5216     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5217     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5218                              &SplatMask[0]);
5219   } else if (VT.is256BitVector()) {
5220     // To use VPERMILPS to splat scalars, the second half of indicies must
5221     // refer to the higher part, which is a duplication of the lower one,
5222     // because VPERMILPS can only handle in-lane permutations.
5223     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5224                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5225
5226     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5227     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5228                              &SplatMask[0]);
5229   } else
5230     llvm_unreachable("Vector size not supported");
5231
5232   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5233 }
5234
5235 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5236 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5237   MVT SrcVT = SV->getSimpleValueType(0);
5238   SDValue V1 = SV->getOperand(0);
5239   SDLoc dl(SV);
5240
5241   int EltNo = SV->getSplatIndex();
5242   int NumElems = SrcVT.getVectorNumElements();
5243   bool Is256BitVec = SrcVT.is256BitVector();
5244
5245   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5246          "Unknown how to promote splat for type");
5247
5248   // Extract the 128-bit part containing the splat element and update
5249   // the splat element index when it refers to the higher register.
5250   if (Is256BitVec) {
5251     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5252     if (EltNo >= NumElems/2)
5253       EltNo -= NumElems/2;
5254   }
5255
5256   // All i16 and i8 vector types can't be used directly by a generic shuffle
5257   // instruction because the target has no such instruction. Generate shuffles
5258   // which repeat i16 and i8 several times until they fit in i32, and then can
5259   // be manipulated by target suported shuffles.
5260   MVT EltVT = SrcVT.getVectorElementType();
5261   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5262     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5263
5264   // Recreate the 256-bit vector and place the same 128-bit vector
5265   // into the low and high part. This is necessary because we want
5266   // to use VPERM* to shuffle the vectors
5267   if (Is256BitVec) {
5268     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5269   }
5270
5271   return getLegalSplat(DAG, V1, EltNo);
5272 }
5273
5274 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5275 /// vector of zero or undef vector.  This produces a shuffle where the low
5276 /// element of V2 is swizzled into the zero/undef vector, landing at element
5277 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5278 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5279                                            bool IsZero,
5280                                            const X86Subtarget *Subtarget,
5281                                            SelectionDAG &DAG) {
5282   MVT VT = V2.getSimpleValueType();
5283   SDValue V1 = IsZero
5284     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5285   unsigned NumElems = VT.getVectorNumElements();
5286   SmallVector<int, 16> MaskVec;
5287   for (unsigned i = 0; i != NumElems; ++i)
5288     // If this is the insertion idx, put the low elt of V2 here.
5289     MaskVec.push_back(i == Idx ? NumElems : i);
5290   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5291 }
5292
5293 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5294 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5295 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5296 /// shuffles which use a single input multiple times, and in those cases it will
5297 /// adjust the mask to only have indices within that single input.
5298 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5299                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5300   unsigned NumElems = VT.getVectorNumElements();
5301   SDValue ImmN;
5302
5303   IsUnary = false;
5304   bool IsFakeUnary = false;
5305   switch(N->getOpcode()) {
5306   case X86ISD::SHUFP:
5307     ImmN = N->getOperand(N->getNumOperands()-1);
5308     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5309     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5310     break;
5311   case X86ISD::UNPCKH:
5312     DecodeUNPCKHMask(VT, Mask);
5313     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5314     break;
5315   case X86ISD::UNPCKL:
5316     DecodeUNPCKLMask(VT, Mask);
5317     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5318     break;
5319   case X86ISD::MOVHLPS:
5320     DecodeMOVHLPSMask(NumElems, Mask);
5321     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5322     break;
5323   case X86ISD::MOVLHPS:
5324     DecodeMOVLHPSMask(NumElems, Mask);
5325     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5326     break;
5327   case X86ISD::PALIGNR:
5328     ImmN = N->getOperand(N->getNumOperands()-1);
5329     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5330     break;
5331   case X86ISD::PSHUFD:
5332   case X86ISD::VPERMILP:
5333     ImmN = N->getOperand(N->getNumOperands()-1);
5334     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5335     IsUnary = true;
5336     break;
5337   case X86ISD::PSHUFHW:
5338     ImmN = N->getOperand(N->getNumOperands()-1);
5339     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5340     IsUnary = true;
5341     break;
5342   case X86ISD::PSHUFLW:
5343     ImmN = N->getOperand(N->getNumOperands()-1);
5344     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5345     IsUnary = true;
5346     break;
5347   case X86ISD::PSHUFB: {
5348     IsUnary = true;
5349     SDValue MaskNode = N->getOperand(1);
5350     while (MaskNode->getOpcode() == ISD::BITCAST)
5351       MaskNode = MaskNode->getOperand(0);
5352
5353     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5354       // If we have a build-vector, then things are easy.
5355       EVT VT = MaskNode.getValueType();
5356       assert(VT.isVector() &&
5357              "Can't produce a non-vector with a build_vector!");
5358       if (!VT.isInteger())
5359         return false;
5360
5361       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5362
5363       SmallVector<uint64_t, 32> RawMask;
5364       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5365         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5366         if (!CN)
5367           return false;
5368         APInt MaskElement = CN->getAPIntValue();
5369
5370         // We now have to decode the element which could be any integer size and
5371         // extract each byte of it.
5372         for (int j = 0; j < NumBytesPerElement; ++j) {
5373           // Note that this is x86 and so always little endian: the low byte is
5374           // the first byte of the mask.
5375           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5376           MaskElement = MaskElement.lshr(8);
5377         }
5378       }
5379       DecodePSHUFBMask(RawMask, Mask);
5380       break;
5381     }
5382
5383     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5384     if (!MaskLoad)
5385       return false;
5386
5387     SDValue Ptr = MaskLoad->getBasePtr();
5388     if (Ptr->getOpcode() == X86ISD::Wrapper)
5389       Ptr = Ptr->getOperand(0);
5390
5391     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5392     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5393       return false;
5394
5395     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5396       // FIXME: Support AVX-512 here.
5397       if (!C->getType()->isVectorTy() ||
5398           (C->getNumElements() != 16 && C->getNumElements() != 32))
5399         return false;
5400
5401       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5402       DecodePSHUFBMask(C, Mask);
5403       break;
5404     }
5405
5406     return false;
5407   }
5408   case X86ISD::VPERMI:
5409     ImmN = N->getOperand(N->getNumOperands()-1);
5410     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5411     IsUnary = true;
5412     break;
5413   case X86ISD::MOVSS:
5414   case X86ISD::MOVSD: {
5415     // The index 0 always comes from the first element of the second source,
5416     // this is why MOVSS and MOVSD are used in the first place. The other
5417     // elements come from the other positions of the first source vector
5418     Mask.push_back(NumElems);
5419     for (unsigned i = 1; i != NumElems; ++i) {
5420       Mask.push_back(i);
5421     }
5422     break;
5423   }
5424   case X86ISD::VPERM2X128:
5425     ImmN = N->getOperand(N->getNumOperands()-1);
5426     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5427     if (Mask.empty()) return false;
5428     break;
5429   case X86ISD::MOVDDUP:
5430   case X86ISD::MOVLHPD:
5431   case X86ISD::MOVLPD:
5432   case X86ISD::MOVLPS:
5433   case X86ISD::MOVSHDUP:
5434   case X86ISD::MOVSLDUP:
5435     // Not yet implemented
5436     return false;
5437   default: llvm_unreachable("unknown target shuffle node");
5438   }
5439
5440   // If we have a fake unary shuffle, the shuffle mask is spread across two
5441   // inputs that are actually the same node. Re-map the mask to always point
5442   // into the first input.
5443   if (IsFakeUnary)
5444     for (int &M : Mask)
5445       if (M >= (int)Mask.size())
5446         M -= Mask.size();
5447
5448   return true;
5449 }
5450
5451 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5452 /// element of the result of the vector shuffle.
5453 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5454                                    unsigned Depth) {
5455   if (Depth == 6)
5456     return SDValue();  // Limit search depth.
5457
5458   SDValue V = SDValue(N, 0);
5459   EVT VT = V.getValueType();
5460   unsigned Opcode = V.getOpcode();
5461
5462   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5463   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5464     int Elt = SV->getMaskElt(Index);
5465
5466     if (Elt < 0)
5467       return DAG.getUNDEF(VT.getVectorElementType());
5468
5469     unsigned NumElems = VT.getVectorNumElements();
5470     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5471                                          : SV->getOperand(1);
5472     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5473   }
5474
5475   // Recurse into target specific vector shuffles to find scalars.
5476   if (isTargetShuffle(Opcode)) {
5477     MVT ShufVT = V.getSimpleValueType();
5478     unsigned NumElems = ShufVT.getVectorNumElements();
5479     SmallVector<int, 16> ShuffleMask;
5480     bool IsUnary;
5481
5482     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5483       return SDValue();
5484
5485     int Elt = ShuffleMask[Index];
5486     if (Elt < 0)
5487       return DAG.getUNDEF(ShufVT.getVectorElementType());
5488
5489     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5490                                          : N->getOperand(1);
5491     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5492                                Depth+1);
5493   }
5494
5495   // Actual nodes that may contain scalar elements
5496   if (Opcode == ISD::BITCAST) {
5497     V = V.getOperand(0);
5498     EVT SrcVT = V.getValueType();
5499     unsigned NumElems = VT.getVectorNumElements();
5500
5501     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5502       return SDValue();
5503   }
5504
5505   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5506     return (Index == 0) ? V.getOperand(0)
5507                         : DAG.getUNDEF(VT.getVectorElementType());
5508
5509   if (V.getOpcode() == ISD::BUILD_VECTOR)
5510     return V.getOperand(Index);
5511
5512   return SDValue();
5513 }
5514
5515 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5516 /// shuffle operation which come from a consecutively from a zero. The
5517 /// search can start in two different directions, from left or right.
5518 /// We count undefs as zeros until PreferredNum is reached.
5519 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5520                                          unsigned NumElems, bool ZerosFromLeft,
5521                                          SelectionDAG &DAG,
5522                                          unsigned PreferredNum = -1U) {
5523   unsigned NumZeros = 0;
5524   for (unsigned i = 0; i != NumElems; ++i) {
5525     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5526     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5527     if (!Elt.getNode())
5528       break;
5529
5530     if (X86::isZeroNode(Elt))
5531       ++NumZeros;
5532     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5533       NumZeros = std::min(NumZeros + 1, PreferredNum);
5534     else
5535       break;
5536   }
5537
5538   return NumZeros;
5539 }
5540
5541 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5542 /// correspond consecutively to elements from one of the vector operands,
5543 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5544 static
5545 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5546                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5547                               unsigned NumElems, unsigned &OpNum) {
5548   bool SeenV1 = false;
5549   bool SeenV2 = false;
5550
5551   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5552     int Idx = SVOp->getMaskElt(i);
5553     // Ignore undef indicies
5554     if (Idx < 0)
5555       continue;
5556
5557     if (Idx < (int)NumElems)
5558       SeenV1 = true;
5559     else
5560       SeenV2 = true;
5561
5562     // Only accept consecutive elements from the same vector
5563     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5564       return false;
5565   }
5566
5567   OpNum = SeenV1 ? 0 : 1;
5568   return true;
5569 }
5570
5571 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5572 /// logical left shift of a vector.
5573 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5574                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5575   unsigned NumElems =
5576     SVOp->getSimpleValueType(0).getVectorNumElements();
5577   unsigned NumZeros = getNumOfConsecutiveZeros(
5578       SVOp, NumElems, false /* check zeros from right */, DAG,
5579       SVOp->getMaskElt(0));
5580   unsigned OpSrc;
5581
5582   if (!NumZeros)
5583     return false;
5584
5585   // Considering the elements in the mask that are not consecutive zeros,
5586   // check if they consecutively come from only one of the source vectors.
5587   //
5588   //               V1 = {X, A, B, C}     0
5589   //                         \  \  \    /
5590   //   vector_shuffle V1, V2 <1, 2, 3, X>
5591   //
5592   if (!isShuffleMaskConsecutive(SVOp,
5593             0,                   // Mask Start Index
5594             NumElems-NumZeros,   // Mask End Index(exclusive)
5595             NumZeros,            // Where to start looking in the src vector
5596             NumElems,            // Number of elements in vector
5597             OpSrc))              // Which source operand ?
5598     return false;
5599
5600   isLeft = false;
5601   ShAmt = NumZeros;
5602   ShVal = SVOp->getOperand(OpSrc);
5603   return true;
5604 }
5605
5606 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5607 /// logical left shift of a vector.
5608 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5609                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5610   unsigned NumElems =
5611     SVOp->getSimpleValueType(0).getVectorNumElements();
5612   unsigned NumZeros = getNumOfConsecutiveZeros(
5613       SVOp, NumElems, true /* check zeros from left */, DAG,
5614       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5615   unsigned OpSrc;
5616
5617   if (!NumZeros)
5618     return false;
5619
5620   // Considering the elements in the mask that are not consecutive zeros,
5621   // check if they consecutively come from only one of the source vectors.
5622   //
5623   //                           0    { A, B, X, X } = V2
5624   //                          / \    /  /
5625   //   vector_shuffle V1, V2 <X, X, 4, 5>
5626   //
5627   if (!isShuffleMaskConsecutive(SVOp,
5628             NumZeros,     // Mask Start Index
5629             NumElems,     // Mask End Index(exclusive)
5630             0,            // Where to start looking in the src vector
5631             NumElems,     // Number of elements in vector
5632             OpSrc))       // Which source operand ?
5633     return false;
5634
5635   isLeft = true;
5636   ShAmt = NumZeros;
5637   ShVal = SVOp->getOperand(OpSrc);
5638   return true;
5639 }
5640
5641 /// isVectorShift - Returns true if the shuffle can be implemented as a
5642 /// logical left or right shift of a vector.
5643 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5644                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5645   // Although the logic below support any bitwidth size, there are no
5646   // shift instructions which handle more than 128-bit vectors.
5647   if (!SVOp->getSimpleValueType(0).is128BitVector())
5648     return false;
5649
5650   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5651       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5652     return true;
5653
5654   return false;
5655 }
5656
5657 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5658 ///
5659 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5660                                        unsigned NumNonZero, unsigned NumZero,
5661                                        SelectionDAG &DAG,
5662                                        const X86Subtarget* Subtarget,
5663                                        const TargetLowering &TLI) {
5664   if (NumNonZero > 8)
5665     return SDValue();
5666
5667   SDLoc dl(Op);
5668   SDValue V;
5669   bool First = true;
5670   for (unsigned i = 0; i < 16; ++i) {
5671     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5672     if (ThisIsNonZero && First) {
5673       if (NumZero)
5674         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5675       else
5676         V = DAG.getUNDEF(MVT::v8i16);
5677       First = false;
5678     }
5679
5680     if ((i & 1) != 0) {
5681       SDValue ThisElt, LastElt;
5682       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5683       if (LastIsNonZero) {
5684         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5685                               MVT::i16, Op.getOperand(i-1));
5686       }
5687       if (ThisIsNonZero) {
5688         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5689         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5690                               ThisElt, DAG.getConstant(8, MVT::i8));
5691         if (LastIsNonZero)
5692           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5693       } else
5694         ThisElt = LastElt;
5695
5696       if (ThisElt.getNode())
5697         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5698                         DAG.getIntPtrConstant(i/2));
5699     }
5700   }
5701
5702   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5703 }
5704
5705 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5706 ///
5707 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5708                                      unsigned NumNonZero, unsigned NumZero,
5709                                      SelectionDAG &DAG,
5710                                      const X86Subtarget* Subtarget,
5711                                      const TargetLowering &TLI) {
5712   if (NumNonZero > 4)
5713     return SDValue();
5714
5715   SDLoc dl(Op);
5716   SDValue V;
5717   bool First = true;
5718   for (unsigned i = 0; i < 8; ++i) {
5719     bool isNonZero = (NonZeros & (1 << i)) != 0;
5720     if (isNonZero) {
5721       if (First) {
5722         if (NumZero)
5723           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5724         else
5725           V = DAG.getUNDEF(MVT::v8i16);
5726         First = false;
5727       }
5728       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5729                       MVT::v8i16, V, Op.getOperand(i),
5730                       DAG.getIntPtrConstant(i));
5731     }
5732   }
5733
5734   return V;
5735 }
5736
5737 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5738 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5739                                      unsigned NonZeros, unsigned NumNonZero,
5740                                      unsigned NumZero, SelectionDAG &DAG,
5741                                      const X86Subtarget *Subtarget,
5742                                      const TargetLowering &TLI) {
5743   // We know there's at least one non-zero element
5744   unsigned FirstNonZeroIdx = 0;
5745   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5746   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5747          X86::isZeroNode(FirstNonZero)) {
5748     ++FirstNonZeroIdx;
5749     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5750   }
5751
5752   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5753       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5754     return SDValue();
5755
5756   SDValue V = FirstNonZero.getOperand(0);
5757   MVT VVT = V.getSimpleValueType();
5758   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5759     return SDValue();
5760
5761   unsigned FirstNonZeroDst =
5762       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5763   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5764   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5765   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5766
5767   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5768     SDValue Elem = Op.getOperand(Idx);
5769     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5770       continue;
5771
5772     // TODO: What else can be here? Deal with it.
5773     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5774       return SDValue();
5775
5776     // TODO: Some optimizations are still possible here
5777     // ex: Getting one element from a vector, and the rest from another.
5778     if (Elem.getOperand(0) != V)
5779       return SDValue();
5780
5781     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5782     if (Dst == Idx)
5783       ++CorrectIdx;
5784     else if (IncorrectIdx == -1U) {
5785       IncorrectIdx = Idx;
5786       IncorrectDst = Dst;
5787     } else
5788       // There was already one element with an incorrect index.
5789       // We can't optimize this case to an insertps.
5790       return SDValue();
5791   }
5792
5793   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5794     SDLoc dl(Op);
5795     EVT VT = Op.getSimpleValueType();
5796     unsigned ElementMoveMask = 0;
5797     if (IncorrectIdx == -1U)
5798       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5799     else
5800       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5801
5802     SDValue InsertpsMask =
5803         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5804     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5805   }
5806
5807   return SDValue();
5808 }
5809
5810 /// getVShift - Return a vector logical shift node.
5811 ///
5812 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5813                          unsigned NumBits, SelectionDAG &DAG,
5814                          const TargetLowering &TLI, SDLoc dl) {
5815   assert(VT.is128BitVector() && "Unknown type for VShift");
5816   EVT ShVT = MVT::v2i64;
5817   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5818   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5819   return DAG.getNode(ISD::BITCAST, dl, VT,
5820                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5821                              DAG.getConstant(NumBits,
5822                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5823 }
5824
5825 static SDValue
5826 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5827
5828   // Check if the scalar load can be widened into a vector load. And if
5829   // the address is "base + cst" see if the cst can be "absorbed" into
5830   // the shuffle mask.
5831   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5832     SDValue Ptr = LD->getBasePtr();
5833     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5834       return SDValue();
5835     EVT PVT = LD->getValueType(0);
5836     if (PVT != MVT::i32 && PVT != MVT::f32)
5837       return SDValue();
5838
5839     int FI = -1;
5840     int64_t Offset = 0;
5841     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5842       FI = FINode->getIndex();
5843       Offset = 0;
5844     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5845                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5846       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5847       Offset = Ptr.getConstantOperandVal(1);
5848       Ptr = Ptr.getOperand(0);
5849     } else {
5850       return SDValue();
5851     }
5852
5853     // FIXME: 256-bit vector instructions don't require a strict alignment,
5854     // improve this code to support it better.
5855     unsigned RequiredAlign = VT.getSizeInBits()/8;
5856     SDValue Chain = LD->getChain();
5857     // Make sure the stack object alignment is at least 16 or 32.
5858     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5859     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5860       if (MFI->isFixedObjectIndex(FI)) {
5861         // Can't change the alignment. FIXME: It's possible to compute
5862         // the exact stack offset and reference FI + adjust offset instead.
5863         // If someone *really* cares about this. That's the way to implement it.
5864         return SDValue();
5865       } else {
5866         MFI->setObjectAlignment(FI, RequiredAlign);
5867       }
5868     }
5869
5870     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5871     // Ptr + (Offset & ~15).
5872     if (Offset < 0)
5873       return SDValue();
5874     if ((Offset % RequiredAlign) & 3)
5875       return SDValue();
5876     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5877     if (StartOffset)
5878       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5879                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5880
5881     int EltNo = (Offset - StartOffset) >> 2;
5882     unsigned NumElems = VT.getVectorNumElements();
5883
5884     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5885     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5886                              LD->getPointerInfo().getWithOffset(StartOffset),
5887                              false, false, false, 0);
5888
5889     SmallVector<int, 8> Mask;
5890     for (unsigned i = 0; i != NumElems; ++i)
5891       Mask.push_back(EltNo);
5892
5893     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5894   }
5895
5896   return SDValue();
5897 }
5898
5899 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5900 /// vector of type 'VT', see if the elements can be replaced by a single large
5901 /// load which has the same value as a build_vector whose operands are 'elts'.
5902 ///
5903 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5904 ///
5905 /// FIXME: we'd also like to handle the case where the last elements are zero
5906 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5907 /// There's even a handy isZeroNode for that purpose.
5908 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5909                                         SDLoc &DL, SelectionDAG &DAG,
5910                                         bool isAfterLegalize) {
5911   EVT EltVT = VT.getVectorElementType();
5912   unsigned NumElems = Elts.size();
5913
5914   LoadSDNode *LDBase = nullptr;
5915   unsigned LastLoadedElt = -1U;
5916
5917   // For each element in the initializer, see if we've found a load or an undef.
5918   // If we don't find an initial load element, or later load elements are
5919   // non-consecutive, bail out.
5920   for (unsigned i = 0; i < NumElems; ++i) {
5921     SDValue Elt = Elts[i];
5922
5923     if (!Elt.getNode() ||
5924         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5925       return SDValue();
5926     if (!LDBase) {
5927       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5928         return SDValue();
5929       LDBase = cast<LoadSDNode>(Elt.getNode());
5930       LastLoadedElt = i;
5931       continue;
5932     }
5933     if (Elt.getOpcode() == ISD::UNDEF)
5934       continue;
5935
5936     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5937     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5938       return SDValue();
5939     LastLoadedElt = i;
5940   }
5941
5942   // If we have found an entire vector of loads and undefs, then return a large
5943   // load of the entire vector width starting at the base pointer.  If we found
5944   // consecutive loads for the low half, generate a vzext_load node.
5945   if (LastLoadedElt == NumElems - 1) {
5946
5947     if (isAfterLegalize &&
5948         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5949       return SDValue();
5950
5951     SDValue NewLd = SDValue();
5952
5953     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5954       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5955                           LDBase->getPointerInfo(),
5956                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5957                           LDBase->isInvariant(), 0);
5958     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5959                         LDBase->getPointerInfo(),
5960                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5961                         LDBase->isInvariant(), LDBase->getAlignment());
5962
5963     if (LDBase->hasAnyUseOfValue(1)) {
5964       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5965                                      SDValue(LDBase, 1),
5966                                      SDValue(NewLd.getNode(), 1));
5967       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5968       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5969                              SDValue(NewLd.getNode(), 1));
5970     }
5971
5972     return NewLd;
5973   }
5974   if (NumElems == 4 && LastLoadedElt == 1 &&
5975       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5976     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5977     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5978     SDValue ResNode =
5979         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5980                                 LDBase->getPointerInfo(),
5981                                 LDBase->getAlignment(),
5982                                 false/*isVolatile*/, true/*ReadMem*/,
5983                                 false/*WriteMem*/);
5984
5985     // Make sure the newly-created LOAD is in the same position as LDBase in
5986     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5987     // update uses of LDBase's output chain to use the TokenFactor.
5988     if (LDBase->hasAnyUseOfValue(1)) {
5989       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5990                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5991       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5992       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5993                              SDValue(ResNode.getNode(), 1));
5994     }
5995
5996     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5997   }
5998   return SDValue();
5999 }
6000
6001 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6002 /// to generate a splat value for the following cases:
6003 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6004 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6005 /// a scalar load, or a constant.
6006 /// The VBROADCAST node is returned when a pattern is found,
6007 /// or SDValue() otherwise.
6008 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6009                                     SelectionDAG &DAG) {
6010   if (!Subtarget->hasFp256())
6011     return SDValue();
6012
6013   MVT VT = Op.getSimpleValueType();
6014   SDLoc dl(Op);
6015
6016   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6017          "Unsupported vector type for broadcast.");
6018
6019   SDValue Ld;
6020   bool ConstSplatVal;
6021
6022   switch (Op.getOpcode()) {
6023     default:
6024       // Unknown pattern found.
6025       return SDValue();
6026
6027     case ISD::BUILD_VECTOR: {
6028       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6029       BitVector UndefElements;
6030       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6031
6032       // We need a splat of a single value to use broadcast, and it doesn't
6033       // make any sense if the value is only in one element of the vector.
6034       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6035         return SDValue();
6036
6037       Ld = Splat;
6038       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6039                        Ld.getOpcode() == ISD::ConstantFP);
6040
6041       // Make sure that all of the users of a non-constant load are from the
6042       // BUILD_VECTOR node.
6043       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6044         return SDValue();
6045       break;
6046     }
6047
6048     case ISD::VECTOR_SHUFFLE: {
6049       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6050
6051       // Shuffles must have a splat mask where the first element is
6052       // broadcasted.
6053       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6054         return SDValue();
6055
6056       SDValue Sc = Op.getOperand(0);
6057       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6058           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6059
6060         if (!Subtarget->hasInt256())
6061           return SDValue();
6062
6063         // Use the register form of the broadcast instruction available on AVX2.
6064         if (VT.getSizeInBits() >= 256)
6065           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6066         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6067       }
6068
6069       Ld = Sc.getOperand(0);
6070       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6071                        Ld.getOpcode() == ISD::ConstantFP);
6072
6073       // The scalar_to_vector node and the suspected
6074       // load node must have exactly one user.
6075       // Constants may have multiple users.
6076
6077       // AVX-512 has register version of the broadcast
6078       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6079         Ld.getValueType().getSizeInBits() >= 32;
6080       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6081           !hasRegVer))
6082         return SDValue();
6083       break;
6084     }
6085   }
6086
6087   bool IsGE256 = (VT.getSizeInBits() >= 256);
6088
6089   // Handle the broadcasting a single constant scalar from the constant pool
6090   // into a vector. On Sandybridge it is still better to load a constant vector
6091   // from the constant pool and not to broadcast it from a scalar.
6092   if (ConstSplatVal && Subtarget->hasInt256()) {
6093     EVT CVT = Ld.getValueType();
6094     assert(!CVT.isVector() && "Must not broadcast a vector type");
6095     unsigned ScalarSize = CVT.getSizeInBits();
6096
6097     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
6098       const Constant *C = nullptr;
6099       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6100         C = CI->getConstantIntValue();
6101       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6102         C = CF->getConstantFPValue();
6103
6104       assert(C && "Invalid constant type");
6105
6106       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6107       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6108       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6109       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6110                        MachinePointerInfo::getConstantPool(),
6111                        false, false, false, Alignment);
6112
6113       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6114     }
6115   }
6116
6117   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6118   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6119
6120   // Handle AVX2 in-register broadcasts.
6121   if (!IsLoad && Subtarget->hasInt256() &&
6122       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6123     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6124
6125   // The scalar source must be a normal load.
6126   if (!IsLoad)
6127     return SDValue();
6128
6129   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6130     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6131
6132   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6133   // double since there is no vbroadcastsd xmm
6134   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6135     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6136       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6137   }
6138
6139   // Unsupported broadcast.
6140   return SDValue();
6141 }
6142
6143 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6144 /// underlying vector and index.
6145 ///
6146 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6147 /// index.
6148 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6149                                          SDValue ExtIdx) {
6150   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6151   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6152     return Idx;
6153
6154   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6155   // lowered this:
6156   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6157   // to:
6158   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6159   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6160   //                           undef)
6161   //                       Constant<0>)
6162   // In this case the vector is the extract_subvector expression and the index
6163   // is 2, as specified by the shuffle.
6164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6165   SDValue ShuffleVec = SVOp->getOperand(0);
6166   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6167   assert(ShuffleVecVT.getVectorElementType() ==
6168          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6169
6170   int ShuffleIdx = SVOp->getMaskElt(Idx);
6171   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6172     ExtractedFromVec = ShuffleVec;
6173     return ShuffleIdx;
6174   }
6175   return Idx;
6176 }
6177
6178 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6179   MVT VT = Op.getSimpleValueType();
6180
6181   // Skip if insert_vec_elt is not supported.
6182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6183   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6184     return SDValue();
6185
6186   SDLoc DL(Op);
6187   unsigned NumElems = Op.getNumOperands();
6188
6189   SDValue VecIn1;
6190   SDValue VecIn2;
6191   SmallVector<unsigned, 4> InsertIndices;
6192   SmallVector<int, 8> Mask(NumElems, -1);
6193
6194   for (unsigned i = 0; i != NumElems; ++i) {
6195     unsigned Opc = Op.getOperand(i).getOpcode();
6196
6197     if (Opc == ISD::UNDEF)
6198       continue;
6199
6200     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6201       // Quit if more than 1 elements need inserting.
6202       if (InsertIndices.size() > 1)
6203         return SDValue();
6204
6205       InsertIndices.push_back(i);
6206       continue;
6207     }
6208
6209     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6210     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6211     // Quit if non-constant index.
6212     if (!isa<ConstantSDNode>(ExtIdx))
6213       return SDValue();
6214     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6215
6216     // Quit if extracted from vector of different type.
6217     if (ExtractedFromVec.getValueType() != VT)
6218       return SDValue();
6219
6220     if (!VecIn1.getNode())
6221       VecIn1 = ExtractedFromVec;
6222     else if (VecIn1 != ExtractedFromVec) {
6223       if (!VecIn2.getNode())
6224         VecIn2 = ExtractedFromVec;
6225       else if (VecIn2 != ExtractedFromVec)
6226         // Quit if more than 2 vectors to shuffle
6227         return SDValue();
6228     }
6229
6230     if (ExtractedFromVec == VecIn1)
6231       Mask[i] = Idx;
6232     else if (ExtractedFromVec == VecIn2)
6233       Mask[i] = Idx + NumElems;
6234   }
6235
6236   if (!VecIn1.getNode())
6237     return SDValue();
6238
6239   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6240   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6241   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6242     unsigned Idx = InsertIndices[i];
6243     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6244                      DAG.getIntPtrConstant(Idx));
6245   }
6246
6247   return NV;
6248 }
6249
6250 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6251 SDValue
6252 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6253
6254   MVT VT = Op.getSimpleValueType();
6255   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6256          "Unexpected type in LowerBUILD_VECTORvXi1!");
6257
6258   SDLoc dl(Op);
6259   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6260     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6261     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6262     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6263   }
6264
6265   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6266     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6267     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6268     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6269   }
6270
6271   bool AllContants = true;
6272   uint64_t Immediate = 0;
6273   int NonConstIdx = -1;
6274   bool IsSplat = true;
6275   unsigned NumNonConsts = 0;
6276   unsigned NumConsts = 0;
6277   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6278     SDValue In = Op.getOperand(idx);
6279     if (In.getOpcode() == ISD::UNDEF)
6280       continue;
6281     if (!isa<ConstantSDNode>(In)) {
6282       AllContants = false;
6283       NonConstIdx = idx;
6284       NumNonConsts++;
6285     }
6286     else {
6287       NumConsts++;
6288       if (cast<ConstantSDNode>(In)->getZExtValue())
6289       Immediate |= (1ULL << idx);
6290     }
6291     if (In != Op.getOperand(0))
6292       IsSplat = false;
6293   }
6294
6295   if (AllContants) {
6296     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6297       DAG.getConstant(Immediate, MVT::i16));
6298     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6299                        DAG.getIntPtrConstant(0));
6300   }
6301
6302   if (NumNonConsts == 1 && NonConstIdx != 0) {
6303     SDValue DstVec;
6304     if (NumConsts) {
6305       SDValue VecAsImm = DAG.getConstant(Immediate,
6306                                          MVT::getIntegerVT(VT.getSizeInBits()));
6307       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6308     }
6309     else 
6310       DstVec = DAG.getUNDEF(VT);
6311     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6312                        Op.getOperand(NonConstIdx),
6313                        DAG.getIntPtrConstant(NonConstIdx));
6314   }
6315   if (!IsSplat && (NonConstIdx != 0))
6316     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6317   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6318   SDValue Select;
6319   if (IsSplat)
6320     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6321                           DAG.getConstant(-1, SelectVT),
6322                           DAG.getConstant(0, SelectVT));
6323   else
6324     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6325                          DAG.getConstant((Immediate | 1), SelectVT),
6326                          DAG.getConstant(Immediate, SelectVT));
6327   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6328 }
6329
6330 /// \brief Return true if \p N implements a horizontal binop and return the
6331 /// operands for the horizontal binop into V0 and V1.
6332 /// 
6333 /// This is a helper function of PerformBUILD_VECTORCombine.
6334 /// This function checks that the build_vector \p N in input implements a
6335 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6336 /// operation to match.
6337 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6338 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6339 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6340 /// arithmetic sub.
6341 ///
6342 /// This function only analyzes elements of \p N whose indices are
6343 /// in range [BaseIdx, LastIdx).
6344 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6345                               SelectionDAG &DAG,
6346                               unsigned BaseIdx, unsigned LastIdx,
6347                               SDValue &V0, SDValue &V1) {
6348   EVT VT = N->getValueType(0);
6349
6350   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6351   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6352          "Invalid Vector in input!");
6353   
6354   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6355   bool CanFold = true;
6356   unsigned ExpectedVExtractIdx = BaseIdx;
6357   unsigned NumElts = LastIdx - BaseIdx;
6358   V0 = DAG.getUNDEF(VT);
6359   V1 = DAG.getUNDEF(VT);
6360
6361   // Check if N implements a horizontal binop.
6362   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6363     SDValue Op = N->getOperand(i + BaseIdx);
6364
6365     // Skip UNDEFs.
6366     if (Op->getOpcode() == ISD::UNDEF) {
6367       // Update the expected vector extract index.
6368       if (i * 2 == NumElts)
6369         ExpectedVExtractIdx = BaseIdx;
6370       ExpectedVExtractIdx += 2;
6371       continue;
6372     }
6373
6374     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6375
6376     if (!CanFold)
6377       break;
6378
6379     SDValue Op0 = Op.getOperand(0);
6380     SDValue Op1 = Op.getOperand(1);
6381
6382     // Try to match the following pattern:
6383     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6384     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6385         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6386         Op0.getOperand(0) == Op1.getOperand(0) &&
6387         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6388         isa<ConstantSDNode>(Op1.getOperand(1)));
6389     if (!CanFold)
6390       break;
6391
6392     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6393     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6394
6395     if (i * 2 < NumElts) {
6396       if (V0.getOpcode() == ISD::UNDEF)
6397         V0 = Op0.getOperand(0);
6398     } else {
6399       if (V1.getOpcode() == ISD::UNDEF)
6400         V1 = Op0.getOperand(0);
6401       if (i * 2 == NumElts)
6402         ExpectedVExtractIdx = BaseIdx;
6403     }
6404
6405     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6406     if (I0 == ExpectedVExtractIdx)
6407       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6408     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6409       // Try to match the following dag sequence:
6410       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6411       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6412     } else
6413       CanFold = false;
6414
6415     ExpectedVExtractIdx += 2;
6416   }
6417
6418   return CanFold;
6419 }
6420
6421 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6422 /// a concat_vector. 
6423 ///
6424 /// This is a helper function of PerformBUILD_VECTORCombine.
6425 /// This function expects two 256-bit vectors called V0 and V1.
6426 /// At first, each vector is split into two separate 128-bit vectors.
6427 /// Then, the resulting 128-bit vectors are used to implement two
6428 /// horizontal binary operations. 
6429 ///
6430 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6431 ///
6432 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6433 /// the two new horizontal binop.
6434 /// When Mode is set, the first horizontal binop dag node would take as input
6435 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6436 /// horizontal binop dag node would take as input the lower 128-bit of V1
6437 /// and the upper 128-bit of V1.
6438 ///   Example:
6439 ///     HADD V0_LO, V0_HI
6440 ///     HADD V1_LO, V1_HI
6441 ///
6442 /// Otherwise, the first horizontal binop dag node takes as input the lower
6443 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6444 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6445 ///   Example:
6446 ///     HADD V0_LO, V1_LO
6447 ///     HADD V0_HI, V1_HI
6448 ///
6449 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6450 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6451 /// the upper 128-bits of the result.
6452 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6453                                      SDLoc DL, SelectionDAG &DAG,
6454                                      unsigned X86Opcode, bool Mode,
6455                                      bool isUndefLO, bool isUndefHI) {
6456   EVT VT = V0.getValueType();
6457   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6458          "Invalid nodes in input!");
6459
6460   unsigned NumElts = VT.getVectorNumElements();
6461   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6462   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6463   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6464   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6465   EVT NewVT = V0_LO.getValueType();
6466
6467   SDValue LO = DAG.getUNDEF(NewVT);
6468   SDValue HI = DAG.getUNDEF(NewVT);
6469
6470   if (Mode) {
6471     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6472     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6473       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6474     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6475       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6476   } else {
6477     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6478     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6479                        V1_LO->getOpcode() != ISD::UNDEF))
6480       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6481
6482     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6483                        V1_HI->getOpcode() != ISD::UNDEF))
6484       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6485   }
6486
6487   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6488 }
6489
6490 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6491 /// sequence of 'vadd + vsub + blendi'.
6492 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6493                            const X86Subtarget *Subtarget) {
6494   SDLoc DL(BV);
6495   EVT VT = BV->getValueType(0);
6496   unsigned NumElts = VT.getVectorNumElements();
6497   SDValue InVec0 = DAG.getUNDEF(VT);
6498   SDValue InVec1 = DAG.getUNDEF(VT);
6499
6500   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6501           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6502
6503   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6505   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6506     return SDValue();
6507
6508   // Odd-numbered elements in the input build vector are obtained from
6509   // adding two integer/float elements.
6510   // Even-numbered elements in the input build vector are obtained from
6511   // subtracting two integer/float elements.
6512   unsigned ExpectedOpcode = ISD::FSUB;
6513   unsigned NextExpectedOpcode = ISD::FADD;
6514   bool AddFound = false;
6515   bool SubFound = false;
6516
6517   for (unsigned i = 0, e = NumElts; i != e; i++) {
6518     SDValue Op = BV->getOperand(i);
6519       
6520     // Skip 'undef' values.
6521     unsigned Opcode = Op.getOpcode();
6522     if (Opcode == ISD::UNDEF) {
6523       std::swap(ExpectedOpcode, NextExpectedOpcode);
6524       continue;
6525     }
6526       
6527     // Early exit if we found an unexpected opcode.
6528     if (Opcode != ExpectedOpcode)
6529       return SDValue();
6530
6531     SDValue Op0 = Op.getOperand(0);
6532     SDValue Op1 = Op.getOperand(1);
6533
6534     // Try to match the following pattern:
6535     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6536     // Early exit if we cannot match that sequence.
6537     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6538         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6539         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6540         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6541         Op0.getOperand(1) != Op1.getOperand(1))
6542       return SDValue();
6543
6544     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6545     if (I0 != i)
6546       return SDValue();
6547
6548     // We found a valid add/sub node. Update the information accordingly.
6549     if (i & 1)
6550       AddFound = true;
6551     else
6552       SubFound = true;
6553
6554     // Update InVec0 and InVec1.
6555     if (InVec0.getOpcode() == ISD::UNDEF)
6556       InVec0 = Op0.getOperand(0);
6557     if (InVec1.getOpcode() == ISD::UNDEF)
6558       InVec1 = Op1.getOperand(0);
6559
6560     // Make sure that operands in input to each add/sub node always
6561     // come from a same pair of vectors.
6562     if (InVec0 != Op0.getOperand(0)) {
6563       if (ExpectedOpcode == ISD::FSUB)
6564         return SDValue();
6565
6566       // FADD is commutable. Try to commute the operands
6567       // and then test again.
6568       std::swap(Op0, Op1);
6569       if (InVec0 != Op0.getOperand(0))
6570         return SDValue();
6571     }
6572
6573     if (InVec1 != Op1.getOperand(0))
6574       return SDValue();
6575
6576     // Update the pair of expected opcodes.
6577     std::swap(ExpectedOpcode, NextExpectedOpcode);
6578   }
6579
6580   // Don't try to fold this build_vector into a VSELECT if it has
6581   // too many UNDEF operands.
6582   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6583       InVec1.getOpcode() != ISD::UNDEF) {
6584     // Emit a sequence of vector add and sub followed by a VSELECT.
6585     // The new VSELECT will be lowered into a BLENDI.
6586     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6587     // and emit a single ADDSUB instruction.
6588     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6589     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6590
6591     // Construct the VSELECT mask.
6592     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6593     EVT SVT = MaskVT.getVectorElementType();
6594     unsigned SVTBits = SVT.getSizeInBits();
6595     SmallVector<SDValue, 8> Ops;
6596
6597     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6598       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6599                             APInt::getAllOnesValue(SVTBits);
6600       SDValue Constant = DAG.getConstant(Value, SVT);
6601       Ops.push_back(Constant);
6602     }
6603
6604     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6605     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6606   }
6607   
6608   return SDValue();
6609 }
6610
6611 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6612                                           const X86Subtarget *Subtarget) {
6613   SDLoc DL(N);
6614   EVT VT = N->getValueType(0);
6615   unsigned NumElts = VT.getVectorNumElements();
6616   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6617   SDValue InVec0, InVec1;
6618
6619   // Try to match an ADDSUB.
6620   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6621       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6622     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6623     if (Value.getNode())
6624       return Value;
6625   }
6626
6627   // Try to match horizontal ADD/SUB.
6628   unsigned NumUndefsLO = 0;
6629   unsigned NumUndefsHI = 0;
6630   unsigned Half = NumElts/2;
6631
6632   // Count the number of UNDEF operands in the build_vector in input.
6633   for (unsigned i = 0, e = Half; i != e; ++i)
6634     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6635       NumUndefsLO++;
6636
6637   for (unsigned i = Half, e = NumElts; i != e; ++i)
6638     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6639       NumUndefsHI++;
6640
6641   // Early exit if this is either a build_vector of all UNDEFs or all the
6642   // operands but one are UNDEF.
6643   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6644     return SDValue();
6645
6646   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6647     // Try to match an SSE3 float HADD/HSUB.
6648     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6649       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6650     
6651     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6652       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6653   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6654     // Try to match an SSSE3 integer HADD/HSUB.
6655     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6656       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6657     
6658     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6659       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6660   }
6661   
6662   if (!Subtarget->hasAVX())
6663     return SDValue();
6664
6665   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6666     // Try to match an AVX horizontal add/sub of packed single/double
6667     // precision floating point values from 256-bit vectors.
6668     SDValue InVec2, InVec3;
6669     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6670         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6671         ((InVec0.getOpcode() == ISD::UNDEF ||
6672           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6673         ((InVec1.getOpcode() == ISD::UNDEF ||
6674           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6675       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6676
6677     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6678         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6679         ((InVec0.getOpcode() == ISD::UNDEF ||
6680           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6681         ((InVec1.getOpcode() == ISD::UNDEF ||
6682           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6683       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6684   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6685     // Try to match an AVX2 horizontal add/sub of signed integers.
6686     SDValue InVec2, InVec3;
6687     unsigned X86Opcode;
6688     bool CanFold = true;
6689
6690     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6691         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6692         ((InVec0.getOpcode() == ISD::UNDEF ||
6693           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6694         ((InVec1.getOpcode() == ISD::UNDEF ||
6695           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6696       X86Opcode = X86ISD::HADD;
6697     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6698         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6699         ((InVec0.getOpcode() == ISD::UNDEF ||
6700           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6701         ((InVec1.getOpcode() == ISD::UNDEF ||
6702           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6703       X86Opcode = X86ISD::HSUB;
6704     else
6705       CanFold = false;
6706
6707     if (CanFold) {
6708       // Fold this build_vector into a single horizontal add/sub.
6709       // Do this only if the target has AVX2.
6710       if (Subtarget->hasAVX2())
6711         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6712  
6713       // Do not try to expand this build_vector into a pair of horizontal
6714       // add/sub if we can emit a pair of scalar add/sub.
6715       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6716         return SDValue();
6717
6718       // Convert this build_vector into a pair of horizontal binop followed by
6719       // a concat vector.
6720       bool isUndefLO = NumUndefsLO == Half;
6721       bool isUndefHI = NumUndefsHI == Half;
6722       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6723                                    isUndefLO, isUndefHI);
6724     }
6725   }
6726
6727   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6728        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6729     unsigned X86Opcode;
6730     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6731       X86Opcode = X86ISD::HADD;
6732     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6733       X86Opcode = X86ISD::HSUB;
6734     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6735       X86Opcode = X86ISD::FHADD;
6736     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6737       X86Opcode = X86ISD::FHSUB;
6738     else
6739       return SDValue();
6740
6741     // Don't try to expand this build_vector into a pair of horizontal add/sub
6742     // if we can simply emit a pair of scalar add/sub.
6743     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6744       return SDValue();
6745
6746     // Convert this build_vector into two horizontal add/sub followed by
6747     // a concat vector.
6748     bool isUndefLO = NumUndefsLO == Half;
6749     bool isUndefHI = NumUndefsHI == Half;
6750     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6751                                  isUndefLO, isUndefHI);
6752   }
6753
6754   return SDValue();
6755 }
6756
6757 SDValue
6758 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6759   SDLoc dl(Op);
6760
6761   MVT VT = Op.getSimpleValueType();
6762   MVT ExtVT = VT.getVectorElementType();
6763   unsigned NumElems = Op.getNumOperands();
6764
6765   // Generate vectors for predicate vectors.
6766   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6767     return LowerBUILD_VECTORvXi1(Op, DAG);
6768
6769   // Vectors containing all zeros can be matched by pxor and xorps later
6770   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6771     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6772     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6773     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6774       return Op;
6775
6776     return getZeroVector(VT, Subtarget, DAG, dl);
6777   }
6778
6779   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6780   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6781   // vpcmpeqd on 256-bit vectors.
6782   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6783     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6784       return Op;
6785
6786     if (!VT.is512BitVector())
6787       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6788   }
6789
6790   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6791   if (Broadcast.getNode())
6792     return Broadcast;
6793
6794   unsigned EVTBits = ExtVT.getSizeInBits();
6795
6796   unsigned NumZero  = 0;
6797   unsigned NumNonZero = 0;
6798   unsigned NonZeros = 0;
6799   bool IsAllConstants = true;
6800   SmallSet<SDValue, 8> Values;
6801   for (unsigned i = 0; i < NumElems; ++i) {
6802     SDValue Elt = Op.getOperand(i);
6803     if (Elt.getOpcode() == ISD::UNDEF)
6804       continue;
6805     Values.insert(Elt);
6806     if (Elt.getOpcode() != ISD::Constant &&
6807         Elt.getOpcode() != ISD::ConstantFP)
6808       IsAllConstants = false;
6809     if (X86::isZeroNode(Elt))
6810       NumZero++;
6811     else {
6812       NonZeros |= (1 << i);
6813       NumNonZero++;
6814     }
6815   }
6816
6817   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6818   if (NumNonZero == 0)
6819     return DAG.getUNDEF(VT);
6820
6821   // Special case for single non-zero, non-undef, element.
6822   if (NumNonZero == 1) {
6823     unsigned Idx = countTrailingZeros(NonZeros);
6824     SDValue Item = Op.getOperand(Idx);
6825
6826     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6827     // the value are obviously zero, truncate the value to i32 and do the
6828     // insertion that way.  Only do this if the value is non-constant or if the
6829     // value is a constant being inserted into element 0.  It is cheaper to do
6830     // a constant pool load than it is to do a movd + shuffle.
6831     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6832         (!IsAllConstants || Idx == 0)) {
6833       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6834         // Handle SSE only.
6835         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6836         EVT VecVT = MVT::v4i32;
6837         unsigned VecElts = 4;
6838
6839         // Truncate the value (which may itself be a constant) to i32, and
6840         // convert it to a vector with movd (S2V+shuffle to zero extend).
6841         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6842         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6843
6844         // If using the new shuffle lowering, just directly insert this.
6845         if (ExperimentalVectorShuffleLowering)
6846           return DAG.getNode(
6847               ISD::BITCAST, dl, VT,
6848               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6849
6850         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6851
6852         // Now we have our 32-bit value zero extended in the low element of
6853         // a vector.  If Idx != 0, swizzle it into place.
6854         if (Idx != 0) {
6855           SmallVector<int, 4> Mask;
6856           Mask.push_back(Idx);
6857           for (unsigned i = 1; i != VecElts; ++i)
6858             Mask.push_back(i);
6859           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6860                                       &Mask[0]);
6861         }
6862         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6863       }
6864     }
6865
6866     // If we have a constant or non-constant insertion into the low element of
6867     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6868     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6869     // depending on what the source datatype is.
6870     if (Idx == 0) {
6871       if (NumZero == 0)
6872         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6873
6874       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6875           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6876         if (VT.is256BitVector() || VT.is512BitVector()) {
6877           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6878           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6879                              Item, DAG.getIntPtrConstant(0));
6880         }
6881         assert(VT.is128BitVector() && "Expected an SSE value type!");
6882         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6883         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6884         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6885       }
6886
6887       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6888         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6889         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6890         if (VT.is256BitVector()) {
6891           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6892           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6893         } else {
6894           assert(VT.is128BitVector() && "Expected an SSE value type!");
6895           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6896         }
6897         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6898       }
6899     }
6900
6901     // Is it a vector logical left shift?
6902     if (NumElems == 2 && Idx == 1 &&
6903         X86::isZeroNode(Op.getOperand(0)) &&
6904         !X86::isZeroNode(Op.getOperand(1))) {
6905       unsigned NumBits = VT.getSizeInBits();
6906       return getVShift(true, VT,
6907                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6908                                    VT, Op.getOperand(1)),
6909                        NumBits/2, DAG, *this, dl);
6910     }
6911
6912     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6913       return SDValue();
6914
6915     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6916     // is a non-constant being inserted into an element other than the low one,
6917     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6918     // movd/movss) to move this into the low element, then shuffle it into
6919     // place.
6920     if (EVTBits == 32) {
6921       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6922
6923       // If using the new shuffle lowering, just directly insert this.
6924       if (ExperimentalVectorShuffleLowering)
6925         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6926
6927       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6928       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6929       SmallVector<int, 8> MaskVec;
6930       for (unsigned i = 0; i != NumElems; ++i)
6931         MaskVec.push_back(i == Idx ? 0 : 1);
6932       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6933     }
6934   }
6935
6936   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6937   if (Values.size() == 1) {
6938     if (EVTBits == 32) {
6939       // Instead of a shuffle like this:
6940       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6941       // Check if it's possible to issue this instead.
6942       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6943       unsigned Idx = countTrailingZeros(NonZeros);
6944       SDValue Item = Op.getOperand(Idx);
6945       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6946         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6947     }
6948     return SDValue();
6949   }
6950
6951   // A vector full of immediates; various special cases are already
6952   // handled, so this is best done with a single constant-pool load.
6953   if (IsAllConstants)
6954     return SDValue();
6955
6956   // For AVX-length vectors, build the individual 128-bit pieces and use
6957   // shuffles to put them in place.
6958   if (VT.is256BitVector() || VT.is512BitVector()) {
6959     SmallVector<SDValue, 64> V;
6960     for (unsigned i = 0; i != NumElems; ++i)
6961       V.push_back(Op.getOperand(i));
6962
6963     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6964
6965     // Build both the lower and upper subvector.
6966     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6967                                 makeArrayRef(&V[0], NumElems/2));
6968     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6969                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6970
6971     // Recreate the wider vector with the lower and upper part.
6972     if (VT.is256BitVector())
6973       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6974     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6975   }
6976
6977   // Let legalizer expand 2-wide build_vectors.
6978   if (EVTBits == 64) {
6979     if (NumNonZero == 1) {
6980       // One half is zero or undef.
6981       unsigned Idx = countTrailingZeros(NonZeros);
6982       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6983                                  Op.getOperand(Idx));
6984       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6985     }
6986     return SDValue();
6987   }
6988
6989   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6990   if (EVTBits == 8 && NumElems == 16) {
6991     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6992                                         Subtarget, *this);
6993     if (V.getNode()) return V;
6994   }
6995
6996   if (EVTBits == 16 && NumElems == 8) {
6997     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6998                                       Subtarget, *this);
6999     if (V.getNode()) return V;
7000   }
7001
7002   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
7003   if (EVTBits == 32 && NumElems == 4) {
7004     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
7005                                       NumZero, DAG, Subtarget, *this);
7006     if (V.getNode())
7007       return V;
7008   }
7009
7010   // If element VT is == 32 bits, turn it into a number of shuffles.
7011   SmallVector<SDValue, 8> V(NumElems);
7012   if (NumElems == 4 && NumZero > 0) {
7013     for (unsigned i = 0; i < 4; ++i) {
7014       bool isZero = !(NonZeros & (1 << i));
7015       if (isZero)
7016         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7017       else
7018         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7019     }
7020
7021     for (unsigned i = 0; i < 2; ++i) {
7022       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7023         default: break;
7024         case 0:
7025           V[i] = V[i*2];  // Must be a zero vector.
7026           break;
7027         case 1:
7028           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7029           break;
7030         case 2:
7031           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7032           break;
7033         case 3:
7034           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7035           break;
7036       }
7037     }
7038
7039     bool Reverse1 = (NonZeros & 0x3) == 2;
7040     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7041     int MaskVec[] = {
7042       Reverse1 ? 1 : 0,
7043       Reverse1 ? 0 : 1,
7044       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7045       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7046     };
7047     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7048   }
7049
7050   if (Values.size() > 1 && VT.is128BitVector()) {
7051     // Check for a build vector of consecutive loads.
7052     for (unsigned i = 0; i < NumElems; ++i)
7053       V[i] = Op.getOperand(i);
7054
7055     // Check for elements which are consecutive loads.
7056     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7057     if (LD.getNode())
7058       return LD;
7059
7060     // Check for a build vector from mostly shuffle plus few inserting.
7061     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7062     if (Sh.getNode())
7063       return Sh;
7064
7065     // For SSE 4.1, use insertps to put the high elements into the low element.
7066     if (getSubtarget()->hasSSE41()) {
7067       SDValue Result;
7068       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7069         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7070       else
7071         Result = DAG.getUNDEF(VT);
7072
7073       for (unsigned i = 1; i < NumElems; ++i) {
7074         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7075         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7076                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7077       }
7078       return Result;
7079     }
7080
7081     // Otherwise, expand into a number of unpckl*, start by extending each of
7082     // our (non-undef) elements to the full vector width with the element in the
7083     // bottom slot of the vector (which generates no code for SSE).
7084     for (unsigned i = 0; i < NumElems; ++i) {
7085       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7086         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7087       else
7088         V[i] = DAG.getUNDEF(VT);
7089     }
7090
7091     // Next, we iteratively mix elements, e.g. for v4f32:
7092     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7093     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7094     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7095     unsigned EltStride = NumElems >> 1;
7096     while (EltStride != 0) {
7097       for (unsigned i = 0; i < EltStride; ++i) {
7098         // If V[i+EltStride] is undef and this is the first round of mixing,
7099         // then it is safe to just drop this shuffle: V[i] is already in the
7100         // right place, the one element (since it's the first round) being
7101         // inserted as undef can be dropped.  This isn't safe for successive
7102         // rounds because they will permute elements within both vectors.
7103         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7104             EltStride == NumElems/2)
7105           continue;
7106
7107         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7108       }
7109       EltStride >>= 1;
7110     }
7111     return V[0];
7112   }
7113   return SDValue();
7114 }
7115
7116 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7117 // to create 256-bit vectors from two other 128-bit ones.
7118 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7119   SDLoc dl(Op);
7120   MVT ResVT = Op.getSimpleValueType();
7121
7122   assert((ResVT.is256BitVector() ||
7123           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7124
7125   SDValue V1 = Op.getOperand(0);
7126   SDValue V2 = Op.getOperand(1);
7127   unsigned NumElems = ResVT.getVectorNumElements();
7128   if(ResVT.is256BitVector())
7129     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7130
7131   if (Op.getNumOperands() == 4) {
7132     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7133                                 ResVT.getVectorNumElements()/2);
7134     SDValue V3 = Op.getOperand(2);
7135     SDValue V4 = Op.getOperand(3);
7136     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7137       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7138   }
7139   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7140 }
7141
7142 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7143   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7144   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7145          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7146           Op.getNumOperands() == 4)));
7147
7148   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7149   // from two other 128-bit ones.
7150
7151   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7152   return LowerAVXCONCAT_VECTORS(Op, DAG);
7153 }
7154
7155
7156 //===----------------------------------------------------------------------===//
7157 // Vector shuffle lowering
7158 //
7159 // This is an experimental code path for lowering vector shuffles on x86. It is
7160 // designed to handle arbitrary vector shuffles and blends, gracefully
7161 // degrading performance as necessary. It works hard to recognize idiomatic
7162 // shuffles and lower them to optimal instruction patterns without leaving
7163 // a framework that allows reasonably efficient handling of all vector shuffle
7164 // patterns.
7165 //===----------------------------------------------------------------------===//
7166
7167 /// \brief Tiny helper function to identify a no-op mask.
7168 ///
7169 /// This is a somewhat boring predicate function. It checks whether the mask
7170 /// array input, which is assumed to be a single-input shuffle mask of the kind
7171 /// used by the X86 shuffle instructions (not a fully general
7172 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7173 /// in-place shuffle are 'no-op's.
7174 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7175   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7176     if (Mask[i] != -1 && Mask[i] != i)
7177       return false;
7178   return true;
7179 }
7180
7181 /// \brief Helper function to classify a mask as a single-input mask.
7182 ///
7183 /// This isn't a generic single-input test because in the vector shuffle
7184 /// lowering we canonicalize single inputs to be the first input operand. This
7185 /// means we can more quickly test for a single input by only checking whether
7186 /// an input from the second operand exists. We also assume that the size of
7187 /// mask corresponds to the size of the input vectors which isn't true in the
7188 /// fully general case.
7189 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7190   for (int M : Mask)
7191     if (M >= (int)Mask.size())
7192       return false;
7193   return true;
7194 }
7195
7196 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7197 // 2013 will allow us to use it as a non-type template parameter.
7198 namespace {
7199
7200 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7201 ///
7202 /// See its documentation for details.
7203 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7204   if (Mask.size() != Args.size())
7205     return false;
7206   for (int i = 0, e = Mask.size(); i < e; ++i) {
7207     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7208     assert(*Args[i] < (int)Args.size() * 2 &&
7209            "Argument outside the range of possible shuffle inputs!");
7210     if (Mask[i] != -1 && Mask[i] != *Args[i])
7211       return false;
7212   }
7213   return true;
7214 }
7215
7216 } // namespace
7217
7218 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7219 /// arguments.
7220 ///
7221 /// This is a fast way to test a shuffle mask against a fixed pattern:
7222 ///
7223 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7224 ///
7225 /// It returns true if the mask is exactly as wide as the argument list, and
7226 /// each element of the mask is either -1 (signifying undef) or the value given
7227 /// in the argument.
7228 static const VariadicFunction1<
7229     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7230
7231 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7232 ///
7233 /// This helper function produces an 8-bit shuffle immediate corresponding to
7234 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7235 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7236 /// example.
7237 ///
7238 /// NB: We rely heavily on "undef" masks preserving the input lane.
7239 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7240                                           SelectionDAG &DAG) {
7241   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7242   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7243   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7244   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7245   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7246
7247   unsigned Imm = 0;
7248   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7249   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7250   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7251   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7252   return DAG.getConstant(Imm, MVT::i8);
7253 }
7254
7255 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7256 ///
7257 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7258 /// support for floating point shuffles but not integer shuffles. These
7259 /// instructions will incur a domain crossing penalty on some chips though so
7260 /// it is better to avoid lowering through this for integer vectors where
7261 /// possible.
7262 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7263                                        const X86Subtarget *Subtarget,
7264                                        SelectionDAG &DAG) {
7265   SDLoc DL(Op);
7266   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7267   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7268   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7269   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7270   ArrayRef<int> Mask = SVOp->getMask();
7271   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7272
7273   if (isSingleInputShuffleMask(Mask)) {
7274     // Straight shuffle of a single input vector. Simulate this by using the
7275     // single input as both of the "inputs" to this instruction..
7276     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7277     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7278                        DAG.getConstant(SHUFPDMask, MVT::i8));
7279   }
7280   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7281   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7282
7283   // Use dedicated unpack instructions for masks that match their pattern.
7284   if (isShuffleEquivalent(Mask, 0, 2))
7285     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7286   if (isShuffleEquivalent(Mask, 1, 3))
7287     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7288
7289   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7290   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7291                      DAG.getConstant(SHUFPDMask, MVT::i8));
7292 }
7293
7294 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7295 ///
7296 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7297 /// the integer unit to minimize domain crossing penalties. However, for blends
7298 /// it falls back to the floating point shuffle operation with appropriate bit
7299 /// casting.
7300 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7301                                        const X86Subtarget *Subtarget,
7302                                        SelectionDAG &DAG) {
7303   SDLoc DL(Op);
7304   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7305   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7306   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7307   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7308   ArrayRef<int> Mask = SVOp->getMask();
7309   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7310
7311   if (isSingleInputShuffleMask(Mask)) {
7312     // Straight shuffle of a single input vector. For everything from SSE2
7313     // onward this has a single fast instruction with no scary immediates.
7314     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7315     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7316     int WidenedMask[4] = {
7317         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7318         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7319     return DAG.getNode(
7320         ISD::BITCAST, DL, MVT::v2i64,
7321         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7322                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7323   }
7324
7325   // Use dedicated unpack instructions for masks that match their pattern.
7326   if (isShuffleEquivalent(Mask, 0, 2))
7327     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7328   if (isShuffleEquivalent(Mask, 1, 3))
7329     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7330
7331   // We implement this with SHUFPD which is pretty lame because it will likely
7332   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7333   // However, all the alternatives are still more cycles and newer chips don't
7334   // have this problem. It would be really nice if x86 had better shuffles here.
7335   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7336   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7337   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7338                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7339 }
7340
7341 /// \brief Lower 4-lane 32-bit floating point shuffles.
7342 ///
7343 /// Uses instructions exclusively from the floating point unit to minimize
7344 /// domain crossing penalties, as these are sufficient to implement all v4f32
7345 /// shuffles.
7346 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7347                                        const X86Subtarget *Subtarget,
7348                                        SelectionDAG &DAG) {
7349   SDLoc DL(Op);
7350   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7351   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7352   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7353   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7354   ArrayRef<int> Mask = SVOp->getMask();
7355   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7356
7357   SDValue LowV = V1, HighV = V2;
7358   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7359
7360   int NumV2Elements =
7361       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7362
7363   if (NumV2Elements == 0)
7364     // Straight shuffle of a single input vector. We pass the input vector to
7365     // both operands to simulate this with a SHUFPS.
7366     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7367                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7368
7369   // Use dedicated unpack instructions for masks that match their pattern.
7370   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7371     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7372   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7373     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7374
7375   if (NumV2Elements == 1) {
7376     int V2Index =
7377         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7378         Mask.begin();
7379
7380     // Check for whether we can use INSERTPS to perform the blend. We only use
7381     // INSERTPS when the V1 elements are already in the correct locations
7382     // because otherwise we can just always use two SHUFPS instructions which
7383     // are much smaller to encode than a SHUFPS and an INSERTPS.
7384     if (Subtarget->hasSSE41()) {
7385       // When using INSERTPS we can zero any lane of the destination. Collect
7386       // the zero inputs into a mask and drop them from the lanes of V1 which
7387       // actually need to be present as inputs to the INSERTPS.
7388       unsigned ZMask = 0;
7389       if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7390         ZMask = 0xF ^ (1 << V2Index);
7391       } else if (V1.getOpcode() == ISD::BUILD_VECTOR) {
7392         for (int i = 0; i < 4; ++i) {
7393           int M = Mask[i];
7394           if (M >= 4)
7395             continue;
7396           if (M > -1) {
7397             SDValue Input = V1.getOperand(M);
7398             if (Input.getOpcode() != ISD::UNDEF &&
7399                 !X86::isZeroNode(Input)) {
7400               // A non-zero input!
7401               ZMask = 0;
7402               break;
7403             }
7404           }
7405           ZMask |= 1 << i;
7406         }
7407       }
7408
7409       // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
7410       int InsertShuffleMask[4] = {-1, -1, -1, -1};
7411       for (int i = 0; i < 4; ++i)
7412         if (i != V2Index && (ZMask & (1 << i)) == 0)
7413           InsertShuffleMask[i] = Mask[i];
7414
7415       if (isNoopShuffleMask(InsertShuffleMask)) {
7416         // Replace V1 with undef if nothing from V1 survives the INSERTPS.
7417         if ((ZMask | 1 << V2Index) == 0xF)
7418           V1 = DAG.getUNDEF(MVT::v4f32);
7419
7420         // Insert the V2 element into the desired position.
7421         SDValue InsertPSMask =
7422             DAG.getIntPtrConstant(Mask[V2Index] << 6 | V2Index << 4 | ZMask);
7423         return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7424                            InsertPSMask);
7425       }
7426     }
7427
7428     // Compute the index adjacent to V2Index and in the same half by toggling
7429     // the low bit.
7430     int V2AdjIndex = V2Index ^ 1;
7431
7432     if (Mask[V2AdjIndex] == -1) {
7433       // Handles all the cases where we have a single V2 element and an undef.
7434       // This will only ever happen in the high lanes because we commute the
7435       // vector otherwise.
7436       if (V2Index < 2)
7437         std::swap(LowV, HighV);
7438       NewMask[V2Index] -= 4;
7439     } else {
7440       // Handle the case where the V2 element ends up adjacent to a V1 element.
7441       // To make this work, blend them together as the first step.
7442       int V1Index = V2AdjIndex;
7443       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7444       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7445                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7446
7447       // Now proceed to reconstruct the final blend as we have the necessary
7448       // high or low half formed.
7449       if (V2Index < 2) {
7450         LowV = V2;
7451         HighV = V1;
7452       } else {
7453         HighV = V2;
7454       }
7455       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7456       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7457     }
7458   } else if (NumV2Elements == 2) {
7459     if (Mask[0] < 4 && Mask[1] < 4) {
7460       // Handle the easy case where we have V1 in the low lanes and V2 in the
7461       // high lanes. We never see this reversed because we sort the shuffle.
7462       NewMask[2] -= 4;
7463       NewMask[3] -= 4;
7464     } else {
7465       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7466       // trying to place elements directly, just blend them and set up the final
7467       // shuffle to place them.
7468
7469       // The first two blend mask elements are for V1, the second two are for
7470       // V2.
7471       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7472                           Mask[2] < 4 ? Mask[2] : Mask[3],
7473                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7474                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7475       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7476                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7477
7478       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7479       // a blend.
7480       LowV = HighV = V1;
7481       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7482       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7483       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7484       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7485     }
7486   }
7487   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7488                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7489 }
7490
7491 static SDValue lowerIntegerElementInsertionVectorShuffle(
7492     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7493     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7494   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7495                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7496                 Mask.begin();
7497
7498   // Check for a single input from a SCALAR_TO_VECTOR node.
7499   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7500   // all the smarts here sunk into that routine. However, the current
7501   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7502   // vector shuffle lowering is dead.
7503   if ((Mask[V2Index] == (int)Mask.size() &&
7504        V2.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
7505       V2.getOpcode() == ISD::BUILD_VECTOR) {
7506     SDValue V2S = V2.getOperand(Mask[V2Index] - Mask.size());
7507
7508     bool V1IsAllZero = false;
7509     if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7510       V1IsAllZero = true;
7511     } else if (V1.getOpcode() == ISD::BUILD_VECTOR) {
7512       V1IsAllZero = true;
7513       for (int M : Mask) {
7514         if (M < 0 || M >= (int)Mask.size())
7515           continue;
7516         SDValue Input = V1.getOperand(M);
7517         if (Input.getOpcode() != ISD::UNDEF && !X86::isZeroNode(Input)) {
7518           // A non-zero input!
7519           V1IsAllZero = false;
7520           break;
7521         }
7522       }
7523     }
7524     if (V1IsAllZero) {
7525       // First, we need to zext the scalar if it is smaller than an i32.
7526       MVT EltVT = VT.getVectorElementType();
7527       assert(EltVT == V2S.getSimpleValueType() &&
7528              "Different scalar and element types!");
7529       MVT ExtVT = VT;
7530       if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7531         // Zero-extend directly to i32.
7532         ExtVT = MVT::v4i32;
7533         V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7534       }
7535
7536       V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT,
7537                        DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S));
7538       if (ExtVT != VT)
7539         V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7540
7541       if (V2Index != 0) {
7542         // If we have 4 or fewer lanes we can cheaply shuffle the element into
7543         // the desired position. Otherwise it is more efficient to do a vector
7544         // shift left. We know that we can do a vector shift left because all
7545         // the inputs are zero.
7546         if (VT.getVectorNumElements() <= 4) {
7547           SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7548           V2Shuffle[V2Index] = 0;
7549           V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7550         } else {
7551           V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7552           V2 = DAG.getNode(
7553               X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7554               DAG.getConstant(
7555                   V2Index * EltVT.getSizeInBits(),
7556                   DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7557           V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7558         }
7559       }
7560       return V2;
7561     }
7562   }
7563   return SDValue();
7564 }
7565
7566 /// \brief Lower 4-lane i32 vector shuffles.
7567 ///
7568 /// We try to handle these with integer-domain shuffles where we can, but for
7569 /// blends we use the floating point domain blend instructions.
7570 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7571                                        const X86Subtarget *Subtarget,
7572                                        SelectionDAG &DAG) {
7573   SDLoc DL(Op);
7574   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7575   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7576   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7577   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7578   ArrayRef<int> Mask = SVOp->getMask();
7579   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7580
7581   int NumV2Elements =
7582       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7583
7584   if (NumV2Elements == 0)
7585     // Straight shuffle of a single input vector. For everything from SSE2
7586     // onward this has a single fast instruction with no scary immediates.
7587     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7588                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7589
7590   // Use dedicated unpack instructions for masks that match their pattern.
7591   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7592     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7593   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7594     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7595
7596   // There are special ways we can lower some single-element blends.
7597   if (NumV2Elements == 1)
7598     if (SDValue V = lowerIntegerElementInsertionVectorShuffle(
7599             MVT::v4i32, DL, V1, V2, Mask, Subtarget, DAG))
7600       return V;
7601
7602   // We implement this with SHUFPS because it can blend from two vectors.
7603   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7604   // up the inputs, bypassing domain shift penalties that we would encur if we
7605   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7606   // relevant.
7607   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7608                      DAG.getVectorShuffle(
7609                          MVT::v4f32, DL,
7610                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7611                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7612 }
7613
7614 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7615 /// shuffle lowering, and the most complex part.
7616 ///
7617 /// The lowering strategy is to try to form pairs of input lanes which are
7618 /// targeted at the same half of the final vector, and then use a dword shuffle
7619 /// to place them onto the right half, and finally unpack the paired lanes into
7620 /// their final position.
7621 ///
7622 /// The exact breakdown of how to form these dword pairs and align them on the
7623 /// correct sides is really tricky. See the comments within the function for
7624 /// more of the details.
7625 static SDValue lowerV8I16SingleInputVectorShuffle(
7626     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7627     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7628   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7629   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7630   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7631
7632   SmallVector<int, 4> LoInputs;
7633   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7634                [](int M) { return M >= 0; });
7635   std::sort(LoInputs.begin(), LoInputs.end());
7636   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7637   SmallVector<int, 4> HiInputs;
7638   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7639                [](int M) { return M >= 0; });
7640   std::sort(HiInputs.begin(), HiInputs.end());
7641   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7642   int NumLToL =
7643       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7644   int NumHToL = LoInputs.size() - NumLToL;
7645   int NumLToH =
7646       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7647   int NumHToH = HiInputs.size() - NumLToH;
7648   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7649   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7650   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7651   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7652
7653   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7654   // such inputs we can swap two of the dwords across the half mark and end up
7655   // with <=2 inputs to each half in each half. Once there, we can fall through
7656   // to the generic code below. For example:
7657   //
7658   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7659   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7660   //
7661   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7662   // and an existing 2-into-2 on the other half. In this case we may have to
7663   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7664   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7665   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7666   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7667   // half than the one we target for fixing) will be fixed when we re-enter this
7668   // path. We will also combine away any sequence of PSHUFD instructions that
7669   // result into a single instruction. Here is an example of the tricky case:
7670   //
7671   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7672   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7673   //
7674   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7675   //
7676   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7677   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7678   //
7679   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7680   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7681   //
7682   // The result is fine to be handled by the generic logic.
7683   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7684                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7685                           int AOffset, int BOffset) {
7686     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7687            "Must call this with A having 3 or 1 inputs from the A half.");
7688     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7689            "Must call this with B having 1 or 3 inputs from the B half.");
7690     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7691            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7692
7693     // Compute the index of dword with only one word among the three inputs in
7694     // a half by taking the sum of the half with three inputs and subtracting
7695     // the sum of the actual three inputs. The difference is the remaining
7696     // slot.
7697     int ADWord, BDWord;
7698     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7699     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7700     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7701     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7702     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7703     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7704     int TripleNonInputIdx =
7705         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7706     TripleDWord = TripleNonInputIdx / 2;
7707
7708     // We use xor with one to compute the adjacent DWord to whichever one the
7709     // OneInput is in.
7710     OneInputDWord = (OneInput / 2) ^ 1;
7711
7712     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7713     // and BToA inputs. If there is also such a problem with the BToB and AToB
7714     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7715     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7716     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7717     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7718       // Compute how many inputs will be flipped by swapping these DWords. We
7719       // need
7720       // to balance this to ensure we don't form a 3-1 shuffle in the other
7721       // half.
7722       int NumFlippedAToBInputs =
7723           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7724           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7725       int NumFlippedBToBInputs =
7726           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7727           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7728       if ((NumFlippedAToBInputs == 1 &&
7729            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7730           (NumFlippedBToBInputs == 1 &&
7731            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7732         // We choose whether to fix the A half or B half based on whether that
7733         // half has zero flipped inputs. At zero, we may not be able to fix it
7734         // with that half. We also bias towards fixing the B half because that
7735         // will more commonly be the high half, and we have to bias one way.
7736         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7737                                                        ArrayRef<int> Inputs) {
7738           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7739           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7740                                          PinnedIdx ^ 1) != Inputs.end();
7741           // Determine whether the free index is in the flipped dword or the
7742           // unflipped dword based on where the pinned index is. We use this bit
7743           // in an xor to conditionally select the adjacent dword.
7744           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7745           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7746                                              FixFreeIdx) != Inputs.end();
7747           if (IsFixIdxInput == IsFixFreeIdxInput)
7748             FixFreeIdx += 1;
7749           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7750                                         FixFreeIdx) != Inputs.end();
7751           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7752                  "We need to be changing the number of flipped inputs!");
7753           int PSHUFHalfMask[] = {0, 1, 2, 3};
7754           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7755           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7756                           MVT::v8i16, V,
7757                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7758
7759           for (int &M : Mask)
7760             if (M != -1 && M == FixIdx)
7761               M = FixFreeIdx;
7762             else if (M != -1 && M == FixFreeIdx)
7763               M = FixIdx;
7764         };
7765         if (NumFlippedBToBInputs != 0) {
7766           int BPinnedIdx =
7767               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7768           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7769         } else {
7770           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7771           int APinnedIdx =
7772               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7773           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7774         }
7775       }
7776     }
7777
7778     int PSHUFDMask[] = {0, 1, 2, 3};
7779     PSHUFDMask[ADWord] = BDWord;
7780     PSHUFDMask[BDWord] = ADWord;
7781     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7782                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7783                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7784                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7785
7786     // Adjust the mask to match the new locations of A and B.
7787     for (int &M : Mask)
7788       if (M != -1 && M/2 == ADWord)
7789         M = 2 * BDWord + M % 2;
7790       else if (M != -1 && M/2 == BDWord)
7791         M = 2 * ADWord + M % 2;
7792
7793     // Recurse back into this routine to re-compute state now that this isn't
7794     // a 3 and 1 problem.
7795     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7796                                 Mask);
7797   };
7798   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7799     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7800   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7801     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7802
7803   // At this point there are at most two inputs to the low and high halves from
7804   // each half. That means the inputs can always be grouped into dwords and
7805   // those dwords can then be moved to the correct half with a dword shuffle.
7806   // We use at most one low and one high word shuffle to collect these paired
7807   // inputs into dwords, and finally a dword shuffle to place them.
7808   int PSHUFLMask[4] = {-1, -1, -1, -1};
7809   int PSHUFHMask[4] = {-1, -1, -1, -1};
7810   int PSHUFDMask[4] = {-1, -1, -1, -1};
7811
7812   // First fix the masks for all the inputs that are staying in their
7813   // original halves. This will then dictate the targets of the cross-half
7814   // shuffles.
7815   auto fixInPlaceInputs =
7816       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7817                     MutableArrayRef<int> SourceHalfMask,
7818                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7819     if (InPlaceInputs.empty())
7820       return;
7821     if (InPlaceInputs.size() == 1) {
7822       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7823           InPlaceInputs[0] - HalfOffset;
7824       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7825       return;
7826     }
7827     if (IncomingInputs.empty()) {
7828       // Just fix all of the in place inputs.
7829       for (int Input : InPlaceInputs) {
7830         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7831         PSHUFDMask[Input / 2] = Input / 2;
7832       }
7833       return;
7834     }
7835
7836     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7837     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7838         InPlaceInputs[0] - HalfOffset;
7839     // Put the second input next to the first so that they are packed into
7840     // a dword. We find the adjacent index by toggling the low bit.
7841     int AdjIndex = InPlaceInputs[0] ^ 1;
7842     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7843     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7844     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7845   };
7846   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7847   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7848
7849   // Now gather the cross-half inputs and place them into a free dword of
7850   // their target half.
7851   // FIXME: This operation could almost certainly be simplified dramatically to
7852   // look more like the 3-1 fixing operation.
7853   auto moveInputsToRightHalf = [&PSHUFDMask](
7854       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7855       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7856       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7857       int DestOffset) {
7858     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7859       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7860     };
7861     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7862                                                int Word) {
7863       int LowWord = Word & ~1;
7864       int HighWord = Word | 1;
7865       return isWordClobbered(SourceHalfMask, LowWord) ||
7866              isWordClobbered(SourceHalfMask, HighWord);
7867     };
7868
7869     if (IncomingInputs.empty())
7870       return;
7871
7872     if (ExistingInputs.empty()) {
7873       // Map any dwords with inputs from them into the right half.
7874       for (int Input : IncomingInputs) {
7875         // If the source half mask maps over the inputs, turn those into
7876         // swaps and use the swapped lane.
7877         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7878           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7879             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7880                 Input - SourceOffset;
7881             // We have to swap the uses in our half mask in one sweep.
7882             for (int &M : HalfMask)
7883               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7884                 M = Input;
7885               else if (M == Input)
7886                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7887           } else {
7888             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7889                        Input - SourceOffset &&
7890                    "Previous placement doesn't match!");
7891           }
7892           // Note that this correctly re-maps both when we do a swap and when
7893           // we observe the other side of the swap above. We rely on that to
7894           // avoid swapping the members of the input list directly.
7895           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7896         }
7897
7898         // Map the input's dword into the correct half.
7899         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7900           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7901         else
7902           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7903                      Input / 2 &&
7904                  "Previous placement doesn't match!");
7905       }
7906
7907       // And just directly shift any other-half mask elements to be same-half
7908       // as we will have mirrored the dword containing the element into the
7909       // same position within that half.
7910       for (int &M : HalfMask)
7911         if (M >= SourceOffset && M < SourceOffset + 4) {
7912           M = M - SourceOffset + DestOffset;
7913           assert(M >= 0 && "This should never wrap below zero!");
7914         }
7915       return;
7916     }
7917
7918     // Ensure we have the input in a viable dword of its current half. This
7919     // is particularly tricky because the original position may be clobbered
7920     // by inputs being moved and *staying* in that half.
7921     if (IncomingInputs.size() == 1) {
7922       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7923         int InputFixed = std::find(std::begin(SourceHalfMask),
7924                                    std::end(SourceHalfMask), -1) -
7925                          std::begin(SourceHalfMask) + SourceOffset;
7926         SourceHalfMask[InputFixed - SourceOffset] =
7927             IncomingInputs[0] - SourceOffset;
7928         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7929                      InputFixed);
7930         IncomingInputs[0] = InputFixed;
7931       }
7932     } else if (IncomingInputs.size() == 2) {
7933       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7934           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7935         // We have two non-adjacent or clobbered inputs we need to extract from
7936         // the source half. To do this, we need to map them into some adjacent
7937         // dword slot in the source mask.
7938         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7939                               IncomingInputs[1] - SourceOffset};
7940
7941         // If there is a free slot in the source half mask adjacent to one of
7942         // the inputs, place the other input in it. We use (Index XOR 1) to
7943         // compute an adjacent index.
7944         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7945             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7946           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7947           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7948           InputsFixed[1] = InputsFixed[0] ^ 1;
7949         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7950                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7951           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7952           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7953           InputsFixed[0] = InputsFixed[1] ^ 1;
7954         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7955                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7956           // The two inputs are in the same DWord but it is clobbered and the
7957           // adjacent DWord isn't used at all. Move both inputs to the free
7958           // slot.
7959           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7960           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7961           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7962           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7963         } else {
7964           // The only way we hit this point is if there is no clobbering
7965           // (because there are no off-half inputs to this half) and there is no
7966           // free slot adjacent to one of the inputs. In this case, we have to
7967           // swap an input with a non-input.
7968           for (int i = 0; i < 4; ++i)
7969             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7970                    "We can't handle any clobbers here!");
7971           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7972                  "Cannot have adjacent inputs here!");
7973
7974           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7975           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7976
7977           // We also have to update the final source mask in this case because
7978           // it may need to undo the above swap.
7979           for (int &M : FinalSourceHalfMask)
7980             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7981               M = InputsFixed[1] + SourceOffset;
7982             else if (M == InputsFixed[1] + SourceOffset)
7983               M = (InputsFixed[0] ^ 1) + SourceOffset;
7984
7985           InputsFixed[1] = InputsFixed[0] ^ 1;
7986         }
7987
7988         // Point everything at the fixed inputs.
7989         for (int &M : HalfMask)
7990           if (M == IncomingInputs[0])
7991             M = InputsFixed[0] + SourceOffset;
7992           else if (M == IncomingInputs[1])
7993             M = InputsFixed[1] + SourceOffset;
7994
7995         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7996         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7997       }
7998     } else {
7999       llvm_unreachable("Unhandled input size!");
8000     }
8001
8002     // Now hoist the DWord down to the right half.
8003     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8004     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8005     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8006     for (int &M : HalfMask)
8007       for (int Input : IncomingInputs)
8008         if (M == Input)
8009           M = FreeDWord * 2 + Input % 2;
8010   };
8011   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8012                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8013   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8014                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8015
8016   // Now enact all the shuffles we've computed to move the inputs into their
8017   // target half.
8018   if (!isNoopShuffleMask(PSHUFLMask))
8019     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8020                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8021   if (!isNoopShuffleMask(PSHUFHMask))
8022     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8023                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8024   if (!isNoopShuffleMask(PSHUFDMask))
8025     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8026                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8027                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8028                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8029
8030   // At this point, each half should contain all its inputs, and we can then
8031   // just shuffle them into their final position.
8032   assert(std::count_if(LoMask.begin(), LoMask.end(),
8033                        [](int M) { return M >= 4; }) == 0 &&
8034          "Failed to lift all the high half inputs to the low mask!");
8035   assert(std::count_if(HiMask.begin(), HiMask.end(),
8036                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8037          "Failed to lift all the low half inputs to the high mask!");
8038
8039   // Do a half shuffle for the low mask.
8040   if (!isNoopShuffleMask(LoMask))
8041     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8042                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8043
8044   // Do a half shuffle with the high mask after shifting its values down.
8045   for (int &M : HiMask)
8046     if (M >= 0)
8047       M -= 4;
8048   if (!isNoopShuffleMask(HiMask))
8049     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8050                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8051
8052   return V;
8053 }
8054
8055 /// \brief Detect whether the mask pattern should be lowered through
8056 /// interleaving.
8057 ///
8058 /// This essentially tests whether viewing the mask as an interleaving of two
8059 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
8060 /// lowering it through interleaving is a significantly better strategy.
8061 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
8062   int NumEvenInputs[2] = {0, 0};
8063   int NumOddInputs[2] = {0, 0};
8064   int NumLoInputs[2] = {0, 0};
8065   int NumHiInputs[2] = {0, 0};
8066   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
8067     if (Mask[i] < 0)
8068       continue;
8069
8070     int InputIdx = Mask[i] >= Size;
8071
8072     if (i < Size / 2)
8073       ++NumLoInputs[InputIdx];
8074     else
8075       ++NumHiInputs[InputIdx];
8076
8077     if ((i % 2) == 0)
8078       ++NumEvenInputs[InputIdx];
8079     else
8080       ++NumOddInputs[InputIdx];
8081   }
8082
8083   // The minimum number of cross-input results for both the interleaved and
8084   // split cases. If interleaving results in fewer cross-input results, return
8085   // true.
8086   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
8087                                     NumEvenInputs[0] + NumOddInputs[1]);
8088   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
8089                               NumLoInputs[0] + NumHiInputs[1]);
8090   return InterleavedCrosses < SplitCrosses;
8091 }
8092
8093 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
8094 ///
8095 /// This strategy only works when the inputs from each vector fit into a single
8096 /// half of that vector, and generally there are not so many inputs as to leave
8097 /// the in-place shuffles required highly constrained (and thus expensive). It
8098 /// shifts all the inputs into a single side of both input vectors and then
8099 /// uses an unpack to interleave these inputs in a single vector. At that
8100 /// point, we will fall back on the generic single input shuffle lowering.
8101 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
8102                                                  SDValue V2,
8103                                                  MutableArrayRef<int> Mask,
8104                                                  const X86Subtarget *Subtarget,
8105                                                  SelectionDAG &DAG) {
8106   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8107   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8108   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
8109   for (int i = 0; i < 8; ++i)
8110     if (Mask[i] >= 0 && Mask[i] < 4)
8111       LoV1Inputs.push_back(i);
8112     else if (Mask[i] >= 4 && Mask[i] < 8)
8113       HiV1Inputs.push_back(i);
8114     else if (Mask[i] >= 8 && Mask[i] < 12)
8115       LoV2Inputs.push_back(i);
8116     else if (Mask[i] >= 12)
8117       HiV2Inputs.push_back(i);
8118
8119   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
8120   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
8121   (void)NumV1Inputs;
8122   (void)NumV2Inputs;
8123   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
8124   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
8125   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
8126
8127   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
8128                      HiV1Inputs.size() + HiV2Inputs.size();
8129
8130   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
8131                               ArrayRef<int> HiInputs, bool MoveToLo,
8132                               int MaskOffset) {
8133     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
8134     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
8135     if (BadInputs.empty())
8136       return V;
8137
8138     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8139     int MoveOffset = MoveToLo ? 0 : 4;
8140
8141     if (GoodInputs.empty()) {
8142       for (int BadInput : BadInputs) {
8143         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
8144         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
8145       }
8146     } else {
8147       if (GoodInputs.size() == 2) {
8148         // If the low inputs are spread across two dwords, pack them into
8149         // a single dword.
8150         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
8151         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
8152         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
8153         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
8154       } else {
8155         // Otherwise pin the good inputs.
8156         for (int GoodInput : GoodInputs)
8157           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
8158       }
8159
8160       if (BadInputs.size() == 2) {
8161         // If we have two bad inputs then there may be either one or two good
8162         // inputs fixed in place. Find a fixed input, and then find the *other*
8163         // two adjacent indices by using modular arithmetic.
8164         int GoodMaskIdx =
8165             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
8166                          [](int M) { return M >= 0; }) -
8167             std::begin(MoveMask);
8168         int MoveMaskIdx =
8169             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
8170         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
8171         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
8172         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8173         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
8174         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8175         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
8176       } else {
8177         assert(BadInputs.size() == 1 && "All sizes handled");
8178         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
8179                                     std::end(MoveMask), -1) -
8180                           std::begin(MoveMask);
8181         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8182         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8183       }
8184     }
8185
8186     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8187                                 MoveMask);
8188   };
8189   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
8190                         /*MaskOffset*/ 0);
8191   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
8192                         /*MaskOffset*/ 8);
8193
8194   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
8195   // cross-half traffic in the final shuffle.
8196
8197   // Munge the mask to be a single-input mask after the unpack merges the
8198   // results.
8199   for (int &M : Mask)
8200     if (M != -1)
8201       M = 2 * (M % 4) + (M / 8);
8202
8203   return DAG.getVectorShuffle(
8204       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
8205                                   DL, MVT::v8i16, V1, V2),
8206       DAG.getUNDEF(MVT::v8i16), Mask);
8207 }
8208
8209 /// \brief Generic lowering of 8-lane i16 shuffles.
8210 ///
8211 /// This handles both single-input shuffles and combined shuffle/blends with
8212 /// two inputs. The single input shuffles are immediately delegated to
8213 /// a dedicated lowering routine.
8214 ///
8215 /// The blends are lowered in one of three fundamental ways. If there are few
8216 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8217 /// of the input is significantly cheaper when lowered as an interleaving of
8218 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8219 /// halves of the inputs separately (making them have relatively few inputs)
8220 /// and then concatenate them.
8221 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8222                                        const X86Subtarget *Subtarget,
8223                                        SelectionDAG &DAG) {
8224   SDLoc DL(Op);
8225   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8226   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8227   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8228   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8229   ArrayRef<int> OrigMask = SVOp->getMask();
8230   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8231                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8232   MutableArrayRef<int> Mask(MaskStorage);
8233
8234   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8235
8236   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8237   auto isV2 = [](int M) { return M >= 8; };
8238
8239   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
8240   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8241
8242   if (NumV2Inputs == 0)
8243     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8244
8245   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
8246                             "to be V1-input shuffles.");
8247
8248   // There are special ways we can lower some single-element blends.
8249   if (NumV2Inputs == 1)
8250     if (SDValue V = lowerIntegerElementInsertionVectorShuffle(
8251             MVT::v8i16, DL, V1, V2, Mask, Subtarget, DAG))
8252       return V;
8253
8254   if (NumV1Inputs + NumV2Inputs <= 4)
8255     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
8256
8257   // Check whether an interleaving lowering is likely to be more efficient.
8258   // This isn't perfect but it is a strong heuristic that tends to work well on
8259   // the kinds of shuffles that show up in practice.
8260   //
8261   // FIXME: Handle 1x, 2x, and 4x interleaving.
8262   if (shouldLowerAsInterleaving(Mask)) {
8263     // FIXME: Figure out whether we should pack these into the low or high
8264     // halves.
8265
8266     int EMask[8], OMask[8];
8267     for (int i = 0; i < 4; ++i) {
8268       EMask[i] = Mask[2*i];
8269       OMask[i] = Mask[2*i + 1];
8270       EMask[i + 4] = -1;
8271       OMask[i + 4] = -1;
8272     }
8273
8274     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8275     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8276
8277     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8278   }
8279
8280   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8281   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8282
8283   for (int i = 0; i < 4; ++i) {
8284     LoBlendMask[i] = Mask[i];
8285     HiBlendMask[i] = Mask[i + 4];
8286   }
8287
8288   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8289   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8290   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8291   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8292
8293   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8294                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8295 }
8296
8297 /// \brief Check whether a compaction lowering can be done by dropping even
8298 /// elements and compute how many times even elements must be dropped.
8299 ///
8300 /// This handles shuffles which take every Nth element where N is a power of
8301 /// two. Example shuffle masks:
8302 ///
8303 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8304 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8305 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8306 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8307 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8308 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8309 ///
8310 /// Any of these lanes can of course be undef.
8311 ///
8312 /// This routine only supports N <= 3.
8313 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8314 /// for larger N.
8315 ///
8316 /// \returns N above, or the number of times even elements must be dropped if
8317 /// there is such a number. Otherwise returns zero.
8318 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8319   // Figure out whether we're looping over two inputs or just one.
8320   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8321
8322   // The modulus for the shuffle vector entries is based on whether this is
8323   // a single input or not.
8324   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8325   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8326          "We should only be called with masks with a power-of-2 size!");
8327
8328   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8329
8330   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8331   // and 2^3 simultaneously. This is because we may have ambiguity with
8332   // partially undef inputs.
8333   bool ViableForN[3] = {true, true, true};
8334
8335   for (int i = 0, e = Mask.size(); i < e; ++i) {
8336     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8337     // want.
8338     if (Mask[i] == -1)
8339       continue;
8340
8341     bool IsAnyViable = false;
8342     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8343       if (ViableForN[j]) {
8344         uint64_t N = j + 1;
8345
8346         // The shuffle mask must be equal to (i * 2^N) % M.
8347         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8348           IsAnyViable = true;
8349         else
8350           ViableForN[j] = false;
8351       }
8352     // Early exit if we exhaust the possible powers of two.
8353     if (!IsAnyViable)
8354       break;
8355   }
8356
8357   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8358     if (ViableForN[j])
8359       return j + 1;
8360
8361   // Return 0 as there is no viable power of two.
8362   return 0;
8363 }
8364
8365 /// \brief Generic lowering of v16i8 shuffles.
8366 ///
8367 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8368 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8369 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8370 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8371 /// back together.
8372 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8373                                        const X86Subtarget *Subtarget,
8374                                        SelectionDAG &DAG) {
8375   SDLoc DL(Op);
8376   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8377   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8378   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8379   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8380   ArrayRef<int> OrigMask = SVOp->getMask();
8381   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8382   int MaskStorage[16] = {
8383       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8384       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8385       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8386       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8387   MutableArrayRef<int> Mask(MaskStorage);
8388   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8389   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8390
8391   int NumV2Elements =
8392       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8393
8394   // For single-input shuffles, there are some nicer lowering tricks we can use.
8395   if (NumV2Elements == 0) {
8396     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8397     // Notably, this handles splat and partial-splat shuffles more efficiently.
8398     // However, it only makes sense if the pre-duplication shuffle simplifies
8399     // things significantly. Currently, this means we need to be able to
8400     // express the pre-duplication shuffle as an i16 shuffle.
8401     //
8402     // FIXME: We should check for other patterns which can be widened into an
8403     // i16 shuffle as well.
8404     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8405       for (int i = 0; i < 16; i += 2) {
8406         if (Mask[i] != Mask[i + 1])
8407           return false;
8408       }
8409       return true;
8410     };
8411     auto tryToWidenViaDuplication = [&]() -> SDValue {
8412       if (!canWidenViaDuplication(Mask))
8413         return SDValue();
8414       SmallVector<int, 4> LoInputs;
8415       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8416                    [](int M) { return M >= 0 && M < 8; });
8417       std::sort(LoInputs.begin(), LoInputs.end());
8418       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8419                      LoInputs.end());
8420       SmallVector<int, 4> HiInputs;
8421       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8422                    [](int M) { return M >= 8; });
8423       std::sort(HiInputs.begin(), HiInputs.end());
8424       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8425                      HiInputs.end());
8426
8427       bool TargetLo = LoInputs.size() >= HiInputs.size();
8428       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8429       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8430
8431       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8432       SmallDenseMap<int, int, 8> LaneMap;
8433       for (int I : InPlaceInputs) {
8434         PreDupI16Shuffle[I/2] = I/2;
8435         LaneMap[I] = I;
8436       }
8437       int j = TargetLo ? 0 : 4, je = j + 4;
8438       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8439         // Check if j is already a shuffle of this input. This happens when
8440         // there are two adjacent bytes after we move the low one.
8441         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8442           // If we haven't yet mapped the input, search for a slot into which
8443           // we can map it.
8444           while (j < je && PreDupI16Shuffle[j] != -1)
8445             ++j;
8446
8447           if (j == je)
8448             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8449             return SDValue();
8450
8451           // Map this input with the i16 shuffle.
8452           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8453         }
8454
8455         // Update the lane map based on the mapping we ended up with.
8456         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8457       }
8458       V1 = DAG.getNode(
8459           ISD::BITCAST, DL, MVT::v16i8,
8460           DAG.getVectorShuffle(MVT::v8i16, DL,
8461                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8462                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8463
8464       // Unpack the bytes to form the i16s that will be shuffled into place.
8465       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8466                        MVT::v16i8, V1, V1);
8467
8468       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8469       for (int i = 0; i < 16; i += 2) {
8470         if (Mask[i] != -1)
8471           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8472         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8473       }
8474       return DAG.getNode(
8475           ISD::BITCAST, DL, MVT::v16i8,
8476           DAG.getVectorShuffle(MVT::v8i16, DL,
8477                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8478                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8479     };
8480     if (SDValue V = tryToWidenViaDuplication())
8481       return V;
8482   }
8483
8484   // Check whether an interleaving lowering is likely to be more efficient.
8485   // This isn't perfect but it is a strong heuristic that tends to work well on
8486   // the kinds of shuffles that show up in practice.
8487   //
8488   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8489   if (shouldLowerAsInterleaving(Mask)) {
8490     // FIXME: Figure out whether we should pack these into the low or high
8491     // halves.
8492
8493     int EMask[16], OMask[16];
8494     for (int i = 0; i < 8; ++i) {
8495       EMask[i] = Mask[2*i];
8496       OMask[i] = Mask[2*i + 1];
8497       EMask[i + 8] = -1;
8498       OMask[i + 8] = -1;
8499     }
8500
8501     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8502     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8503
8504     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8505   }
8506
8507   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8508   // with PSHUFB. It is important to do this before we attempt to generate any
8509   // blends but after all of the single-input lowerings. If the single input
8510   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8511   // want to preserve that and we can DAG combine any longer sequences into
8512   // a PSHUFB in the end. But once we start blending from multiple inputs,
8513   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8514   // and there are *very* few patterns that would actually be faster than the
8515   // PSHUFB approach because of its ability to zero lanes.
8516   //
8517   // FIXME: The only exceptions to the above are blends which are exact
8518   // interleavings with direct instructions supporting them. We currently don't
8519   // handle those well here.
8520   if (Subtarget->hasSSSE3()) {
8521     SDValue V1Mask[16];
8522     SDValue V2Mask[16];
8523     for (int i = 0; i < 16; ++i)
8524       if (Mask[i] == -1) {
8525         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8526       } else {
8527         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8528         V2Mask[i] =
8529             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8530       }
8531     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8532                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8533     if (isSingleInputShuffleMask(Mask))
8534       return V1; // Single inputs are easy.
8535
8536     // Otherwise, blend the two.
8537     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8538                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8539     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8540   }
8541
8542   // There are special ways we can lower some single-element blends.
8543   if (NumV2Elements == 1)
8544     if (SDValue V = lowerIntegerElementInsertionVectorShuffle(
8545             MVT::v16i8, DL, V1, V2, Mask, Subtarget, DAG))
8546       return V;
8547
8548   // Check whether a compaction lowering can be done. This handles shuffles
8549   // which take every Nth element for some even N. See the helper function for
8550   // details.
8551   //
8552   // We special case these as they can be particularly efficiently handled with
8553   // the PACKUSB instruction on x86 and they show up in common patterns of
8554   // rearranging bytes to truncate wide elements.
8555   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8556     // NumEvenDrops is the power of two stride of the elements. Another way of
8557     // thinking about it is that we need to drop the even elements this many
8558     // times to get the original input.
8559     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8560
8561     // First we need to zero all the dropped bytes.
8562     assert(NumEvenDrops <= 3 &&
8563            "No support for dropping even elements more than 3 times.");
8564     // We use the mask type to pick which bytes are preserved based on how many
8565     // elements are dropped.
8566     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8567     SDValue ByteClearMask =
8568         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8569                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8570     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8571     if (!IsSingleInput)
8572       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8573
8574     // Now pack things back together.
8575     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8576     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8577     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8578     for (int i = 1; i < NumEvenDrops; ++i) {
8579       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8580       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8581     }
8582
8583     return Result;
8584   }
8585
8586   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8587   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8588   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8589   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8590
8591   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8592                             MutableArrayRef<int> V1HalfBlendMask,
8593                             MutableArrayRef<int> V2HalfBlendMask) {
8594     for (int i = 0; i < 8; ++i)
8595       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8596         V1HalfBlendMask[i] = HalfMask[i];
8597         HalfMask[i] = i;
8598       } else if (HalfMask[i] >= 16) {
8599         V2HalfBlendMask[i] = HalfMask[i] - 16;
8600         HalfMask[i] = i + 8;
8601       }
8602   };
8603   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8604   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8605
8606   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8607
8608   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8609                              MutableArrayRef<int> HiBlendMask) {
8610     SDValue V1, V2;
8611     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8612     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8613     // i16s.
8614     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8615                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8616         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8617                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8618       // Use a mask to drop the high bytes.
8619       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8620       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8621                        DAG.getConstant(0x00FF, MVT::v8i16));
8622
8623       // This will be a single vector shuffle instead of a blend so nuke V2.
8624       V2 = DAG.getUNDEF(MVT::v8i16);
8625
8626       // Squash the masks to point directly into V1.
8627       for (int &M : LoBlendMask)
8628         if (M >= 0)
8629           M /= 2;
8630       for (int &M : HiBlendMask)
8631         if (M >= 0)
8632           M /= 2;
8633     } else {
8634       // Otherwise just unpack the low half of V into V1 and the high half into
8635       // V2 so that we can blend them as i16s.
8636       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8637                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8638       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8639                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8640     }
8641
8642     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8643     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8644     return std::make_pair(BlendedLo, BlendedHi);
8645   };
8646   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8647   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8648   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8649
8650   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8651   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8652
8653   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8654 }
8655
8656 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8657 ///
8658 /// This routine breaks down the specific type of 128-bit shuffle and
8659 /// dispatches to the lowering routines accordingly.
8660 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8661                                         MVT VT, const X86Subtarget *Subtarget,
8662                                         SelectionDAG &DAG) {
8663   switch (VT.SimpleTy) {
8664   case MVT::v2i64:
8665     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8666   case MVT::v2f64:
8667     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8668   case MVT::v4i32:
8669     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8670   case MVT::v4f32:
8671     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8672   case MVT::v8i16:
8673     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8674   case MVT::v16i8:
8675     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8676
8677   default:
8678     llvm_unreachable("Unimplemented!");
8679   }
8680 }
8681
8682 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8683   int Size = Mask.size();
8684   for (int M : Mask.slice(0, Size / 2))
8685     if (M >= 0 && (M % Size) >= Size / 2)
8686       return true;
8687   for (int M : Mask.slice(Size / 2, Size / 2))
8688     if (M >= 0 && (M % Size) < Size / 2)
8689       return true;
8690   return false;
8691 }
8692
8693 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8694 /// shuffles.
8695 ///
8696 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8697 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8698 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8699 /// we encode the logic here for specific shuffle lowering routines to bail to
8700 /// when they exhaust the features avaible to more directly handle the shuffle.
8701 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8702                                                 SDValue V2,
8703                                                 const X86Subtarget *Subtarget,
8704                                                 SelectionDAG &DAG) {
8705   SDLoc DL(Op);
8706   MVT VT = Op.getSimpleValueType();
8707   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8708   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8709   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8710   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8711   ArrayRef<int> Mask = SVOp->getMask();
8712
8713   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8714   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8715
8716   int NumElements = VT.getVectorNumElements();
8717   int SplitNumElements = NumElements / 2;
8718   MVT ScalarVT = VT.getScalarType();
8719   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8720
8721   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8722                              DAG.getIntPtrConstant(0));
8723   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8724                              DAG.getIntPtrConstant(SplitNumElements));
8725   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8726                              DAG.getIntPtrConstant(0));
8727   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8728                              DAG.getIntPtrConstant(SplitNumElements));
8729
8730   // Now create two 4-way blends of these half-width vectors.
8731   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8732     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8733     for (int i = 0; i < SplitNumElements; ++i) {
8734       int M = HalfMask[i];
8735       if (M >= NumElements) {
8736         V2BlendMask.push_back(M - NumElements);
8737         V1BlendMask.push_back(-1);
8738         BlendMask.push_back(SplitNumElements + i);
8739       } else if (M >= 0) {
8740         V2BlendMask.push_back(-1);
8741         V1BlendMask.push_back(M);
8742         BlendMask.push_back(i);
8743       } else {
8744         V2BlendMask.push_back(-1);
8745         V1BlendMask.push_back(-1);
8746         BlendMask.push_back(-1);
8747       }
8748     }
8749     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8750     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8751     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8752   };
8753   SDValue Lo = HalfBlend(LoMask);
8754   SDValue Hi = HalfBlend(HiMask);
8755   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8756 }
8757
8758 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8759 ///
8760 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8761 /// isn't available.
8762 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8763                                        const X86Subtarget *Subtarget,
8764                                        SelectionDAG &DAG) {
8765   SDLoc DL(Op);
8766   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8767   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8768   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8769   ArrayRef<int> Mask = SVOp->getMask();
8770   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8771
8772   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8773   // shuffles aren't a problem and FP and int have the same patterns.
8774
8775   // FIXME: We can handle these more cleverly than splitting for v4f64.
8776   if (isHalfCrossingShuffleMask(Mask))
8777     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8778
8779   if (isSingleInputShuffleMask(Mask)) {
8780     // Non-half-crossing single input shuffles can be lowerid with an
8781     // interleaved permutation.
8782     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8783                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8784     return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8785                        DAG.getConstant(VPERMILPMask, MVT::i8));
8786   }
8787
8788   // X86 has dedicated unpack instructions that can handle specific blend
8789   // operations: UNPCKH and UNPCKL.
8790   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8791     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8792   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8793     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8794   // FIXME: It would be nice to find a way to get canonicalization to commute
8795   // these patterns.
8796   if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8797     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8798   if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8799     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8800
8801   // Check if the blend happens to exactly fit that of SHUFPD.
8802   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8803       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8804     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8805                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8806     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8807                        DAG.getConstant(SHUFPDMask, MVT::i8));
8808   }
8809   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8810       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8811     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8812                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8813     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8814                        DAG.getConstant(SHUFPDMask, MVT::i8));
8815   }
8816
8817   // Shuffle the input elements into the desired positions in V1 and V2 and
8818   // blend them together.
8819   int V1Mask[] = {-1, -1, -1, -1};
8820   int V2Mask[] = {-1, -1, -1, -1};
8821   for (int i = 0; i < 4; ++i)
8822     if (Mask[i] >= 0 && Mask[i] < 4)
8823       V1Mask[i] = Mask[i];
8824     else if (Mask[i] >= 4)
8825       V2Mask[i] = Mask[i] - 4;
8826
8827   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8828   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8829
8830   unsigned BlendMask = 0;
8831   for (int i = 0; i < 4; ++i)
8832     if (Mask[i] >= 4)
8833       BlendMask |= 1 << i;
8834
8835   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8836                      DAG.getConstant(BlendMask, MVT::i8));
8837 }
8838
8839 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8840 ///
8841 /// Largely delegates to common code when we have AVX2 and to the floating-point
8842 /// code when we only have AVX.
8843 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8844                                        const X86Subtarget *Subtarget,
8845                                        SelectionDAG &DAG) {
8846   SDLoc DL(Op);
8847   assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8848   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8849   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8850   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8851   ArrayRef<int> Mask = SVOp->getMask();
8852   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8853
8854   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8855   // shuffles aren't a problem and FP and int have the same patterns.
8856
8857   if (isHalfCrossingShuffleMask(Mask))
8858     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8859
8860   // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8861   // delegate to floating point code.
8862   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8863   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8864   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8865                      lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8866 }
8867
8868 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8869 ///
8870 /// This routine either breaks down the specific type of a 256-bit x86 vector
8871 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8872 /// together based on the available instructions.
8873 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8874                                         MVT VT, const X86Subtarget *Subtarget,
8875                                         SelectionDAG &DAG) {
8876   switch (VT.SimpleTy) {
8877   case MVT::v4f64:
8878     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8879   case MVT::v4i64:
8880     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8881   case MVT::v8i32:
8882   case MVT::v8f32:
8883   case MVT::v16i16:
8884   case MVT::v32i8:
8885     // Fall back to the basic pattern of extracting the high half and forming
8886     // a 4-way blend.
8887     // FIXME: Add targeted lowering for each type that can document rationale
8888     // for delegating to this when necessary.
8889     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8890
8891   default:
8892     llvm_unreachable("Not a valid 256-bit x86 vector type!");
8893   }
8894 }
8895
8896 /// \brief Tiny helper function to test whether a shuffle mask could be
8897 /// simplified by widening the elements being shuffled.
8898 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8899   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8900     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8901       return false;
8902
8903   return true;
8904 }
8905
8906 /// \brief Top-level lowering for x86 vector shuffles.
8907 ///
8908 /// This handles decomposition, canonicalization, and lowering of all x86
8909 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8910 /// above in helper routines. The canonicalization attempts to widen shuffles
8911 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8912 /// s.t. only one of the two inputs needs to be tested, etc.
8913 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8914                                   SelectionDAG &DAG) {
8915   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8916   ArrayRef<int> Mask = SVOp->getMask();
8917   SDValue V1 = Op.getOperand(0);
8918   SDValue V2 = Op.getOperand(1);
8919   MVT VT = Op.getSimpleValueType();
8920   int NumElements = VT.getVectorNumElements();
8921   SDLoc dl(Op);
8922
8923   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8924
8925   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8926   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8927   if (V1IsUndef && V2IsUndef)
8928     return DAG.getUNDEF(VT);
8929
8930   // When we create a shuffle node we put the UNDEF node to second operand,
8931   // but in some cases the first operand may be transformed to UNDEF.
8932   // In this case we should just commute the node.
8933   if (V1IsUndef)
8934     return DAG.getCommutedVectorShuffle(*SVOp);
8935
8936   // Check for non-undef masks pointing at an undef vector and make the masks
8937   // undef as well. This makes it easier to match the shuffle based solely on
8938   // the mask.
8939   if (V2IsUndef)
8940     for (int M : Mask)
8941       if (M >= NumElements) {
8942         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8943         for (int &M : NewMask)
8944           if (M >= NumElements)
8945             M = -1;
8946         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8947       }
8948
8949   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8950   // lanes but wider integers. We cap this to not form integers larger than i64
8951   // but it might be interesting to form i128 integers to handle flipping the
8952   // low and high halves of AVX 256-bit vectors.
8953   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8954       canWidenShuffleElements(Mask)) {
8955     SmallVector<int, 8> NewMask;
8956     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8957       NewMask.push_back(Mask[i] / 2);
8958     MVT NewVT =
8959         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8960                          VT.getVectorNumElements() / 2);
8961     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8962     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8963     return DAG.getNode(ISD::BITCAST, dl, VT,
8964                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8965   }
8966
8967   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8968   for (int M : SVOp->getMask())
8969     if (M < 0)
8970       ++NumUndefElements;
8971     else if (M < NumElements)
8972       ++NumV1Elements;
8973     else
8974       ++NumV2Elements;
8975
8976   // Commute the shuffle as needed such that more elements come from V1 than
8977   // V2. This allows us to match the shuffle pattern strictly on how many
8978   // elements come from V1 without handling the symmetric cases.
8979   if (NumV2Elements > NumV1Elements)
8980     return DAG.getCommutedVectorShuffle(*SVOp);
8981
8982   // When the number of V1 and V2 elements are the same, try to minimize the
8983   // number of uses of V2 in the low half of the vector.
8984   if (NumV1Elements == NumV2Elements) {
8985     int LowV1Elements = 0, LowV2Elements = 0;
8986     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8987       if (M >= NumElements)
8988         ++LowV2Elements;
8989       else if (M >= 0)
8990         ++LowV1Elements;
8991     if (LowV2Elements > LowV1Elements)
8992       return DAG.getCommutedVectorShuffle(*SVOp);
8993   }
8994
8995   // For each vector width, delegate to a specialized lowering routine.
8996   if (VT.getSizeInBits() == 128)
8997     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8998
8999   if (VT.getSizeInBits() == 256)
9000     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
9001
9002   llvm_unreachable("Unimplemented!");
9003 }
9004
9005
9006 //===----------------------------------------------------------------------===//
9007 // Legacy vector shuffle lowering
9008 //
9009 // This code is the legacy code handling vector shuffles until the above
9010 // replaces its functionality and performance.
9011 //===----------------------------------------------------------------------===//
9012
9013 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
9014                         bool hasInt256, unsigned *MaskOut = nullptr) {
9015   MVT EltVT = VT.getVectorElementType();
9016
9017   // There is no blend with immediate in AVX-512.
9018   if (VT.is512BitVector())
9019     return false;
9020
9021   if (!hasSSE41 || EltVT == MVT::i8)
9022     return false;
9023   if (!hasInt256 && VT == MVT::v16i16)
9024     return false;
9025
9026   unsigned MaskValue = 0;
9027   unsigned NumElems = VT.getVectorNumElements();
9028   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9029   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9030   unsigned NumElemsInLane = NumElems / NumLanes;
9031
9032   // Blend for v16i16 should be symetric for the both lanes.
9033   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9034
9035     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
9036     int EltIdx = MaskVals[i];
9037
9038     if ((EltIdx < 0 || EltIdx == (int)i) &&
9039         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
9040       continue;
9041
9042     if (((unsigned)EltIdx == (i + NumElems)) &&
9043         (SndLaneEltIdx < 0 ||
9044          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
9045       MaskValue |= (1 << i);
9046     else
9047       return false;
9048   }
9049
9050   if (MaskOut)
9051     *MaskOut = MaskValue;
9052   return true;
9053 }
9054
9055 // Try to lower a shuffle node into a simple blend instruction.
9056 // This function assumes isBlendMask returns true for this
9057 // SuffleVectorSDNode
9058 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
9059                                           unsigned MaskValue,
9060                                           const X86Subtarget *Subtarget,
9061                                           SelectionDAG &DAG) {
9062   MVT VT = SVOp->getSimpleValueType(0);
9063   MVT EltVT = VT.getVectorElementType();
9064   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
9065                      Subtarget->hasInt256() && "Trying to lower a "
9066                                                "VECTOR_SHUFFLE to a Blend but "
9067                                                "with the wrong mask"));
9068   SDValue V1 = SVOp->getOperand(0);
9069   SDValue V2 = SVOp->getOperand(1);
9070   SDLoc dl(SVOp);
9071   unsigned NumElems = VT.getVectorNumElements();
9072
9073   // Convert i32 vectors to floating point if it is not AVX2.
9074   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9075   MVT BlendVT = VT;
9076   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9077     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9078                                NumElems);
9079     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
9080     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
9081   }
9082
9083   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
9084                             DAG.getConstant(MaskValue, MVT::i32));
9085   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9086 }
9087
9088 /// In vector type \p VT, return true if the element at index \p InputIdx
9089 /// falls on a different 128-bit lane than \p OutputIdx.
9090 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
9091                                      unsigned OutputIdx) {
9092   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
9093   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
9094 }
9095
9096 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
9097 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
9098 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
9099 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
9100 /// zero.
9101 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
9102                          SelectionDAG &DAG) {
9103   MVT VT = V1.getSimpleValueType();
9104   assert(VT.is128BitVector() || VT.is256BitVector());
9105
9106   MVT EltVT = VT.getVectorElementType();
9107   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
9108   unsigned NumElts = VT.getVectorNumElements();
9109
9110   SmallVector<SDValue, 32> PshufbMask;
9111   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
9112     int InputIdx = MaskVals[OutputIdx];
9113     unsigned InputByteIdx;
9114
9115     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
9116       InputByteIdx = 0x80;
9117     else {
9118       // Cross lane is not allowed.
9119       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
9120         return SDValue();
9121       InputByteIdx = InputIdx * EltSizeInBytes;
9122       // Index is an byte offset within the 128-bit lane.
9123       InputByteIdx &= 0xf;
9124     }
9125
9126     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
9127       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
9128       if (InputByteIdx != 0x80)
9129         ++InputByteIdx;
9130     }
9131   }
9132
9133   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
9134   if (ShufVT != VT)
9135     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
9136   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
9137                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
9138 }
9139
9140 // v8i16 shuffles - Prefer shuffles in the following order:
9141 // 1. [all]   pshuflw, pshufhw, optional move
9142 // 2. [ssse3] 1 x pshufb
9143 // 3. [ssse3] 2 x pshufb + 1 x por
9144 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
9145 static SDValue
9146 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
9147                          SelectionDAG &DAG) {
9148   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9149   SDValue V1 = SVOp->getOperand(0);
9150   SDValue V2 = SVOp->getOperand(1);
9151   SDLoc dl(SVOp);
9152   SmallVector<int, 8> MaskVals;
9153
9154   // Determine if more than 1 of the words in each of the low and high quadwords
9155   // of the result come from the same quadword of one of the two inputs.  Undef
9156   // mask values count as coming from any quadword, for better codegen.
9157   //
9158   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
9159   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
9160   unsigned LoQuad[] = { 0, 0, 0, 0 };
9161   unsigned HiQuad[] = { 0, 0, 0, 0 };
9162   // Indices of quads used.
9163   std::bitset<4> InputQuads;
9164   for (unsigned i = 0; i < 8; ++i) {
9165     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
9166     int EltIdx = SVOp->getMaskElt(i);
9167     MaskVals.push_back(EltIdx);
9168     if (EltIdx < 0) {
9169       ++Quad[0];
9170       ++Quad[1];
9171       ++Quad[2];
9172       ++Quad[3];
9173       continue;
9174     }
9175     ++Quad[EltIdx / 4];
9176     InputQuads.set(EltIdx / 4);
9177   }
9178
9179   int BestLoQuad = -1;
9180   unsigned MaxQuad = 1;
9181   for (unsigned i = 0; i < 4; ++i) {
9182     if (LoQuad[i] > MaxQuad) {
9183       BestLoQuad = i;
9184       MaxQuad = LoQuad[i];
9185     }
9186   }
9187
9188   int BestHiQuad = -1;
9189   MaxQuad = 1;
9190   for (unsigned i = 0; i < 4; ++i) {
9191     if (HiQuad[i] > MaxQuad) {
9192       BestHiQuad = i;
9193       MaxQuad = HiQuad[i];
9194     }
9195   }
9196
9197   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
9198   // of the two input vectors, shuffle them into one input vector so only a
9199   // single pshufb instruction is necessary. If there are more than 2 input
9200   // quads, disable the next transformation since it does not help SSSE3.
9201   bool V1Used = InputQuads[0] || InputQuads[1];
9202   bool V2Used = InputQuads[2] || InputQuads[3];
9203   if (Subtarget->hasSSSE3()) {
9204     if (InputQuads.count() == 2 && V1Used && V2Used) {
9205       BestLoQuad = InputQuads[0] ? 0 : 1;
9206       BestHiQuad = InputQuads[2] ? 2 : 3;
9207     }
9208     if (InputQuads.count() > 2) {
9209       BestLoQuad = -1;
9210       BestHiQuad = -1;
9211     }
9212   }
9213
9214   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
9215   // the shuffle mask.  If a quad is scored as -1, that means that it contains
9216   // words from all 4 input quadwords.
9217   SDValue NewV;
9218   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
9219     int MaskV[] = {
9220       BestLoQuad < 0 ? 0 : BestLoQuad,
9221       BestHiQuad < 0 ? 1 : BestHiQuad
9222     };
9223     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
9224                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
9225                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
9226     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
9227
9228     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
9229     // source words for the shuffle, to aid later transformations.
9230     bool AllWordsInNewV = true;
9231     bool InOrder[2] = { true, true };
9232     for (unsigned i = 0; i != 8; ++i) {
9233       int idx = MaskVals[i];
9234       if (idx != (int)i)
9235         InOrder[i/4] = false;
9236       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
9237         continue;
9238       AllWordsInNewV = false;
9239       break;
9240     }
9241
9242     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
9243     if (AllWordsInNewV) {
9244       for (int i = 0; i != 8; ++i) {
9245         int idx = MaskVals[i];
9246         if (idx < 0)
9247           continue;
9248         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
9249         if ((idx != i) && idx < 4)
9250           pshufhw = false;
9251         if ((idx != i) && idx > 3)
9252           pshuflw = false;
9253       }
9254       V1 = NewV;
9255       V2Used = false;
9256       BestLoQuad = 0;
9257       BestHiQuad = 1;
9258     }
9259
9260     // If we've eliminated the use of V2, and the new mask is a pshuflw or
9261     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
9262     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
9263       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
9264       unsigned TargetMask = 0;
9265       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
9266                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
9267       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9268       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
9269                              getShufflePSHUFLWImmediate(SVOp);
9270       V1 = NewV.getOperand(0);
9271       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
9272     }
9273   }
9274
9275   // Promote splats to a larger type which usually leads to more efficient code.
9276   // FIXME: Is this true if pshufb is available?
9277   if (SVOp->isSplat())
9278     return PromoteSplat(SVOp, DAG);
9279
9280   // If we have SSSE3, and all words of the result are from 1 input vector,
9281   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
9282   // is present, fall back to case 4.
9283   if (Subtarget->hasSSSE3()) {
9284     SmallVector<SDValue,16> pshufbMask;
9285
9286     // If we have elements from both input vectors, set the high bit of the
9287     // shuffle mask element to zero out elements that come from V2 in the V1
9288     // mask, and elements that come from V1 in the V2 mask, so that the two
9289     // results can be OR'd together.
9290     bool TwoInputs = V1Used && V2Used;
9291     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9292     if (!TwoInputs)
9293       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9294
9295     // Calculate the shuffle mask for the second input, shuffle it, and
9296     // OR it with the first shuffled input.
9297     CommuteVectorShuffleMask(MaskVals, 8);
9298     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9299     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9300     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9301   }
9302
9303   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9304   // and update MaskVals with new element order.
9305   std::bitset<8> InOrder;
9306   if (BestLoQuad >= 0) {
9307     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9308     for (int i = 0; i != 4; ++i) {
9309       int idx = MaskVals[i];
9310       if (idx < 0) {
9311         InOrder.set(i);
9312       } else if ((idx / 4) == BestLoQuad) {
9313         MaskV[i] = idx & 3;
9314         InOrder.set(i);
9315       }
9316     }
9317     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9318                                 &MaskV[0]);
9319
9320     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9321       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9322       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9323                                   NewV.getOperand(0),
9324                                   getShufflePSHUFLWImmediate(SVOp), DAG);
9325     }
9326   }
9327
9328   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9329   // and update MaskVals with the new element order.
9330   if (BestHiQuad >= 0) {
9331     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9332     for (unsigned i = 4; i != 8; ++i) {
9333       int idx = MaskVals[i];
9334       if (idx < 0) {
9335         InOrder.set(i);
9336       } else if ((idx / 4) == BestHiQuad) {
9337         MaskV[i] = (idx & 3) + 4;
9338         InOrder.set(i);
9339       }
9340     }
9341     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9342                                 &MaskV[0]);
9343
9344     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9345       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9346       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9347                                   NewV.getOperand(0),
9348                                   getShufflePSHUFHWImmediate(SVOp), DAG);
9349     }
9350   }
9351
9352   // In case BestHi & BestLo were both -1, which means each quadword has a word
9353   // from each of the four input quadwords, calculate the InOrder bitvector now
9354   // before falling through to the insert/extract cleanup.
9355   if (BestLoQuad == -1 && BestHiQuad == -1) {
9356     NewV = V1;
9357     for (int i = 0; i != 8; ++i)
9358       if (MaskVals[i] < 0 || MaskVals[i] == i)
9359         InOrder.set(i);
9360   }
9361
9362   // The other elements are put in the right place using pextrw and pinsrw.
9363   for (unsigned i = 0; i != 8; ++i) {
9364     if (InOrder[i])
9365       continue;
9366     int EltIdx = MaskVals[i];
9367     if (EltIdx < 0)
9368       continue;
9369     SDValue ExtOp = (EltIdx < 8) ?
9370       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9371                   DAG.getIntPtrConstant(EltIdx)) :
9372       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9373                   DAG.getIntPtrConstant(EltIdx - 8));
9374     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9375                        DAG.getIntPtrConstant(i));
9376   }
9377   return NewV;
9378 }
9379
9380 /// \brief v16i16 shuffles
9381 ///
9382 /// FIXME: We only support generation of a single pshufb currently.  We can
9383 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9384 /// well (e.g 2 x pshufb + 1 x por).
9385 static SDValue
9386 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9387   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9388   SDValue V1 = SVOp->getOperand(0);
9389   SDValue V2 = SVOp->getOperand(1);
9390   SDLoc dl(SVOp);
9391
9392   if (V2.getOpcode() != ISD::UNDEF)
9393     return SDValue();
9394
9395   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9396   return getPSHUFB(MaskVals, V1, dl, DAG);
9397 }
9398
9399 // v16i8 shuffles - Prefer shuffles in the following order:
9400 // 1. [ssse3] 1 x pshufb
9401 // 2. [ssse3] 2 x pshufb + 1 x por
9402 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
9403 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9404                                         const X86Subtarget* Subtarget,
9405                                         SelectionDAG &DAG) {
9406   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9407   SDValue V1 = SVOp->getOperand(0);
9408   SDValue V2 = SVOp->getOperand(1);
9409   SDLoc dl(SVOp);
9410   ArrayRef<int> MaskVals = SVOp->getMask();
9411
9412   // Promote splats to a larger type which usually leads to more efficient code.
9413   // FIXME: Is this true if pshufb is available?
9414   if (SVOp->isSplat())
9415     return PromoteSplat(SVOp, DAG);
9416
9417   // If we have SSSE3, case 1 is generated when all result bytes come from
9418   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
9419   // present, fall back to case 3.
9420
9421   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9422   if (Subtarget->hasSSSE3()) {
9423     SmallVector<SDValue,16> pshufbMask;
9424
9425     // If all result elements are from one input vector, then only translate
9426     // undef mask values to 0x80 (zero out result) in the pshufb mask.
9427     //
9428     // Otherwise, we have elements from both input vectors, and must zero out
9429     // elements that come from V2 in the first mask, and V1 in the second mask
9430     // so that we can OR them together.
9431     for (unsigned i = 0; i != 16; ++i) {
9432       int EltIdx = MaskVals[i];
9433       if (EltIdx < 0 || EltIdx >= 16)
9434         EltIdx = 0x80;
9435       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9436     }
9437     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9438                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9439                                  MVT::v16i8, pshufbMask));
9440
9441     // As PSHUFB will zero elements with negative indices, it's safe to ignore
9442     // the 2nd operand if it's undefined or zero.
9443     if (V2.getOpcode() == ISD::UNDEF ||
9444         ISD::isBuildVectorAllZeros(V2.getNode()))
9445       return V1;
9446
9447     // Calculate the shuffle mask for the second input, shuffle it, and
9448     // OR it with the first shuffled input.
9449     pshufbMask.clear();
9450     for (unsigned i = 0; i != 16; ++i) {
9451       int EltIdx = MaskVals[i];
9452       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9453       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9454     }
9455     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9456                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9457                                  MVT::v16i8, pshufbMask));
9458     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9459   }
9460
9461   // No SSSE3 - Calculate in place words and then fix all out of place words
9462   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
9463   // the 16 different words that comprise the two doublequadword input vectors.
9464   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9465   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9466   SDValue NewV = V1;
9467   for (int i = 0; i != 8; ++i) {
9468     int Elt0 = MaskVals[i*2];
9469     int Elt1 = MaskVals[i*2+1];
9470
9471     // This word of the result is all undef, skip it.
9472     if (Elt0 < 0 && Elt1 < 0)
9473       continue;
9474
9475     // This word of the result is already in the correct place, skip it.
9476     if ((Elt0 == i*2) && (Elt1 == i*2+1))
9477       continue;
9478
9479     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9480     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9481     SDValue InsElt;
9482
9483     // If Elt0 and Elt1 are defined, are consecutive, and can be load
9484     // using a single extract together, load it and store it.
9485     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9486       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9487                            DAG.getIntPtrConstant(Elt1 / 2));
9488       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9489                         DAG.getIntPtrConstant(i));
9490       continue;
9491     }
9492
9493     // If Elt1 is defined, extract it from the appropriate source.  If the
9494     // source byte is not also odd, shift the extracted word left 8 bits
9495     // otherwise clear the bottom 8 bits if we need to do an or.
9496     if (Elt1 >= 0) {
9497       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9498                            DAG.getIntPtrConstant(Elt1 / 2));
9499       if ((Elt1 & 1) == 0)
9500         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9501                              DAG.getConstant(8,
9502                                   TLI.getShiftAmountTy(InsElt.getValueType())));
9503       else if (Elt0 >= 0)
9504         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9505                              DAG.getConstant(0xFF00, MVT::i16));
9506     }
9507     // If Elt0 is defined, extract it from the appropriate source.  If the
9508     // source byte is not also even, shift the extracted word right 8 bits. If
9509     // Elt1 was also defined, OR the extracted values together before
9510     // inserting them in the result.
9511     if (Elt0 >= 0) {
9512       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9513                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9514       if ((Elt0 & 1) != 0)
9515         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9516                               DAG.getConstant(8,
9517                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
9518       else if (Elt1 >= 0)
9519         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9520                              DAG.getConstant(0x00FF, MVT::i16));
9521       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9522                          : InsElt0;
9523     }
9524     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9525                        DAG.getIntPtrConstant(i));
9526   }
9527   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9528 }
9529
9530 // v32i8 shuffles - Translate to VPSHUFB if possible.
9531 static
9532 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9533                                  const X86Subtarget *Subtarget,
9534                                  SelectionDAG &DAG) {
9535   MVT VT = SVOp->getSimpleValueType(0);
9536   SDValue V1 = SVOp->getOperand(0);
9537   SDValue V2 = SVOp->getOperand(1);
9538   SDLoc dl(SVOp);
9539   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9540
9541   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9542   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9543   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9544
9545   // VPSHUFB may be generated if
9546   // (1) one of input vector is undefined or zeroinitializer.
9547   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9548   // And (2) the mask indexes don't cross the 128-bit lane.
9549   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9550       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9551     return SDValue();
9552
9553   if (V1IsAllZero && !V2IsAllZero) {
9554     CommuteVectorShuffleMask(MaskVals, 32);
9555     V1 = V2;
9556   }
9557   return getPSHUFB(MaskVals, V1, dl, DAG);
9558 }
9559
9560 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9561 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9562 /// done when every pair / quad of shuffle mask elements point to elements in
9563 /// the right sequence. e.g.
9564 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9565 static
9566 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9567                                  SelectionDAG &DAG) {
9568   MVT VT = SVOp->getSimpleValueType(0);
9569   SDLoc dl(SVOp);
9570   unsigned NumElems = VT.getVectorNumElements();
9571   MVT NewVT;
9572   unsigned Scale;
9573   switch (VT.SimpleTy) {
9574   default: llvm_unreachable("Unexpected!");
9575   case MVT::v2i64:
9576   case MVT::v2f64:
9577            return SDValue(SVOp, 0);
9578   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9579   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9580   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9581   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9582   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9583   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9584   }
9585
9586   SmallVector<int, 8> MaskVec;
9587   for (unsigned i = 0; i != NumElems; i += Scale) {
9588     int StartIdx = -1;
9589     for (unsigned j = 0; j != Scale; ++j) {
9590       int EltIdx = SVOp->getMaskElt(i+j);
9591       if (EltIdx < 0)
9592         continue;
9593       if (StartIdx < 0)
9594         StartIdx = (EltIdx / Scale);
9595       if (EltIdx != (int)(StartIdx*Scale + j))
9596         return SDValue();
9597     }
9598     MaskVec.push_back(StartIdx);
9599   }
9600
9601   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9602   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9603   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9604 }
9605
9606 /// getVZextMovL - Return a zero-extending vector move low node.
9607 ///
9608 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9609                             SDValue SrcOp, SelectionDAG &DAG,
9610                             const X86Subtarget *Subtarget, SDLoc dl) {
9611   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9612     LoadSDNode *LD = nullptr;
9613     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9614       LD = dyn_cast<LoadSDNode>(SrcOp);
9615     if (!LD) {
9616       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9617       // instead.
9618       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9619       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9620           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9621           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9622           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9623         // PR2108
9624         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9625         return DAG.getNode(ISD::BITCAST, dl, VT,
9626                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9627                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9628                                                    OpVT,
9629                                                    SrcOp.getOperand(0)
9630                                                           .getOperand(0))));
9631       }
9632     }
9633   }
9634
9635   return DAG.getNode(ISD::BITCAST, dl, VT,
9636                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9637                                  DAG.getNode(ISD::BITCAST, dl,
9638                                              OpVT, SrcOp)));
9639 }
9640
9641 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9642 /// which could not be matched by any known target speficic shuffle
9643 static SDValue
9644 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9645
9646   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9647   if (NewOp.getNode())
9648     return NewOp;
9649
9650   MVT VT = SVOp->getSimpleValueType(0);
9651
9652   unsigned NumElems = VT.getVectorNumElements();
9653   unsigned NumLaneElems = NumElems / 2;
9654
9655   SDLoc dl(SVOp);
9656   MVT EltVT = VT.getVectorElementType();
9657   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9658   SDValue Output[2];
9659
9660   SmallVector<int, 16> Mask;
9661   for (unsigned l = 0; l < 2; ++l) {
9662     // Build a shuffle mask for the output, discovering on the fly which
9663     // input vectors to use as shuffle operands (recorded in InputUsed).
9664     // If building a suitable shuffle vector proves too hard, then bail
9665     // out with UseBuildVector set.
9666     bool UseBuildVector = false;
9667     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9668     unsigned LaneStart = l * NumLaneElems;
9669     for (unsigned i = 0; i != NumLaneElems; ++i) {
9670       // The mask element.  This indexes into the input.
9671       int Idx = SVOp->getMaskElt(i+LaneStart);
9672       if (Idx < 0) {
9673         // the mask element does not index into any input vector.
9674         Mask.push_back(-1);
9675         continue;
9676       }
9677
9678       // The input vector this mask element indexes into.
9679       int Input = Idx / NumLaneElems;
9680
9681       // Turn the index into an offset from the start of the input vector.
9682       Idx -= Input * NumLaneElems;
9683
9684       // Find or create a shuffle vector operand to hold this input.
9685       unsigned OpNo;
9686       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9687         if (InputUsed[OpNo] == Input)
9688           // This input vector is already an operand.
9689           break;
9690         if (InputUsed[OpNo] < 0) {
9691           // Create a new operand for this input vector.
9692           InputUsed[OpNo] = Input;
9693           break;
9694         }
9695       }
9696
9697       if (OpNo >= array_lengthof(InputUsed)) {
9698         // More than two input vectors used!  Give up on trying to create a
9699         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9700         UseBuildVector = true;
9701         break;
9702       }
9703
9704       // Add the mask index for the new shuffle vector.
9705       Mask.push_back(Idx + OpNo * NumLaneElems);
9706     }
9707
9708     if (UseBuildVector) {
9709       SmallVector<SDValue, 16> SVOps;
9710       for (unsigned i = 0; i != NumLaneElems; ++i) {
9711         // The mask element.  This indexes into the input.
9712         int Idx = SVOp->getMaskElt(i+LaneStart);
9713         if (Idx < 0) {
9714           SVOps.push_back(DAG.getUNDEF(EltVT));
9715           continue;
9716         }
9717
9718         // The input vector this mask element indexes into.
9719         int Input = Idx / NumElems;
9720
9721         // Turn the index into an offset from the start of the input vector.
9722         Idx -= Input * NumElems;
9723
9724         // Extract the vector element by hand.
9725         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9726                                     SVOp->getOperand(Input),
9727                                     DAG.getIntPtrConstant(Idx)));
9728       }
9729
9730       // Construct the output using a BUILD_VECTOR.
9731       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9732     } else if (InputUsed[0] < 0) {
9733       // No input vectors were used! The result is undefined.
9734       Output[l] = DAG.getUNDEF(NVT);
9735     } else {
9736       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9737                                         (InputUsed[0] % 2) * NumLaneElems,
9738                                         DAG, dl);
9739       // If only one input was used, use an undefined vector for the other.
9740       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9741         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9742                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9743       // At least one input vector was used. Create a new shuffle vector.
9744       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9745     }
9746
9747     Mask.clear();
9748   }
9749
9750   // Concatenate the result back
9751   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9752 }
9753
9754 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9755 /// 4 elements, and match them with several different shuffle types.
9756 static SDValue
9757 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9758   SDValue V1 = SVOp->getOperand(0);
9759   SDValue V2 = SVOp->getOperand(1);
9760   SDLoc dl(SVOp);
9761   MVT VT = SVOp->getSimpleValueType(0);
9762
9763   assert(VT.is128BitVector() && "Unsupported vector size");
9764
9765   std::pair<int, int> Locs[4];
9766   int Mask1[] = { -1, -1, -1, -1 };
9767   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9768
9769   unsigned NumHi = 0;
9770   unsigned NumLo = 0;
9771   for (unsigned i = 0; i != 4; ++i) {
9772     int Idx = PermMask[i];
9773     if (Idx < 0) {
9774       Locs[i] = std::make_pair(-1, -1);
9775     } else {
9776       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9777       if (Idx < 4) {
9778         Locs[i] = std::make_pair(0, NumLo);
9779         Mask1[NumLo] = Idx;
9780         NumLo++;
9781       } else {
9782         Locs[i] = std::make_pair(1, NumHi);
9783         if (2+NumHi < 4)
9784           Mask1[2+NumHi] = Idx;
9785         NumHi++;
9786       }
9787     }
9788   }
9789
9790   if (NumLo <= 2 && NumHi <= 2) {
9791     // If no more than two elements come from either vector. This can be
9792     // implemented with two shuffles. First shuffle gather the elements.
9793     // The second shuffle, which takes the first shuffle as both of its
9794     // vector operands, put the elements into the right order.
9795     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9796
9797     int Mask2[] = { -1, -1, -1, -1 };
9798
9799     for (unsigned i = 0; i != 4; ++i)
9800       if (Locs[i].first != -1) {
9801         unsigned Idx = (i < 2) ? 0 : 4;
9802         Idx += Locs[i].first * 2 + Locs[i].second;
9803         Mask2[i] = Idx;
9804       }
9805
9806     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9807   }
9808
9809   if (NumLo == 3 || NumHi == 3) {
9810     // Otherwise, we must have three elements from one vector, call it X, and
9811     // one element from the other, call it Y.  First, use a shufps to build an
9812     // intermediate vector with the one element from Y and the element from X
9813     // that will be in the same half in the final destination (the indexes don't
9814     // matter). Then, use a shufps to build the final vector, taking the half
9815     // containing the element from Y from the intermediate, and the other half
9816     // from X.
9817     if (NumHi == 3) {
9818       // Normalize it so the 3 elements come from V1.
9819       CommuteVectorShuffleMask(PermMask, 4);
9820       std::swap(V1, V2);
9821     }
9822
9823     // Find the element from V2.
9824     unsigned HiIndex;
9825     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9826       int Val = PermMask[HiIndex];
9827       if (Val < 0)
9828         continue;
9829       if (Val >= 4)
9830         break;
9831     }
9832
9833     Mask1[0] = PermMask[HiIndex];
9834     Mask1[1] = -1;
9835     Mask1[2] = PermMask[HiIndex^1];
9836     Mask1[3] = -1;
9837     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9838
9839     if (HiIndex >= 2) {
9840       Mask1[0] = PermMask[0];
9841       Mask1[1] = PermMask[1];
9842       Mask1[2] = HiIndex & 1 ? 6 : 4;
9843       Mask1[3] = HiIndex & 1 ? 4 : 6;
9844       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9845     }
9846
9847     Mask1[0] = HiIndex & 1 ? 2 : 0;
9848     Mask1[1] = HiIndex & 1 ? 0 : 2;
9849     Mask1[2] = PermMask[2];
9850     Mask1[3] = PermMask[3];
9851     if (Mask1[2] >= 0)
9852       Mask1[2] += 4;
9853     if (Mask1[3] >= 0)
9854       Mask1[3] += 4;
9855     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9856   }
9857
9858   // Break it into (shuffle shuffle_hi, shuffle_lo).
9859   int LoMask[] = { -1, -1, -1, -1 };
9860   int HiMask[] = { -1, -1, -1, -1 };
9861
9862   int *MaskPtr = LoMask;
9863   unsigned MaskIdx = 0;
9864   unsigned LoIdx = 0;
9865   unsigned HiIdx = 2;
9866   for (unsigned i = 0; i != 4; ++i) {
9867     if (i == 2) {
9868       MaskPtr = HiMask;
9869       MaskIdx = 1;
9870       LoIdx = 0;
9871       HiIdx = 2;
9872     }
9873     int Idx = PermMask[i];
9874     if (Idx < 0) {
9875       Locs[i] = std::make_pair(-1, -1);
9876     } else if (Idx < 4) {
9877       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9878       MaskPtr[LoIdx] = Idx;
9879       LoIdx++;
9880     } else {
9881       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9882       MaskPtr[HiIdx] = Idx;
9883       HiIdx++;
9884     }
9885   }
9886
9887   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9888   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9889   int MaskOps[] = { -1, -1, -1, -1 };
9890   for (unsigned i = 0; i != 4; ++i)
9891     if (Locs[i].first != -1)
9892       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9893   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9894 }
9895
9896 static bool MayFoldVectorLoad(SDValue V) {
9897   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9898     V = V.getOperand(0);
9899
9900   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9901     V = V.getOperand(0);
9902   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9903       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9904     // BUILD_VECTOR (load), undef
9905     V = V.getOperand(0);
9906
9907   return MayFoldLoad(V);
9908 }
9909
9910 static
9911 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9912   MVT VT = Op.getSimpleValueType();
9913
9914   // Canonizalize to v2f64.
9915   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9916   return DAG.getNode(ISD::BITCAST, dl, VT,
9917                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9918                                           V1, DAG));
9919 }
9920
9921 static
9922 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9923                         bool HasSSE2) {
9924   SDValue V1 = Op.getOperand(0);
9925   SDValue V2 = Op.getOperand(1);
9926   MVT VT = Op.getSimpleValueType();
9927
9928   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9929
9930   if (HasSSE2 && VT == MVT::v2f64)
9931     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9932
9933   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9934   return DAG.getNode(ISD::BITCAST, dl, VT,
9935                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9936                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9937                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9938 }
9939
9940 static
9941 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9942   SDValue V1 = Op.getOperand(0);
9943   SDValue V2 = Op.getOperand(1);
9944   MVT VT = Op.getSimpleValueType();
9945
9946   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9947          "unsupported shuffle type");
9948
9949   if (V2.getOpcode() == ISD::UNDEF)
9950     V2 = V1;
9951
9952   // v4i32 or v4f32
9953   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9954 }
9955
9956 static
9957 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9958   SDValue V1 = Op.getOperand(0);
9959   SDValue V2 = Op.getOperand(1);
9960   MVT VT = Op.getSimpleValueType();
9961   unsigned NumElems = VT.getVectorNumElements();
9962
9963   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9964   // operand of these instructions is only memory, so check if there's a
9965   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9966   // same masks.
9967   bool CanFoldLoad = false;
9968
9969   // Trivial case, when V2 comes from a load.
9970   if (MayFoldVectorLoad(V2))
9971     CanFoldLoad = true;
9972
9973   // When V1 is a load, it can be folded later into a store in isel, example:
9974   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9975   //    turns into:
9976   //  (MOVLPSmr addr:$src1, VR128:$src2)
9977   // So, recognize this potential and also use MOVLPS or MOVLPD
9978   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9979     CanFoldLoad = true;
9980
9981   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9982   if (CanFoldLoad) {
9983     if (HasSSE2 && NumElems == 2)
9984       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9985
9986     if (NumElems == 4)
9987       // If we don't care about the second element, proceed to use movss.
9988       if (SVOp->getMaskElt(1) != -1)
9989         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9990   }
9991
9992   // movl and movlp will both match v2i64, but v2i64 is never matched by
9993   // movl earlier because we make it strict to avoid messing with the movlp load
9994   // folding logic (see the code above getMOVLP call). Match it here then,
9995   // this is horrible, but will stay like this until we move all shuffle
9996   // matching to x86 specific nodes. Note that for the 1st condition all
9997   // types are matched with movsd.
9998   if (HasSSE2) {
9999     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
10000     // as to remove this logic from here, as much as possible
10001     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
10002       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10003     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10004   }
10005
10006   assert(VT != MVT::v4i32 && "unsupported shuffle type");
10007
10008   // Invert the operand order and use SHUFPS to match it.
10009   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
10010                               getShuffleSHUFImmediate(SVOp), DAG);
10011 }
10012
10013 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
10014                                          SelectionDAG &DAG) {
10015   SDLoc dl(Load);
10016   MVT VT = Load->getSimpleValueType(0);
10017   MVT EVT = VT.getVectorElementType();
10018   SDValue Addr = Load->getOperand(1);
10019   SDValue NewAddr = DAG.getNode(
10020       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
10021       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
10022
10023   SDValue NewLoad =
10024       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
10025                   DAG.getMachineFunction().getMachineMemOperand(
10026                       Load->getMemOperand(), 0, EVT.getStoreSize()));
10027   return NewLoad;
10028 }
10029
10030 // It is only safe to call this function if isINSERTPSMask is true for
10031 // this shufflevector mask.
10032 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
10033                            SelectionDAG &DAG) {
10034   // Generate an insertps instruction when inserting an f32 from memory onto a
10035   // v4f32 or when copying a member from one v4f32 to another.
10036   // We also use it for transferring i32 from one register to another,
10037   // since it simply copies the same bits.
10038   // If we're transferring an i32 from memory to a specific element in a
10039   // register, we output a generic DAG that will match the PINSRD
10040   // instruction.
10041   MVT VT = SVOp->getSimpleValueType(0);
10042   MVT EVT = VT.getVectorElementType();
10043   SDValue V1 = SVOp->getOperand(0);
10044   SDValue V2 = SVOp->getOperand(1);
10045   auto Mask = SVOp->getMask();
10046   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
10047          "unsupported vector type for insertps/pinsrd");
10048
10049   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
10050   auto FromV2Predicate = [](const int &i) { return i >= 4; };
10051   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
10052
10053   SDValue From;
10054   SDValue To;
10055   unsigned DestIndex;
10056   if (FromV1 == 1) {
10057     From = V1;
10058     To = V2;
10059     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
10060                 Mask.begin();
10061
10062     // If we have 1 element from each vector, we have to check if we're
10063     // changing V1's element's place. If so, we're done. Otherwise, we
10064     // should assume we're changing V2's element's place and behave
10065     // accordingly.
10066     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
10067     assert(DestIndex <= INT32_MAX && "truncated destination index");
10068     if (FromV1 == FromV2 &&
10069         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
10070       From = V2;
10071       To = V1;
10072       DestIndex =
10073           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
10074     }
10075   } else {
10076     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
10077            "More than one element from V1 and from V2, or no elements from one "
10078            "of the vectors. This case should not have returned true from "
10079            "isINSERTPSMask");
10080     From = V2;
10081     To = V1;
10082     DestIndex =
10083         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
10084   }
10085
10086   // Get an index into the source vector in the range [0,4) (the mask is
10087   // in the range [0,8) because it can address V1 and V2)
10088   unsigned SrcIndex = Mask[DestIndex] % 4;
10089   if (MayFoldLoad(From)) {
10090     // Trivial case, when From comes from a load and is only used by the
10091     // shuffle. Make it use insertps from the vector that we need from that
10092     // load.
10093     SDValue NewLoad =
10094         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
10095     if (!NewLoad.getNode())
10096       return SDValue();
10097
10098     if (EVT == MVT::f32) {
10099       // Create this as a scalar to vector to match the instruction pattern.
10100       SDValue LoadScalarToVector =
10101           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
10102       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
10103       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
10104                          InsertpsMask);
10105     } else { // EVT == MVT::i32
10106       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
10107       // instruction, to match the PINSRD instruction, which loads an i32 to a
10108       // certain vector element.
10109       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
10110                          DAG.getConstant(DestIndex, MVT::i32));
10111     }
10112   }
10113
10114   // Vector-element-to-vector
10115   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
10116   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
10117 }
10118
10119 // Reduce a vector shuffle to zext.
10120 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
10121                                     SelectionDAG &DAG) {
10122   // PMOVZX is only available from SSE41.
10123   if (!Subtarget->hasSSE41())
10124     return SDValue();
10125
10126   MVT VT = Op.getSimpleValueType();
10127
10128   // Only AVX2 support 256-bit vector integer extending.
10129   if (!Subtarget->hasInt256() && VT.is256BitVector())
10130     return SDValue();
10131
10132   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10133   SDLoc DL(Op);
10134   SDValue V1 = Op.getOperand(0);
10135   SDValue V2 = Op.getOperand(1);
10136   unsigned NumElems = VT.getVectorNumElements();
10137
10138   // Extending is an unary operation and the element type of the source vector
10139   // won't be equal to or larger than i64.
10140   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
10141       VT.getVectorElementType() == MVT::i64)
10142     return SDValue();
10143
10144   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
10145   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
10146   while ((1U << Shift) < NumElems) {
10147     if (SVOp->getMaskElt(1U << Shift) == 1)
10148       break;
10149     Shift += 1;
10150     // The maximal ratio is 8, i.e. from i8 to i64.
10151     if (Shift > 3)
10152       return SDValue();
10153   }
10154
10155   // Check the shuffle mask.
10156   unsigned Mask = (1U << Shift) - 1;
10157   for (unsigned i = 0; i != NumElems; ++i) {
10158     int EltIdx = SVOp->getMaskElt(i);
10159     if ((i & Mask) != 0 && EltIdx != -1)
10160       return SDValue();
10161     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
10162       return SDValue();
10163   }
10164
10165   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
10166   MVT NeVT = MVT::getIntegerVT(NBits);
10167   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
10168
10169   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
10170     return SDValue();
10171
10172   // Simplify the operand as it's prepared to be fed into shuffle.
10173   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
10174   if (V1.getOpcode() == ISD::BITCAST &&
10175       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
10176       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10177       V1.getOperand(0).getOperand(0)
10178         .getSimpleValueType().getSizeInBits() == SignificantBits) {
10179     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
10180     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
10181     ConstantSDNode *CIdx =
10182       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
10183     // If it's foldable, i.e. normal load with single use, we will let code
10184     // selection to fold it. Otherwise, we will short the conversion sequence.
10185     if (CIdx && CIdx->getZExtValue() == 0 &&
10186         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
10187       MVT FullVT = V.getSimpleValueType();
10188       MVT V1VT = V1.getSimpleValueType();
10189       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
10190         // The "ext_vec_elt" node is wider than the result node.
10191         // In this case we should extract subvector from V.
10192         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
10193         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
10194         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
10195                                         FullVT.getVectorNumElements()/Ratio);
10196         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
10197                         DAG.getIntPtrConstant(0));
10198       }
10199       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
10200     }
10201   }
10202
10203   return DAG.getNode(ISD::BITCAST, DL, VT,
10204                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
10205 }
10206
10207 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10208                                       SelectionDAG &DAG) {
10209   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10210   MVT VT = Op.getSimpleValueType();
10211   SDLoc dl(Op);
10212   SDValue V1 = Op.getOperand(0);
10213   SDValue V2 = Op.getOperand(1);
10214
10215   if (isZeroShuffle(SVOp))
10216     return getZeroVector(VT, Subtarget, DAG, dl);
10217
10218   // Handle splat operations
10219   if (SVOp->isSplat()) {
10220     // Use vbroadcast whenever the splat comes from a foldable load
10221     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
10222     if (Broadcast.getNode())
10223       return Broadcast;
10224   }
10225
10226   // Check integer expanding shuffles.
10227   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
10228   if (NewOp.getNode())
10229     return NewOp;
10230
10231   // If the shuffle can be profitably rewritten as a narrower shuffle, then
10232   // do it!
10233   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
10234       VT == MVT::v32i8) {
10235     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10236     if (NewOp.getNode())
10237       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
10238   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
10239     // FIXME: Figure out a cleaner way to do this.
10240     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
10241       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10242       if (NewOp.getNode()) {
10243         MVT NewVT = NewOp.getSimpleValueType();
10244         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
10245                                NewVT, true, false))
10246           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
10247                               dl);
10248       }
10249     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
10250       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10251       if (NewOp.getNode()) {
10252         MVT NewVT = NewOp.getSimpleValueType();
10253         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
10254           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
10255                               dl);
10256       }
10257     }
10258   }
10259   return SDValue();
10260 }
10261
10262 SDValue
10263 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
10264   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10265   SDValue V1 = Op.getOperand(0);
10266   SDValue V2 = Op.getOperand(1);
10267   MVT VT = Op.getSimpleValueType();
10268   SDLoc dl(Op);
10269   unsigned NumElems = VT.getVectorNumElements();
10270   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10271   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10272   bool V1IsSplat = false;
10273   bool V2IsSplat = false;
10274   bool HasSSE2 = Subtarget->hasSSE2();
10275   bool HasFp256    = Subtarget->hasFp256();
10276   bool HasInt256   = Subtarget->hasInt256();
10277   MachineFunction &MF = DAG.getMachineFunction();
10278   bool OptForSize = MF.getFunction()->getAttributes().
10279     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10280
10281   // Check if we should use the experimental vector shuffle lowering. If so,
10282   // delegate completely to that code path.
10283   if (ExperimentalVectorShuffleLowering)
10284     return lowerVectorShuffle(Op, Subtarget, DAG);
10285
10286   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10287
10288   if (V1IsUndef && V2IsUndef)
10289     return DAG.getUNDEF(VT);
10290
10291   // When we create a shuffle node we put the UNDEF node to second operand,
10292   // but in some cases the first operand may be transformed to UNDEF.
10293   // In this case we should just commute the node.
10294   if (V1IsUndef)
10295     return DAG.getCommutedVectorShuffle(*SVOp);
10296
10297   // Vector shuffle lowering takes 3 steps:
10298   //
10299   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10300   //    narrowing and commutation of operands should be handled.
10301   // 2) Matching of shuffles with known shuffle masks to x86 target specific
10302   //    shuffle nodes.
10303   // 3) Rewriting of unmatched masks into new generic shuffle operations,
10304   //    so the shuffle can be broken into other shuffles and the legalizer can
10305   //    try the lowering again.
10306   //
10307   // The general idea is that no vector_shuffle operation should be left to
10308   // be matched during isel, all of them must be converted to a target specific
10309   // node here.
10310
10311   // Normalize the input vectors. Here splats, zeroed vectors, profitable
10312   // narrowing and commutation of operands should be handled. The actual code
10313   // doesn't include all of those, work in progress...
10314   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10315   if (NewOp.getNode())
10316     return NewOp;
10317
10318   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10319
10320   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10321   // unpckh_undef). Only use pshufd if speed is more important than size.
10322   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10323     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10324   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10325     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10326
10327   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10328       V2IsUndef && MayFoldVectorLoad(V1))
10329     return getMOVDDup(Op, dl, V1, DAG);
10330
10331   if (isMOVHLPS_v_undef_Mask(M, VT))
10332     return getMOVHighToLow(Op, dl, DAG);
10333
10334   // Use to match splats
10335   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10336       (VT == MVT::v2f64 || VT == MVT::v2i64))
10337     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10338
10339   if (isPSHUFDMask(M, VT)) {
10340     // The actual implementation will match the mask in the if above and then
10341     // during isel it can match several different instructions, not only pshufd
10342     // as its name says, sad but true, emulate the behavior for now...
10343     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10344       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10345
10346     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10347
10348     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10349       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10350
10351     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10352       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10353                                   DAG);
10354
10355     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10356                                 TargetMask, DAG);
10357   }
10358
10359   if (isPALIGNRMask(M, VT, Subtarget))
10360     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10361                                 getShufflePALIGNRImmediate(SVOp),
10362                                 DAG);
10363
10364   if (isVALIGNMask(M, VT, Subtarget))
10365     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10366                                 getShuffleVALIGNImmediate(SVOp),
10367                                 DAG);
10368
10369   // Check if this can be converted into a logical shift.
10370   bool isLeft = false;
10371   unsigned ShAmt = 0;
10372   SDValue ShVal;
10373   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10374   if (isShift && ShVal.hasOneUse()) {
10375     // If the shifted value has multiple uses, it may be cheaper to use
10376     // v_set0 + movlhps or movhlps, etc.
10377     MVT EltVT = VT.getVectorElementType();
10378     ShAmt *= EltVT.getSizeInBits();
10379     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10380   }
10381
10382   if (isMOVLMask(M, VT)) {
10383     if (ISD::isBuildVectorAllZeros(V1.getNode()))
10384       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10385     if (!isMOVLPMask(M, VT)) {
10386       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10387         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10388
10389       if (VT == MVT::v4i32 || VT == MVT::v4f32)
10390         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10391     }
10392   }
10393
10394   // FIXME: fold these into legal mask.
10395   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10396     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10397
10398   if (isMOVHLPSMask(M, VT))
10399     return getMOVHighToLow(Op, dl, DAG);
10400
10401   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10402     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10403
10404   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10405     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10406
10407   if (isMOVLPMask(M, VT))
10408     return getMOVLP(Op, dl, DAG, HasSSE2);
10409
10410   if (ShouldXformToMOVHLPS(M, VT) ||
10411       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10412     return DAG.getCommutedVectorShuffle(*SVOp);
10413
10414   if (isShift) {
10415     // No better options. Use a vshldq / vsrldq.
10416     MVT EltVT = VT.getVectorElementType();
10417     ShAmt *= EltVT.getSizeInBits();
10418     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10419   }
10420
10421   bool Commuted = false;
10422   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
10423   // 1,1,1,1 -> v8i16 though.
10424   BitVector UndefElements;
10425   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10426     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10427       V1IsSplat = true;
10428   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10429     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10430       V2IsSplat = true;
10431
10432   // Canonicalize the splat or undef, if present, to be on the RHS.
10433   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10434     CommuteVectorShuffleMask(M, NumElems);
10435     std::swap(V1, V2);
10436     std::swap(V1IsSplat, V2IsSplat);
10437     Commuted = true;
10438   }
10439
10440   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10441     // Shuffling low element of v1 into undef, just return v1.
10442     if (V2IsUndef)
10443       return V1;
10444     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10445     // the instruction selector will not match, so get a canonical MOVL with
10446     // swapped operands to undo the commute.
10447     return getMOVL(DAG, dl, VT, V2, V1);
10448   }
10449
10450   if (isUNPCKLMask(M, VT, HasInt256))
10451     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10452
10453   if (isUNPCKHMask(M, VT, HasInt256))
10454     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10455
10456   if (V2IsSplat) {
10457     // Normalize mask so all entries that point to V2 points to its first
10458     // element then try to match unpck{h|l} again. If match, return a
10459     // new vector_shuffle with the corrected mask.p
10460     SmallVector<int, 8> NewMask(M.begin(), M.end());
10461     NormalizeMask(NewMask, NumElems);
10462     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10463       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10464     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10465       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10466   }
10467
10468   if (Commuted) {
10469     // Commute is back and try unpck* again.
10470     // FIXME: this seems wrong.
10471     CommuteVectorShuffleMask(M, NumElems);
10472     std::swap(V1, V2);
10473     std::swap(V1IsSplat, V2IsSplat);
10474
10475     if (isUNPCKLMask(M, VT, HasInt256))
10476       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10477
10478     if (isUNPCKHMask(M, VT, HasInt256))
10479       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10480   }
10481
10482   // Normalize the node to match x86 shuffle ops if needed
10483   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10484     return DAG.getCommutedVectorShuffle(*SVOp);
10485
10486   // The checks below are all present in isShuffleMaskLegal, but they are
10487   // inlined here right now to enable us to directly emit target specific
10488   // nodes, and remove one by one until they don't return Op anymore.
10489
10490   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10491       SVOp->getSplatIndex() == 0 && V2IsUndef) {
10492     if (VT == MVT::v2f64 || VT == MVT::v2i64)
10493       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10494   }
10495
10496   if (isPSHUFHWMask(M, VT, HasInt256))
10497     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10498                                 getShufflePSHUFHWImmediate(SVOp),
10499                                 DAG);
10500
10501   if (isPSHUFLWMask(M, VT, HasInt256))
10502     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10503                                 getShufflePSHUFLWImmediate(SVOp),
10504                                 DAG);
10505
10506   unsigned MaskValue;
10507   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10508                   &MaskValue))
10509     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10510
10511   if (isSHUFPMask(M, VT))
10512     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10513                                 getShuffleSHUFImmediate(SVOp), DAG);
10514
10515   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10516     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10517   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10518     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10519
10520   //===--------------------------------------------------------------------===//
10521   // Generate target specific nodes for 128 or 256-bit shuffles only
10522   // supported in the AVX instruction set.
10523   //
10524
10525   // Handle VMOVDDUPY permutations
10526   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10527     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10528
10529   // Handle VPERMILPS/D* permutations
10530   if (isVPERMILPMask(M, VT)) {
10531     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10532       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10533                                   getShuffleSHUFImmediate(SVOp), DAG);
10534     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10535                                 getShuffleSHUFImmediate(SVOp), DAG);
10536   }
10537
10538   unsigned Idx;
10539   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10540     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10541                               Idx*(NumElems/2), DAG, dl);
10542
10543   // Handle VPERM2F128/VPERM2I128 permutations
10544   if (isVPERM2X128Mask(M, VT, HasFp256))
10545     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10546                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10547
10548   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10549     return getINSERTPS(SVOp, dl, DAG);
10550
10551   unsigned Imm8;
10552   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10553     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10554
10555   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10556       VT.is512BitVector()) {
10557     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10558     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10559     SmallVector<SDValue, 16> permclMask;
10560     for (unsigned i = 0; i != NumElems; ++i) {
10561       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10562     }
10563
10564     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10565     if (V2IsUndef)
10566       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10567       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10568                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10569     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10570                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10571   }
10572
10573   //===--------------------------------------------------------------------===//
10574   // Since no target specific shuffle was selected for this generic one,
10575   // lower it into other known shuffles. FIXME: this isn't true yet, but
10576   // this is the plan.
10577   //
10578
10579   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10580   if (VT == MVT::v8i16) {
10581     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10582     if (NewOp.getNode())
10583       return NewOp;
10584   }
10585
10586   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10587     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10588     if (NewOp.getNode())
10589       return NewOp;
10590   }
10591
10592   if (VT == MVT::v16i8) {
10593     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10594     if (NewOp.getNode())
10595       return NewOp;
10596   }
10597
10598   if (VT == MVT::v32i8) {
10599     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10600     if (NewOp.getNode())
10601       return NewOp;
10602   }
10603
10604   // Handle all 128-bit wide vectors with 4 elements, and match them with
10605   // several different shuffle types.
10606   if (NumElems == 4 && VT.is128BitVector())
10607     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10608
10609   // Handle general 256-bit shuffles
10610   if (VT.is256BitVector())
10611     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10612
10613   return SDValue();
10614 }
10615
10616 // This function assumes its argument is a BUILD_VECTOR of constants or
10617 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10618 // true.
10619 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10620                                     unsigned &MaskValue) {
10621   MaskValue = 0;
10622   unsigned NumElems = BuildVector->getNumOperands();
10623   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10624   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10625   unsigned NumElemsInLane = NumElems / NumLanes;
10626
10627   // Blend for v16i16 should be symetric for the both lanes.
10628   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10629     SDValue EltCond = BuildVector->getOperand(i);
10630     SDValue SndLaneEltCond =
10631         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10632
10633     int Lane1Cond = -1, Lane2Cond = -1;
10634     if (isa<ConstantSDNode>(EltCond))
10635       Lane1Cond = !isZero(EltCond);
10636     if (isa<ConstantSDNode>(SndLaneEltCond))
10637       Lane2Cond = !isZero(SndLaneEltCond);
10638
10639     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10640       // Lane1Cond != 0, means we want the first argument.
10641       // Lane1Cond == 0, means we want the second argument.
10642       // The encoding of this argument is 0 for the first argument, 1
10643       // for the second. Therefore, invert the condition.
10644       MaskValue |= !Lane1Cond << i;
10645     else if (Lane1Cond < 0)
10646       MaskValue |= !Lane2Cond << i;
10647     else
10648       return false;
10649   }
10650   return true;
10651 }
10652
10653 // Try to lower a vselect node into a simple blend instruction.
10654 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10655                                    SelectionDAG &DAG) {
10656   SDValue Cond = Op.getOperand(0);
10657   SDValue LHS = Op.getOperand(1);
10658   SDValue RHS = Op.getOperand(2);
10659   SDLoc dl(Op);
10660   MVT VT = Op.getSimpleValueType();
10661   MVT EltVT = VT.getVectorElementType();
10662   unsigned NumElems = VT.getVectorNumElements();
10663
10664   // There is no blend with immediate in AVX-512.
10665   if (VT.is512BitVector())
10666     return SDValue();
10667
10668   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10669     return SDValue();
10670   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10671     return SDValue();
10672
10673   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10674     return SDValue();
10675
10676   // Check the mask for BLEND and build the value.
10677   unsigned MaskValue = 0;
10678   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10679     return SDValue();
10680
10681   // Convert i32 vectors to floating point if it is not AVX2.
10682   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10683   MVT BlendVT = VT;
10684   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10685     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10686                                NumElems);
10687     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10688     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10689   }
10690
10691   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10692                             DAG.getConstant(MaskValue, MVT::i32));
10693   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10694 }
10695
10696 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10697   // A vselect where all conditions and data are constants can be optimized into
10698   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10699   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10700       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10701       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10702     return SDValue();
10703   
10704   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10705   if (BlendOp.getNode())
10706     return BlendOp;
10707
10708   // Some types for vselect were previously set to Expand, not Legal or
10709   // Custom. Return an empty SDValue so we fall-through to Expand, after
10710   // the Custom lowering phase.
10711   MVT VT = Op.getSimpleValueType();
10712   switch (VT.SimpleTy) {
10713   default:
10714     break;
10715   case MVT::v8i16:
10716   case MVT::v16i16:
10717     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10718       break;
10719     return SDValue();
10720   }
10721
10722   // We couldn't create a "Blend with immediate" node.
10723   // This node should still be legal, but we'll have to emit a blendv*
10724   // instruction.
10725   return Op;
10726 }
10727
10728 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10729   MVT VT = Op.getSimpleValueType();
10730   SDLoc dl(Op);
10731
10732   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10733     return SDValue();
10734
10735   if (VT.getSizeInBits() == 8) {
10736     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10737                                   Op.getOperand(0), Op.getOperand(1));
10738     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10739                                   DAG.getValueType(VT));
10740     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10741   }
10742
10743   if (VT.getSizeInBits() == 16) {
10744     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10745     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10746     if (Idx == 0)
10747       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10748                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10749                                      DAG.getNode(ISD::BITCAST, dl,
10750                                                  MVT::v4i32,
10751                                                  Op.getOperand(0)),
10752                                      Op.getOperand(1)));
10753     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10754                                   Op.getOperand(0), Op.getOperand(1));
10755     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10756                                   DAG.getValueType(VT));
10757     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10758   }
10759
10760   if (VT == MVT::f32) {
10761     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10762     // the result back to FR32 register. It's only worth matching if the
10763     // result has a single use which is a store or a bitcast to i32.  And in
10764     // the case of a store, it's not worth it if the index is a constant 0,
10765     // because a MOVSSmr can be used instead, which is smaller and faster.
10766     if (!Op.hasOneUse())
10767       return SDValue();
10768     SDNode *User = *Op.getNode()->use_begin();
10769     if ((User->getOpcode() != ISD::STORE ||
10770          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10771           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10772         (User->getOpcode() != ISD::BITCAST ||
10773          User->getValueType(0) != MVT::i32))
10774       return SDValue();
10775     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10776                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10777                                               Op.getOperand(0)),
10778                                               Op.getOperand(1));
10779     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10780   }
10781
10782   if (VT == MVT::i32 || VT == MVT::i64) {
10783     // ExtractPS/pextrq works with constant index.
10784     if (isa<ConstantSDNode>(Op.getOperand(1)))
10785       return Op;
10786   }
10787   return SDValue();
10788 }
10789
10790 /// Extract one bit from mask vector, like v16i1 or v8i1.
10791 /// AVX-512 feature.
10792 SDValue
10793 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10794   SDValue Vec = Op.getOperand(0);
10795   SDLoc dl(Vec);
10796   MVT VecVT = Vec.getSimpleValueType();
10797   SDValue Idx = Op.getOperand(1);
10798   MVT EltVT = Op.getSimpleValueType();
10799
10800   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10801
10802   // variable index can't be handled in mask registers,
10803   // extend vector to VR512
10804   if (!isa<ConstantSDNode>(Idx)) {
10805     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10806     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10807     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10808                               ExtVT.getVectorElementType(), Ext, Idx);
10809     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10810   }
10811
10812   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10813   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10814   unsigned MaxSift = rc->getSize()*8 - 1;
10815   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10816                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10817   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10818                     DAG.getConstant(MaxSift, MVT::i8));
10819   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10820                        DAG.getIntPtrConstant(0));
10821 }
10822
10823 SDValue
10824 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10825                                            SelectionDAG &DAG) const {
10826   SDLoc dl(Op);
10827   SDValue Vec = Op.getOperand(0);
10828   MVT VecVT = Vec.getSimpleValueType();
10829   SDValue Idx = Op.getOperand(1);
10830
10831   if (Op.getSimpleValueType() == MVT::i1)
10832     return ExtractBitFromMaskVector(Op, DAG);
10833
10834   if (!isa<ConstantSDNode>(Idx)) {
10835     if (VecVT.is512BitVector() ||
10836         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10837          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10838
10839       MVT MaskEltVT =
10840         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10841       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10842                                     MaskEltVT.getSizeInBits());
10843
10844       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10845       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10846                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10847                                 Idx, DAG.getConstant(0, getPointerTy()));
10848       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10849       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10850                         Perm, DAG.getConstant(0, getPointerTy()));
10851     }
10852     return SDValue();
10853   }
10854
10855   // If this is a 256-bit vector result, first extract the 128-bit vector and
10856   // then extract the element from the 128-bit vector.
10857   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10858
10859     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10860     // Get the 128-bit vector.
10861     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10862     MVT EltVT = VecVT.getVectorElementType();
10863
10864     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10865
10866     //if (IdxVal >= NumElems/2)
10867     //  IdxVal -= NumElems/2;
10868     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10869     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10870                        DAG.getConstant(IdxVal, MVT::i32));
10871   }
10872
10873   assert(VecVT.is128BitVector() && "Unexpected vector length");
10874
10875   if (Subtarget->hasSSE41()) {
10876     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10877     if (Res.getNode())
10878       return Res;
10879   }
10880
10881   MVT VT = Op.getSimpleValueType();
10882   // TODO: handle v16i8.
10883   if (VT.getSizeInBits() == 16) {
10884     SDValue Vec = Op.getOperand(0);
10885     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10886     if (Idx == 0)
10887       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10888                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10889                                      DAG.getNode(ISD::BITCAST, dl,
10890                                                  MVT::v4i32, Vec),
10891                                      Op.getOperand(1)));
10892     // Transform it so it match pextrw which produces a 32-bit result.
10893     MVT EltVT = MVT::i32;
10894     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10895                                   Op.getOperand(0), Op.getOperand(1));
10896     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10897                                   DAG.getValueType(VT));
10898     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10899   }
10900
10901   if (VT.getSizeInBits() == 32) {
10902     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10903     if (Idx == 0)
10904       return Op;
10905
10906     // SHUFPS the element to the lowest double word, then movss.
10907     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10908     MVT VVT = Op.getOperand(0).getSimpleValueType();
10909     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10910                                        DAG.getUNDEF(VVT), Mask);
10911     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10912                        DAG.getIntPtrConstant(0));
10913   }
10914
10915   if (VT.getSizeInBits() == 64) {
10916     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10917     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10918     //        to match extract_elt for f64.
10919     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10920     if (Idx == 0)
10921       return Op;
10922
10923     // UNPCKHPD the element to the lowest double word, then movsd.
10924     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10925     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10926     int Mask[2] = { 1, -1 };
10927     MVT VVT = Op.getOperand(0).getSimpleValueType();
10928     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10929                                        DAG.getUNDEF(VVT), Mask);
10930     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10931                        DAG.getIntPtrConstant(0));
10932   }
10933
10934   return SDValue();
10935 }
10936
10937 /// Insert one bit to mask vector, like v16i1 or v8i1.
10938 /// AVX-512 feature.
10939 SDValue 
10940 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10941   SDLoc dl(Op);
10942   SDValue Vec = Op.getOperand(0);
10943   SDValue Elt = Op.getOperand(1);
10944   SDValue Idx = Op.getOperand(2);
10945   MVT VecVT = Vec.getSimpleValueType();
10946
10947   if (!isa<ConstantSDNode>(Idx)) {
10948     // Non constant index. Extend source and destination,
10949     // insert element and then truncate the result.
10950     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10951     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10952     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10953       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10954       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10955     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10956   }
10957
10958   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10959   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10960   if (Vec.getOpcode() == ISD::UNDEF)
10961     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10962                        DAG.getConstant(IdxVal, MVT::i8));
10963   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10964   unsigned MaxSift = rc->getSize()*8 - 1;
10965   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10966                     DAG.getConstant(MaxSift, MVT::i8));
10967   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10968                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10969   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10970 }
10971
10972 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10973                                                   SelectionDAG &DAG) const {
10974   MVT VT = Op.getSimpleValueType();
10975   MVT EltVT = VT.getVectorElementType();
10976
10977   if (EltVT == MVT::i1)
10978     return InsertBitToMaskVector(Op, DAG);
10979
10980   SDLoc dl(Op);
10981   SDValue N0 = Op.getOperand(0);
10982   SDValue N1 = Op.getOperand(1);
10983   SDValue N2 = Op.getOperand(2);
10984   if (!isa<ConstantSDNode>(N2))
10985     return SDValue();
10986   auto *N2C = cast<ConstantSDNode>(N2);
10987   unsigned IdxVal = N2C->getZExtValue();
10988
10989   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10990   // into that, and then insert the subvector back into the result.
10991   if (VT.is256BitVector() || VT.is512BitVector()) {
10992     // Get the desired 128-bit vector half.
10993     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10994
10995     // Insert the element into the desired half.
10996     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10997     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10998
10999     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11000                     DAG.getConstant(IdxIn128, MVT::i32));
11001
11002     // Insert the changed part back to the 256-bit vector
11003     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11004   }
11005   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11006
11007   if (Subtarget->hasSSE41()) {
11008     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11009       unsigned Opc;
11010       if (VT == MVT::v8i16) {
11011         Opc = X86ISD::PINSRW;
11012       } else {
11013         assert(VT == MVT::v16i8);
11014         Opc = X86ISD::PINSRB;
11015       }
11016
11017       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11018       // argument.
11019       if (N1.getValueType() != MVT::i32)
11020         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11021       if (N2.getValueType() != MVT::i32)
11022         N2 = DAG.getIntPtrConstant(IdxVal);
11023       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11024     }
11025
11026     if (EltVT == MVT::f32) {
11027       // Bits [7:6] of the constant are the source select.  This will always be
11028       //  zero here.  The DAG Combiner may combine an extract_elt index into
11029       //  these
11030       //  bits.  For example (insert (extract, 3), 2) could be matched by
11031       //  putting
11032       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
11033       // Bits [5:4] of the constant are the destination select.  This is the
11034       //  value of the incoming immediate.
11035       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
11036       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11037       N2 = DAG.getIntPtrConstant(IdxVal << 4);
11038       // Create this as a scalar to vector..
11039       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11040       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11041     }
11042
11043     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11044       // PINSR* works with constant index.
11045       return Op;
11046     }
11047   }
11048
11049   if (EltVT == MVT::i8)
11050     return SDValue();
11051
11052   if (EltVT.getSizeInBits() == 16) {
11053     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11054     // as its second argument.
11055     if (N1.getValueType() != MVT::i32)
11056       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11057     if (N2.getValueType() != MVT::i32)
11058       N2 = DAG.getIntPtrConstant(IdxVal);
11059     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11060   }
11061   return SDValue();
11062 }
11063
11064 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11065   SDLoc dl(Op);
11066   MVT OpVT = Op.getSimpleValueType();
11067
11068   // If this is a 256-bit vector result, first insert into a 128-bit
11069   // vector and then insert into the 256-bit vector.
11070   if (!OpVT.is128BitVector()) {
11071     // Insert into a 128-bit vector.
11072     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11073     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11074                                  OpVT.getVectorNumElements() / SizeFactor);
11075
11076     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11077
11078     // Insert the 128-bit vector.
11079     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11080   }
11081
11082   if (OpVT == MVT::v1i64 &&
11083       Op.getOperand(0).getValueType() == MVT::i64)
11084     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11085
11086   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11087   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11088   return DAG.getNode(ISD::BITCAST, dl, OpVT,
11089                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
11090 }
11091
11092 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11093 // a simple subregister reference or explicit instructions to grab
11094 // upper bits of a vector.
11095 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11096                                       SelectionDAG &DAG) {
11097   SDLoc dl(Op);
11098   SDValue In =  Op.getOperand(0);
11099   SDValue Idx = Op.getOperand(1);
11100   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11101   MVT ResVT   = Op.getSimpleValueType();
11102   MVT InVT    = In.getSimpleValueType();
11103
11104   if (Subtarget->hasFp256()) {
11105     if (ResVT.is128BitVector() &&
11106         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11107         isa<ConstantSDNode>(Idx)) {
11108       return Extract128BitVector(In, IdxVal, DAG, dl);
11109     }
11110     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11111         isa<ConstantSDNode>(Idx)) {
11112       return Extract256BitVector(In, IdxVal, DAG, dl);
11113     }
11114   }
11115   return SDValue();
11116 }
11117
11118 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11119 // simple superregister reference or explicit instructions to insert
11120 // the upper bits of a vector.
11121 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11122                                      SelectionDAG &DAG) {
11123   if (Subtarget->hasFp256()) {
11124     SDLoc dl(Op.getNode());
11125     SDValue Vec = Op.getNode()->getOperand(0);
11126     SDValue SubVec = Op.getNode()->getOperand(1);
11127     SDValue Idx = Op.getNode()->getOperand(2);
11128
11129     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
11130          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
11131         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
11132         isa<ConstantSDNode>(Idx)) {
11133       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11134       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11135     }
11136
11137     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
11138         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
11139         isa<ConstantSDNode>(Idx)) {
11140       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11141       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11142     }
11143   }
11144   return SDValue();
11145 }
11146
11147 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11148 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11149 // one of the above mentioned nodes. It has to be wrapped because otherwise
11150 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11151 // be used to form addressing mode. These wrapped nodes will be selected
11152 // into MOV32ri.
11153 SDValue
11154 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11155   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11156
11157   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11158   // global base reg.
11159   unsigned char OpFlag = 0;
11160   unsigned WrapperKind = X86ISD::Wrapper;
11161   CodeModel::Model M = DAG.getTarget().getCodeModel();
11162
11163   if (Subtarget->isPICStyleRIPRel() &&
11164       (M == CodeModel::Small || M == CodeModel::Kernel))
11165     WrapperKind = X86ISD::WrapperRIP;
11166   else if (Subtarget->isPICStyleGOT())
11167     OpFlag = X86II::MO_GOTOFF;
11168   else if (Subtarget->isPICStyleStubPIC())
11169     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11170
11171   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11172                                              CP->getAlignment(),
11173                                              CP->getOffset(), OpFlag);
11174   SDLoc DL(CP);
11175   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11176   // With PIC, the address is actually $g + Offset.
11177   if (OpFlag) {
11178     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11179                          DAG.getNode(X86ISD::GlobalBaseReg,
11180                                      SDLoc(), getPointerTy()),
11181                          Result);
11182   }
11183
11184   return Result;
11185 }
11186
11187 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11188   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11189
11190   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11191   // global base reg.
11192   unsigned char OpFlag = 0;
11193   unsigned WrapperKind = X86ISD::Wrapper;
11194   CodeModel::Model M = DAG.getTarget().getCodeModel();
11195
11196   if (Subtarget->isPICStyleRIPRel() &&
11197       (M == CodeModel::Small || M == CodeModel::Kernel))
11198     WrapperKind = X86ISD::WrapperRIP;
11199   else if (Subtarget->isPICStyleGOT())
11200     OpFlag = X86II::MO_GOTOFF;
11201   else if (Subtarget->isPICStyleStubPIC())
11202     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11203
11204   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11205                                           OpFlag);
11206   SDLoc DL(JT);
11207   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11208
11209   // With PIC, the address is actually $g + Offset.
11210   if (OpFlag)
11211     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11212                          DAG.getNode(X86ISD::GlobalBaseReg,
11213                                      SDLoc(), getPointerTy()),
11214                          Result);
11215
11216   return Result;
11217 }
11218
11219 SDValue
11220 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11221   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11222
11223   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11224   // global base reg.
11225   unsigned char OpFlag = 0;
11226   unsigned WrapperKind = X86ISD::Wrapper;
11227   CodeModel::Model M = DAG.getTarget().getCodeModel();
11228
11229   if (Subtarget->isPICStyleRIPRel() &&
11230       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11231     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11232       OpFlag = X86II::MO_GOTPCREL;
11233     WrapperKind = X86ISD::WrapperRIP;
11234   } else if (Subtarget->isPICStyleGOT()) {
11235     OpFlag = X86II::MO_GOT;
11236   } else if (Subtarget->isPICStyleStubPIC()) {
11237     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11238   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11239     OpFlag = X86II::MO_DARWIN_NONLAZY;
11240   }
11241
11242   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11243
11244   SDLoc DL(Op);
11245   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11246
11247   // With PIC, the address is actually $g + Offset.
11248   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11249       !Subtarget->is64Bit()) {
11250     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11251                          DAG.getNode(X86ISD::GlobalBaseReg,
11252                                      SDLoc(), getPointerTy()),
11253                          Result);
11254   }
11255
11256   // For symbols that require a load from a stub to get the address, emit the
11257   // load.
11258   if (isGlobalStubReference(OpFlag))
11259     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11260                          MachinePointerInfo::getGOT(), false, false, false, 0);
11261
11262   return Result;
11263 }
11264
11265 SDValue
11266 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11267   // Create the TargetBlockAddressAddress node.
11268   unsigned char OpFlags =
11269     Subtarget->ClassifyBlockAddressReference();
11270   CodeModel::Model M = DAG.getTarget().getCodeModel();
11271   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11272   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11273   SDLoc dl(Op);
11274   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11275                                              OpFlags);
11276
11277   if (Subtarget->isPICStyleRIPRel() &&
11278       (M == CodeModel::Small || M == CodeModel::Kernel))
11279     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11280   else
11281     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11282
11283   // With PIC, the address is actually $g + Offset.
11284   if (isGlobalRelativeToPICBase(OpFlags)) {
11285     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11286                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11287                          Result);
11288   }
11289
11290   return Result;
11291 }
11292
11293 SDValue
11294 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11295                                       int64_t Offset, SelectionDAG &DAG) const {
11296   // Create the TargetGlobalAddress node, folding in the constant
11297   // offset if it is legal.
11298   unsigned char OpFlags =
11299       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11300   CodeModel::Model M = DAG.getTarget().getCodeModel();
11301   SDValue Result;
11302   if (OpFlags == X86II::MO_NO_FLAG &&
11303       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11304     // A direct static reference to a global.
11305     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11306     Offset = 0;
11307   } else {
11308     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11309   }
11310
11311   if (Subtarget->isPICStyleRIPRel() &&
11312       (M == CodeModel::Small || M == CodeModel::Kernel))
11313     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11314   else
11315     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11316
11317   // With PIC, the address is actually $g + Offset.
11318   if (isGlobalRelativeToPICBase(OpFlags)) {
11319     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11320                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11321                          Result);
11322   }
11323
11324   // For globals that require a load from a stub to get the address, emit the
11325   // load.
11326   if (isGlobalStubReference(OpFlags))
11327     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11328                          MachinePointerInfo::getGOT(), false, false, false, 0);
11329
11330   // If there was a non-zero offset that we didn't fold, create an explicit
11331   // addition for it.
11332   if (Offset != 0)
11333     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11334                          DAG.getConstant(Offset, getPointerTy()));
11335
11336   return Result;
11337 }
11338
11339 SDValue
11340 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11341   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11342   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11343   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11344 }
11345
11346 static SDValue
11347 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11348            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11349            unsigned char OperandFlags, bool LocalDynamic = false) {
11350   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11351   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11352   SDLoc dl(GA);
11353   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11354                                            GA->getValueType(0),
11355                                            GA->getOffset(),
11356                                            OperandFlags);
11357
11358   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11359                                            : X86ISD::TLSADDR;
11360
11361   if (InFlag) {
11362     SDValue Ops[] = { Chain,  TGA, *InFlag };
11363     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11364   } else {
11365     SDValue Ops[]  = { Chain, TGA };
11366     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11367   }
11368
11369   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11370   MFI->setAdjustsStack(true);
11371
11372   SDValue Flag = Chain.getValue(1);
11373   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11374 }
11375
11376 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11377 static SDValue
11378 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11379                                 const EVT PtrVT) {
11380   SDValue InFlag;
11381   SDLoc dl(GA);  // ? function entry point might be better
11382   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11383                                    DAG.getNode(X86ISD::GlobalBaseReg,
11384                                                SDLoc(), PtrVT), InFlag);
11385   InFlag = Chain.getValue(1);
11386
11387   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11388 }
11389
11390 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11391 static SDValue
11392 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11393                                 const EVT PtrVT) {
11394   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11395                     X86::RAX, X86II::MO_TLSGD);
11396 }
11397
11398 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11399                                            SelectionDAG &DAG,
11400                                            const EVT PtrVT,
11401                                            bool is64Bit) {
11402   SDLoc dl(GA);
11403
11404   // Get the start address of the TLS block for this module.
11405   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11406       .getInfo<X86MachineFunctionInfo>();
11407   MFI->incNumLocalDynamicTLSAccesses();
11408
11409   SDValue Base;
11410   if (is64Bit) {
11411     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11412                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11413   } else {
11414     SDValue InFlag;
11415     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11416         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11417     InFlag = Chain.getValue(1);
11418     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11419                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11420   }
11421
11422   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11423   // of Base.
11424
11425   // Build x@dtpoff.
11426   unsigned char OperandFlags = X86II::MO_DTPOFF;
11427   unsigned WrapperKind = X86ISD::Wrapper;
11428   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11429                                            GA->getValueType(0),
11430                                            GA->getOffset(), OperandFlags);
11431   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11432
11433   // Add x@dtpoff with the base.
11434   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11435 }
11436
11437 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11438 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11439                                    const EVT PtrVT, TLSModel::Model model,
11440                                    bool is64Bit, bool isPIC) {
11441   SDLoc dl(GA);
11442
11443   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11444   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11445                                                          is64Bit ? 257 : 256));
11446
11447   SDValue ThreadPointer =
11448       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11449                   MachinePointerInfo(Ptr), false, false, false, 0);
11450
11451   unsigned char OperandFlags = 0;
11452   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11453   // initialexec.
11454   unsigned WrapperKind = X86ISD::Wrapper;
11455   if (model == TLSModel::LocalExec) {
11456     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11457   } else if (model == TLSModel::InitialExec) {
11458     if (is64Bit) {
11459       OperandFlags = X86II::MO_GOTTPOFF;
11460       WrapperKind = X86ISD::WrapperRIP;
11461     } else {
11462       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11463     }
11464   } else {
11465     llvm_unreachable("Unexpected model");
11466   }
11467
11468   // emit "addl x@ntpoff,%eax" (local exec)
11469   // or "addl x@indntpoff,%eax" (initial exec)
11470   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11471   SDValue TGA =
11472       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11473                                  GA->getOffset(), OperandFlags);
11474   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11475
11476   if (model == TLSModel::InitialExec) {
11477     if (isPIC && !is64Bit) {
11478       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11479                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11480                            Offset);
11481     }
11482
11483     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11484                          MachinePointerInfo::getGOT(), false, false, false, 0);
11485   }
11486
11487   // The address of the thread local variable is the add of the thread
11488   // pointer with the offset of the variable.
11489   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11490 }
11491
11492 SDValue
11493 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11494
11495   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11496   const GlobalValue *GV = GA->getGlobal();
11497
11498   if (Subtarget->isTargetELF()) {
11499     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11500
11501     switch (model) {
11502       case TLSModel::GeneralDynamic:
11503         if (Subtarget->is64Bit())
11504           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11505         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11506       case TLSModel::LocalDynamic:
11507         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11508                                            Subtarget->is64Bit());
11509       case TLSModel::InitialExec:
11510       case TLSModel::LocalExec:
11511         return LowerToTLSExecModel(
11512             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11513             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11514     }
11515     llvm_unreachable("Unknown TLS model.");
11516   }
11517
11518   if (Subtarget->isTargetDarwin()) {
11519     // Darwin only has one model of TLS.  Lower to that.
11520     unsigned char OpFlag = 0;
11521     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11522                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11523
11524     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11525     // global base reg.
11526     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11527                  !Subtarget->is64Bit();
11528     if (PIC32)
11529       OpFlag = X86II::MO_TLVP_PIC_BASE;
11530     else
11531       OpFlag = X86II::MO_TLVP;
11532     SDLoc DL(Op);
11533     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11534                                                 GA->getValueType(0),
11535                                                 GA->getOffset(), OpFlag);
11536     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11537
11538     // With PIC32, the address is actually $g + Offset.
11539     if (PIC32)
11540       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11541                            DAG.getNode(X86ISD::GlobalBaseReg,
11542                                        SDLoc(), getPointerTy()),
11543                            Offset);
11544
11545     // Lowering the machine isd will make sure everything is in the right
11546     // location.
11547     SDValue Chain = DAG.getEntryNode();
11548     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11549     SDValue Args[] = { Chain, Offset };
11550     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11551
11552     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11553     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11554     MFI->setAdjustsStack(true);
11555
11556     // And our return value (tls address) is in the standard call return value
11557     // location.
11558     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11559     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11560                               Chain.getValue(1));
11561   }
11562
11563   if (Subtarget->isTargetKnownWindowsMSVC() ||
11564       Subtarget->isTargetWindowsGNU()) {
11565     // Just use the implicit TLS architecture
11566     // Need to generate someting similar to:
11567     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11568     //                                  ; from TEB
11569     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11570     //   mov     rcx, qword [rdx+rcx*8]
11571     //   mov     eax, .tls$:tlsvar
11572     //   [rax+rcx] contains the address
11573     // Windows 64bit: gs:0x58
11574     // Windows 32bit: fs:__tls_array
11575
11576     SDLoc dl(GA);
11577     SDValue Chain = DAG.getEntryNode();
11578
11579     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11580     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11581     // use its literal value of 0x2C.
11582     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11583                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11584                                                              256)
11585                                         : Type::getInt32PtrTy(*DAG.getContext(),
11586                                                               257));
11587
11588     SDValue TlsArray =
11589         Subtarget->is64Bit()
11590             ? DAG.getIntPtrConstant(0x58)
11591             : (Subtarget->isTargetWindowsGNU()
11592                    ? DAG.getIntPtrConstant(0x2C)
11593                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11594
11595     SDValue ThreadPointer =
11596         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11597                     MachinePointerInfo(Ptr), false, false, false, 0);
11598
11599     // Load the _tls_index variable
11600     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11601     if (Subtarget->is64Bit())
11602       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11603                            IDX, MachinePointerInfo(), MVT::i32,
11604                            false, false, false, 0);
11605     else
11606       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11607                         false, false, false, 0);
11608
11609     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11610                                     getPointerTy());
11611     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11612
11613     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11614     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11615                       false, false, false, 0);
11616
11617     // Get the offset of start of .tls section
11618     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11619                                              GA->getValueType(0),
11620                                              GA->getOffset(), X86II::MO_SECREL);
11621     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11622
11623     // The address of the thread local variable is the add of the thread
11624     // pointer with the offset of the variable.
11625     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11626   }
11627
11628   llvm_unreachable("TLS not implemented for this target.");
11629 }
11630
11631 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11632 /// and take a 2 x i32 value to shift plus a shift amount.
11633 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11634   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11635   MVT VT = Op.getSimpleValueType();
11636   unsigned VTBits = VT.getSizeInBits();
11637   SDLoc dl(Op);
11638   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11639   SDValue ShOpLo = Op.getOperand(0);
11640   SDValue ShOpHi = Op.getOperand(1);
11641   SDValue ShAmt  = Op.getOperand(2);
11642   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11643   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11644   // during isel.
11645   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11646                                   DAG.getConstant(VTBits - 1, MVT::i8));
11647   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11648                                      DAG.getConstant(VTBits - 1, MVT::i8))
11649                        : DAG.getConstant(0, VT);
11650
11651   SDValue Tmp2, Tmp3;
11652   if (Op.getOpcode() == ISD::SHL_PARTS) {
11653     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11654     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11655   } else {
11656     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11657     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11658   }
11659
11660   // If the shift amount is larger or equal than the width of a part we can't
11661   // rely on the results of shld/shrd. Insert a test and select the appropriate
11662   // values for large shift amounts.
11663   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11664                                 DAG.getConstant(VTBits, MVT::i8));
11665   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11666                              AndNode, DAG.getConstant(0, MVT::i8));
11667
11668   SDValue Hi, Lo;
11669   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11670   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11671   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11672
11673   if (Op.getOpcode() == ISD::SHL_PARTS) {
11674     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11675     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11676   } else {
11677     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11678     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11679   }
11680
11681   SDValue Ops[2] = { Lo, Hi };
11682   return DAG.getMergeValues(Ops, dl);
11683 }
11684
11685 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11686                                            SelectionDAG &DAG) const {
11687   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11688
11689   if (SrcVT.isVector())
11690     return SDValue();
11691
11692   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11693          "Unknown SINT_TO_FP to lower!");
11694
11695   // These are really Legal; return the operand so the caller accepts it as
11696   // Legal.
11697   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11698     return Op;
11699   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11700       Subtarget->is64Bit()) {
11701     return Op;
11702   }
11703
11704   SDLoc dl(Op);
11705   unsigned Size = SrcVT.getSizeInBits()/8;
11706   MachineFunction &MF = DAG.getMachineFunction();
11707   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11708   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11709   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11710                                StackSlot,
11711                                MachinePointerInfo::getFixedStack(SSFI),
11712                                false, false, 0);
11713   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11714 }
11715
11716 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11717                                      SDValue StackSlot,
11718                                      SelectionDAG &DAG) const {
11719   // Build the FILD
11720   SDLoc DL(Op);
11721   SDVTList Tys;
11722   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11723   if (useSSE)
11724     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11725   else
11726     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11727
11728   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11729
11730   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11731   MachineMemOperand *MMO;
11732   if (FI) {
11733     int SSFI = FI->getIndex();
11734     MMO =
11735       DAG.getMachineFunction()
11736       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11737                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11738   } else {
11739     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11740     StackSlot = StackSlot.getOperand(1);
11741   }
11742   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11743   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11744                                            X86ISD::FILD, DL,
11745                                            Tys, Ops, SrcVT, MMO);
11746
11747   if (useSSE) {
11748     Chain = Result.getValue(1);
11749     SDValue InFlag = Result.getValue(2);
11750
11751     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11752     // shouldn't be necessary except that RFP cannot be live across
11753     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11754     MachineFunction &MF = DAG.getMachineFunction();
11755     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11756     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11757     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11758     Tys = DAG.getVTList(MVT::Other);
11759     SDValue Ops[] = {
11760       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11761     };
11762     MachineMemOperand *MMO =
11763       DAG.getMachineFunction()
11764       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11765                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11766
11767     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11768                                     Ops, Op.getValueType(), MMO);
11769     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11770                          MachinePointerInfo::getFixedStack(SSFI),
11771                          false, false, false, 0);
11772   }
11773
11774   return Result;
11775 }
11776
11777 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11778 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11779                                                SelectionDAG &DAG) const {
11780   // This algorithm is not obvious. Here it is what we're trying to output:
11781   /*
11782      movq       %rax,  %xmm0
11783      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11784      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11785      #ifdef __SSE3__
11786        haddpd   %xmm0, %xmm0
11787      #else
11788        pshufd   $0x4e, %xmm0, %xmm1
11789        addpd    %xmm1, %xmm0
11790      #endif
11791   */
11792
11793   SDLoc dl(Op);
11794   LLVMContext *Context = DAG.getContext();
11795
11796   // Build some magic constants.
11797   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11798   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11799   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11800
11801   SmallVector<Constant*,2> CV1;
11802   CV1.push_back(
11803     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11804                                       APInt(64, 0x4330000000000000ULL))));
11805   CV1.push_back(
11806     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11807                                       APInt(64, 0x4530000000000000ULL))));
11808   Constant *C1 = ConstantVector::get(CV1);
11809   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11810
11811   // Load the 64-bit value into an XMM register.
11812   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11813                             Op.getOperand(0));
11814   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11815                               MachinePointerInfo::getConstantPool(),
11816                               false, false, false, 16);
11817   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11818                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11819                               CLod0);
11820
11821   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11822                               MachinePointerInfo::getConstantPool(),
11823                               false, false, false, 16);
11824   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11825   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11826   SDValue Result;
11827
11828   if (Subtarget->hasSSE3()) {
11829     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11830     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11831   } else {
11832     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11833     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11834                                            S2F, 0x4E, DAG);
11835     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11836                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11837                          Sub);
11838   }
11839
11840   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11841                      DAG.getIntPtrConstant(0));
11842 }
11843
11844 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11845 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11846                                                SelectionDAG &DAG) const {
11847   SDLoc dl(Op);
11848   // FP constant to bias correct the final result.
11849   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11850                                    MVT::f64);
11851
11852   // Load the 32-bit value into an XMM register.
11853   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11854                              Op.getOperand(0));
11855
11856   // Zero out the upper parts of the register.
11857   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11858
11859   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11860                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11861                      DAG.getIntPtrConstant(0));
11862
11863   // Or the load with the bias.
11864   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11865                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11866                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11867                                                    MVT::v2f64, Load)),
11868                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11869                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11870                                                    MVT::v2f64, Bias)));
11871   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11872                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11873                    DAG.getIntPtrConstant(0));
11874
11875   // Subtract the bias.
11876   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11877
11878   // Handle final rounding.
11879   EVT DestVT = Op.getValueType();
11880
11881   if (DestVT.bitsLT(MVT::f64))
11882     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11883                        DAG.getIntPtrConstant(0));
11884   if (DestVT.bitsGT(MVT::f64))
11885     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11886
11887   // Handle final rounding.
11888   return Sub;
11889 }
11890
11891 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11892                                                SelectionDAG &DAG) const {
11893   SDValue N0 = Op.getOperand(0);
11894   MVT SVT = N0.getSimpleValueType();
11895   SDLoc dl(Op);
11896
11897   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11898           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11899          "Custom UINT_TO_FP is not supported!");
11900
11901   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11902   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11903                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11904 }
11905
11906 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11907                                            SelectionDAG &DAG) const {
11908   SDValue N0 = Op.getOperand(0);
11909   SDLoc dl(Op);
11910
11911   if (Op.getValueType().isVector())
11912     return lowerUINT_TO_FP_vec(Op, DAG);
11913
11914   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11915   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11916   // the optimization here.
11917   if (DAG.SignBitIsZero(N0))
11918     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11919
11920   MVT SrcVT = N0.getSimpleValueType();
11921   MVT DstVT = Op.getSimpleValueType();
11922   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11923     return LowerUINT_TO_FP_i64(Op, DAG);
11924   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11925     return LowerUINT_TO_FP_i32(Op, DAG);
11926   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11927     return SDValue();
11928
11929   // Make a 64-bit buffer, and use it to build an FILD.
11930   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11931   if (SrcVT == MVT::i32) {
11932     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11933     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11934                                      getPointerTy(), StackSlot, WordOff);
11935     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11936                                   StackSlot, MachinePointerInfo(),
11937                                   false, false, 0);
11938     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11939                                   OffsetSlot, MachinePointerInfo(),
11940                                   false, false, 0);
11941     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11942     return Fild;
11943   }
11944
11945   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11946   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11947                                StackSlot, MachinePointerInfo(),
11948                                false, false, 0);
11949   // For i64 source, we need to add the appropriate power of 2 if the input
11950   // was negative.  This is the same as the optimization in
11951   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11952   // we must be careful to do the computation in x87 extended precision, not
11953   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11954   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11955   MachineMemOperand *MMO =
11956     DAG.getMachineFunction()
11957     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11958                           MachineMemOperand::MOLoad, 8, 8);
11959
11960   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11961   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11962   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11963                                          MVT::i64, MMO);
11964
11965   APInt FF(32, 0x5F800000ULL);
11966
11967   // Check whether the sign bit is set.
11968   SDValue SignSet = DAG.getSetCC(dl,
11969                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11970                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11971                                  ISD::SETLT);
11972
11973   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11974   SDValue FudgePtr = DAG.getConstantPool(
11975                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11976                                          getPointerTy());
11977
11978   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11979   SDValue Zero = DAG.getIntPtrConstant(0);
11980   SDValue Four = DAG.getIntPtrConstant(4);
11981   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11982                                Zero, Four);
11983   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11984
11985   // Load the value out, extending it from f32 to f80.
11986   // FIXME: Avoid the extend by constructing the right constant pool?
11987   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11988                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11989                                  MVT::f32, false, false, false, 4);
11990   // Extend everything to 80 bits to force it to be done on x87.
11991   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11992   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11993 }
11994
11995 std::pair<SDValue,SDValue>
11996 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11997                                     bool IsSigned, bool IsReplace) const {
11998   SDLoc DL(Op);
11999
12000   EVT DstTy = Op.getValueType();
12001
12002   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12003     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12004     DstTy = MVT::i64;
12005   }
12006
12007   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12008          DstTy.getSimpleVT() >= MVT::i16 &&
12009          "Unknown FP_TO_INT to lower!");
12010
12011   // These are really Legal.
12012   if (DstTy == MVT::i32 &&
12013       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12014     return std::make_pair(SDValue(), SDValue());
12015   if (Subtarget->is64Bit() &&
12016       DstTy == MVT::i64 &&
12017       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12018     return std::make_pair(SDValue(), SDValue());
12019
12020   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12021   // stack slot, or into the FTOL runtime function.
12022   MachineFunction &MF = DAG.getMachineFunction();
12023   unsigned MemSize = DstTy.getSizeInBits()/8;
12024   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12025   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12026
12027   unsigned Opc;
12028   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12029     Opc = X86ISD::WIN_FTOL;
12030   else
12031     switch (DstTy.getSimpleVT().SimpleTy) {
12032     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12033     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12034     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12035     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12036     }
12037
12038   SDValue Chain = DAG.getEntryNode();
12039   SDValue Value = Op.getOperand(0);
12040   EVT TheVT = Op.getOperand(0).getValueType();
12041   // FIXME This causes a redundant load/store if the SSE-class value is already
12042   // in memory, such as if it is on the callstack.
12043   if (isScalarFPTypeInSSEReg(TheVT)) {
12044     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12045     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12046                          MachinePointerInfo::getFixedStack(SSFI),
12047                          false, false, 0);
12048     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12049     SDValue Ops[] = {
12050       Chain, StackSlot, DAG.getValueType(TheVT)
12051     };
12052
12053     MachineMemOperand *MMO =
12054       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12055                               MachineMemOperand::MOLoad, MemSize, MemSize);
12056     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12057     Chain = Value.getValue(1);
12058     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12059     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12060   }
12061
12062   MachineMemOperand *MMO =
12063     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12064                             MachineMemOperand::MOStore, MemSize, MemSize);
12065
12066   if (Opc != X86ISD::WIN_FTOL) {
12067     // Build the FP_TO_INT*_IN_MEM
12068     SDValue Ops[] = { Chain, Value, StackSlot };
12069     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12070                                            Ops, DstTy, MMO);
12071     return std::make_pair(FIST, StackSlot);
12072   } else {
12073     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12074       DAG.getVTList(MVT::Other, MVT::Glue),
12075       Chain, Value);
12076     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12077       MVT::i32, ftol.getValue(1));
12078     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12079       MVT::i32, eax.getValue(2));
12080     SDValue Ops[] = { eax, edx };
12081     SDValue pair = IsReplace
12082       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12083       : DAG.getMergeValues(Ops, DL);
12084     return std::make_pair(pair, SDValue());
12085   }
12086 }
12087
12088 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12089                               const X86Subtarget *Subtarget) {
12090   MVT VT = Op->getSimpleValueType(0);
12091   SDValue In = Op->getOperand(0);
12092   MVT InVT = In.getSimpleValueType();
12093   SDLoc dl(Op);
12094
12095   // Optimize vectors in AVX mode:
12096   //
12097   //   v8i16 -> v8i32
12098   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12099   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12100   //   Concat upper and lower parts.
12101   //
12102   //   v4i32 -> v4i64
12103   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12104   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12105   //   Concat upper and lower parts.
12106   //
12107
12108   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12109       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12110       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12111     return SDValue();
12112
12113   if (Subtarget->hasInt256())
12114     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12115
12116   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12117   SDValue Undef = DAG.getUNDEF(InVT);
12118   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12119   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12120   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12121
12122   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12123                              VT.getVectorNumElements()/2);
12124
12125   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12126   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12127
12128   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12129 }
12130
12131 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12132                                         SelectionDAG &DAG) {
12133   MVT VT = Op->getSimpleValueType(0);
12134   SDValue In = Op->getOperand(0);
12135   MVT InVT = In.getSimpleValueType();
12136   SDLoc DL(Op);
12137   unsigned int NumElts = VT.getVectorNumElements();
12138   if (NumElts != 8 && NumElts != 16)
12139     return SDValue();
12140
12141   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12142     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12143
12144   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
12145   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12146   // Now we have only mask extension
12147   assert(InVT.getVectorElementType() == MVT::i1);
12148   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
12149   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12150   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12151   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12152   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12153                            MachinePointerInfo::getConstantPool(),
12154                            false, false, false, Alignment);
12155
12156   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
12157   if (VT.is512BitVector())
12158     return Brcst;
12159   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
12160 }
12161
12162 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12163                                SelectionDAG &DAG) {
12164   if (Subtarget->hasFp256()) {
12165     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12166     if (Res.getNode())
12167       return Res;
12168   }
12169
12170   return SDValue();
12171 }
12172
12173 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12174                                 SelectionDAG &DAG) {
12175   SDLoc DL(Op);
12176   MVT VT = Op.getSimpleValueType();
12177   SDValue In = Op.getOperand(0);
12178   MVT SVT = In.getSimpleValueType();
12179
12180   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12181     return LowerZERO_EXTEND_AVX512(Op, DAG);
12182
12183   if (Subtarget->hasFp256()) {
12184     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12185     if (Res.getNode())
12186       return Res;
12187   }
12188
12189   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12190          VT.getVectorNumElements() != SVT.getVectorNumElements());
12191   return SDValue();
12192 }
12193
12194 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12195   SDLoc DL(Op);
12196   MVT VT = Op.getSimpleValueType();
12197   SDValue In = Op.getOperand(0);
12198   MVT InVT = In.getSimpleValueType();
12199
12200   if (VT == MVT::i1) {
12201     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12202            "Invalid scalar TRUNCATE operation");
12203     if (InVT.getSizeInBits() >= 32)
12204       return SDValue();
12205     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12206     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12207   }
12208   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12209          "Invalid TRUNCATE operation");
12210
12211   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12212     if (VT.getVectorElementType().getSizeInBits() >=8)
12213       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12214
12215     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12216     unsigned NumElts = InVT.getVectorNumElements();
12217     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12218     if (InVT.getSizeInBits() < 512) {
12219       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12220       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12221       InVT = ExtVT;
12222     }
12223     
12224     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12225     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12226     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12227     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12228     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12229                            MachinePointerInfo::getConstantPool(),
12230                            false, false, false, Alignment);
12231     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12232     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12233     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12234   }
12235
12236   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12237     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12238     if (Subtarget->hasInt256()) {
12239       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12240       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12241       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12242                                 ShufMask);
12243       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12244                          DAG.getIntPtrConstant(0));
12245     }
12246
12247     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12248                                DAG.getIntPtrConstant(0));
12249     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12250                                DAG.getIntPtrConstant(2));
12251     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12252     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12253     static const int ShufMask[] = {0, 2, 4, 6};
12254     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12255   }
12256
12257   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12258     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12259     if (Subtarget->hasInt256()) {
12260       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12261
12262       SmallVector<SDValue,32> pshufbMask;
12263       for (unsigned i = 0; i < 2; ++i) {
12264         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12265         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12266         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12267         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12268         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12269         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12270         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12271         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12272         for (unsigned j = 0; j < 8; ++j)
12273           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12274       }
12275       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12276       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12277       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12278
12279       static const int ShufMask[] = {0,  2,  -1,  -1};
12280       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12281                                 &ShufMask[0]);
12282       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12283                        DAG.getIntPtrConstant(0));
12284       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12285     }
12286
12287     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12288                                DAG.getIntPtrConstant(0));
12289
12290     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12291                                DAG.getIntPtrConstant(4));
12292
12293     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12294     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12295
12296     // The PSHUFB mask:
12297     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12298                                    -1, -1, -1, -1, -1, -1, -1, -1};
12299
12300     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12301     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12302     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12303
12304     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12305     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12306
12307     // The MOVLHPS Mask:
12308     static const int ShufMask2[] = {0, 1, 4, 5};
12309     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12310     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12311   }
12312
12313   // Handle truncation of V256 to V128 using shuffles.
12314   if (!VT.is128BitVector() || !InVT.is256BitVector())
12315     return SDValue();
12316
12317   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12318
12319   unsigned NumElems = VT.getVectorNumElements();
12320   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12321
12322   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12323   // Prepare truncation shuffle mask
12324   for (unsigned i = 0; i != NumElems; ++i)
12325     MaskVec[i] = i * 2;
12326   SDValue V = DAG.getVectorShuffle(NVT, DL,
12327                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12328                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12329   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12330                      DAG.getIntPtrConstant(0));
12331 }
12332
12333 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12334                                            SelectionDAG &DAG) const {
12335   assert(!Op.getSimpleValueType().isVector());
12336
12337   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12338     /*IsSigned=*/ true, /*IsReplace=*/ false);
12339   SDValue FIST = Vals.first, StackSlot = Vals.second;
12340   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12341   if (!FIST.getNode()) return Op;
12342
12343   if (StackSlot.getNode())
12344     // Load the result.
12345     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12346                        FIST, StackSlot, MachinePointerInfo(),
12347                        false, false, false, 0);
12348
12349   // The node is the result.
12350   return FIST;
12351 }
12352
12353 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12354                                            SelectionDAG &DAG) const {
12355   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12356     /*IsSigned=*/ false, /*IsReplace=*/ false);
12357   SDValue FIST = Vals.first, StackSlot = Vals.second;
12358   assert(FIST.getNode() && "Unexpected failure");
12359
12360   if (StackSlot.getNode())
12361     // Load the result.
12362     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12363                        FIST, StackSlot, MachinePointerInfo(),
12364                        false, false, false, 0);
12365
12366   // The node is the result.
12367   return FIST;
12368 }
12369
12370 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12371   SDLoc DL(Op);
12372   MVT VT = Op.getSimpleValueType();
12373   SDValue In = Op.getOperand(0);
12374   MVT SVT = In.getSimpleValueType();
12375
12376   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12377
12378   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12379                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12380                                  In, DAG.getUNDEF(SVT)));
12381 }
12382
12383 // The only differences between FABS and FNEG are the mask and the logic op.
12384 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12385   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12386          "Wrong opcode for lowering FABS or FNEG.");
12387
12388   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12389   SDLoc dl(Op);
12390   MVT VT = Op.getSimpleValueType();
12391   // Assume scalar op for initialization; update for vector if needed.
12392   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12393   // generate a 16-byte vector constant and logic op even for the scalar case.
12394   // Using a 16-byte mask allows folding the load of the mask with
12395   // the logic op, so it can save (~4 bytes) on code size.
12396   MVT EltVT = VT;
12397   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12398   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12399   // decide if we should generate a 16-byte constant mask when we only need 4 or
12400   // 8 bytes for the scalar case.
12401   if (VT.isVector()) {
12402     EltVT = VT.getVectorElementType();
12403     NumElts = VT.getVectorNumElements();
12404   }
12405   
12406   unsigned EltBits = EltVT.getSizeInBits();
12407   LLVMContext *Context = DAG.getContext();
12408   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12409   APInt MaskElt =
12410     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12411   Constant *C = ConstantInt::get(*Context, MaskElt);
12412   C = ConstantVector::getSplat(NumElts, C);
12413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12414   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12415   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12416   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12417                              MachinePointerInfo::getConstantPool(),
12418                              false, false, false, Alignment);
12419
12420   if (VT.isVector()) {
12421     // For a vector, cast operands to a vector type, perform the logic op,
12422     // and cast the result back to the original value type.
12423     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12424     SDValue Op0Casted = DAG.getNode(ISD::BITCAST, dl, VecVT, Op.getOperand(0));
12425     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12426     unsigned LogicOp = IsFABS ? ISD::AND : ISD::XOR;
12427     return DAG.getNode(ISD::BITCAST, dl, VT,
12428                        DAG.getNode(LogicOp, dl, VecVT, Op0Casted, MaskCasted));
12429   }
12430   // If not vector, then scalar.
12431   unsigned LogicOp = IsFABS ? X86ISD::FAND : X86ISD::FXOR;
12432   return DAG.getNode(LogicOp, dl, VT, Op.getOperand(0), Mask);
12433 }
12434
12435 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12437   LLVMContext *Context = DAG.getContext();
12438   SDValue Op0 = Op.getOperand(0);
12439   SDValue Op1 = Op.getOperand(1);
12440   SDLoc dl(Op);
12441   MVT VT = Op.getSimpleValueType();
12442   MVT SrcVT = Op1.getSimpleValueType();
12443
12444   // If second operand is smaller, extend it first.
12445   if (SrcVT.bitsLT(VT)) {
12446     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12447     SrcVT = VT;
12448   }
12449   // And if it is bigger, shrink it first.
12450   if (SrcVT.bitsGT(VT)) {
12451     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12452     SrcVT = VT;
12453   }
12454
12455   // At this point the operands and the result should have the same
12456   // type, and that won't be f80 since that is not custom lowered.
12457
12458   // First get the sign bit of second operand.
12459   SmallVector<Constant*,4> CV;
12460   if (SrcVT == MVT::f64) {
12461     const fltSemantics &Sem = APFloat::IEEEdouble;
12462     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12463     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12464   } else {
12465     const fltSemantics &Sem = APFloat::IEEEsingle;
12466     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12467     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12468     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12469     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12470   }
12471   Constant *C = ConstantVector::get(CV);
12472   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12473   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12474                               MachinePointerInfo::getConstantPool(),
12475                               false, false, false, 16);
12476   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12477
12478   // Shift sign bit right or left if the two operands have different types.
12479   if (SrcVT.bitsGT(VT)) {
12480     // Op0 is MVT::f32, Op1 is MVT::f64.
12481     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12482     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12483                           DAG.getConstant(32, MVT::i32));
12484     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12485     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12486                           DAG.getIntPtrConstant(0));
12487   }
12488
12489   // Clear first operand sign bit.
12490   CV.clear();
12491   if (VT == MVT::f64) {
12492     const fltSemantics &Sem = APFloat::IEEEdouble;
12493     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12494                                                    APInt(64, ~(1ULL << 63)))));
12495     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12496   } else {
12497     const fltSemantics &Sem = APFloat::IEEEsingle;
12498     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12499                                                    APInt(32, ~(1U << 31)))));
12500     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12501     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12502     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12503   }
12504   C = ConstantVector::get(CV);
12505   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12506   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12507                               MachinePointerInfo::getConstantPool(),
12508                               false, false, false, 16);
12509   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12510
12511   // Or the value with the sign bit.
12512   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12513 }
12514
12515 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12516   SDValue N0 = Op.getOperand(0);
12517   SDLoc dl(Op);
12518   MVT VT = Op.getSimpleValueType();
12519
12520   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12521   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12522                                   DAG.getConstant(1, VT));
12523   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12524 }
12525
12526 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12527 //
12528 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12529                                       SelectionDAG &DAG) {
12530   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12531
12532   if (!Subtarget->hasSSE41())
12533     return SDValue();
12534
12535   if (!Op->hasOneUse())
12536     return SDValue();
12537
12538   SDNode *N = Op.getNode();
12539   SDLoc DL(N);
12540
12541   SmallVector<SDValue, 8> Opnds;
12542   DenseMap<SDValue, unsigned> VecInMap;
12543   SmallVector<SDValue, 8> VecIns;
12544   EVT VT = MVT::Other;
12545
12546   // Recognize a special case where a vector is casted into wide integer to
12547   // test all 0s.
12548   Opnds.push_back(N->getOperand(0));
12549   Opnds.push_back(N->getOperand(1));
12550
12551   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12552     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12553     // BFS traverse all OR'd operands.
12554     if (I->getOpcode() == ISD::OR) {
12555       Opnds.push_back(I->getOperand(0));
12556       Opnds.push_back(I->getOperand(1));
12557       // Re-evaluate the number of nodes to be traversed.
12558       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12559       continue;
12560     }
12561
12562     // Quit if a non-EXTRACT_VECTOR_ELT
12563     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12564       return SDValue();
12565
12566     // Quit if without a constant index.
12567     SDValue Idx = I->getOperand(1);
12568     if (!isa<ConstantSDNode>(Idx))
12569       return SDValue();
12570
12571     SDValue ExtractedFromVec = I->getOperand(0);
12572     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12573     if (M == VecInMap.end()) {
12574       VT = ExtractedFromVec.getValueType();
12575       // Quit if not 128/256-bit vector.
12576       if (!VT.is128BitVector() && !VT.is256BitVector())
12577         return SDValue();
12578       // Quit if not the same type.
12579       if (VecInMap.begin() != VecInMap.end() &&
12580           VT != VecInMap.begin()->first.getValueType())
12581         return SDValue();
12582       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12583       VecIns.push_back(ExtractedFromVec);
12584     }
12585     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12586   }
12587
12588   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12589          "Not extracted from 128-/256-bit vector.");
12590
12591   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12592
12593   for (DenseMap<SDValue, unsigned>::const_iterator
12594         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12595     // Quit if not all elements are used.
12596     if (I->second != FullMask)
12597       return SDValue();
12598   }
12599
12600   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12601
12602   // Cast all vectors into TestVT for PTEST.
12603   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12604     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12605
12606   // If more than one full vectors are evaluated, OR them first before PTEST.
12607   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12608     // Each iteration will OR 2 nodes and append the result until there is only
12609     // 1 node left, i.e. the final OR'd value of all vectors.
12610     SDValue LHS = VecIns[Slot];
12611     SDValue RHS = VecIns[Slot + 1];
12612     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12613   }
12614
12615   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12616                      VecIns.back(), VecIns.back());
12617 }
12618
12619 /// \brief return true if \c Op has a use that doesn't just read flags.
12620 static bool hasNonFlagsUse(SDValue Op) {
12621   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12622        ++UI) {
12623     SDNode *User = *UI;
12624     unsigned UOpNo = UI.getOperandNo();
12625     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12626       // Look pass truncate.
12627       UOpNo = User->use_begin().getOperandNo();
12628       User = *User->use_begin();
12629     }
12630
12631     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12632         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12633       return true;
12634   }
12635   return false;
12636 }
12637
12638 /// Emit nodes that will be selected as "test Op0,Op0", or something
12639 /// equivalent.
12640 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12641                                     SelectionDAG &DAG) const {
12642   if (Op.getValueType() == MVT::i1)
12643     // KORTEST instruction should be selected
12644     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12645                        DAG.getConstant(0, Op.getValueType()));
12646
12647   // CF and OF aren't always set the way we want. Determine which
12648   // of these we need.
12649   bool NeedCF = false;
12650   bool NeedOF = false;
12651   switch (X86CC) {
12652   default: break;
12653   case X86::COND_A: case X86::COND_AE:
12654   case X86::COND_B: case X86::COND_BE:
12655     NeedCF = true;
12656     break;
12657   case X86::COND_G: case X86::COND_GE:
12658   case X86::COND_L: case X86::COND_LE:
12659   case X86::COND_O: case X86::COND_NO: {
12660     // Check if we really need to set the
12661     // Overflow flag. If NoSignedWrap is present
12662     // that is not actually needed.
12663     switch (Op->getOpcode()) {
12664     case ISD::ADD:
12665     case ISD::SUB:
12666     case ISD::MUL:
12667     case ISD::SHL: {
12668       const BinaryWithFlagsSDNode *BinNode =
12669           cast<BinaryWithFlagsSDNode>(Op.getNode());
12670       if (BinNode->hasNoSignedWrap())
12671         break;
12672     }
12673     default:
12674       NeedOF = true;
12675       break;
12676     }
12677     break;
12678   }
12679   }
12680   // See if we can use the EFLAGS value from the operand instead of
12681   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12682   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12683   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12684     // Emit a CMP with 0, which is the TEST pattern.
12685     //if (Op.getValueType() == MVT::i1)
12686     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12687     //                     DAG.getConstant(0, MVT::i1));
12688     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12689                        DAG.getConstant(0, Op.getValueType()));
12690   }
12691   unsigned Opcode = 0;
12692   unsigned NumOperands = 0;
12693
12694   // Truncate operations may prevent the merge of the SETCC instruction
12695   // and the arithmetic instruction before it. Attempt to truncate the operands
12696   // of the arithmetic instruction and use a reduced bit-width instruction.
12697   bool NeedTruncation = false;
12698   SDValue ArithOp = Op;
12699   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12700     SDValue Arith = Op->getOperand(0);
12701     // Both the trunc and the arithmetic op need to have one user each.
12702     if (Arith->hasOneUse())
12703       switch (Arith.getOpcode()) {
12704         default: break;
12705         case ISD::ADD:
12706         case ISD::SUB:
12707         case ISD::AND:
12708         case ISD::OR:
12709         case ISD::XOR: {
12710           NeedTruncation = true;
12711           ArithOp = Arith;
12712         }
12713       }
12714   }
12715
12716   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12717   // which may be the result of a CAST.  We use the variable 'Op', which is the
12718   // non-casted variable when we check for possible users.
12719   switch (ArithOp.getOpcode()) {
12720   case ISD::ADD:
12721     // Due to an isel shortcoming, be conservative if this add is likely to be
12722     // selected as part of a load-modify-store instruction. When the root node
12723     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12724     // uses of other nodes in the match, such as the ADD in this case. This
12725     // leads to the ADD being left around and reselected, with the result being
12726     // two adds in the output.  Alas, even if none our users are stores, that
12727     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12728     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12729     // climbing the DAG back to the root, and it doesn't seem to be worth the
12730     // effort.
12731     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12732          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12733       if (UI->getOpcode() != ISD::CopyToReg &&
12734           UI->getOpcode() != ISD::SETCC &&
12735           UI->getOpcode() != ISD::STORE)
12736         goto default_case;
12737
12738     if (ConstantSDNode *C =
12739         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12740       // An add of one will be selected as an INC.
12741       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12742         Opcode = X86ISD::INC;
12743         NumOperands = 1;
12744         break;
12745       }
12746
12747       // An add of negative one (subtract of one) will be selected as a DEC.
12748       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12749         Opcode = X86ISD::DEC;
12750         NumOperands = 1;
12751         break;
12752       }
12753     }
12754
12755     // Otherwise use a regular EFLAGS-setting add.
12756     Opcode = X86ISD::ADD;
12757     NumOperands = 2;
12758     break;
12759   case ISD::SHL:
12760   case ISD::SRL:
12761     // If we have a constant logical shift that's only used in a comparison
12762     // against zero turn it into an equivalent AND. This allows turning it into
12763     // a TEST instruction later.
12764     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12765         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12766       EVT VT = Op.getValueType();
12767       unsigned BitWidth = VT.getSizeInBits();
12768       unsigned ShAmt = Op->getConstantOperandVal(1);
12769       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12770         break;
12771       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12772                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12773                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12774       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12775         break;
12776       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12777                                 DAG.getConstant(Mask, VT));
12778       DAG.ReplaceAllUsesWith(Op, New);
12779       Op = New;
12780     }
12781     break;
12782
12783   case ISD::AND:
12784     // If the primary and result isn't used, don't bother using X86ISD::AND,
12785     // because a TEST instruction will be better.
12786     if (!hasNonFlagsUse(Op))
12787       break;
12788     // FALL THROUGH
12789   case ISD::SUB:
12790   case ISD::OR:
12791   case ISD::XOR:
12792     // Due to the ISEL shortcoming noted above, be conservative if this op is
12793     // likely to be selected as part of a load-modify-store instruction.
12794     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12795            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12796       if (UI->getOpcode() == ISD::STORE)
12797         goto default_case;
12798
12799     // Otherwise use a regular EFLAGS-setting instruction.
12800     switch (ArithOp.getOpcode()) {
12801     default: llvm_unreachable("unexpected operator!");
12802     case ISD::SUB: Opcode = X86ISD::SUB; break;
12803     case ISD::XOR: Opcode = X86ISD::XOR; break;
12804     case ISD::AND: Opcode = X86ISD::AND; break;
12805     case ISD::OR: {
12806       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12807         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12808         if (EFLAGS.getNode())
12809           return EFLAGS;
12810       }
12811       Opcode = X86ISD::OR;
12812       break;
12813     }
12814     }
12815
12816     NumOperands = 2;
12817     break;
12818   case X86ISD::ADD:
12819   case X86ISD::SUB:
12820   case X86ISD::INC:
12821   case X86ISD::DEC:
12822   case X86ISD::OR:
12823   case X86ISD::XOR:
12824   case X86ISD::AND:
12825     return SDValue(Op.getNode(), 1);
12826   default:
12827   default_case:
12828     break;
12829   }
12830
12831   // If we found that truncation is beneficial, perform the truncation and
12832   // update 'Op'.
12833   if (NeedTruncation) {
12834     EVT VT = Op.getValueType();
12835     SDValue WideVal = Op->getOperand(0);
12836     EVT WideVT = WideVal.getValueType();
12837     unsigned ConvertedOp = 0;
12838     // Use a target machine opcode to prevent further DAGCombine
12839     // optimizations that may separate the arithmetic operations
12840     // from the setcc node.
12841     switch (WideVal.getOpcode()) {
12842       default: break;
12843       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12844       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12845       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12846       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12847       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12848     }
12849
12850     if (ConvertedOp) {
12851       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12852       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12853         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12854         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12855         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12856       }
12857     }
12858   }
12859
12860   if (Opcode == 0)
12861     // Emit a CMP with 0, which is the TEST pattern.
12862     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12863                        DAG.getConstant(0, Op.getValueType()));
12864
12865   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12866   SmallVector<SDValue, 4> Ops;
12867   for (unsigned i = 0; i != NumOperands; ++i)
12868     Ops.push_back(Op.getOperand(i));
12869
12870   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12871   DAG.ReplaceAllUsesWith(Op, New);
12872   return SDValue(New.getNode(), 1);
12873 }
12874
12875 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12876 /// equivalent.
12877 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12878                                    SDLoc dl, SelectionDAG &DAG) const {
12879   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12880     if (C->getAPIntValue() == 0)
12881       return EmitTest(Op0, X86CC, dl, DAG);
12882
12883      if (Op0.getValueType() == MVT::i1)
12884        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12885   }
12886  
12887   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12888        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12889     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12890     // This avoids subregister aliasing issues. Keep the smaller reference 
12891     // if we're optimizing for size, however, as that'll allow better folding 
12892     // of memory operations.
12893     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12894         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12895              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12896         !Subtarget->isAtom()) {
12897       unsigned ExtendOp =
12898           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12899       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12900       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12901     }
12902     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12903     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12904     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12905                               Op0, Op1);
12906     return SDValue(Sub.getNode(), 1);
12907   }
12908   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12909 }
12910
12911 /// Convert a comparison if required by the subtarget.
12912 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12913                                                  SelectionDAG &DAG) const {
12914   // If the subtarget does not support the FUCOMI instruction, floating-point
12915   // comparisons have to be converted.
12916   if (Subtarget->hasCMov() ||
12917       Cmp.getOpcode() != X86ISD::CMP ||
12918       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12919       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12920     return Cmp;
12921
12922   // The instruction selector will select an FUCOM instruction instead of
12923   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12924   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12925   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12926   SDLoc dl(Cmp);
12927   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12928   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12929   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12930                             DAG.getConstant(8, MVT::i8));
12931   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12932   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12933 }
12934
12935 static bool isAllOnes(SDValue V) {
12936   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12937   return C && C->isAllOnesValue();
12938 }
12939
12940 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12941 /// if it's possible.
12942 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12943                                      SDLoc dl, SelectionDAG &DAG) const {
12944   SDValue Op0 = And.getOperand(0);
12945   SDValue Op1 = And.getOperand(1);
12946   if (Op0.getOpcode() == ISD::TRUNCATE)
12947     Op0 = Op0.getOperand(0);
12948   if (Op1.getOpcode() == ISD::TRUNCATE)
12949     Op1 = Op1.getOperand(0);
12950
12951   SDValue LHS, RHS;
12952   if (Op1.getOpcode() == ISD::SHL)
12953     std::swap(Op0, Op1);
12954   if (Op0.getOpcode() == ISD::SHL) {
12955     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12956       if (And00C->getZExtValue() == 1) {
12957         // If we looked past a truncate, check that it's only truncating away
12958         // known zeros.
12959         unsigned BitWidth = Op0.getValueSizeInBits();
12960         unsigned AndBitWidth = And.getValueSizeInBits();
12961         if (BitWidth > AndBitWidth) {
12962           APInt Zeros, Ones;
12963           DAG.computeKnownBits(Op0, Zeros, Ones);
12964           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12965             return SDValue();
12966         }
12967         LHS = Op1;
12968         RHS = Op0.getOperand(1);
12969       }
12970   } else if (Op1.getOpcode() == ISD::Constant) {
12971     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12972     uint64_t AndRHSVal = AndRHS->getZExtValue();
12973     SDValue AndLHS = Op0;
12974
12975     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12976       LHS = AndLHS.getOperand(0);
12977       RHS = AndLHS.getOperand(1);
12978     }
12979
12980     // Use BT if the immediate can't be encoded in a TEST instruction.
12981     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12982       LHS = AndLHS;
12983       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12984     }
12985   }
12986
12987   if (LHS.getNode()) {
12988     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12989     // instruction.  Since the shift amount is in-range-or-undefined, we know
12990     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12991     // the encoding for the i16 version is larger than the i32 version.
12992     // Also promote i16 to i32 for performance / code size reason.
12993     if (LHS.getValueType() == MVT::i8 ||
12994         LHS.getValueType() == MVT::i16)
12995       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12996
12997     // If the operand types disagree, extend the shift amount to match.  Since
12998     // BT ignores high bits (like shifts) we can use anyextend.
12999     if (LHS.getValueType() != RHS.getValueType())
13000       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13001
13002     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13003     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13004     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13005                        DAG.getConstant(Cond, MVT::i8), BT);
13006   }
13007
13008   return SDValue();
13009 }
13010
13011 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13012 /// mask CMPs.
13013 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13014                               SDValue &Op1) {
13015   unsigned SSECC;
13016   bool Swap = false;
13017
13018   // SSE Condition code mapping:
13019   //  0 - EQ
13020   //  1 - LT
13021   //  2 - LE
13022   //  3 - UNORD
13023   //  4 - NEQ
13024   //  5 - NLT
13025   //  6 - NLE
13026   //  7 - ORD
13027   switch (SetCCOpcode) {
13028   default: llvm_unreachable("Unexpected SETCC condition");
13029   case ISD::SETOEQ:
13030   case ISD::SETEQ:  SSECC = 0; break;
13031   case ISD::SETOGT:
13032   case ISD::SETGT:  Swap = true; // Fallthrough
13033   case ISD::SETLT:
13034   case ISD::SETOLT: SSECC = 1; break;
13035   case ISD::SETOGE:
13036   case ISD::SETGE:  Swap = true; // Fallthrough
13037   case ISD::SETLE:
13038   case ISD::SETOLE: SSECC = 2; break;
13039   case ISD::SETUO:  SSECC = 3; break;
13040   case ISD::SETUNE:
13041   case ISD::SETNE:  SSECC = 4; break;
13042   case ISD::SETULE: Swap = true; // Fallthrough
13043   case ISD::SETUGE: SSECC = 5; break;
13044   case ISD::SETULT: Swap = true; // Fallthrough
13045   case ISD::SETUGT: SSECC = 6; break;
13046   case ISD::SETO:   SSECC = 7; break;
13047   case ISD::SETUEQ:
13048   case ISD::SETONE: SSECC = 8; break;
13049   }
13050   if (Swap)
13051     std::swap(Op0, Op1);
13052
13053   return SSECC;
13054 }
13055
13056 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13057 // ones, and then concatenate the result back.
13058 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13059   MVT VT = Op.getSimpleValueType();
13060
13061   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13062          "Unsupported value type for operation");
13063
13064   unsigned NumElems = VT.getVectorNumElements();
13065   SDLoc dl(Op);
13066   SDValue CC = Op.getOperand(2);
13067
13068   // Extract the LHS vectors
13069   SDValue LHS = Op.getOperand(0);
13070   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13071   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13072
13073   // Extract the RHS vectors
13074   SDValue RHS = Op.getOperand(1);
13075   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13076   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13077
13078   // Issue the operation on the smaller types and concatenate the result back
13079   MVT EltVT = VT.getVectorElementType();
13080   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13081   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13082                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13083                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13084 }
13085
13086 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13087                                      const X86Subtarget *Subtarget) {
13088   SDValue Op0 = Op.getOperand(0);
13089   SDValue Op1 = Op.getOperand(1);
13090   SDValue CC = Op.getOperand(2);
13091   MVT VT = Op.getSimpleValueType();
13092   SDLoc dl(Op);
13093
13094   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13095          Op.getValueType().getScalarType() == MVT::i1 &&
13096          "Cannot set masked compare for this operation");
13097
13098   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13099   unsigned  Opc = 0;
13100   bool Unsigned = false;
13101   bool Swap = false;
13102   unsigned SSECC;
13103   switch (SetCCOpcode) {
13104   default: llvm_unreachable("Unexpected SETCC condition");
13105   case ISD::SETNE:  SSECC = 4; break;
13106   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13107   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13108   case ISD::SETLT:  Swap = true; //fall-through
13109   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13110   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13111   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13112   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13113   case ISD::SETULE: Unsigned = true; //fall-through
13114   case ISD::SETLE:  SSECC = 2; break;
13115   }
13116
13117   if (Swap)
13118     std::swap(Op0, Op1);
13119   if (Opc)
13120     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13121   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13122   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13123                      DAG.getConstant(SSECC, MVT::i8));
13124 }
13125
13126 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13127 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13128 /// return an empty value.
13129 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13130 {
13131   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13132   if (!BV)
13133     return SDValue();
13134
13135   MVT VT = Op1.getSimpleValueType();
13136   MVT EVT = VT.getVectorElementType();
13137   unsigned n = VT.getVectorNumElements();
13138   SmallVector<SDValue, 8> ULTOp1;
13139
13140   for (unsigned i = 0; i < n; ++i) {
13141     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13142     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13143       return SDValue();
13144
13145     // Avoid underflow.
13146     APInt Val = Elt->getAPIntValue();
13147     if (Val == 0)
13148       return SDValue();
13149
13150     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13151   }
13152
13153   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13154 }
13155
13156 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13157                            SelectionDAG &DAG) {
13158   SDValue Op0 = Op.getOperand(0);
13159   SDValue Op1 = Op.getOperand(1);
13160   SDValue CC = Op.getOperand(2);
13161   MVT VT = Op.getSimpleValueType();
13162   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13163   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13164   SDLoc dl(Op);
13165
13166   if (isFP) {
13167 #ifndef NDEBUG
13168     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13169     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13170 #endif
13171
13172     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13173     unsigned Opc = X86ISD::CMPP;
13174     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13175       assert(VT.getVectorNumElements() <= 16);
13176       Opc = X86ISD::CMPM;
13177     }
13178     // In the two special cases we can't handle, emit two comparisons.
13179     if (SSECC == 8) {
13180       unsigned CC0, CC1;
13181       unsigned CombineOpc;
13182       if (SetCCOpcode == ISD::SETUEQ) {
13183         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13184       } else {
13185         assert(SetCCOpcode == ISD::SETONE);
13186         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13187       }
13188
13189       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13190                                  DAG.getConstant(CC0, MVT::i8));
13191       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13192                                  DAG.getConstant(CC1, MVT::i8));
13193       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13194     }
13195     // Handle all other FP comparisons here.
13196     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13197                        DAG.getConstant(SSECC, MVT::i8));
13198   }
13199
13200   // Break 256-bit integer vector compare into smaller ones.
13201   if (VT.is256BitVector() && !Subtarget->hasInt256())
13202     return Lower256IntVSETCC(Op, DAG);
13203
13204   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13205   EVT OpVT = Op1.getValueType();
13206   if (Subtarget->hasAVX512()) {
13207     if (Op1.getValueType().is512BitVector() ||
13208         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13209         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13210       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13211
13212     // In AVX-512 architecture setcc returns mask with i1 elements,
13213     // But there is no compare instruction for i8 and i16 elements in KNL.
13214     // We are not talking about 512-bit operands in this case, these
13215     // types are illegal.
13216     if (MaskResult &&
13217         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13218          OpVT.getVectorElementType().getSizeInBits() >= 8))
13219       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13220                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13221   }
13222
13223   // We are handling one of the integer comparisons here.  Since SSE only has
13224   // GT and EQ comparisons for integer, swapping operands and multiple
13225   // operations may be required for some comparisons.
13226   unsigned Opc;
13227   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13228   bool Subus = false;
13229
13230   switch (SetCCOpcode) {
13231   default: llvm_unreachable("Unexpected SETCC condition");
13232   case ISD::SETNE:  Invert = true;
13233   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13234   case ISD::SETLT:  Swap = true;
13235   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13236   case ISD::SETGE:  Swap = true;
13237   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13238                     Invert = true; break;
13239   case ISD::SETULT: Swap = true;
13240   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13241                     FlipSigns = true; break;
13242   case ISD::SETUGE: Swap = true;
13243   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13244                     FlipSigns = true; Invert = true; break;
13245   }
13246
13247   // Special case: Use min/max operations for SETULE/SETUGE
13248   MVT VET = VT.getVectorElementType();
13249   bool hasMinMax =
13250        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13251     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13252
13253   if (hasMinMax) {
13254     switch (SetCCOpcode) {
13255     default: break;
13256     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13257     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13258     }
13259
13260     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13261   }
13262
13263   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13264   if (!MinMax && hasSubus) {
13265     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13266     // Op0 u<= Op1:
13267     //   t = psubus Op0, Op1
13268     //   pcmpeq t, <0..0>
13269     switch (SetCCOpcode) {
13270     default: break;
13271     case ISD::SETULT: {
13272       // If the comparison is against a constant we can turn this into a
13273       // setule.  With psubus, setule does not require a swap.  This is
13274       // beneficial because the constant in the register is no longer
13275       // destructed as the destination so it can be hoisted out of a loop.
13276       // Only do this pre-AVX since vpcmp* is no longer destructive.
13277       if (Subtarget->hasAVX())
13278         break;
13279       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13280       if (ULEOp1.getNode()) {
13281         Op1 = ULEOp1;
13282         Subus = true; Invert = false; Swap = false;
13283       }
13284       break;
13285     }
13286     // Psubus is better than flip-sign because it requires no inversion.
13287     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13288     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13289     }
13290
13291     if (Subus) {
13292       Opc = X86ISD::SUBUS;
13293       FlipSigns = false;
13294     }
13295   }
13296
13297   if (Swap)
13298     std::swap(Op0, Op1);
13299
13300   // Check that the operation in question is available (most are plain SSE2,
13301   // but PCMPGTQ and PCMPEQQ have different requirements).
13302   if (VT == MVT::v2i64) {
13303     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13304       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13305
13306       // First cast everything to the right type.
13307       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13308       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13309
13310       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13311       // bits of the inputs before performing those operations. The lower
13312       // compare is always unsigned.
13313       SDValue SB;
13314       if (FlipSigns) {
13315         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13316       } else {
13317         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13318         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13319         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13320                          Sign, Zero, Sign, Zero);
13321       }
13322       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13323       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13324
13325       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13326       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13327       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13328
13329       // Create masks for only the low parts/high parts of the 64 bit integers.
13330       static const int MaskHi[] = { 1, 1, 3, 3 };
13331       static const int MaskLo[] = { 0, 0, 2, 2 };
13332       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13333       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13334       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13335
13336       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13337       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13338
13339       if (Invert)
13340         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13341
13342       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13343     }
13344
13345     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13346       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13347       // pcmpeqd + pshufd + pand.
13348       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13349
13350       // First cast everything to the right type.
13351       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13352       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13353
13354       // Do the compare.
13355       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13356
13357       // Make sure the lower and upper halves are both all-ones.
13358       static const int Mask[] = { 1, 0, 3, 2 };
13359       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13360       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13361
13362       if (Invert)
13363         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13364
13365       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13366     }
13367   }
13368
13369   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13370   // bits of the inputs before performing those operations.
13371   if (FlipSigns) {
13372     EVT EltVT = VT.getVectorElementType();
13373     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13374     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13375     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13376   }
13377
13378   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13379
13380   // If the logical-not of the result is required, perform that now.
13381   if (Invert)
13382     Result = DAG.getNOT(dl, Result, VT);
13383
13384   if (MinMax)
13385     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13386
13387   if (Subus)
13388     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13389                          getZeroVector(VT, Subtarget, DAG, dl));
13390
13391   return Result;
13392 }
13393
13394 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13395
13396   MVT VT = Op.getSimpleValueType();
13397
13398   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13399
13400   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13401          && "SetCC type must be 8-bit or 1-bit integer");
13402   SDValue Op0 = Op.getOperand(0);
13403   SDValue Op1 = Op.getOperand(1);
13404   SDLoc dl(Op);
13405   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13406
13407   // Optimize to BT if possible.
13408   // Lower (X & (1 << N)) == 0 to BT(X, N).
13409   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13410   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13411   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13412       Op1.getOpcode() == ISD::Constant &&
13413       cast<ConstantSDNode>(Op1)->isNullValue() &&
13414       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13415     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13416     if (NewSetCC.getNode())
13417       return NewSetCC;
13418   }
13419
13420   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13421   // these.
13422   if (Op1.getOpcode() == ISD::Constant &&
13423       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13424        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13425       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13426
13427     // If the input is a setcc, then reuse the input setcc or use a new one with
13428     // the inverted condition.
13429     if (Op0.getOpcode() == X86ISD::SETCC) {
13430       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13431       bool Invert = (CC == ISD::SETNE) ^
13432         cast<ConstantSDNode>(Op1)->isNullValue();
13433       if (!Invert)
13434         return Op0;
13435
13436       CCode = X86::GetOppositeBranchCondition(CCode);
13437       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13438                                   DAG.getConstant(CCode, MVT::i8),
13439                                   Op0.getOperand(1));
13440       if (VT == MVT::i1)
13441         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13442       return SetCC;
13443     }
13444   }
13445   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13446       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13447       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13448
13449     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13450     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13451   }
13452
13453   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13454   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13455   if (X86CC == X86::COND_INVALID)
13456     return SDValue();
13457
13458   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13459   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13460   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13461                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13462   if (VT == MVT::i1)
13463     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13464   return SetCC;
13465 }
13466
13467 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13468 static bool isX86LogicalCmp(SDValue Op) {
13469   unsigned Opc = Op.getNode()->getOpcode();
13470   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13471       Opc == X86ISD::SAHF)
13472     return true;
13473   if (Op.getResNo() == 1 &&
13474       (Opc == X86ISD::ADD ||
13475        Opc == X86ISD::SUB ||
13476        Opc == X86ISD::ADC ||
13477        Opc == X86ISD::SBB ||
13478        Opc == X86ISD::SMUL ||
13479        Opc == X86ISD::UMUL ||
13480        Opc == X86ISD::INC ||
13481        Opc == X86ISD::DEC ||
13482        Opc == X86ISD::OR ||
13483        Opc == X86ISD::XOR ||
13484        Opc == X86ISD::AND))
13485     return true;
13486
13487   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13488     return true;
13489
13490   return false;
13491 }
13492
13493 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13494   if (V.getOpcode() != ISD::TRUNCATE)
13495     return false;
13496
13497   SDValue VOp0 = V.getOperand(0);
13498   unsigned InBits = VOp0.getValueSizeInBits();
13499   unsigned Bits = V.getValueSizeInBits();
13500   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13501 }
13502
13503 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13504   bool addTest = true;
13505   SDValue Cond  = Op.getOperand(0);
13506   SDValue Op1 = Op.getOperand(1);
13507   SDValue Op2 = Op.getOperand(2);
13508   SDLoc DL(Op);
13509   EVT VT = Op1.getValueType();
13510   SDValue CC;
13511
13512   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13513   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13514   // sequence later on.
13515   if (Cond.getOpcode() == ISD::SETCC &&
13516       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13517        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13518       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13519     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13520     int SSECC = translateX86FSETCC(
13521         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13522
13523     if (SSECC != 8) {
13524       if (Subtarget->hasAVX512()) {
13525         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13526                                   DAG.getConstant(SSECC, MVT::i8));
13527         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13528       }
13529       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13530                                 DAG.getConstant(SSECC, MVT::i8));
13531       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13532       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13533       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13534     }
13535   }
13536
13537   if (Cond.getOpcode() == ISD::SETCC) {
13538     SDValue NewCond = LowerSETCC(Cond, DAG);
13539     if (NewCond.getNode())
13540       Cond = NewCond;
13541   }
13542
13543   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13544   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13545   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13546   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13547   if (Cond.getOpcode() == X86ISD::SETCC &&
13548       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13549       isZero(Cond.getOperand(1).getOperand(1))) {
13550     SDValue Cmp = Cond.getOperand(1);
13551
13552     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13553
13554     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13555         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13556       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13557
13558       SDValue CmpOp0 = Cmp.getOperand(0);
13559       // Apply further optimizations for special cases
13560       // (select (x != 0), -1, 0) -> neg & sbb
13561       // (select (x == 0), 0, -1) -> neg & sbb
13562       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13563         if (YC->isNullValue() &&
13564             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13565           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13566           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13567                                     DAG.getConstant(0, CmpOp0.getValueType()),
13568                                     CmpOp0);
13569           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13570                                     DAG.getConstant(X86::COND_B, MVT::i8),
13571                                     SDValue(Neg.getNode(), 1));
13572           return Res;
13573         }
13574
13575       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13576                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13577       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13578
13579       SDValue Res =   // Res = 0 or -1.
13580         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13581                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13582
13583       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13584         Res = DAG.getNOT(DL, Res, Res.getValueType());
13585
13586       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13587       if (!N2C || !N2C->isNullValue())
13588         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13589       return Res;
13590     }
13591   }
13592
13593   // Look past (and (setcc_carry (cmp ...)), 1).
13594   if (Cond.getOpcode() == ISD::AND &&
13595       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13596     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13597     if (C && C->getAPIntValue() == 1)
13598       Cond = Cond.getOperand(0);
13599   }
13600
13601   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13602   // setting operand in place of the X86ISD::SETCC.
13603   unsigned CondOpcode = Cond.getOpcode();
13604   if (CondOpcode == X86ISD::SETCC ||
13605       CondOpcode == X86ISD::SETCC_CARRY) {
13606     CC = Cond.getOperand(0);
13607
13608     SDValue Cmp = Cond.getOperand(1);
13609     unsigned Opc = Cmp.getOpcode();
13610     MVT VT = Op.getSimpleValueType();
13611
13612     bool IllegalFPCMov = false;
13613     if (VT.isFloatingPoint() && !VT.isVector() &&
13614         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13615       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13616
13617     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13618         Opc == X86ISD::BT) { // FIXME
13619       Cond = Cmp;
13620       addTest = false;
13621     }
13622   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13623              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13624              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13625               Cond.getOperand(0).getValueType() != MVT::i8)) {
13626     SDValue LHS = Cond.getOperand(0);
13627     SDValue RHS = Cond.getOperand(1);
13628     unsigned X86Opcode;
13629     unsigned X86Cond;
13630     SDVTList VTs;
13631     switch (CondOpcode) {
13632     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13633     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13634     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13635     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13636     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13637     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13638     default: llvm_unreachable("unexpected overflowing operator");
13639     }
13640     if (CondOpcode == ISD::UMULO)
13641       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13642                           MVT::i32);
13643     else
13644       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13645
13646     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13647
13648     if (CondOpcode == ISD::UMULO)
13649       Cond = X86Op.getValue(2);
13650     else
13651       Cond = X86Op.getValue(1);
13652
13653     CC = DAG.getConstant(X86Cond, MVT::i8);
13654     addTest = false;
13655   }
13656
13657   if (addTest) {
13658     // Look pass the truncate if the high bits are known zero.
13659     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13660         Cond = Cond.getOperand(0);
13661
13662     // We know the result of AND is compared against zero. Try to match
13663     // it to BT.
13664     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13665       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13666       if (NewSetCC.getNode()) {
13667         CC = NewSetCC.getOperand(0);
13668         Cond = NewSetCC.getOperand(1);
13669         addTest = false;
13670       }
13671     }
13672   }
13673
13674   if (addTest) {
13675     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13676     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13677   }
13678
13679   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13680   // a <  b ?  0 : -1 -> RES = setcc_carry
13681   // a >= b ? -1 :  0 -> RES = setcc_carry
13682   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13683   if (Cond.getOpcode() == X86ISD::SUB) {
13684     Cond = ConvertCmpIfNecessary(Cond, DAG);
13685     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13686
13687     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13688         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13689       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13690                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13691       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13692         return DAG.getNOT(DL, Res, Res.getValueType());
13693       return Res;
13694     }
13695   }
13696
13697   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13698   // widen the cmov and push the truncate through. This avoids introducing a new
13699   // branch during isel and doesn't add any extensions.
13700   if (Op.getValueType() == MVT::i8 &&
13701       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13702     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13703     if (T1.getValueType() == T2.getValueType() &&
13704         // Blacklist CopyFromReg to avoid partial register stalls.
13705         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13706       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13707       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13708       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13709     }
13710   }
13711
13712   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13713   // condition is true.
13714   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13715   SDValue Ops[] = { Op2, Op1, CC, Cond };
13716   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13717 }
13718
13719 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13720   MVT VT = Op->getSimpleValueType(0);
13721   SDValue In = Op->getOperand(0);
13722   MVT InVT = In.getSimpleValueType();
13723   SDLoc dl(Op);
13724
13725   unsigned int NumElts = VT.getVectorNumElements();
13726   if (NumElts != 8 && NumElts != 16)
13727     return SDValue();
13728
13729   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13730     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13731
13732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13733   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13734
13735   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13736   Constant *C = ConstantInt::get(*DAG.getContext(),
13737     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13738
13739   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13740   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13741   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13742                           MachinePointerInfo::getConstantPool(),
13743                           false, false, false, Alignment);
13744   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13745   if (VT.is512BitVector())
13746     return Brcst;
13747   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13748 }
13749
13750 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13751                                 SelectionDAG &DAG) {
13752   MVT VT = Op->getSimpleValueType(0);
13753   SDValue In = Op->getOperand(0);
13754   MVT InVT = In.getSimpleValueType();
13755   SDLoc dl(Op);
13756
13757   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13758     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13759
13760   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13761       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13762       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13763     return SDValue();
13764
13765   if (Subtarget->hasInt256())
13766     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13767
13768   // Optimize vectors in AVX mode
13769   // Sign extend  v8i16 to v8i32 and
13770   //              v4i32 to v4i64
13771   //
13772   // Divide input vector into two parts
13773   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13774   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13775   // concat the vectors to original VT
13776
13777   unsigned NumElems = InVT.getVectorNumElements();
13778   SDValue Undef = DAG.getUNDEF(InVT);
13779
13780   SmallVector<int,8> ShufMask1(NumElems, -1);
13781   for (unsigned i = 0; i != NumElems/2; ++i)
13782     ShufMask1[i] = i;
13783
13784   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13785
13786   SmallVector<int,8> ShufMask2(NumElems, -1);
13787   for (unsigned i = 0; i != NumElems/2; ++i)
13788     ShufMask2[i] = i + NumElems/2;
13789
13790   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13791
13792   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13793                                 VT.getVectorNumElements()/2);
13794
13795   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13796   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13797
13798   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13799 }
13800
13801 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13802 // may emit an illegal shuffle but the expansion is still better than scalar
13803 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13804 // we'll emit a shuffle and a arithmetic shift.
13805 // TODO: It is possible to support ZExt by zeroing the undef values during
13806 // the shuffle phase or after the shuffle.
13807 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13808                                  SelectionDAG &DAG) {
13809   MVT RegVT = Op.getSimpleValueType();
13810   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13811   assert(RegVT.isInteger() &&
13812          "We only custom lower integer vector sext loads.");
13813
13814   // Nothing useful we can do without SSE2 shuffles.
13815   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13816
13817   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13818   SDLoc dl(Ld);
13819   EVT MemVT = Ld->getMemoryVT();
13820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13821   unsigned RegSz = RegVT.getSizeInBits();
13822
13823   ISD::LoadExtType Ext = Ld->getExtensionType();
13824
13825   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13826          && "Only anyext and sext are currently implemented.");
13827   assert(MemVT != RegVT && "Cannot extend to the same type");
13828   assert(MemVT.isVector() && "Must load a vector from memory");
13829
13830   unsigned NumElems = RegVT.getVectorNumElements();
13831   unsigned MemSz = MemVT.getSizeInBits();
13832   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13833
13834   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13835     // The only way in which we have a legal 256-bit vector result but not the
13836     // integer 256-bit operations needed to directly lower a sextload is if we
13837     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13838     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13839     // correctly legalized. We do this late to allow the canonical form of
13840     // sextload to persist throughout the rest of the DAG combiner -- it wants
13841     // to fold together any extensions it can, and so will fuse a sign_extend
13842     // of an sextload into a sextload targeting a wider value.
13843     SDValue Load;
13844     if (MemSz == 128) {
13845       // Just switch this to a normal load.
13846       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13847                                        "it must be a legal 128-bit vector "
13848                                        "type!");
13849       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13850                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13851                   Ld->isInvariant(), Ld->getAlignment());
13852     } else {
13853       assert(MemSz < 128 &&
13854              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13855       // Do an sext load to a 128-bit vector type. We want to use the same
13856       // number of elements, but elements half as wide. This will end up being
13857       // recursively lowered by this routine, but will succeed as we definitely
13858       // have all the necessary features if we're using AVX1.
13859       EVT HalfEltVT =
13860           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13861       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13862       Load =
13863           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13864                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13865                          Ld->isNonTemporal(), Ld->isInvariant(),
13866                          Ld->getAlignment());
13867     }
13868
13869     // Replace chain users with the new chain.
13870     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13871     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13872
13873     // Finally, do a normal sign-extend to the desired register.
13874     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13875   }
13876
13877   // All sizes must be a power of two.
13878   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13879          "Non-power-of-two elements are not custom lowered!");
13880
13881   // Attempt to load the original value using scalar loads.
13882   // Find the largest scalar type that divides the total loaded size.
13883   MVT SclrLoadTy = MVT::i8;
13884   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13885        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13886     MVT Tp = (MVT::SimpleValueType)tp;
13887     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13888       SclrLoadTy = Tp;
13889     }
13890   }
13891
13892   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13893   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13894       (64 <= MemSz))
13895     SclrLoadTy = MVT::f64;
13896
13897   // Calculate the number of scalar loads that we need to perform
13898   // in order to load our vector from memory.
13899   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13900
13901   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13902          "Can only lower sext loads with a single scalar load!");
13903
13904   unsigned loadRegZize = RegSz;
13905   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13906     loadRegZize /= 2;
13907
13908   // Represent our vector as a sequence of elements which are the
13909   // largest scalar that we can load.
13910   EVT LoadUnitVecVT = EVT::getVectorVT(
13911       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13912
13913   // Represent the data using the same element type that is stored in
13914   // memory. In practice, we ''widen'' MemVT.
13915   EVT WideVecVT =
13916       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13917                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13918
13919   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13920          "Invalid vector type");
13921
13922   // We can't shuffle using an illegal type.
13923   assert(TLI.isTypeLegal(WideVecVT) &&
13924          "We only lower types that form legal widened vector types");
13925
13926   SmallVector<SDValue, 8> Chains;
13927   SDValue Ptr = Ld->getBasePtr();
13928   SDValue Increment =
13929       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13930   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13931
13932   for (unsigned i = 0; i < NumLoads; ++i) {
13933     // Perform a single load.
13934     SDValue ScalarLoad =
13935         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13936                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13937                     Ld->getAlignment());
13938     Chains.push_back(ScalarLoad.getValue(1));
13939     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13940     // another round of DAGCombining.
13941     if (i == 0)
13942       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13943     else
13944       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13945                         ScalarLoad, DAG.getIntPtrConstant(i));
13946
13947     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13948   }
13949
13950   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13951
13952   // Bitcast the loaded value to a vector of the original element type, in
13953   // the size of the target vector type.
13954   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13955   unsigned SizeRatio = RegSz / MemSz;
13956
13957   if (Ext == ISD::SEXTLOAD) {
13958     // If we have SSE4.1, we can directly emit a VSEXT node.
13959     if (Subtarget->hasSSE41()) {
13960       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13961       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13962       return Sext;
13963     }
13964
13965     // Otherwise we'll shuffle the small elements in the high bits of the
13966     // larger type and perform an arithmetic shift. If the shift is not legal
13967     // it's better to scalarize.
13968     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13969            "We can't implement a sext load without an arithmetic right shift!");
13970
13971     // Redistribute the loaded elements into the different locations.
13972     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13973     for (unsigned i = 0; i != NumElems; ++i)
13974       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13975
13976     SDValue Shuff = DAG.getVectorShuffle(
13977         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13978
13979     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13980
13981     // Build the arithmetic shift.
13982     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13983                    MemVT.getVectorElementType().getSizeInBits();
13984     Shuff =
13985         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13986
13987     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13988     return Shuff;
13989   }
13990
13991   // Redistribute the loaded elements into the different locations.
13992   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13993   for (unsigned i = 0; i != NumElems; ++i)
13994     ShuffleVec[i * SizeRatio] = i;
13995
13996   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13997                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13998
13999   // Bitcast to the requested type.
14000   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14001   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14002   return Shuff;
14003 }
14004
14005 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14006 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14007 // from the AND / OR.
14008 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14009   Opc = Op.getOpcode();
14010   if (Opc != ISD::OR && Opc != ISD::AND)
14011     return false;
14012   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14013           Op.getOperand(0).hasOneUse() &&
14014           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14015           Op.getOperand(1).hasOneUse());
14016 }
14017
14018 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14019 // 1 and that the SETCC node has a single use.
14020 static bool isXor1OfSetCC(SDValue Op) {
14021   if (Op.getOpcode() != ISD::XOR)
14022     return false;
14023   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14024   if (N1C && N1C->getAPIntValue() == 1) {
14025     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14026       Op.getOperand(0).hasOneUse();
14027   }
14028   return false;
14029 }
14030
14031 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14032   bool addTest = true;
14033   SDValue Chain = Op.getOperand(0);
14034   SDValue Cond  = Op.getOperand(1);
14035   SDValue Dest  = Op.getOperand(2);
14036   SDLoc dl(Op);
14037   SDValue CC;
14038   bool Inverted = false;
14039
14040   if (Cond.getOpcode() == ISD::SETCC) {
14041     // Check for setcc([su]{add,sub,mul}o == 0).
14042     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14043         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14044         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14045         Cond.getOperand(0).getResNo() == 1 &&
14046         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14047          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14048          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14049          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14050          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14051          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14052       Inverted = true;
14053       Cond = Cond.getOperand(0);
14054     } else {
14055       SDValue NewCond = LowerSETCC(Cond, DAG);
14056       if (NewCond.getNode())
14057         Cond = NewCond;
14058     }
14059   }
14060 #if 0
14061   // FIXME: LowerXALUO doesn't handle these!!
14062   else if (Cond.getOpcode() == X86ISD::ADD  ||
14063            Cond.getOpcode() == X86ISD::SUB  ||
14064            Cond.getOpcode() == X86ISD::SMUL ||
14065            Cond.getOpcode() == X86ISD::UMUL)
14066     Cond = LowerXALUO(Cond, DAG);
14067 #endif
14068
14069   // Look pass (and (setcc_carry (cmp ...)), 1).
14070   if (Cond.getOpcode() == ISD::AND &&
14071       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14072     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14073     if (C && C->getAPIntValue() == 1)
14074       Cond = Cond.getOperand(0);
14075   }
14076
14077   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14078   // setting operand in place of the X86ISD::SETCC.
14079   unsigned CondOpcode = Cond.getOpcode();
14080   if (CondOpcode == X86ISD::SETCC ||
14081       CondOpcode == X86ISD::SETCC_CARRY) {
14082     CC = Cond.getOperand(0);
14083
14084     SDValue Cmp = Cond.getOperand(1);
14085     unsigned Opc = Cmp.getOpcode();
14086     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14087     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14088       Cond = Cmp;
14089       addTest = false;
14090     } else {
14091       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14092       default: break;
14093       case X86::COND_O:
14094       case X86::COND_B:
14095         // These can only come from an arithmetic instruction with overflow,
14096         // e.g. SADDO, UADDO.
14097         Cond = Cond.getNode()->getOperand(1);
14098         addTest = false;
14099         break;
14100       }
14101     }
14102   }
14103   CondOpcode = Cond.getOpcode();
14104   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14105       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14106       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14107        Cond.getOperand(0).getValueType() != MVT::i8)) {
14108     SDValue LHS = Cond.getOperand(0);
14109     SDValue RHS = Cond.getOperand(1);
14110     unsigned X86Opcode;
14111     unsigned X86Cond;
14112     SDVTList VTs;
14113     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14114     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14115     // X86ISD::INC).
14116     switch (CondOpcode) {
14117     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14118     case ISD::SADDO:
14119       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14120         if (C->isOne()) {
14121           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14122           break;
14123         }
14124       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14125     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14126     case ISD::SSUBO:
14127       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14128         if (C->isOne()) {
14129           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14130           break;
14131         }
14132       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14133     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14134     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14135     default: llvm_unreachable("unexpected overflowing operator");
14136     }
14137     if (Inverted)
14138       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14139     if (CondOpcode == ISD::UMULO)
14140       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14141                           MVT::i32);
14142     else
14143       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14144
14145     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14146
14147     if (CondOpcode == ISD::UMULO)
14148       Cond = X86Op.getValue(2);
14149     else
14150       Cond = X86Op.getValue(1);
14151
14152     CC = DAG.getConstant(X86Cond, MVT::i8);
14153     addTest = false;
14154   } else {
14155     unsigned CondOpc;
14156     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14157       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14158       if (CondOpc == ISD::OR) {
14159         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14160         // two branches instead of an explicit OR instruction with a
14161         // separate test.
14162         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14163             isX86LogicalCmp(Cmp)) {
14164           CC = Cond.getOperand(0).getOperand(0);
14165           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14166                               Chain, Dest, CC, Cmp);
14167           CC = Cond.getOperand(1).getOperand(0);
14168           Cond = Cmp;
14169           addTest = false;
14170         }
14171       } else { // ISD::AND
14172         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14173         // two branches instead of an explicit AND instruction with a
14174         // separate test. However, we only do this if this block doesn't
14175         // have a fall-through edge, because this requires an explicit
14176         // jmp when the condition is false.
14177         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14178             isX86LogicalCmp(Cmp) &&
14179             Op.getNode()->hasOneUse()) {
14180           X86::CondCode CCode =
14181             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14182           CCode = X86::GetOppositeBranchCondition(CCode);
14183           CC = DAG.getConstant(CCode, MVT::i8);
14184           SDNode *User = *Op.getNode()->use_begin();
14185           // Look for an unconditional branch following this conditional branch.
14186           // We need this because we need to reverse the successors in order
14187           // to implement FCMP_OEQ.
14188           if (User->getOpcode() == ISD::BR) {
14189             SDValue FalseBB = User->getOperand(1);
14190             SDNode *NewBR =
14191               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14192             assert(NewBR == User);
14193             (void)NewBR;
14194             Dest = FalseBB;
14195
14196             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14197                                 Chain, Dest, CC, Cmp);
14198             X86::CondCode CCode =
14199               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14200             CCode = X86::GetOppositeBranchCondition(CCode);
14201             CC = DAG.getConstant(CCode, MVT::i8);
14202             Cond = Cmp;
14203             addTest = false;
14204           }
14205         }
14206       }
14207     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14208       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14209       // It should be transformed during dag combiner except when the condition
14210       // is set by a arithmetics with overflow node.
14211       X86::CondCode CCode =
14212         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14213       CCode = X86::GetOppositeBranchCondition(CCode);
14214       CC = DAG.getConstant(CCode, MVT::i8);
14215       Cond = Cond.getOperand(0).getOperand(1);
14216       addTest = false;
14217     } else if (Cond.getOpcode() == ISD::SETCC &&
14218                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14219       // For FCMP_OEQ, we can emit
14220       // two branches instead of an explicit AND instruction with a
14221       // separate test. However, we only do this if this block doesn't
14222       // have a fall-through edge, because this requires an explicit
14223       // jmp when the condition is false.
14224       if (Op.getNode()->hasOneUse()) {
14225         SDNode *User = *Op.getNode()->use_begin();
14226         // Look for an unconditional branch following this conditional branch.
14227         // We need this because we need to reverse the successors in order
14228         // to implement FCMP_OEQ.
14229         if (User->getOpcode() == ISD::BR) {
14230           SDValue FalseBB = User->getOperand(1);
14231           SDNode *NewBR =
14232             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14233           assert(NewBR == User);
14234           (void)NewBR;
14235           Dest = FalseBB;
14236
14237           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14238                                     Cond.getOperand(0), Cond.getOperand(1));
14239           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14240           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14241           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14242                               Chain, Dest, CC, Cmp);
14243           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14244           Cond = Cmp;
14245           addTest = false;
14246         }
14247       }
14248     } else if (Cond.getOpcode() == ISD::SETCC &&
14249                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14250       // For FCMP_UNE, we can emit
14251       // two branches instead of an explicit AND instruction with a
14252       // separate test. However, we only do this if this block doesn't
14253       // have a fall-through edge, because this requires an explicit
14254       // jmp when the condition is false.
14255       if (Op.getNode()->hasOneUse()) {
14256         SDNode *User = *Op.getNode()->use_begin();
14257         // Look for an unconditional branch following this conditional branch.
14258         // We need this because we need to reverse the successors in order
14259         // to implement FCMP_UNE.
14260         if (User->getOpcode() == ISD::BR) {
14261           SDValue FalseBB = User->getOperand(1);
14262           SDNode *NewBR =
14263             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14264           assert(NewBR == User);
14265           (void)NewBR;
14266
14267           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14268                                     Cond.getOperand(0), Cond.getOperand(1));
14269           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14270           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14271           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14272                               Chain, Dest, CC, Cmp);
14273           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14274           Cond = Cmp;
14275           addTest = false;
14276           Dest = FalseBB;
14277         }
14278       }
14279     }
14280   }
14281
14282   if (addTest) {
14283     // Look pass the truncate if the high bits are known zero.
14284     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14285         Cond = Cond.getOperand(0);
14286
14287     // We know the result of AND is compared against zero. Try to match
14288     // it to BT.
14289     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14290       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14291       if (NewSetCC.getNode()) {
14292         CC = NewSetCC.getOperand(0);
14293         Cond = NewSetCC.getOperand(1);
14294         addTest = false;
14295       }
14296     }
14297   }
14298
14299   if (addTest) {
14300     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14301     CC = DAG.getConstant(X86Cond, MVT::i8);
14302     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14303   }
14304   Cond = ConvertCmpIfNecessary(Cond, DAG);
14305   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14306                      Chain, Dest, CC, Cond);
14307 }
14308
14309 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14310 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14311 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14312 // that the guard pages used by the OS virtual memory manager are allocated in
14313 // correct sequence.
14314 SDValue
14315 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14316                                            SelectionDAG &DAG) const {
14317   MachineFunction &MF = DAG.getMachineFunction();
14318   bool SplitStack = MF.shouldSplitStack();
14319   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14320                SplitStack;
14321   SDLoc dl(Op);
14322
14323   if (!Lower) {
14324     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14325     SDNode* Node = Op.getNode();
14326
14327     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14328     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14329         " not tell us which reg is the stack pointer!");
14330     EVT VT = Node->getValueType(0);
14331     SDValue Tmp1 = SDValue(Node, 0);
14332     SDValue Tmp2 = SDValue(Node, 1);
14333     SDValue Tmp3 = Node->getOperand(2);
14334     SDValue Chain = Tmp1.getOperand(0);
14335
14336     // Chain the dynamic stack allocation so that it doesn't modify the stack
14337     // pointer when other instructions are using the stack.
14338     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14339         SDLoc(Node));
14340
14341     SDValue Size = Tmp2.getOperand(1);
14342     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14343     Chain = SP.getValue(1);
14344     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14345     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14346     unsigned StackAlign = TFI.getStackAlignment();
14347     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14348     if (Align > StackAlign)
14349       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14350           DAG.getConstant(-(uint64_t)Align, VT));
14351     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14352
14353     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14354         DAG.getIntPtrConstant(0, true), SDValue(),
14355         SDLoc(Node));
14356
14357     SDValue Ops[2] = { Tmp1, Tmp2 };
14358     return DAG.getMergeValues(Ops, dl);
14359   }
14360
14361   // Get the inputs.
14362   SDValue Chain = Op.getOperand(0);
14363   SDValue Size  = Op.getOperand(1);
14364   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14365   EVT VT = Op.getNode()->getValueType(0);
14366
14367   bool Is64Bit = Subtarget->is64Bit();
14368   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14369
14370   if (SplitStack) {
14371     MachineRegisterInfo &MRI = MF.getRegInfo();
14372
14373     if (Is64Bit) {
14374       // The 64 bit implementation of segmented stacks needs to clobber both r10
14375       // r11. This makes it impossible to use it along with nested parameters.
14376       const Function *F = MF.getFunction();
14377
14378       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14379            I != E; ++I)
14380         if (I->hasNestAttr())
14381           report_fatal_error("Cannot use segmented stacks with functions that "
14382                              "have nested arguments.");
14383     }
14384
14385     const TargetRegisterClass *AddrRegClass =
14386       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14387     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14388     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14389     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14390                                 DAG.getRegister(Vreg, SPTy));
14391     SDValue Ops1[2] = { Value, Chain };
14392     return DAG.getMergeValues(Ops1, dl);
14393   } else {
14394     SDValue Flag;
14395     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14396
14397     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14398     Flag = Chain.getValue(1);
14399     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14400
14401     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14402
14403     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14404         DAG.getSubtarget().getRegisterInfo());
14405     unsigned SPReg = RegInfo->getStackRegister();
14406     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14407     Chain = SP.getValue(1);
14408
14409     if (Align) {
14410       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14411                        DAG.getConstant(-(uint64_t)Align, VT));
14412       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14413     }
14414
14415     SDValue Ops1[2] = { SP, Chain };
14416     return DAG.getMergeValues(Ops1, dl);
14417   }
14418 }
14419
14420 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14421   MachineFunction &MF = DAG.getMachineFunction();
14422   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14423
14424   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14425   SDLoc DL(Op);
14426
14427   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14428     // vastart just stores the address of the VarArgsFrameIndex slot into the
14429     // memory location argument.
14430     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14431                                    getPointerTy());
14432     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14433                         MachinePointerInfo(SV), false, false, 0);
14434   }
14435
14436   // __va_list_tag:
14437   //   gp_offset         (0 - 6 * 8)
14438   //   fp_offset         (48 - 48 + 8 * 16)
14439   //   overflow_arg_area (point to parameters coming in memory).
14440   //   reg_save_area
14441   SmallVector<SDValue, 8> MemOps;
14442   SDValue FIN = Op.getOperand(1);
14443   // Store gp_offset
14444   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14445                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14446                                                MVT::i32),
14447                                FIN, MachinePointerInfo(SV), false, false, 0);
14448   MemOps.push_back(Store);
14449
14450   // Store fp_offset
14451   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14452                     FIN, DAG.getIntPtrConstant(4));
14453   Store = DAG.getStore(Op.getOperand(0), DL,
14454                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14455                                        MVT::i32),
14456                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14457   MemOps.push_back(Store);
14458
14459   // Store ptr to overflow_arg_area
14460   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14461                     FIN, DAG.getIntPtrConstant(4));
14462   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14463                                     getPointerTy());
14464   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14465                        MachinePointerInfo(SV, 8),
14466                        false, false, 0);
14467   MemOps.push_back(Store);
14468
14469   // Store ptr to reg_save_area.
14470   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14471                     FIN, DAG.getIntPtrConstant(8));
14472   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14473                                     getPointerTy());
14474   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14475                        MachinePointerInfo(SV, 16), false, false, 0);
14476   MemOps.push_back(Store);
14477   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14478 }
14479
14480 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14481   assert(Subtarget->is64Bit() &&
14482          "LowerVAARG only handles 64-bit va_arg!");
14483   assert((Subtarget->isTargetLinux() ||
14484           Subtarget->isTargetDarwin()) &&
14485           "Unhandled target in LowerVAARG");
14486   assert(Op.getNode()->getNumOperands() == 4);
14487   SDValue Chain = Op.getOperand(0);
14488   SDValue SrcPtr = Op.getOperand(1);
14489   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14490   unsigned Align = Op.getConstantOperandVal(3);
14491   SDLoc dl(Op);
14492
14493   EVT ArgVT = Op.getNode()->getValueType(0);
14494   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14495   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14496   uint8_t ArgMode;
14497
14498   // Decide which area this value should be read from.
14499   // TODO: Implement the AMD64 ABI in its entirety. This simple
14500   // selection mechanism works only for the basic types.
14501   if (ArgVT == MVT::f80) {
14502     llvm_unreachable("va_arg for f80 not yet implemented");
14503   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14504     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14505   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14506     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14507   } else {
14508     llvm_unreachable("Unhandled argument type in LowerVAARG");
14509   }
14510
14511   if (ArgMode == 2) {
14512     // Sanity Check: Make sure using fp_offset makes sense.
14513     assert(!DAG.getTarget().Options.UseSoftFloat &&
14514            !(DAG.getMachineFunction()
14515                 .getFunction()->getAttributes()
14516                 .hasAttribute(AttributeSet::FunctionIndex,
14517                               Attribute::NoImplicitFloat)) &&
14518            Subtarget->hasSSE1());
14519   }
14520
14521   // Insert VAARG_64 node into the DAG
14522   // VAARG_64 returns two values: Variable Argument Address, Chain
14523   SmallVector<SDValue, 11> InstOps;
14524   InstOps.push_back(Chain);
14525   InstOps.push_back(SrcPtr);
14526   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14527   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14528   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14529   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14530   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14531                                           VTs, InstOps, MVT::i64,
14532                                           MachinePointerInfo(SV),
14533                                           /*Align=*/0,
14534                                           /*Volatile=*/false,
14535                                           /*ReadMem=*/true,
14536                                           /*WriteMem=*/true);
14537   Chain = VAARG.getValue(1);
14538
14539   // Load the next argument and return it
14540   return DAG.getLoad(ArgVT, dl,
14541                      Chain,
14542                      VAARG,
14543                      MachinePointerInfo(),
14544                      false, false, false, 0);
14545 }
14546
14547 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14548                            SelectionDAG &DAG) {
14549   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14550   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14551   SDValue Chain = Op.getOperand(0);
14552   SDValue DstPtr = Op.getOperand(1);
14553   SDValue SrcPtr = Op.getOperand(2);
14554   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14555   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14556   SDLoc DL(Op);
14557
14558   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14559                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14560                        false,
14561                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14562 }
14563
14564 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14565 // amount is a constant. Takes immediate version of shift as input.
14566 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14567                                           SDValue SrcOp, uint64_t ShiftAmt,
14568                                           SelectionDAG &DAG) {
14569   MVT ElementType = VT.getVectorElementType();
14570
14571   // Fold this packed shift into its first operand if ShiftAmt is 0.
14572   if (ShiftAmt == 0)
14573     return SrcOp;
14574
14575   // Check for ShiftAmt >= element width
14576   if (ShiftAmt >= ElementType.getSizeInBits()) {
14577     if (Opc == X86ISD::VSRAI)
14578       ShiftAmt = ElementType.getSizeInBits() - 1;
14579     else
14580       return DAG.getConstant(0, VT);
14581   }
14582
14583   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14584          && "Unknown target vector shift-by-constant node");
14585
14586   // Fold this packed vector shift into a build vector if SrcOp is a
14587   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14588   if (VT == SrcOp.getSimpleValueType() &&
14589       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14590     SmallVector<SDValue, 8> Elts;
14591     unsigned NumElts = SrcOp->getNumOperands();
14592     ConstantSDNode *ND;
14593
14594     switch(Opc) {
14595     default: llvm_unreachable(nullptr);
14596     case X86ISD::VSHLI:
14597       for (unsigned i=0; i!=NumElts; ++i) {
14598         SDValue CurrentOp = SrcOp->getOperand(i);
14599         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14600           Elts.push_back(CurrentOp);
14601           continue;
14602         }
14603         ND = cast<ConstantSDNode>(CurrentOp);
14604         const APInt &C = ND->getAPIntValue();
14605         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14606       }
14607       break;
14608     case X86ISD::VSRLI:
14609       for (unsigned i=0; i!=NumElts; ++i) {
14610         SDValue CurrentOp = SrcOp->getOperand(i);
14611         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14612           Elts.push_back(CurrentOp);
14613           continue;
14614         }
14615         ND = cast<ConstantSDNode>(CurrentOp);
14616         const APInt &C = ND->getAPIntValue();
14617         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14618       }
14619       break;
14620     case X86ISD::VSRAI:
14621       for (unsigned i=0; i!=NumElts; ++i) {
14622         SDValue CurrentOp = SrcOp->getOperand(i);
14623         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14624           Elts.push_back(CurrentOp);
14625           continue;
14626         }
14627         ND = cast<ConstantSDNode>(CurrentOp);
14628         const APInt &C = ND->getAPIntValue();
14629         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14630       }
14631       break;
14632     }
14633
14634     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14635   }
14636
14637   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14638 }
14639
14640 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14641 // may or may not be a constant. Takes immediate version of shift as input.
14642 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14643                                    SDValue SrcOp, SDValue ShAmt,
14644                                    SelectionDAG &DAG) {
14645   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14646
14647   // Catch shift-by-constant.
14648   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14649     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14650                                       CShAmt->getZExtValue(), DAG);
14651
14652   // Change opcode to non-immediate version
14653   switch (Opc) {
14654     default: llvm_unreachable("Unknown target vector shift node");
14655     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14656     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14657     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14658   }
14659
14660   // Need to build a vector containing shift amount
14661   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14662   SDValue ShOps[4];
14663   ShOps[0] = ShAmt;
14664   ShOps[1] = DAG.getConstant(0, MVT::i32);
14665   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14666   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14667
14668   // The return type has to be a 128-bit type with the same element
14669   // type as the input type.
14670   MVT EltVT = VT.getVectorElementType();
14671   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14672
14673   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14674   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14675 }
14676
14677 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14678 /// necessary casting for \p Mask when lowering masking intrinsics.
14679 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14680                                     SDValue PreservedSrc, SelectionDAG &DAG) {
14681     EVT VT = Op.getValueType();
14682     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14683                                   MVT::i1, VT.getVectorNumElements());
14684     SDLoc dl(Op);
14685
14686     assert(MaskVT.isSimple() && "invalid mask type");
14687     return DAG.getNode(ISD::VSELECT, dl, VT,
14688                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14689                        Op, PreservedSrc);
14690 }
14691
14692 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14693     switch (IntNo) {
14694     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14695     case Intrinsic::x86_fma_vfmadd_ps:
14696     case Intrinsic::x86_fma_vfmadd_pd:
14697     case Intrinsic::x86_fma_vfmadd_ps_256:
14698     case Intrinsic::x86_fma_vfmadd_pd_256:
14699     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14700     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14701       return X86ISD::FMADD;
14702     case Intrinsic::x86_fma_vfmsub_ps:
14703     case Intrinsic::x86_fma_vfmsub_pd:
14704     case Intrinsic::x86_fma_vfmsub_ps_256:
14705     case Intrinsic::x86_fma_vfmsub_pd_256:
14706     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14707     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14708       return X86ISD::FMSUB;
14709     case Intrinsic::x86_fma_vfnmadd_ps:
14710     case Intrinsic::x86_fma_vfnmadd_pd:
14711     case Intrinsic::x86_fma_vfnmadd_ps_256:
14712     case Intrinsic::x86_fma_vfnmadd_pd_256:
14713     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14714     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14715       return X86ISD::FNMADD;
14716     case Intrinsic::x86_fma_vfnmsub_ps:
14717     case Intrinsic::x86_fma_vfnmsub_pd:
14718     case Intrinsic::x86_fma_vfnmsub_ps_256:
14719     case Intrinsic::x86_fma_vfnmsub_pd_256:
14720     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14721     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14722       return X86ISD::FNMSUB;
14723     case Intrinsic::x86_fma_vfmaddsub_ps:
14724     case Intrinsic::x86_fma_vfmaddsub_pd:
14725     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14726     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14727     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14728     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14729       return X86ISD::FMADDSUB;
14730     case Intrinsic::x86_fma_vfmsubadd_ps:
14731     case Intrinsic::x86_fma_vfmsubadd_pd:
14732     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14733     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14734     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14735     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14736       return X86ISD::FMSUBADD;
14737     }
14738 }
14739
14740 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14741   SDLoc dl(Op);
14742   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14743
14744   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14745   if (IntrData) {
14746     switch(IntrData->Type) {
14747     case INTR_TYPE_1OP:
14748       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14749     case INTR_TYPE_2OP:
14750       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14751         Op.getOperand(2));
14752     case INTR_TYPE_3OP:
14753       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14754         Op.getOperand(2), Op.getOperand(3));
14755     case COMI: { // Comparison intrinsics
14756       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14757       SDValue LHS = Op.getOperand(1);
14758       SDValue RHS = Op.getOperand(2);
14759       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14760       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14761       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14762       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14763                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14764       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14765     }
14766     case VSHIFT:
14767       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14768                                  Op.getOperand(1), Op.getOperand(2), DAG);
14769     default:
14770       break;
14771     }
14772   }
14773
14774   switch (IntNo) {
14775   default: return SDValue();    // Don't custom lower most intrinsics.
14776
14777   // Arithmetic intrinsics.
14778   case Intrinsic::x86_sse2_pmulu_dq:
14779   case Intrinsic::x86_avx2_pmulu_dq:
14780     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14781                        Op.getOperand(1), Op.getOperand(2));
14782
14783   case Intrinsic::x86_sse41_pmuldq:
14784   case Intrinsic::x86_avx2_pmul_dq:
14785     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14786                        Op.getOperand(1), Op.getOperand(2));
14787
14788   case Intrinsic::x86_sse2_pmulhu_w:
14789   case Intrinsic::x86_avx2_pmulhu_w:
14790     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14791                        Op.getOperand(1), Op.getOperand(2));
14792
14793   case Intrinsic::x86_sse2_pmulh_w:
14794   case Intrinsic::x86_avx2_pmulh_w:
14795     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14796                        Op.getOperand(1), Op.getOperand(2));
14797
14798   // SSE/SSE2/AVX floating point max/min intrinsics.
14799   case Intrinsic::x86_sse_max_ps:
14800   case Intrinsic::x86_sse2_max_pd:
14801   case Intrinsic::x86_avx_max_ps_256:
14802   case Intrinsic::x86_avx_max_pd_256:
14803   case Intrinsic::x86_sse_min_ps:
14804   case Intrinsic::x86_sse2_min_pd:
14805   case Intrinsic::x86_avx_min_ps_256:
14806   case Intrinsic::x86_avx_min_pd_256: {
14807     unsigned Opcode;
14808     switch (IntNo) {
14809     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14810     case Intrinsic::x86_sse_max_ps:
14811     case Intrinsic::x86_sse2_max_pd:
14812     case Intrinsic::x86_avx_max_ps_256:
14813     case Intrinsic::x86_avx_max_pd_256:
14814       Opcode = X86ISD::FMAX;
14815       break;
14816     case Intrinsic::x86_sse_min_ps:
14817     case Intrinsic::x86_sse2_min_pd:
14818     case Intrinsic::x86_avx_min_ps_256:
14819     case Intrinsic::x86_avx_min_pd_256:
14820       Opcode = X86ISD::FMIN;
14821       break;
14822     }
14823     return DAG.getNode(Opcode, dl, Op.getValueType(),
14824                        Op.getOperand(1), Op.getOperand(2));
14825   }
14826
14827   // AVX2 variable shift intrinsics
14828   case Intrinsic::x86_avx2_psllv_d:
14829   case Intrinsic::x86_avx2_psllv_q:
14830   case Intrinsic::x86_avx2_psllv_d_256:
14831   case Intrinsic::x86_avx2_psllv_q_256:
14832   case Intrinsic::x86_avx2_psrlv_d:
14833   case Intrinsic::x86_avx2_psrlv_q:
14834   case Intrinsic::x86_avx2_psrlv_d_256:
14835   case Intrinsic::x86_avx2_psrlv_q_256:
14836   case Intrinsic::x86_avx2_psrav_d:
14837   case Intrinsic::x86_avx2_psrav_d_256: {
14838     unsigned Opcode;
14839     switch (IntNo) {
14840     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14841     case Intrinsic::x86_avx2_psllv_d:
14842     case Intrinsic::x86_avx2_psllv_q:
14843     case Intrinsic::x86_avx2_psllv_d_256:
14844     case Intrinsic::x86_avx2_psllv_q_256:
14845       Opcode = ISD::SHL;
14846       break;
14847     case Intrinsic::x86_avx2_psrlv_d:
14848     case Intrinsic::x86_avx2_psrlv_q:
14849     case Intrinsic::x86_avx2_psrlv_d_256:
14850     case Intrinsic::x86_avx2_psrlv_q_256:
14851       Opcode = ISD::SRL;
14852       break;
14853     case Intrinsic::x86_avx2_psrav_d:
14854     case Intrinsic::x86_avx2_psrav_d_256:
14855       Opcode = ISD::SRA;
14856       break;
14857     }
14858     return DAG.getNode(Opcode, dl, Op.getValueType(),
14859                        Op.getOperand(1), Op.getOperand(2));
14860   }
14861
14862   case Intrinsic::x86_sse2_packssdw_128:
14863   case Intrinsic::x86_sse2_packsswb_128:
14864   case Intrinsic::x86_avx2_packssdw:
14865   case Intrinsic::x86_avx2_packsswb:
14866     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14867                        Op.getOperand(1), Op.getOperand(2));
14868
14869   case Intrinsic::x86_sse2_packuswb_128:
14870   case Intrinsic::x86_sse41_packusdw:
14871   case Intrinsic::x86_avx2_packuswb:
14872   case Intrinsic::x86_avx2_packusdw:
14873     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14874                        Op.getOperand(1), Op.getOperand(2));
14875
14876   case Intrinsic::x86_ssse3_pshuf_b_128:
14877   case Intrinsic::x86_avx2_pshuf_b:
14878     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14879                        Op.getOperand(1), Op.getOperand(2));
14880
14881   case Intrinsic::x86_sse2_pshuf_d:
14882     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14883                        Op.getOperand(1), Op.getOperand(2));
14884
14885   case Intrinsic::x86_sse2_pshufl_w:
14886     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14887                        Op.getOperand(1), Op.getOperand(2));
14888
14889   case Intrinsic::x86_sse2_pshufh_w:
14890     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14891                        Op.getOperand(1), Op.getOperand(2));
14892
14893   case Intrinsic::x86_ssse3_psign_b_128:
14894   case Intrinsic::x86_ssse3_psign_w_128:
14895   case Intrinsic::x86_ssse3_psign_d_128:
14896   case Intrinsic::x86_avx2_psign_b:
14897   case Intrinsic::x86_avx2_psign_w:
14898   case Intrinsic::x86_avx2_psign_d:
14899     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14900                        Op.getOperand(1), Op.getOperand(2));
14901
14902   case Intrinsic::x86_avx2_permd:
14903   case Intrinsic::x86_avx2_permps:
14904     // Operands intentionally swapped. Mask is last operand to intrinsic,
14905     // but second operand for node/instruction.
14906     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14907                        Op.getOperand(2), Op.getOperand(1));
14908
14909   case Intrinsic::x86_avx512_mask_valign_q_512:
14910   case Intrinsic::x86_avx512_mask_valign_d_512:
14911     // Vector source operands are swapped.
14912     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14913                                             Op.getValueType(), Op.getOperand(2),
14914                                             Op.getOperand(1),
14915                                             Op.getOperand(3)),
14916                                 Op.getOperand(5), Op.getOperand(4), DAG);
14917
14918   // ptest and testp intrinsics. The intrinsic these come from are designed to
14919   // return an integer value, not just an instruction so lower it to the ptest
14920   // or testp pattern and a setcc for the result.
14921   case Intrinsic::x86_sse41_ptestz:
14922   case Intrinsic::x86_sse41_ptestc:
14923   case Intrinsic::x86_sse41_ptestnzc:
14924   case Intrinsic::x86_avx_ptestz_256:
14925   case Intrinsic::x86_avx_ptestc_256:
14926   case Intrinsic::x86_avx_ptestnzc_256:
14927   case Intrinsic::x86_avx_vtestz_ps:
14928   case Intrinsic::x86_avx_vtestc_ps:
14929   case Intrinsic::x86_avx_vtestnzc_ps:
14930   case Intrinsic::x86_avx_vtestz_pd:
14931   case Intrinsic::x86_avx_vtestc_pd:
14932   case Intrinsic::x86_avx_vtestnzc_pd:
14933   case Intrinsic::x86_avx_vtestz_ps_256:
14934   case Intrinsic::x86_avx_vtestc_ps_256:
14935   case Intrinsic::x86_avx_vtestnzc_ps_256:
14936   case Intrinsic::x86_avx_vtestz_pd_256:
14937   case Intrinsic::x86_avx_vtestc_pd_256:
14938   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14939     bool IsTestPacked = false;
14940     unsigned X86CC;
14941     switch (IntNo) {
14942     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14943     case Intrinsic::x86_avx_vtestz_ps:
14944     case Intrinsic::x86_avx_vtestz_pd:
14945     case Intrinsic::x86_avx_vtestz_ps_256:
14946     case Intrinsic::x86_avx_vtestz_pd_256:
14947       IsTestPacked = true; // Fallthrough
14948     case Intrinsic::x86_sse41_ptestz:
14949     case Intrinsic::x86_avx_ptestz_256:
14950       // ZF = 1
14951       X86CC = X86::COND_E;
14952       break;
14953     case Intrinsic::x86_avx_vtestc_ps:
14954     case Intrinsic::x86_avx_vtestc_pd:
14955     case Intrinsic::x86_avx_vtestc_ps_256:
14956     case Intrinsic::x86_avx_vtestc_pd_256:
14957       IsTestPacked = true; // Fallthrough
14958     case Intrinsic::x86_sse41_ptestc:
14959     case Intrinsic::x86_avx_ptestc_256:
14960       // CF = 1
14961       X86CC = X86::COND_B;
14962       break;
14963     case Intrinsic::x86_avx_vtestnzc_ps:
14964     case Intrinsic::x86_avx_vtestnzc_pd:
14965     case Intrinsic::x86_avx_vtestnzc_ps_256:
14966     case Intrinsic::x86_avx_vtestnzc_pd_256:
14967       IsTestPacked = true; // Fallthrough
14968     case Intrinsic::x86_sse41_ptestnzc:
14969     case Intrinsic::x86_avx_ptestnzc_256:
14970       // ZF and CF = 0
14971       X86CC = X86::COND_A;
14972       break;
14973     }
14974
14975     SDValue LHS = Op.getOperand(1);
14976     SDValue RHS = Op.getOperand(2);
14977     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14978     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14979     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14980     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14981     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14982   }
14983   case Intrinsic::x86_avx512_kortestz_w:
14984   case Intrinsic::x86_avx512_kortestc_w: {
14985     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14986     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14987     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14988     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14989     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14990     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14991     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14992   }
14993
14994   case Intrinsic::x86_sse42_pcmpistria128:
14995   case Intrinsic::x86_sse42_pcmpestria128:
14996   case Intrinsic::x86_sse42_pcmpistric128:
14997   case Intrinsic::x86_sse42_pcmpestric128:
14998   case Intrinsic::x86_sse42_pcmpistrio128:
14999   case Intrinsic::x86_sse42_pcmpestrio128:
15000   case Intrinsic::x86_sse42_pcmpistris128:
15001   case Intrinsic::x86_sse42_pcmpestris128:
15002   case Intrinsic::x86_sse42_pcmpistriz128:
15003   case Intrinsic::x86_sse42_pcmpestriz128: {
15004     unsigned Opcode;
15005     unsigned X86CC;
15006     switch (IntNo) {
15007     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15008     case Intrinsic::x86_sse42_pcmpistria128:
15009       Opcode = X86ISD::PCMPISTRI;
15010       X86CC = X86::COND_A;
15011       break;
15012     case Intrinsic::x86_sse42_pcmpestria128:
15013       Opcode = X86ISD::PCMPESTRI;
15014       X86CC = X86::COND_A;
15015       break;
15016     case Intrinsic::x86_sse42_pcmpistric128:
15017       Opcode = X86ISD::PCMPISTRI;
15018       X86CC = X86::COND_B;
15019       break;
15020     case Intrinsic::x86_sse42_pcmpestric128:
15021       Opcode = X86ISD::PCMPESTRI;
15022       X86CC = X86::COND_B;
15023       break;
15024     case Intrinsic::x86_sse42_pcmpistrio128:
15025       Opcode = X86ISD::PCMPISTRI;
15026       X86CC = X86::COND_O;
15027       break;
15028     case Intrinsic::x86_sse42_pcmpestrio128:
15029       Opcode = X86ISD::PCMPESTRI;
15030       X86CC = X86::COND_O;
15031       break;
15032     case Intrinsic::x86_sse42_pcmpistris128:
15033       Opcode = X86ISD::PCMPISTRI;
15034       X86CC = X86::COND_S;
15035       break;
15036     case Intrinsic::x86_sse42_pcmpestris128:
15037       Opcode = X86ISD::PCMPESTRI;
15038       X86CC = X86::COND_S;
15039       break;
15040     case Intrinsic::x86_sse42_pcmpistriz128:
15041       Opcode = X86ISD::PCMPISTRI;
15042       X86CC = X86::COND_E;
15043       break;
15044     case Intrinsic::x86_sse42_pcmpestriz128:
15045       Opcode = X86ISD::PCMPESTRI;
15046       X86CC = X86::COND_E;
15047       break;
15048     }
15049     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15050     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15051     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15052     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15053                                 DAG.getConstant(X86CC, MVT::i8),
15054                                 SDValue(PCMP.getNode(), 1));
15055     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15056   }
15057
15058   case Intrinsic::x86_sse42_pcmpistri128:
15059   case Intrinsic::x86_sse42_pcmpestri128: {
15060     unsigned Opcode;
15061     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15062       Opcode = X86ISD::PCMPISTRI;
15063     else
15064       Opcode = X86ISD::PCMPESTRI;
15065
15066     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15067     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15068     return DAG.getNode(Opcode, dl, VTs, NewOps);
15069   }
15070
15071   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
15072   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
15073   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
15074   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
15075   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
15076   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
15077   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
15078   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
15079   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
15080   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
15081   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
15082   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
15083     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
15084     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
15085       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
15086                                               dl, Op.getValueType(),
15087                                               Op.getOperand(1),
15088                                               Op.getOperand(2),
15089                                               Op.getOperand(3)),
15090                                   Op.getOperand(4), Op.getOperand(1), DAG);
15091     else
15092       return SDValue();
15093   }
15094
15095   case Intrinsic::x86_fma_vfmadd_ps:
15096   case Intrinsic::x86_fma_vfmadd_pd:
15097   case Intrinsic::x86_fma_vfmsub_ps:
15098   case Intrinsic::x86_fma_vfmsub_pd:
15099   case Intrinsic::x86_fma_vfnmadd_ps:
15100   case Intrinsic::x86_fma_vfnmadd_pd:
15101   case Intrinsic::x86_fma_vfnmsub_ps:
15102   case Intrinsic::x86_fma_vfnmsub_pd:
15103   case Intrinsic::x86_fma_vfmaddsub_ps:
15104   case Intrinsic::x86_fma_vfmaddsub_pd:
15105   case Intrinsic::x86_fma_vfmsubadd_ps:
15106   case Intrinsic::x86_fma_vfmsubadd_pd:
15107   case Intrinsic::x86_fma_vfmadd_ps_256:
15108   case Intrinsic::x86_fma_vfmadd_pd_256:
15109   case Intrinsic::x86_fma_vfmsub_ps_256:
15110   case Intrinsic::x86_fma_vfmsub_pd_256:
15111   case Intrinsic::x86_fma_vfnmadd_ps_256:
15112   case Intrinsic::x86_fma_vfnmadd_pd_256:
15113   case Intrinsic::x86_fma_vfnmsub_ps_256:
15114   case Intrinsic::x86_fma_vfnmsub_pd_256:
15115   case Intrinsic::x86_fma_vfmaddsub_ps_256:
15116   case Intrinsic::x86_fma_vfmaddsub_pd_256:
15117   case Intrinsic::x86_fma_vfmsubadd_ps_256:
15118   case Intrinsic::x86_fma_vfmsubadd_pd_256:
15119     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
15120                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
15121   }
15122 }
15123
15124 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15125                               SDValue Src, SDValue Mask, SDValue Base,
15126                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15127                               const X86Subtarget * Subtarget) {
15128   SDLoc dl(Op);
15129   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15130   assert(C && "Invalid scale type");
15131   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15132   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15133                              Index.getSimpleValueType().getVectorNumElements());
15134   SDValue MaskInReg;
15135   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15136   if (MaskC)
15137     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15138   else
15139     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15140   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15141   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15142   SDValue Segment = DAG.getRegister(0, MVT::i32);
15143   if (Src.getOpcode() == ISD::UNDEF)
15144     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15145   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15146   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15147   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15148   return DAG.getMergeValues(RetOps, dl);
15149 }
15150
15151 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15152                                SDValue Src, SDValue Mask, SDValue Base,
15153                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15154   SDLoc dl(Op);
15155   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15156   assert(C && "Invalid scale type");
15157   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15158   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15159   SDValue Segment = DAG.getRegister(0, MVT::i32);
15160   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15161                              Index.getSimpleValueType().getVectorNumElements());
15162   SDValue MaskInReg;
15163   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15164   if (MaskC)
15165     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15166   else
15167     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15168   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15169   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15170   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15171   return SDValue(Res, 1);
15172 }
15173
15174 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15175                                SDValue Mask, SDValue Base, SDValue Index,
15176                                SDValue ScaleOp, SDValue Chain) {
15177   SDLoc dl(Op);
15178   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15179   assert(C && "Invalid scale type");
15180   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15181   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15182   SDValue Segment = DAG.getRegister(0, MVT::i32);
15183   EVT MaskVT =
15184     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15185   SDValue MaskInReg;
15186   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15187   if (MaskC)
15188     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15189   else
15190     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15191   //SDVTList VTs = DAG.getVTList(MVT::Other);
15192   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15193   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15194   return SDValue(Res, 0);
15195 }
15196
15197 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15198 // read performance monitor counters (x86_rdpmc).
15199 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15200                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15201                               SmallVectorImpl<SDValue> &Results) {
15202   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15203   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15204   SDValue LO, HI;
15205
15206   // The ECX register is used to select the index of the performance counter
15207   // to read.
15208   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15209                                    N->getOperand(2));
15210   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15211
15212   // Reads the content of a 64-bit performance counter and returns it in the
15213   // registers EDX:EAX.
15214   if (Subtarget->is64Bit()) {
15215     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15216     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15217                             LO.getValue(2));
15218   } else {
15219     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15220     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15221                             LO.getValue(2));
15222   }
15223   Chain = HI.getValue(1);
15224
15225   if (Subtarget->is64Bit()) {
15226     // The EAX register is loaded with the low-order 32 bits. The EDX register
15227     // is loaded with the supported high-order bits of the counter.
15228     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15229                               DAG.getConstant(32, MVT::i8));
15230     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15231     Results.push_back(Chain);
15232     return;
15233   }
15234
15235   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15236   SDValue Ops[] = { LO, HI };
15237   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15238   Results.push_back(Pair);
15239   Results.push_back(Chain);
15240 }
15241
15242 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15243 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15244 // also used to custom lower READCYCLECOUNTER nodes.
15245 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15246                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15247                               SmallVectorImpl<SDValue> &Results) {
15248   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15249   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15250   SDValue LO, HI;
15251
15252   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15253   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15254   // and the EAX register is loaded with the low-order 32 bits.
15255   if (Subtarget->is64Bit()) {
15256     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15257     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15258                             LO.getValue(2));
15259   } else {
15260     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15261     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15262                             LO.getValue(2));
15263   }
15264   SDValue Chain = HI.getValue(1);
15265
15266   if (Opcode == X86ISD::RDTSCP_DAG) {
15267     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15268
15269     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15270     // the ECX register. Add 'ecx' explicitly to the chain.
15271     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15272                                      HI.getValue(2));
15273     // Explicitly store the content of ECX at the location passed in input
15274     // to the 'rdtscp' intrinsic.
15275     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15276                          MachinePointerInfo(), false, false, 0);
15277   }
15278
15279   if (Subtarget->is64Bit()) {
15280     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15281     // the EAX register is loaded with the low-order 32 bits.
15282     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15283                               DAG.getConstant(32, MVT::i8));
15284     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15285     Results.push_back(Chain);
15286     return;
15287   }
15288
15289   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15290   SDValue Ops[] = { LO, HI };
15291   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15292   Results.push_back(Pair);
15293   Results.push_back(Chain);
15294 }
15295
15296 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15297                                      SelectionDAG &DAG) {
15298   SmallVector<SDValue, 2> Results;
15299   SDLoc DL(Op);
15300   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15301                           Results);
15302   return DAG.getMergeValues(Results, DL);
15303 }
15304
15305
15306 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15307                                       SelectionDAG &DAG) {
15308   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15309
15310   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15311   if (!IntrData)
15312     return SDValue();
15313
15314   SDLoc dl(Op);
15315   switch(IntrData->Type) {
15316   default:
15317     llvm_unreachable("Unknown Intrinsic Type");
15318     break;    
15319   case RDSEED:
15320   case RDRAND: {
15321     // Emit the node with the right value type.
15322     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15323     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15324
15325     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15326     // Otherwise return the value from Rand, which is always 0, casted to i32.
15327     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15328                       DAG.getConstant(1, Op->getValueType(1)),
15329                       DAG.getConstant(X86::COND_B, MVT::i32),
15330                       SDValue(Result.getNode(), 1) };
15331     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15332                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15333                                   Ops);
15334
15335     // Return { result, isValid, chain }.
15336     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15337                        SDValue(Result.getNode(), 2));
15338   }
15339   case GATHER: {
15340   //gather(v1, mask, index, base, scale);
15341     SDValue Chain = Op.getOperand(0);
15342     SDValue Src   = Op.getOperand(2);
15343     SDValue Base  = Op.getOperand(3);
15344     SDValue Index = Op.getOperand(4);
15345     SDValue Mask  = Op.getOperand(5);
15346     SDValue Scale = Op.getOperand(6);
15347     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15348                           Subtarget);
15349   }
15350   case SCATTER: {
15351   //scatter(base, mask, index, v1, scale);
15352     SDValue Chain = Op.getOperand(0);
15353     SDValue Base  = Op.getOperand(2);
15354     SDValue Mask  = Op.getOperand(3);
15355     SDValue Index = Op.getOperand(4);
15356     SDValue Src   = Op.getOperand(5);
15357     SDValue Scale = Op.getOperand(6);
15358     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15359   }
15360   case PREFETCH: {
15361     SDValue Hint = Op.getOperand(6);
15362     unsigned HintVal;
15363     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15364         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15365       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15366     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15367     SDValue Chain = Op.getOperand(0);
15368     SDValue Mask  = Op.getOperand(2);
15369     SDValue Index = Op.getOperand(3);
15370     SDValue Base  = Op.getOperand(4);
15371     SDValue Scale = Op.getOperand(5);
15372     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15373   }
15374   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15375   case RDTSC: {
15376     SmallVector<SDValue, 2> Results;
15377     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15378     return DAG.getMergeValues(Results, dl);
15379   }
15380   // Read Performance Monitoring Counters.
15381   case RDPMC: {
15382     SmallVector<SDValue, 2> Results;
15383     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15384     return DAG.getMergeValues(Results, dl);
15385   }
15386   // XTEST intrinsics.
15387   case XTEST: {
15388     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15389     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15390     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15391                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15392                                 InTrans);
15393     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15394     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15395                        Ret, SDValue(InTrans.getNode(), 1));
15396   }
15397   // ADC/ADCX/SBB
15398   case ADX: {
15399     SmallVector<SDValue, 2> Results;
15400     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15401     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15402     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15403                                 DAG.getConstant(-1, MVT::i8));
15404     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15405                               Op.getOperand(4), GenCF.getValue(1));
15406     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15407                                  Op.getOperand(5), MachinePointerInfo(),
15408                                  false, false, 0);
15409     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15410                                 DAG.getConstant(X86::COND_B, MVT::i8),
15411                                 Res.getValue(1));
15412     Results.push_back(SetCC);
15413     Results.push_back(Store);
15414     return DAG.getMergeValues(Results, dl);
15415   }
15416   }
15417 }
15418
15419 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15420                                            SelectionDAG &DAG) const {
15421   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15422   MFI->setReturnAddressIsTaken(true);
15423
15424   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15425     return SDValue();
15426
15427   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15428   SDLoc dl(Op);
15429   EVT PtrVT = getPointerTy();
15430
15431   if (Depth > 0) {
15432     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15433     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15434         DAG.getSubtarget().getRegisterInfo());
15435     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15436     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15437                        DAG.getNode(ISD::ADD, dl, PtrVT,
15438                                    FrameAddr, Offset),
15439                        MachinePointerInfo(), false, false, false, 0);
15440   }
15441
15442   // Just load the return address.
15443   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15444   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15445                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15446 }
15447
15448 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15449   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15450   MFI->setFrameAddressIsTaken(true);
15451
15452   EVT VT = Op.getValueType();
15453   SDLoc dl(Op);  // FIXME probably not meaningful
15454   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15455   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15456       DAG.getSubtarget().getRegisterInfo());
15457   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15458   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15459           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15460          "Invalid Frame Register!");
15461   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15462   while (Depth--)
15463     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15464                             MachinePointerInfo(),
15465                             false, false, false, 0);
15466   return FrameAddr;
15467 }
15468
15469 // FIXME? Maybe this could be a TableGen attribute on some registers and
15470 // this table could be generated automatically from RegInfo.
15471 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15472                                               EVT VT) const {
15473   unsigned Reg = StringSwitch<unsigned>(RegName)
15474                        .Case("esp", X86::ESP)
15475                        .Case("rsp", X86::RSP)
15476                        .Default(0);
15477   if (Reg)
15478     return Reg;
15479   report_fatal_error("Invalid register name global variable");
15480 }
15481
15482 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15483                                                      SelectionDAG &DAG) const {
15484   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15485       DAG.getSubtarget().getRegisterInfo());
15486   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15487 }
15488
15489 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15490   SDValue Chain     = Op.getOperand(0);
15491   SDValue Offset    = Op.getOperand(1);
15492   SDValue Handler   = Op.getOperand(2);
15493   SDLoc dl      (Op);
15494
15495   EVT PtrVT = getPointerTy();
15496   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15497       DAG.getSubtarget().getRegisterInfo());
15498   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15499   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15500           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15501          "Invalid Frame Register!");
15502   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15503   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15504
15505   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15506                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15507   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15508   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15509                        false, false, 0);
15510   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15511
15512   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15513                      DAG.getRegister(StoreAddrReg, PtrVT));
15514 }
15515
15516 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15517                                                SelectionDAG &DAG) const {
15518   SDLoc DL(Op);
15519   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15520                      DAG.getVTList(MVT::i32, MVT::Other),
15521                      Op.getOperand(0), Op.getOperand(1));
15522 }
15523
15524 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15525                                                 SelectionDAG &DAG) const {
15526   SDLoc DL(Op);
15527   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15528                      Op.getOperand(0), Op.getOperand(1));
15529 }
15530
15531 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15532   return Op.getOperand(0);
15533 }
15534
15535 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15536                                                 SelectionDAG &DAG) const {
15537   SDValue Root = Op.getOperand(0);
15538   SDValue Trmp = Op.getOperand(1); // trampoline
15539   SDValue FPtr = Op.getOperand(2); // nested function
15540   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15541   SDLoc dl (Op);
15542
15543   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15544   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15545
15546   if (Subtarget->is64Bit()) {
15547     SDValue OutChains[6];
15548
15549     // Large code-model.
15550     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15551     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15552
15553     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15554     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15555
15556     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15557
15558     // Load the pointer to the nested function into R11.
15559     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15560     SDValue Addr = Trmp;
15561     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15562                                 Addr, MachinePointerInfo(TrmpAddr),
15563                                 false, false, 0);
15564
15565     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15566                        DAG.getConstant(2, MVT::i64));
15567     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15568                                 MachinePointerInfo(TrmpAddr, 2),
15569                                 false, false, 2);
15570
15571     // Load the 'nest' parameter value into R10.
15572     // R10 is specified in X86CallingConv.td
15573     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15574     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15575                        DAG.getConstant(10, MVT::i64));
15576     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15577                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15578                                 false, false, 0);
15579
15580     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15581                        DAG.getConstant(12, MVT::i64));
15582     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15583                                 MachinePointerInfo(TrmpAddr, 12),
15584                                 false, false, 2);
15585
15586     // Jump to the nested function.
15587     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15588     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15589                        DAG.getConstant(20, MVT::i64));
15590     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15591                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15592                                 false, false, 0);
15593
15594     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15595     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15596                        DAG.getConstant(22, MVT::i64));
15597     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15598                                 MachinePointerInfo(TrmpAddr, 22),
15599                                 false, false, 0);
15600
15601     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15602   } else {
15603     const Function *Func =
15604       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15605     CallingConv::ID CC = Func->getCallingConv();
15606     unsigned NestReg;
15607
15608     switch (CC) {
15609     default:
15610       llvm_unreachable("Unsupported calling convention");
15611     case CallingConv::C:
15612     case CallingConv::X86_StdCall: {
15613       // Pass 'nest' parameter in ECX.
15614       // Must be kept in sync with X86CallingConv.td
15615       NestReg = X86::ECX;
15616
15617       // Check that ECX wasn't needed by an 'inreg' parameter.
15618       FunctionType *FTy = Func->getFunctionType();
15619       const AttributeSet &Attrs = Func->getAttributes();
15620
15621       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15622         unsigned InRegCount = 0;
15623         unsigned Idx = 1;
15624
15625         for (FunctionType::param_iterator I = FTy->param_begin(),
15626              E = FTy->param_end(); I != E; ++I, ++Idx)
15627           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15628             // FIXME: should only count parameters that are lowered to integers.
15629             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15630
15631         if (InRegCount > 2) {
15632           report_fatal_error("Nest register in use - reduce number of inreg"
15633                              " parameters!");
15634         }
15635       }
15636       break;
15637     }
15638     case CallingConv::X86_FastCall:
15639     case CallingConv::X86_ThisCall:
15640     case CallingConv::Fast:
15641       // Pass 'nest' parameter in EAX.
15642       // Must be kept in sync with X86CallingConv.td
15643       NestReg = X86::EAX;
15644       break;
15645     }
15646
15647     SDValue OutChains[4];
15648     SDValue Addr, Disp;
15649
15650     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15651                        DAG.getConstant(10, MVT::i32));
15652     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15653
15654     // This is storing the opcode for MOV32ri.
15655     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15656     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15657     OutChains[0] = DAG.getStore(Root, dl,
15658                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15659                                 Trmp, MachinePointerInfo(TrmpAddr),
15660                                 false, false, 0);
15661
15662     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15663                        DAG.getConstant(1, MVT::i32));
15664     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15665                                 MachinePointerInfo(TrmpAddr, 1),
15666                                 false, false, 1);
15667
15668     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15669     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15670                        DAG.getConstant(5, MVT::i32));
15671     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15672                                 MachinePointerInfo(TrmpAddr, 5),
15673                                 false, false, 1);
15674
15675     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15676                        DAG.getConstant(6, MVT::i32));
15677     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15678                                 MachinePointerInfo(TrmpAddr, 6),
15679                                 false, false, 1);
15680
15681     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15682   }
15683 }
15684
15685 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15686                                             SelectionDAG &DAG) const {
15687   /*
15688    The rounding mode is in bits 11:10 of FPSR, and has the following
15689    settings:
15690      00 Round to nearest
15691      01 Round to -inf
15692      10 Round to +inf
15693      11 Round to 0
15694
15695   FLT_ROUNDS, on the other hand, expects the following:
15696     -1 Undefined
15697      0 Round to 0
15698      1 Round to nearest
15699      2 Round to +inf
15700      3 Round to -inf
15701
15702   To perform the conversion, we do:
15703     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15704   */
15705
15706   MachineFunction &MF = DAG.getMachineFunction();
15707   const TargetMachine &TM = MF.getTarget();
15708   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15709   unsigned StackAlignment = TFI.getStackAlignment();
15710   MVT VT = Op.getSimpleValueType();
15711   SDLoc DL(Op);
15712
15713   // Save FP Control Word to stack slot
15714   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15715   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15716
15717   MachineMemOperand *MMO =
15718    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15719                            MachineMemOperand::MOStore, 2, 2);
15720
15721   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15722   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15723                                           DAG.getVTList(MVT::Other),
15724                                           Ops, MVT::i16, MMO);
15725
15726   // Load FP Control Word from stack slot
15727   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15728                             MachinePointerInfo(), false, false, false, 0);
15729
15730   // Transform as necessary
15731   SDValue CWD1 =
15732     DAG.getNode(ISD::SRL, DL, MVT::i16,
15733                 DAG.getNode(ISD::AND, DL, MVT::i16,
15734                             CWD, DAG.getConstant(0x800, MVT::i16)),
15735                 DAG.getConstant(11, MVT::i8));
15736   SDValue CWD2 =
15737     DAG.getNode(ISD::SRL, DL, MVT::i16,
15738                 DAG.getNode(ISD::AND, DL, MVT::i16,
15739                             CWD, DAG.getConstant(0x400, MVT::i16)),
15740                 DAG.getConstant(9, MVT::i8));
15741
15742   SDValue RetVal =
15743     DAG.getNode(ISD::AND, DL, MVT::i16,
15744                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15745                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15746                             DAG.getConstant(1, MVT::i16)),
15747                 DAG.getConstant(3, MVT::i16));
15748
15749   return DAG.getNode((VT.getSizeInBits() < 16 ?
15750                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15751 }
15752
15753 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15754   MVT VT = Op.getSimpleValueType();
15755   EVT OpVT = VT;
15756   unsigned NumBits = VT.getSizeInBits();
15757   SDLoc dl(Op);
15758
15759   Op = Op.getOperand(0);
15760   if (VT == MVT::i8) {
15761     // Zero extend to i32 since there is not an i8 bsr.
15762     OpVT = MVT::i32;
15763     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15764   }
15765
15766   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15767   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15768   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15769
15770   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15771   SDValue Ops[] = {
15772     Op,
15773     DAG.getConstant(NumBits+NumBits-1, OpVT),
15774     DAG.getConstant(X86::COND_E, MVT::i8),
15775     Op.getValue(1)
15776   };
15777   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15778
15779   // Finally xor with NumBits-1.
15780   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15781
15782   if (VT == MVT::i8)
15783     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15784   return Op;
15785 }
15786
15787 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15788   MVT VT = Op.getSimpleValueType();
15789   EVT OpVT = VT;
15790   unsigned NumBits = VT.getSizeInBits();
15791   SDLoc dl(Op);
15792
15793   Op = Op.getOperand(0);
15794   if (VT == MVT::i8) {
15795     // Zero extend to i32 since there is not an i8 bsr.
15796     OpVT = MVT::i32;
15797     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15798   }
15799
15800   // Issue a bsr (scan bits in reverse).
15801   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15802   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15803
15804   // And xor with NumBits-1.
15805   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15806
15807   if (VT == MVT::i8)
15808     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15809   return Op;
15810 }
15811
15812 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15813   MVT VT = Op.getSimpleValueType();
15814   unsigned NumBits = VT.getSizeInBits();
15815   SDLoc dl(Op);
15816   Op = Op.getOperand(0);
15817
15818   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15819   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15820   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15821
15822   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15823   SDValue Ops[] = {
15824     Op,
15825     DAG.getConstant(NumBits, VT),
15826     DAG.getConstant(X86::COND_E, MVT::i8),
15827     Op.getValue(1)
15828   };
15829   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15830 }
15831
15832 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15833 // ones, and then concatenate the result back.
15834 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15835   MVT VT = Op.getSimpleValueType();
15836
15837   assert(VT.is256BitVector() && VT.isInteger() &&
15838          "Unsupported value type for operation");
15839
15840   unsigned NumElems = VT.getVectorNumElements();
15841   SDLoc dl(Op);
15842
15843   // Extract the LHS vectors
15844   SDValue LHS = Op.getOperand(0);
15845   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15846   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15847
15848   // Extract the RHS vectors
15849   SDValue RHS = Op.getOperand(1);
15850   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15851   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15852
15853   MVT EltVT = VT.getVectorElementType();
15854   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15855
15856   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15857                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15858                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15859 }
15860
15861 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15862   assert(Op.getSimpleValueType().is256BitVector() &&
15863          Op.getSimpleValueType().isInteger() &&
15864          "Only handle AVX 256-bit vector integer operation");
15865   return Lower256IntArith(Op, DAG);
15866 }
15867
15868 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15869   assert(Op.getSimpleValueType().is256BitVector() &&
15870          Op.getSimpleValueType().isInteger() &&
15871          "Only handle AVX 256-bit vector integer operation");
15872   return Lower256IntArith(Op, DAG);
15873 }
15874
15875 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15876                         SelectionDAG &DAG) {
15877   SDLoc dl(Op);
15878   MVT VT = Op.getSimpleValueType();
15879
15880   // Decompose 256-bit ops into smaller 128-bit ops.
15881   if (VT.is256BitVector() && !Subtarget->hasInt256())
15882     return Lower256IntArith(Op, DAG);
15883
15884   SDValue A = Op.getOperand(0);
15885   SDValue B = Op.getOperand(1);
15886
15887   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15888   if (VT == MVT::v4i32) {
15889     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15890            "Should not custom lower when pmuldq is available!");
15891
15892     // Extract the odd parts.
15893     static const int UnpackMask[] = { 1, -1, 3, -1 };
15894     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15895     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15896
15897     // Multiply the even parts.
15898     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15899     // Now multiply odd parts.
15900     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15901
15902     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15903     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15904
15905     // Merge the two vectors back together with a shuffle. This expands into 2
15906     // shuffles.
15907     static const int ShufMask[] = { 0, 4, 2, 6 };
15908     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15909   }
15910
15911   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15912          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15913
15914   //  Ahi = psrlqi(a, 32);
15915   //  Bhi = psrlqi(b, 32);
15916   //
15917   //  AloBlo = pmuludq(a, b);
15918   //  AloBhi = pmuludq(a, Bhi);
15919   //  AhiBlo = pmuludq(Ahi, b);
15920
15921   //  AloBhi = psllqi(AloBhi, 32);
15922   //  AhiBlo = psllqi(AhiBlo, 32);
15923   //  return AloBlo + AloBhi + AhiBlo;
15924
15925   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15926   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15927
15928   // Bit cast to 32-bit vectors for MULUDQ
15929   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15930                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15931   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15932   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15933   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15934   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15935
15936   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15937   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15938   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15939
15940   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15941   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15942
15943   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15944   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15945 }
15946
15947 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15948   assert(Subtarget->isTargetWin64() && "Unexpected target");
15949   EVT VT = Op.getValueType();
15950   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15951          "Unexpected return type for lowering");
15952
15953   RTLIB::Libcall LC;
15954   bool isSigned;
15955   switch (Op->getOpcode()) {
15956   default: llvm_unreachable("Unexpected request for libcall!");
15957   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15958   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15959   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15960   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15961   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15962   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15963   }
15964
15965   SDLoc dl(Op);
15966   SDValue InChain = DAG.getEntryNode();
15967
15968   TargetLowering::ArgListTy Args;
15969   TargetLowering::ArgListEntry Entry;
15970   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15971     EVT ArgVT = Op->getOperand(i).getValueType();
15972     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15973            "Unexpected argument type for lowering");
15974     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15975     Entry.Node = StackPtr;
15976     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15977                            false, false, 16);
15978     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15979     Entry.Ty = PointerType::get(ArgTy,0);
15980     Entry.isSExt = false;
15981     Entry.isZExt = false;
15982     Args.push_back(Entry);
15983   }
15984
15985   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15986                                          getPointerTy());
15987
15988   TargetLowering::CallLoweringInfo CLI(DAG);
15989   CLI.setDebugLoc(dl).setChain(InChain)
15990     .setCallee(getLibcallCallingConv(LC),
15991                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15992                Callee, std::move(Args), 0)
15993     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15994
15995   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15996   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15997 }
15998
15999 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16000                              SelectionDAG &DAG) {
16001   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16002   EVT VT = Op0.getValueType();
16003   SDLoc dl(Op);
16004
16005   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16006          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16007
16008   // PMULxD operations multiply each even value (starting at 0) of LHS with
16009   // the related value of RHS and produce a widen result.
16010   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16011   // => <2 x i64> <ae|cg>
16012   //
16013   // In other word, to have all the results, we need to perform two PMULxD:
16014   // 1. one with the even values.
16015   // 2. one with the odd values.
16016   // To achieve #2, with need to place the odd values at an even position.
16017   //
16018   // Place the odd value at an even position (basically, shift all values 1
16019   // step to the left):
16020   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16021   // <a|b|c|d> => <b|undef|d|undef>
16022   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16023   // <e|f|g|h> => <f|undef|h|undef>
16024   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16025
16026   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16027   // ints.
16028   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16029   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16030   unsigned Opcode =
16031       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16032   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16033   // => <2 x i64> <ae|cg>
16034   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16035                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16036   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16037   // => <2 x i64> <bf|dh>
16038   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16039                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16040
16041   // Shuffle it back into the right order.
16042   SDValue Highs, Lows;
16043   if (VT == MVT::v8i32) {
16044     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16045     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16046     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16047     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16048   } else {
16049     const int HighMask[] = {1, 5, 3, 7};
16050     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16051     const int LowMask[] = {0, 4, 2, 6};
16052     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16053   }
16054
16055   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16056   // unsigned multiply.
16057   if (IsSigned && !Subtarget->hasSSE41()) {
16058     SDValue ShAmt =
16059         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16060     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16061                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16062     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16063                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16064
16065     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16066     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16067   }
16068
16069   // The first result of MUL_LOHI is actually the low value, followed by the
16070   // high value.
16071   SDValue Ops[] = {Lows, Highs};
16072   return DAG.getMergeValues(Ops, dl);
16073 }
16074
16075 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16076                                          const X86Subtarget *Subtarget) {
16077   MVT VT = Op.getSimpleValueType();
16078   SDLoc dl(Op);
16079   SDValue R = Op.getOperand(0);
16080   SDValue Amt = Op.getOperand(1);
16081
16082   // Optimize shl/srl/sra with constant shift amount.
16083   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16084     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16085       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16086
16087       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16088           (Subtarget->hasInt256() &&
16089            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16090           (Subtarget->hasAVX512() &&
16091            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16092         if (Op.getOpcode() == ISD::SHL)
16093           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16094                                             DAG);
16095         if (Op.getOpcode() == ISD::SRL)
16096           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16097                                             DAG);
16098         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16099           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16100                                             DAG);
16101       }
16102
16103       if (VT == MVT::v16i8) {
16104         if (Op.getOpcode() == ISD::SHL) {
16105           // Make a large shift.
16106           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16107                                                    MVT::v8i16, R, ShiftAmt,
16108                                                    DAG);
16109           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16110           // Zero out the rightmost bits.
16111           SmallVector<SDValue, 16> V(16,
16112                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16113                                                      MVT::i8));
16114           return DAG.getNode(ISD::AND, dl, VT, SHL,
16115                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16116         }
16117         if (Op.getOpcode() == ISD::SRL) {
16118           // Make a large shift.
16119           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16120                                                    MVT::v8i16, R, ShiftAmt,
16121                                                    DAG);
16122           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16123           // Zero out the leftmost bits.
16124           SmallVector<SDValue, 16> V(16,
16125                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16126                                                      MVT::i8));
16127           return DAG.getNode(ISD::AND, dl, VT, SRL,
16128                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16129         }
16130         if (Op.getOpcode() == ISD::SRA) {
16131           if (ShiftAmt == 7) {
16132             // R s>> 7  ===  R s< 0
16133             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16134             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16135           }
16136
16137           // R s>> a === ((R u>> a) ^ m) - m
16138           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16139           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
16140                                                          MVT::i8));
16141           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16142           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16143           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16144           return Res;
16145         }
16146         llvm_unreachable("Unknown shift opcode.");
16147       }
16148
16149       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16150         if (Op.getOpcode() == ISD::SHL) {
16151           // Make a large shift.
16152           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16153                                                    MVT::v16i16, R, ShiftAmt,
16154                                                    DAG);
16155           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16156           // Zero out the rightmost bits.
16157           SmallVector<SDValue, 32> V(32,
16158                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16159                                                      MVT::i8));
16160           return DAG.getNode(ISD::AND, dl, VT, SHL,
16161                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16162         }
16163         if (Op.getOpcode() == ISD::SRL) {
16164           // Make a large shift.
16165           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16166                                                    MVT::v16i16, R, ShiftAmt,
16167                                                    DAG);
16168           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16169           // Zero out the leftmost bits.
16170           SmallVector<SDValue, 32> V(32,
16171                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16172                                                      MVT::i8));
16173           return DAG.getNode(ISD::AND, dl, VT, SRL,
16174                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16175         }
16176         if (Op.getOpcode() == ISD::SRA) {
16177           if (ShiftAmt == 7) {
16178             // R s>> 7  ===  R s< 0
16179             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16180             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16181           }
16182
16183           // R s>> a === ((R u>> a) ^ m) - m
16184           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16185           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16186                                                          MVT::i8));
16187           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16188           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16189           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16190           return Res;
16191         }
16192         llvm_unreachable("Unknown shift opcode.");
16193       }
16194     }
16195   }
16196
16197   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16198   if (!Subtarget->is64Bit() &&
16199       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16200       Amt.getOpcode() == ISD::BITCAST &&
16201       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16202     Amt = Amt.getOperand(0);
16203     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16204                      VT.getVectorNumElements();
16205     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16206     uint64_t ShiftAmt = 0;
16207     for (unsigned i = 0; i != Ratio; ++i) {
16208       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16209       if (!C)
16210         return SDValue();
16211       // 6 == Log2(64)
16212       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16213     }
16214     // Check remaining shift amounts.
16215     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16216       uint64_t ShAmt = 0;
16217       for (unsigned j = 0; j != Ratio; ++j) {
16218         ConstantSDNode *C =
16219           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16220         if (!C)
16221           return SDValue();
16222         // 6 == Log2(64)
16223         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16224       }
16225       if (ShAmt != ShiftAmt)
16226         return SDValue();
16227     }
16228     switch (Op.getOpcode()) {
16229     default:
16230       llvm_unreachable("Unknown shift opcode!");
16231     case ISD::SHL:
16232       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16233                                         DAG);
16234     case ISD::SRL:
16235       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16236                                         DAG);
16237     case ISD::SRA:
16238       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16239                                         DAG);
16240     }
16241   }
16242
16243   return SDValue();
16244 }
16245
16246 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16247                                         const X86Subtarget* Subtarget) {
16248   MVT VT = Op.getSimpleValueType();
16249   SDLoc dl(Op);
16250   SDValue R = Op.getOperand(0);
16251   SDValue Amt = Op.getOperand(1);
16252
16253   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16254       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16255       (Subtarget->hasInt256() &&
16256        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16257         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16258        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16259     SDValue BaseShAmt;
16260     EVT EltVT = VT.getVectorElementType();
16261
16262     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16263       unsigned NumElts = VT.getVectorNumElements();
16264       unsigned i, j;
16265       for (i = 0; i != NumElts; ++i) {
16266         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16267           continue;
16268         break;
16269       }
16270       for (j = i; j != NumElts; ++j) {
16271         SDValue Arg = Amt.getOperand(j);
16272         if (Arg.getOpcode() == ISD::UNDEF) continue;
16273         if (Arg != Amt.getOperand(i))
16274           break;
16275       }
16276       if (i != NumElts && j == NumElts)
16277         BaseShAmt = Amt.getOperand(i);
16278     } else {
16279       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16280         Amt = Amt.getOperand(0);
16281       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16282                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16283         SDValue InVec = Amt.getOperand(0);
16284         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16285           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16286           unsigned i = 0;
16287           for (; i != NumElts; ++i) {
16288             SDValue Arg = InVec.getOperand(i);
16289             if (Arg.getOpcode() == ISD::UNDEF) continue;
16290             BaseShAmt = Arg;
16291             break;
16292           }
16293         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16294            if (ConstantSDNode *C =
16295                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16296              unsigned SplatIdx =
16297                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16298              if (C->getZExtValue() == SplatIdx)
16299                BaseShAmt = InVec.getOperand(1);
16300            }
16301         }
16302         if (!BaseShAmt.getNode())
16303           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16304                                   DAG.getIntPtrConstant(0));
16305       }
16306     }
16307
16308     if (BaseShAmt.getNode()) {
16309       if (EltVT.bitsGT(MVT::i32))
16310         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16311       else if (EltVT.bitsLT(MVT::i32))
16312         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16313
16314       switch (Op.getOpcode()) {
16315       default:
16316         llvm_unreachable("Unknown shift opcode!");
16317       case ISD::SHL:
16318         switch (VT.SimpleTy) {
16319         default: return SDValue();
16320         case MVT::v2i64:
16321         case MVT::v4i32:
16322         case MVT::v8i16:
16323         case MVT::v4i64:
16324         case MVT::v8i32:
16325         case MVT::v16i16:
16326         case MVT::v16i32:
16327         case MVT::v8i64:
16328           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16329         }
16330       case ISD::SRA:
16331         switch (VT.SimpleTy) {
16332         default: return SDValue();
16333         case MVT::v4i32:
16334         case MVT::v8i16:
16335         case MVT::v8i32:
16336         case MVT::v16i16:
16337         case MVT::v16i32:
16338         case MVT::v8i64:
16339           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16340         }
16341       case ISD::SRL:
16342         switch (VT.SimpleTy) {
16343         default: return SDValue();
16344         case MVT::v2i64:
16345         case MVT::v4i32:
16346         case MVT::v8i16:
16347         case MVT::v4i64:
16348         case MVT::v8i32:
16349         case MVT::v16i16:
16350         case MVT::v16i32:
16351         case MVT::v8i64:
16352           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16353         }
16354       }
16355     }
16356   }
16357
16358   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16359   if (!Subtarget->is64Bit() &&
16360       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16361       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16362       Amt.getOpcode() == ISD::BITCAST &&
16363       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16364     Amt = Amt.getOperand(0);
16365     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16366                      VT.getVectorNumElements();
16367     std::vector<SDValue> Vals(Ratio);
16368     for (unsigned i = 0; i != Ratio; ++i)
16369       Vals[i] = Amt.getOperand(i);
16370     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16371       for (unsigned j = 0; j != Ratio; ++j)
16372         if (Vals[j] != Amt.getOperand(i + j))
16373           return SDValue();
16374     }
16375     switch (Op.getOpcode()) {
16376     default:
16377       llvm_unreachable("Unknown shift opcode!");
16378     case ISD::SHL:
16379       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16380     case ISD::SRL:
16381       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16382     case ISD::SRA:
16383       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16384     }
16385   }
16386
16387   return SDValue();
16388 }
16389
16390 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16391                           SelectionDAG &DAG) {
16392   MVT VT = Op.getSimpleValueType();
16393   SDLoc dl(Op);
16394   SDValue R = Op.getOperand(0);
16395   SDValue Amt = Op.getOperand(1);
16396   SDValue V;
16397
16398   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16399   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16400
16401   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16402   if (V.getNode())
16403     return V;
16404
16405   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16406   if (V.getNode())
16407       return V;
16408
16409   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16410     return Op;
16411   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16412   if (Subtarget->hasInt256()) {
16413     if (Op.getOpcode() == ISD::SRL &&
16414         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16415          VT == MVT::v4i64 || VT == MVT::v8i32))
16416       return Op;
16417     if (Op.getOpcode() == ISD::SHL &&
16418         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16419          VT == MVT::v4i64 || VT == MVT::v8i32))
16420       return Op;
16421     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16422       return Op;
16423   }
16424
16425   // If possible, lower this packed shift into a vector multiply instead of
16426   // expanding it into a sequence of scalar shifts.
16427   // Do this only if the vector shift count is a constant build_vector.
16428   if (Op.getOpcode() == ISD::SHL && 
16429       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16430        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16431       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16432     SmallVector<SDValue, 8> Elts;
16433     EVT SVT = VT.getScalarType();
16434     unsigned SVTBits = SVT.getSizeInBits();
16435     const APInt &One = APInt(SVTBits, 1);
16436     unsigned NumElems = VT.getVectorNumElements();
16437
16438     for (unsigned i=0; i !=NumElems; ++i) {
16439       SDValue Op = Amt->getOperand(i);
16440       if (Op->getOpcode() == ISD::UNDEF) {
16441         Elts.push_back(Op);
16442         continue;
16443       }
16444
16445       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16446       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16447       uint64_t ShAmt = C.getZExtValue();
16448       if (ShAmt >= SVTBits) {
16449         Elts.push_back(DAG.getUNDEF(SVT));
16450         continue;
16451       }
16452       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16453     }
16454     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16455     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16456   }
16457
16458   // Lower SHL with variable shift amount.
16459   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16460     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16461
16462     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16463     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16464     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16465     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16466   }
16467
16468   // If possible, lower this shift as a sequence of two shifts by
16469   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16470   // Example:
16471   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16472   //
16473   // Could be rewritten as:
16474   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16475   //
16476   // The advantage is that the two shifts from the example would be
16477   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16478   // the vector shift into four scalar shifts plus four pairs of vector
16479   // insert/extract.
16480   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16481       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16482     unsigned TargetOpcode = X86ISD::MOVSS;
16483     bool CanBeSimplified;
16484     // The splat value for the first packed shift (the 'X' from the example).
16485     SDValue Amt1 = Amt->getOperand(0);
16486     // The splat value for the second packed shift (the 'Y' from the example).
16487     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16488                                         Amt->getOperand(2);
16489
16490     // See if it is possible to replace this node with a sequence of
16491     // two shifts followed by a MOVSS/MOVSD
16492     if (VT == MVT::v4i32) {
16493       // Check if it is legal to use a MOVSS.
16494       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16495                         Amt2 == Amt->getOperand(3);
16496       if (!CanBeSimplified) {
16497         // Otherwise, check if we can still simplify this node using a MOVSD.
16498         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16499                           Amt->getOperand(2) == Amt->getOperand(3);
16500         TargetOpcode = X86ISD::MOVSD;
16501         Amt2 = Amt->getOperand(2);
16502       }
16503     } else {
16504       // Do similar checks for the case where the machine value type
16505       // is MVT::v8i16.
16506       CanBeSimplified = Amt1 == Amt->getOperand(1);
16507       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16508         CanBeSimplified = Amt2 == Amt->getOperand(i);
16509
16510       if (!CanBeSimplified) {
16511         TargetOpcode = X86ISD::MOVSD;
16512         CanBeSimplified = true;
16513         Amt2 = Amt->getOperand(4);
16514         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16515           CanBeSimplified = Amt1 == Amt->getOperand(i);
16516         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16517           CanBeSimplified = Amt2 == Amt->getOperand(j);
16518       }
16519     }
16520     
16521     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16522         isa<ConstantSDNode>(Amt2)) {
16523       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16524       EVT CastVT = MVT::v4i32;
16525       SDValue Splat1 = 
16526         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16527       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16528       SDValue Splat2 = 
16529         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16530       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16531       if (TargetOpcode == X86ISD::MOVSD)
16532         CastVT = MVT::v2i64;
16533       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16534       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16535       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16536                                             BitCast1, DAG);
16537       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16538     }
16539   }
16540
16541   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16542     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16543
16544     // a = a << 5;
16545     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16546     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16547
16548     // Turn 'a' into a mask suitable for VSELECT
16549     SDValue VSelM = DAG.getConstant(0x80, VT);
16550     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16551     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16552
16553     SDValue CM1 = DAG.getConstant(0x0f, VT);
16554     SDValue CM2 = DAG.getConstant(0x3f, VT);
16555
16556     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16557     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16558     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16559     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16560     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16561
16562     // a += a
16563     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16564     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16565     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16566
16567     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16568     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16569     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16570     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16571     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16572
16573     // a += a
16574     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16575     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16576     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16577
16578     // return VSELECT(r, r+r, a);
16579     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16580                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16581     return R;
16582   }
16583
16584   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16585   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16586   // solution better.
16587   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16588     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16589     unsigned ExtOpc =
16590         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16591     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16592     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16593     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16594                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16595     }
16596
16597   // Decompose 256-bit shifts into smaller 128-bit shifts.
16598   if (VT.is256BitVector()) {
16599     unsigned NumElems = VT.getVectorNumElements();
16600     MVT EltVT = VT.getVectorElementType();
16601     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16602
16603     // Extract the two vectors
16604     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16605     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16606
16607     // Recreate the shift amount vectors
16608     SDValue Amt1, Amt2;
16609     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16610       // Constant shift amount
16611       SmallVector<SDValue, 4> Amt1Csts;
16612       SmallVector<SDValue, 4> Amt2Csts;
16613       for (unsigned i = 0; i != NumElems/2; ++i)
16614         Amt1Csts.push_back(Amt->getOperand(i));
16615       for (unsigned i = NumElems/2; i != NumElems; ++i)
16616         Amt2Csts.push_back(Amt->getOperand(i));
16617
16618       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16619       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16620     } else {
16621       // Variable shift amount
16622       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16623       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16624     }
16625
16626     // Issue new vector shifts for the smaller types
16627     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16628     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16629
16630     // Concatenate the result back
16631     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16632   }
16633
16634   return SDValue();
16635 }
16636
16637 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16638   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16639   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16640   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16641   // has only one use.
16642   SDNode *N = Op.getNode();
16643   SDValue LHS = N->getOperand(0);
16644   SDValue RHS = N->getOperand(1);
16645   unsigned BaseOp = 0;
16646   unsigned Cond = 0;
16647   SDLoc DL(Op);
16648   switch (Op.getOpcode()) {
16649   default: llvm_unreachable("Unknown ovf instruction!");
16650   case ISD::SADDO:
16651     // A subtract of one will be selected as a INC. Note that INC doesn't
16652     // set CF, so we can't do this for UADDO.
16653     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16654       if (C->isOne()) {
16655         BaseOp = X86ISD::INC;
16656         Cond = X86::COND_O;
16657         break;
16658       }
16659     BaseOp = X86ISD::ADD;
16660     Cond = X86::COND_O;
16661     break;
16662   case ISD::UADDO:
16663     BaseOp = X86ISD::ADD;
16664     Cond = X86::COND_B;
16665     break;
16666   case ISD::SSUBO:
16667     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16668     // set CF, so we can't do this for USUBO.
16669     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16670       if (C->isOne()) {
16671         BaseOp = X86ISD::DEC;
16672         Cond = X86::COND_O;
16673         break;
16674       }
16675     BaseOp = X86ISD::SUB;
16676     Cond = X86::COND_O;
16677     break;
16678   case ISD::USUBO:
16679     BaseOp = X86ISD::SUB;
16680     Cond = X86::COND_B;
16681     break;
16682   case ISD::SMULO:
16683     BaseOp = X86ISD::SMUL;
16684     Cond = X86::COND_O;
16685     break;
16686   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16687     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16688                                  MVT::i32);
16689     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16690
16691     SDValue SetCC =
16692       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16693                   DAG.getConstant(X86::COND_O, MVT::i32),
16694                   SDValue(Sum.getNode(), 2));
16695
16696     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16697   }
16698   }
16699
16700   // Also sets EFLAGS.
16701   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16702   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16703
16704   SDValue SetCC =
16705     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16706                 DAG.getConstant(Cond, MVT::i32),
16707                 SDValue(Sum.getNode(), 1));
16708
16709   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16710 }
16711
16712 // Sign extension of the low part of vector elements. This may be used either
16713 // when sign extend instructions are not available or if the vector element
16714 // sizes already match the sign-extended size. If the vector elements are in
16715 // their pre-extended size and sign extend instructions are available, that will
16716 // be handled by LowerSIGN_EXTEND.
16717 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16718                                                   SelectionDAG &DAG) const {
16719   SDLoc dl(Op);
16720   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16721   MVT VT = Op.getSimpleValueType();
16722
16723   if (!Subtarget->hasSSE2() || !VT.isVector())
16724     return SDValue();
16725
16726   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16727                       ExtraVT.getScalarType().getSizeInBits();
16728
16729   switch (VT.SimpleTy) {
16730     default: return SDValue();
16731     case MVT::v8i32:
16732     case MVT::v16i16:
16733       if (!Subtarget->hasFp256())
16734         return SDValue();
16735       if (!Subtarget->hasInt256()) {
16736         // needs to be split
16737         unsigned NumElems = VT.getVectorNumElements();
16738
16739         // Extract the LHS vectors
16740         SDValue LHS = Op.getOperand(0);
16741         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16742         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16743
16744         MVT EltVT = VT.getVectorElementType();
16745         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16746
16747         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16748         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16749         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16750                                    ExtraNumElems/2);
16751         SDValue Extra = DAG.getValueType(ExtraVT);
16752
16753         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16754         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16755
16756         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16757       }
16758       // fall through
16759     case MVT::v4i32:
16760     case MVT::v8i16: {
16761       SDValue Op0 = Op.getOperand(0);
16762
16763       // This is a sign extension of some low part of vector elements without
16764       // changing the size of the vector elements themselves:
16765       // Shift-Left + Shift-Right-Algebraic.
16766       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
16767                                                BitsDiff, DAG);
16768       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
16769                                         DAG);
16770     }
16771   }
16772 }
16773
16774 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16775                                  SelectionDAG &DAG) {
16776   SDLoc dl(Op);
16777   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16778     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16779   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16780     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16781
16782   // The only fence that needs an instruction is a sequentially-consistent
16783   // cross-thread fence.
16784   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16785     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16786     // no-sse2). There isn't any reason to disable it if the target processor
16787     // supports it.
16788     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16789       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16790
16791     SDValue Chain = Op.getOperand(0);
16792     SDValue Zero = DAG.getConstant(0, MVT::i32);
16793     SDValue Ops[] = {
16794       DAG.getRegister(X86::ESP, MVT::i32), // Base
16795       DAG.getTargetConstant(1, MVT::i8),   // Scale
16796       DAG.getRegister(0, MVT::i32),        // Index
16797       DAG.getTargetConstant(0, MVT::i32),  // Disp
16798       DAG.getRegister(0, MVT::i32),        // Segment.
16799       Zero,
16800       Chain
16801     };
16802     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16803     return SDValue(Res, 0);
16804   }
16805
16806   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16807   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16808 }
16809
16810 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16811                              SelectionDAG &DAG) {
16812   MVT T = Op.getSimpleValueType();
16813   SDLoc DL(Op);
16814   unsigned Reg = 0;
16815   unsigned size = 0;
16816   switch(T.SimpleTy) {
16817   default: llvm_unreachable("Invalid value type!");
16818   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16819   case MVT::i16: Reg = X86::AX;  size = 2; break;
16820   case MVT::i32: Reg = X86::EAX; size = 4; break;
16821   case MVT::i64:
16822     assert(Subtarget->is64Bit() && "Node not type legal!");
16823     Reg = X86::RAX; size = 8;
16824     break;
16825   }
16826   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16827                                   Op.getOperand(2), SDValue());
16828   SDValue Ops[] = { cpIn.getValue(0),
16829                     Op.getOperand(1),
16830                     Op.getOperand(3),
16831                     DAG.getTargetConstant(size, MVT::i8),
16832                     cpIn.getValue(1) };
16833   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16834   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16835   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16836                                            Ops, T, MMO);
16837
16838   SDValue cpOut =
16839     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16840   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16841                                       MVT::i32, cpOut.getValue(2));
16842   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16843                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16844
16845   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16846   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16847   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16848   return SDValue();
16849 }
16850
16851 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16852                             SelectionDAG &DAG) {
16853   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16854   MVT DstVT = Op.getSimpleValueType();
16855
16856   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16857     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16858     if (DstVT != MVT::f64)
16859       // This conversion needs to be expanded.
16860       return SDValue();
16861
16862     SDValue InVec = Op->getOperand(0);
16863     SDLoc dl(Op);
16864     unsigned NumElts = SrcVT.getVectorNumElements();
16865     EVT SVT = SrcVT.getVectorElementType();
16866
16867     // Widen the vector in input in the case of MVT::v2i32.
16868     // Example: from MVT::v2i32 to MVT::v4i32.
16869     SmallVector<SDValue, 16> Elts;
16870     for (unsigned i = 0, e = NumElts; i != e; ++i)
16871       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16872                                  DAG.getIntPtrConstant(i)));
16873
16874     // Explicitly mark the extra elements as Undef.
16875     SDValue Undef = DAG.getUNDEF(SVT);
16876     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16877       Elts.push_back(Undef);
16878
16879     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16880     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16881     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16882     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16883                        DAG.getIntPtrConstant(0));
16884   }
16885
16886   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16887          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16888   assert((DstVT == MVT::i64 ||
16889           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16890          "Unexpected custom BITCAST");
16891   // i64 <=> MMX conversions are Legal.
16892   if (SrcVT==MVT::i64 && DstVT.isVector())
16893     return Op;
16894   if (DstVT==MVT::i64 && SrcVT.isVector())
16895     return Op;
16896   // MMX <=> MMX conversions are Legal.
16897   if (SrcVT.isVector() && DstVT.isVector())
16898     return Op;
16899   // All other conversions need to be expanded.
16900   return SDValue();
16901 }
16902
16903 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16904   SDNode *Node = Op.getNode();
16905   SDLoc dl(Node);
16906   EVT T = Node->getValueType(0);
16907   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16908                               DAG.getConstant(0, T), Node->getOperand(2));
16909   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16910                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16911                        Node->getOperand(0),
16912                        Node->getOperand(1), negOp,
16913                        cast<AtomicSDNode>(Node)->getMemOperand(),
16914                        cast<AtomicSDNode>(Node)->getOrdering(),
16915                        cast<AtomicSDNode>(Node)->getSynchScope());
16916 }
16917
16918 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16919   SDNode *Node = Op.getNode();
16920   SDLoc dl(Node);
16921   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16922
16923   // Convert seq_cst store -> xchg
16924   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16925   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16926   //        (The only way to get a 16-byte store is cmpxchg16b)
16927   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16928   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16929       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16930     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16931                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16932                                  Node->getOperand(0),
16933                                  Node->getOperand(1), Node->getOperand(2),
16934                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16935                                  cast<AtomicSDNode>(Node)->getOrdering(),
16936                                  cast<AtomicSDNode>(Node)->getSynchScope());
16937     return Swap.getValue(1);
16938   }
16939   // Other atomic stores have a simple pattern.
16940   return Op;
16941 }
16942
16943 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16944   EVT VT = Op.getNode()->getSimpleValueType(0);
16945
16946   // Let legalize expand this if it isn't a legal type yet.
16947   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16948     return SDValue();
16949
16950   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16951
16952   unsigned Opc;
16953   bool ExtraOp = false;
16954   switch (Op.getOpcode()) {
16955   default: llvm_unreachable("Invalid code");
16956   case ISD::ADDC: Opc = X86ISD::ADD; break;
16957   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16958   case ISD::SUBC: Opc = X86ISD::SUB; break;
16959   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16960   }
16961
16962   if (!ExtraOp)
16963     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16964                        Op.getOperand(1));
16965   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16966                      Op.getOperand(1), Op.getOperand(2));
16967 }
16968
16969 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16970                             SelectionDAG &DAG) {
16971   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16972
16973   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16974   // which returns the values as { float, float } (in XMM0) or
16975   // { double, double } (which is returned in XMM0, XMM1).
16976   SDLoc dl(Op);
16977   SDValue Arg = Op.getOperand(0);
16978   EVT ArgVT = Arg.getValueType();
16979   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16980
16981   TargetLowering::ArgListTy Args;
16982   TargetLowering::ArgListEntry Entry;
16983
16984   Entry.Node = Arg;
16985   Entry.Ty = ArgTy;
16986   Entry.isSExt = false;
16987   Entry.isZExt = false;
16988   Args.push_back(Entry);
16989
16990   bool isF64 = ArgVT == MVT::f64;
16991   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16992   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16993   // the results are returned via SRet in memory.
16994   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16996   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16997
16998   Type *RetTy = isF64
16999     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
17000     : (Type*)VectorType::get(ArgTy, 4);
17001
17002   TargetLowering::CallLoweringInfo CLI(DAG);
17003   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17004     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17005
17006   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17007
17008   if (isF64)
17009     // Returned in xmm0 and xmm1.
17010     return CallResult.first;
17011
17012   // Returned in bits 0:31 and 32:64 xmm0.
17013   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17014                                CallResult.first, DAG.getIntPtrConstant(0));
17015   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17016                                CallResult.first, DAG.getIntPtrConstant(1));
17017   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17018   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17019 }
17020
17021 /// LowerOperation - Provide custom lowering hooks for some operations.
17022 ///
17023 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17024   switch (Op.getOpcode()) {
17025   default: llvm_unreachable("Should not custom lower this!");
17026   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
17027   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17028   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17029     return LowerCMP_SWAP(Op, Subtarget, DAG);
17030   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17031   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17032   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17033   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
17034   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
17035   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17036   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17037   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17038   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17039   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17040   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17041   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17042   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17043   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17044   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17045   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17046   case ISD::SHL_PARTS:
17047   case ISD::SRA_PARTS:
17048   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17049   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17050   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17051   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17052   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17053   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17054   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17055   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17056   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17057   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17058   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17059   case ISD::FABS:
17060   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17061   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17062   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17063   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17064   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17065   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17066   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17067   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17068   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17069   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17070   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
17071   case ISD::INTRINSIC_VOID:
17072   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17073   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17074   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17075   case ISD::FRAME_TO_ARGS_OFFSET:
17076                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17077   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17078   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17079   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17080   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17081   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17082   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17083   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17084   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17085   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17086   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17087   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17088   case ISD::UMUL_LOHI:
17089   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17090   case ISD::SRA:
17091   case ISD::SRL:
17092   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17093   case ISD::SADDO:
17094   case ISD::UADDO:
17095   case ISD::SSUBO:
17096   case ISD::USUBO:
17097   case ISD::SMULO:
17098   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17099   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17100   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17101   case ISD::ADDC:
17102   case ISD::ADDE:
17103   case ISD::SUBC:
17104   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17105   case ISD::ADD:                return LowerADD(Op, DAG);
17106   case ISD::SUB:                return LowerSUB(Op, DAG);
17107   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17108   }
17109 }
17110
17111 static void ReplaceATOMIC_LOAD(SDNode *Node,
17112                                SmallVectorImpl<SDValue> &Results,
17113                                SelectionDAG &DAG) {
17114   SDLoc dl(Node);
17115   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17116
17117   // Convert wide load -> cmpxchg8b/cmpxchg16b
17118   // FIXME: On 32-bit, load -> fild or movq would be more efficient
17119   //        (The only way to get a 16-byte load is cmpxchg16b)
17120   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
17121   SDValue Zero = DAG.getConstant(0, VT);
17122   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
17123   SDValue Swap =
17124       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
17125                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
17126                            cast<AtomicSDNode>(Node)->getMemOperand(),
17127                            cast<AtomicSDNode>(Node)->getOrdering(),
17128                            cast<AtomicSDNode>(Node)->getOrdering(),
17129                            cast<AtomicSDNode>(Node)->getSynchScope());
17130   Results.push_back(Swap.getValue(0));
17131   Results.push_back(Swap.getValue(2));
17132 }
17133
17134 /// ReplaceNodeResults - Replace a node with an illegal result type
17135 /// with a new node built out of custom code.
17136 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17137                                            SmallVectorImpl<SDValue>&Results,
17138                                            SelectionDAG &DAG) const {
17139   SDLoc dl(N);
17140   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17141   switch (N->getOpcode()) {
17142   default:
17143     llvm_unreachable("Do not know how to custom type legalize this operation!");
17144   case ISD::SIGN_EXTEND_INREG:
17145   case ISD::ADDC:
17146   case ISD::ADDE:
17147   case ISD::SUBC:
17148   case ISD::SUBE:
17149     // We don't want to expand or promote these.
17150     return;
17151   case ISD::SDIV:
17152   case ISD::UDIV:
17153   case ISD::SREM:
17154   case ISD::UREM:
17155   case ISD::SDIVREM:
17156   case ISD::UDIVREM: {
17157     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17158     Results.push_back(V);
17159     return;
17160   }
17161   case ISD::FP_TO_SINT:
17162   case ISD::FP_TO_UINT: {
17163     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17164
17165     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17166       return;
17167
17168     std::pair<SDValue,SDValue> Vals =
17169         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17170     SDValue FIST = Vals.first, StackSlot = Vals.second;
17171     if (FIST.getNode()) {
17172       EVT VT = N->getValueType(0);
17173       // Return a load from the stack slot.
17174       if (StackSlot.getNode())
17175         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17176                                       MachinePointerInfo(),
17177                                       false, false, false, 0));
17178       else
17179         Results.push_back(FIST);
17180     }
17181     return;
17182   }
17183   case ISD::UINT_TO_FP: {
17184     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17185     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17186         N->getValueType(0) != MVT::v2f32)
17187       return;
17188     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17189                                  N->getOperand(0));
17190     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17191                                      MVT::f64);
17192     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17193     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17194                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17195     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17196     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17197     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17198     return;
17199   }
17200   case ISD::FP_ROUND: {
17201     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17202         return;
17203     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17204     Results.push_back(V);
17205     return;
17206   }
17207   case ISD::INTRINSIC_W_CHAIN: {
17208     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17209     switch (IntNo) {
17210     default : llvm_unreachable("Do not know how to custom type "
17211                                "legalize this intrinsic operation!");
17212     case Intrinsic::x86_rdtsc:
17213       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17214                                      Results);
17215     case Intrinsic::x86_rdtscp:
17216       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17217                                      Results);
17218     case Intrinsic::x86_rdpmc:
17219       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17220     }
17221   }
17222   case ISD::READCYCLECOUNTER: {
17223     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17224                                    Results);
17225   }
17226   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17227     EVT T = N->getValueType(0);
17228     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17229     bool Regs64bit = T == MVT::i128;
17230     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17231     SDValue cpInL, cpInH;
17232     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17233                         DAG.getConstant(0, HalfT));
17234     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17235                         DAG.getConstant(1, HalfT));
17236     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17237                              Regs64bit ? X86::RAX : X86::EAX,
17238                              cpInL, SDValue());
17239     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17240                              Regs64bit ? X86::RDX : X86::EDX,
17241                              cpInH, cpInL.getValue(1));
17242     SDValue swapInL, swapInH;
17243     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17244                           DAG.getConstant(0, HalfT));
17245     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17246                           DAG.getConstant(1, HalfT));
17247     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17248                                Regs64bit ? X86::RBX : X86::EBX,
17249                                swapInL, cpInH.getValue(1));
17250     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17251                                Regs64bit ? X86::RCX : X86::ECX,
17252                                swapInH, swapInL.getValue(1));
17253     SDValue Ops[] = { swapInH.getValue(0),
17254                       N->getOperand(1),
17255                       swapInH.getValue(1) };
17256     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17257     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17258     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17259                                   X86ISD::LCMPXCHG8_DAG;
17260     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17261     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17262                                         Regs64bit ? X86::RAX : X86::EAX,
17263                                         HalfT, Result.getValue(1));
17264     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17265                                         Regs64bit ? X86::RDX : X86::EDX,
17266                                         HalfT, cpOutL.getValue(2));
17267     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17268
17269     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17270                                         MVT::i32, cpOutH.getValue(2));
17271     SDValue Success =
17272         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17273                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17274     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17275
17276     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17277     Results.push_back(Success);
17278     Results.push_back(EFLAGS.getValue(1));
17279     return;
17280   }
17281   case ISD::ATOMIC_SWAP:
17282   case ISD::ATOMIC_LOAD_ADD:
17283   case ISD::ATOMIC_LOAD_SUB:
17284   case ISD::ATOMIC_LOAD_AND:
17285   case ISD::ATOMIC_LOAD_OR:
17286   case ISD::ATOMIC_LOAD_XOR:
17287   case ISD::ATOMIC_LOAD_NAND:
17288   case ISD::ATOMIC_LOAD_MIN:
17289   case ISD::ATOMIC_LOAD_MAX:
17290   case ISD::ATOMIC_LOAD_UMIN:
17291   case ISD::ATOMIC_LOAD_UMAX:
17292     // Delegate to generic TypeLegalization. Situations we can really handle
17293     // should have already been dealt with by X86AtomicExpandPass.cpp.
17294     break;
17295   case ISD::ATOMIC_LOAD: {
17296     ReplaceATOMIC_LOAD(N, Results, DAG);
17297     return;
17298   }
17299   case ISD::BITCAST: {
17300     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17301     EVT DstVT = N->getValueType(0);
17302     EVT SrcVT = N->getOperand(0)->getValueType(0);
17303
17304     if (SrcVT != MVT::f64 ||
17305         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17306       return;
17307
17308     unsigned NumElts = DstVT.getVectorNumElements();
17309     EVT SVT = DstVT.getVectorElementType();
17310     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17311     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17312                                    MVT::v2f64, N->getOperand(0));
17313     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17314
17315     if (ExperimentalVectorWideningLegalization) {
17316       // If we are legalizing vectors by widening, we already have the desired
17317       // legal vector type, just return it.
17318       Results.push_back(ToVecInt);
17319       return;
17320     }
17321
17322     SmallVector<SDValue, 8> Elts;
17323     for (unsigned i = 0, e = NumElts; i != e; ++i)
17324       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17325                                    ToVecInt, DAG.getIntPtrConstant(i)));
17326
17327     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17328   }
17329   }
17330 }
17331
17332 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17333   switch (Opcode) {
17334   default: return nullptr;
17335   case X86ISD::BSF:                return "X86ISD::BSF";
17336   case X86ISD::BSR:                return "X86ISD::BSR";
17337   case X86ISD::SHLD:               return "X86ISD::SHLD";
17338   case X86ISD::SHRD:               return "X86ISD::SHRD";
17339   case X86ISD::FAND:               return "X86ISD::FAND";
17340   case X86ISD::FANDN:              return "X86ISD::FANDN";
17341   case X86ISD::FOR:                return "X86ISD::FOR";
17342   case X86ISD::FXOR:               return "X86ISD::FXOR";
17343   case X86ISD::FSRL:               return "X86ISD::FSRL";
17344   case X86ISD::FILD:               return "X86ISD::FILD";
17345   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17346   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17347   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17348   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17349   case X86ISD::FLD:                return "X86ISD::FLD";
17350   case X86ISD::FST:                return "X86ISD::FST";
17351   case X86ISD::CALL:               return "X86ISD::CALL";
17352   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17353   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17354   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17355   case X86ISD::BT:                 return "X86ISD::BT";
17356   case X86ISD::CMP:                return "X86ISD::CMP";
17357   case X86ISD::COMI:               return "X86ISD::COMI";
17358   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17359   case X86ISD::CMPM:               return "X86ISD::CMPM";
17360   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17361   case X86ISD::SETCC:              return "X86ISD::SETCC";
17362   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17363   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17364   case X86ISD::CMOV:               return "X86ISD::CMOV";
17365   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17366   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17367   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17368   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17369   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17370   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17371   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17372   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17373   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17374   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17375   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17376   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17377   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17378   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17379   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17380   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17381   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17382   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17383   case X86ISD::HADD:               return "X86ISD::HADD";
17384   case X86ISD::HSUB:               return "X86ISD::HSUB";
17385   case X86ISD::FHADD:              return "X86ISD::FHADD";
17386   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17387   case X86ISD::UMAX:               return "X86ISD::UMAX";
17388   case X86ISD::UMIN:               return "X86ISD::UMIN";
17389   case X86ISD::SMAX:               return "X86ISD::SMAX";
17390   case X86ISD::SMIN:               return "X86ISD::SMIN";
17391   case X86ISD::FMAX:               return "X86ISD::FMAX";
17392   case X86ISD::FMIN:               return "X86ISD::FMIN";
17393   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17394   case X86ISD::FMINC:              return "X86ISD::FMINC";
17395   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17396   case X86ISD::FRCP:               return "X86ISD::FRCP";
17397   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17398   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17399   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17400   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17401   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17402   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17403   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17404   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17405   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17406   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17407   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17408   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17409   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17410   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17411   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17412   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17413   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17414   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17415   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17416   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17417   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17418   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17419   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17420   case X86ISD::VSHL:               return "X86ISD::VSHL";
17421   case X86ISD::VSRL:               return "X86ISD::VSRL";
17422   case X86ISD::VSRA:               return "X86ISD::VSRA";
17423   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17424   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17425   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17426   case X86ISD::CMPP:               return "X86ISD::CMPP";
17427   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17428   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17429   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17430   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17431   case X86ISD::ADD:                return "X86ISD::ADD";
17432   case X86ISD::SUB:                return "X86ISD::SUB";
17433   case X86ISD::ADC:                return "X86ISD::ADC";
17434   case X86ISD::SBB:                return "X86ISD::SBB";
17435   case X86ISD::SMUL:               return "X86ISD::SMUL";
17436   case X86ISD::UMUL:               return "X86ISD::UMUL";
17437   case X86ISD::INC:                return "X86ISD::INC";
17438   case X86ISD::DEC:                return "X86ISD::DEC";
17439   case X86ISD::OR:                 return "X86ISD::OR";
17440   case X86ISD::XOR:                return "X86ISD::XOR";
17441   case X86ISD::AND:                return "X86ISD::AND";
17442   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17443   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17444   case X86ISD::PTEST:              return "X86ISD::PTEST";
17445   case X86ISD::TESTP:              return "X86ISD::TESTP";
17446   case X86ISD::TESTM:              return "X86ISD::TESTM";
17447   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17448   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17449   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17450   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17451   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17452   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17453   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17454   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17455   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17456   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17457   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17458   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17459   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17460   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17461   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17462   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17463   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17464   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17465   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17466   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17467   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17468   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17469   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17470   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17471   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17472   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17473   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17474   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17475   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17476   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17477   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17478   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17479   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17480   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17481   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17482   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17483   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17484   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17485   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17486   case X86ISD::SAHF:               return "X86ISD::SAHF";
17487   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17488   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17489   case X86ISD::FMADD:              return "X86ISD::FMADD";
17490   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17491   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17492   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17493   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17494   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17495   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17496   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17497   case X86ISD::XTEST:              return "X86ISD::XTEST";
17498   }
17499 }
17500
17501 // isLegalAddressingMode - Return true if the addressing mode represented
17502 // by AM is legal for this target, for a load/store of the specified type.
17503 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17504                                               Type *Ty) const {
17505   // X86 supports extremely general addressing modes.
17506   CodeModel::Model M = getTargetMachine().getCodeModel();
17507   Reloc::Model R = getTargetMachine().getRelocationModel();
17508
17509   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17510   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17511     return false;
17512
17513   if (AM.BaseGV) {
17514     unsigned GVFlags =
17515       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17516
17517     // If a reference to this global requires an extra load, we can't fold it.
17518     if (isGlobalStubReference(GVFlags))
17519       return false;
17520
17521     // If BaseGV requires a register for the PIC base, we cannot also have a
17522     // BaseReg specified.
17523     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17524       return false;
17525
17526     // If lower 4G is not available, then we must use rip-relative addressing.
17527     if ((M != CodeModel::Small || R != Reloc::Static) &&
17528         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17529       return false;
17530   }
17531
17532   switch (AM.Scale) {
17533   case 0:
17534   case 1:
17535   case 2:
17536   case 4:
17537   case 8:
17538     // These scales always work.
17539     break;
17540   case 3:
17541   case 5:
17542   case 9:
17543     // These scales are formed with basereg+scalereg.  Only accept if there is
17544     // no basereg yet.
17545     if (AM.HasBaseReg)
17546       return false;
17547     break;
17548   default:  // Other stuff never works.
17549     return false;
17550   }
17551
17552   return true;
17553 }
17554
17555 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17556   unsigned Bits = Ty->getScalarSizeInBits();
17557
17558   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17559   // particularly cheaper than those without.
17560   if (Bits == 8)
17561     return false;
17562
17563   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17564   // variable shifts just as cheap as scalar ones.
17565   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17566     return false;
17567
17568   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17569   // fully general vector.
17570   return true;
17571 }
17572
17573 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17574   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17575     return false;
17576   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17577   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17578   return NumBits1 > NumBits2;
17579 }
17580
17581 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17582   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17583     return false;
17584
17585   if (!isTypeLegal(EVT::getEVT(Ty1)))
17586     return false;
17587
17588   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17589
17590   // Assuming the caller doesn't have a zeroext or signext return parameter,
17591   // truncation all the way down to i1 is valid.
17592   return true;
17593 }
17594
17595 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17596   return isInt<32>(Imm);
17597 }
17598
17599 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17600   // Can also use sub to handle negated immediates.
17601   return isInt<32>(Imm);
17602 }
17603
17604 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17605   if (!VT1.isInteger() || !VT2.isInteger())
17606     return false;
17607   unsigned NumBits1 = VT1.getSizeInBits();
17608   unsigned NumBits2 = VT2.getSizeInBits();
17609   return NumBits1 > NumBits2;
17610 }
17611
17612 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17613   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17614   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17615 }
17616
17617 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17618   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17619   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17620 }
17621
17622 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17623   EVT VT1 = Val.getValueType();
17624   if (isZExtFree(VT1, VT2))
17625     return true;
17626
17627   if (Val.getOpcode() != ISD::LOAD)
17628     return false;
17629
17630   if (!VT1.isSimple() || !VT1.isInteger() ||
17631       !VT2.isSimple() || !VT2.isInteger())
17632     return false;
17633
17634   switch (VT1.getSimpleVT().SimpleTy) {
17635   default: break;
17636   case MVT::i8:
17637   case MVT::i16:
17638   case MVT::i32:
17639     // X86 has 8, 16, and 32-bit zero-extending loads.
17640     return true;
17641   }
17642
17643   return false;
17644 }
17645
17646 bool
17647 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17648   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17649     return false;
17650
17651   VT = VT.getScalarType();
17652
17653   if (!VT.isSimple())
17654     return false;
17655
17656   switch (VT.getSimpleVT().SimpleTy) {
17657   case MVT::f32:
17658   case MVT::f64:
17659     return true;
17660   default:
17661     break;
17662   }
17663
17664   return false;
17665 }
17666
17667 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17668   // i16 instructions are longer (0x66 prefix) and potentially slower.
17669   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17670 }
17671
17672 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17673 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17674 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17675 /// are assumed to be legal.
17676 bool
17677 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17678                                       EVT VT) const {
17679   if (!VT.isSimple())
17680     return false;
17681
17682   MVT SVT = VT.getSimpleVT();
17683
17684   // Very little shuffling can be done for 64-bit vectors right now.
17685   if (VT.getSizeInBits() == 64)
17686     return false;
17687
17688   // If this is a single-input shuffle with no 128 bit lane crossings we can
17689   // lower it into pshufb.
17690   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17691       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17692     bool isLegal = true;
17693     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17694       if (M[I] >= (int)SVT.getVectorNumElements() ||
17695           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17696         isLegal = false;
17697         break;
17698       }
17699     }
17700     if (isLegal)
17701       return true;
17702   }
17703
17704   // FIXME: blends, shifts.
17705   return (SVT.getVectorNumElements() == 2 ||
17706           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17707           isMOVLMask(M, SVT) ||
17708           isMOVHLPSMask(M, SVT) ||
17709           isSHUFPMask(M, SVT) ||
17710           isPSHUFDMask(M, SVT) ||
17711           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17712           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17713           isPALIGNRMask(M, SVT, Subtarget) ||
17714           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17715           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17716           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17717           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17718           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17719 }
17720
17721 bool
17722 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17723                                           EVT VT) const {
17724   if (!VT.isSimple())
17725     return false;
17726
17727   MVT SVT = VT.getSimpleVT();
17728   unsigned NumElts = SVT.getVectorNumElements();
17729   // FIXME: This collection of masks seems suspect.
17730   if (NumElts == 2)
17731     return true;
17732   if (NumElts == 4 && SVT.is128BitVector()) {
17733     return (isMOVLMask(Mask, SVT)  ||
17734             isCommutedMOVLMask(Mask, SVT, true) ||
17735             isSHUFPMask(Mask, SVT) ||
17736             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17737   }
17738   return false;
17739 }
17740
17741 //===----------------------------------------------------------------------===//
17742 //                           X86 Scheduler Hooks
17743 //===----------------------------------------------------------------------===//
17744
17745 /// Utility function to emit xbegin specifying the start of an RTM region.
17746 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17747                                      const TargetInstrInfo *TII) {
17748   DebugLoc DL = MI->getDebugLoc();
17749
17750   const BasicBlock *BB = MBB->getBasicBlock();
17751   MachineFunction::iterator I = MBB;
17752   ++I;
17753
17754   // For the v = xbegin(), we generate
17755   //
17756   // thisMBB:
17757   //  xbegin sinkMBB
17758   //
17759   // mainMBB:
17760   //  eax = -1
17761   //
17762   // sinkMBB:
17763   //  v = eax
17764
17765   MachineBasicBlock *thisMBB = MBB;
17766   MachineFunction *MF = MBB->getParent();
17767   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17768   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17769   MF->insert(I, mainMBB);
17770   MF->insert(I, sinkMBB);
17771
17772   // Transfer the remainder of BB and its successor edges to sinkMBB.
17773   sinkMBB->splice(sinkMBB->begin(), MBB,
17774                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17775   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17776
17777   // thisMBB:
17778   //  xbegin sinkMBB
17779   //  # fallthrough to mainMBB
17780   //  # abortion to sinkMBB
17781   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17782   thisMBB->addSuccessor(mainMBB);
17783   thisMBB->addSuccessor(sinkMBB);
17784
17785   // mainMBB:
17786   //  EAX = -1
17787   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17788   mainMBB->addSuccessor(sinkMBB);
17789
17790   // sinkMBB:
17791   // EAX is live into the sinkMBB
17792   sinkMBB->addLiveIn(X86::EAX);
17793   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17794           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17795     .addReg(X86::EAX);
17796
17797   MI->eraseFromParent();
17798   return sinkMBB;
17799 }
17800
17801 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17802 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17803 // in the .td file.
17804 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17805                                        const TargetInstrInfo *TII) {
17806   unsigned Opc;
17807   switch (MI->getOpcode()) {
17808   default: llvm_unreachable("illegal opcode!");
17809   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17810   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17811   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17812   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17813   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17814   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17815   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17816   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17817   }
17818
17819   DebugLoc dl = MI->getDebugLoc();
17820   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17821
17822   unsigned NumArgs = MI->getNumOperands();
17823   for (unsigned i = 1; i < NumArgs; ++i) {
17824     MachineOperand &Op = MI->getOperand(i);
17825     if (!(Op.isReg() && Op.isImplicit()))
17826       MIB.addOperand(Op);
17827   }
17828   if (MI->hasOneMemOperand())
17829     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17830
17831   BuildMI(*BB, MI, dl,
17832     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17833     .addReg(X86::XMM0);
17834
17835   MI->eraseFromParent();
17836   return BB;
17837 }
17838
17839 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17840 // defs in an instruction pattern
17841 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17842                                        const TargetInstrInfo *TII) {
17843   unsigned Opc;
17844   switch (MI->getOpcode()) {
17845   default: llvm_unreachable("illegal opcode!");
17846   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17847   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17848   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17849   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17850   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17851   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17852   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17853   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17854   }
17855
17856   DebugLoc dl = MI->getDebugLoc();
17857   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17858
17859   unsigned NumArgs = MI->getNumOperands(); // remove the results
17860   for (unsigned i = 1; i < NumArgs; ++i) {
17861     MachineOperand &Op = MI->getOperand(i);
17862     if (!(Op.isReg() && Op.isImplicit()))
17863       MIB.addOperand(Op);
17864   }
17865   if (MI->hasOneMemOperand())
17866     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17867
17868   BuildMI(*BB, MI, dl,
17869     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17870     .addReg(X86::ECX);
17871
17872   MI->eraseFromParent();
17873   return BB;
17874 }
17875
17876 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17877                                        const TargetInstrInfo *TII,
17878                                        const X86Subtarget* Subtarget) {
17879   DebugLoc dl = MI->getDebugLoc();
17880
17881   // Address into RAX/EAX, other two args into ECX, EDX.
17882   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17883   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17884   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17885   for (int i = 0; i < X86::AddrNumOperands; ++i)
17886     MIB.addOperand(MI->getOperand(i));
17887
17888   unsigned ValOps = X86::AddrNumOperands;
17889   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17890     .addReg(MI->getOperand(ValOps).getReg());
17891   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17892     .addReg(MI->getOperand(ValOps+1).getReg());
17893
17894   // The instruction doesn't actually take any operands though.
17895   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17896
17897   MI->eraseFromParent(); // The pseudo is gone now.
17898   return BB;
17899 }
17900
17901 MachineBasicBlock *
17902 X86TargetLowering::EmitVAARG64WithCustomInserter(
17903                    MachineInstr *MI,
17904                    MachineBasicBlock *MBB) const {
17905   // Emit va_arg instruction on X86-64.
17906
17907   // Operands to this pseudo-instruction:
17908   // 0  ) Output        : destination address (reg)
17909   // 1-5) Input         : va_list address (addr, i64mem)
17910   // 6  ) ArgSize       : Size (in bytes) of vararg type
17911   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17912   // 8  ) Align         : Alignment of type
17913   // 9  ) EFLAGS (implicit-def)
17914
17915   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17916   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17917
17918   unsigned DestReg = MI->getOperand(0).getReg();
17919   MachineOperand &Base = MI->getOperand(1);
17920   MachineOperand &Scale = MI->getOperand(2);
17921   MachineOperand &Index = MI->getOperand(3);
17922   MachineOperand &Disp = MI->getOperand(4);
17923   MachineOperand &Segment = MI->getOperand(5);
17924   unsigned ArgSize = MI->getOperand(6).getImm();
17925   unsigned ArgMode = MI->getOperand(7).getImm();
17926   unsigned Align = MI->getOperand(8).getImm();
17927
17928   // Memory Reference
17929   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17930   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17931   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17932
17933   // Machine Information
17934   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17935   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17936   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17937   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17938   DebugLoc DL = MI->getDebugLoc();
17939
17940   // struct va_list {
17941   //   i32   gp_offset
17942   //   i32   fp_offset
17943   //   i64   overflow_area (address)
17944   //   i64   reg_save_area (address)
17945   // }
17946   // sizeof(va_list) = 24
17947   // alignment(va_list) = 8
17948
17949   unsigned TotalNumIntRegs = 6;
17950   unsigned TotalNumXMMRegs = 8;
17951   bool UseGPOffset = (ArgMode == 1);
17952   bool UseFPOffset = (ArgMode == 2);
17953   unsigned MaxOffset = TotalNumIntRegs * 8 +
17954                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17955
17956   /* Align ArgSize to a multiple of 8 */
17957   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17958   bool NeedsAlign = (Align > 8);
17959
17960   MachineBasicBlock *thisMBB = MBB;
17961   MachineBasicBlock *overflowMBB;
17962   MachineBasicBlock *offsetMBB;
17963   MachineBasicBlock *endMBB;
17964
17965   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17966   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17967   unsigned OffsetReg = 0;
17968
17969   if (!UseGPOffset && !UseFPOffset) {
17970     // If we only pull from the overflow region, we don't create a branch.
17971     // We don't need to alter control flow.
17972     OffsetDestReg = 0; // unused
17973     OverflowDestReg = DestReg;
17974
17975     offsetMBB = nullptr;
17976     overflowMBB = thisMBB;
17977     endMBB = thisMBB;
17978   } else {
17979     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17980     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17981     // If not, pull from overflow_area. (branch to overflowMBB)
17982     //
17983     //       thisMBB
17984     //         |     .
17985     //         |        .
17986     //     offsetMBB   overflowMBB
17987     //         |        .
17988     //         |     .
17989     //        endMBB
17990
17991     // Registers for the PHI in endMBB
17992     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17993     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17994
17995     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17996     MachineFunction *MF = MBB->getParent();
17997     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17998     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17999     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18000
18001     MachineFunction::iterator MBBIter = MBB;
18002     ++MBBIter;
18003
18004     // Insert the new basic blocks
18005     MF->insert(MBBIter, offsetMBB);
18006     MF->insert(MBBIter, overflowMBB);
18007     MF->insert(MBBIter, endMBB);
18008
18009     // Transfer the remainder of MBB and its successor edges to endMBB.
18010     endMBB->splice(endMBB->begin(), thisMBB,
18011                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18012     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18013
18014     // Make offsetMBB and overflowMBB successors of thisMBB
18015     thisMBB->addSuccessor(offsetMBB);
18016     thisMBB->addSuccessor(overflowMBB);
18017
18018     // endMBB is a successor of both offsetMBB and overflowMBB
18019     offsetMBB->addSuccessor(endMBB);
18020     overflowMBB->addSuccessor(endMBB);
18021
18022     // Load the offset value into a register
18023     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18024     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18025       .addOperand(Base)
18026       .addOperand(Scale)
18027       .addOperand(Index)
18028       .addDisp(Disp, UseFPOffset ? 4 : 0)
18029       .addOperand(Segment)
18030       .setMemRefs(MMOBegin, MMOEnd);
18031
18032     // Check if there is enough room left to pull this argument.
18033     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18034       .addReg(OffsetReg)
18035       .addImm(MaxOffset + 8 - ArgSizeA8);
18036
18037     // Branch to "overflowMBB" if offset >= max
18038     // Fall through to "offsetMBB" otherwise
18039     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18040       .addMBB(overflowMBB);
18041   }
18042
18043   // In offsetMBB, emit code to use the reg_save_area.
18044   if (offsetMBB) {
18045     assert(OffsetReg != 0);
18046
18047     // Read the reg_save_area address.
18048     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18049     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18050       .addOperand(Base)
18051       .addOperand(Scale)
18052       .addOperand(Index)
18053       .addDisp(Disp, 16)
18054       .addOperand(Segment)
18055       .setMemRefs(MMOBegin, MMOEnd);
18056
18057     // Zero-extend the offset
18058     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18059       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18060         .addImm(0)
18061         .addReg(OffsetReg)
18062         .addImm(X86::sub_32bit);
18063
18064     // Add the offset to the reg_save_area to get the final address.
18065     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18066       .addReg(OffsetReg64)
18067       .addReg(RegSaveReg);
18068
18069     // Compute the offset for the next argument
18070     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18071     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18072       .addReg(OffsetReg)
18073       .addImm(UseFPOffset ? 16 : 8);
18074
18075     // Store it back into the va_list.
18076     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18077       .addOperand(Base)
18078       .addOperand(Scale)
18079       .addOperand(Index)
18080       .addDisp(Disp, UseFPOffset ? 4 : 0)
18081       .addOperand(Segment)
18082       .addReg(NextOffsetReg)
18083       .setMemRefs(MMOBegin, MMOEnd);
18084
18085     // Jump to endMBB
18086     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
18087       .addMBB(endMBB);
18088   }
18089
18090   //
18091   // Emit code to use overflow area
18092   //
18093
18094   // Load the overflow_area address into a register.
18095   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18096   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18097     .addOperand(Base)
18098     .addOperand(Scale)
18099     .addOperand(Index)
18100     .addDisp(Disp, 8)
18101     .addOperand(Segment)
18102     .setMemRefs(MMOBegin, MMOEnd);
18103
18104   // If we need to align it, do so. Otherwise, just copy the address
18105   // to OverflowDestReg.
18106   if (NeedsAlign) {
18107     // Align the overflow address
18108     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18109     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18110
18111     // aligned_addr = (addr + (align-1)) & ~(align-1)
18112     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18113       .addReg(OverflowAddrReg)
18114       .addImm(Align-1);
18115
18116     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18117       .addReg(TmpReg)
18118       .addImm(~(uint64_t)(Align-1));
18119   } else {
18120     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18121       .addReg(OverflowAddrReg);
18122   }
18123
18124   // Compute the next overflow address after this argument.
18125   // (the overflow address should be kept 8-byte aligned)
18126   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18127   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18128     .addReg(OverflowDestReg)
18129     .addImm(ArgSizeA8);
18130
18131   // Store the new overflow address.
18132   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18133     .addOperand(Base)
18134     .addOperand(Scale)
18135     .addOperand(Index)
18136     .addDisp(Disp, 8)
18137     .addOperand(Segment)
18138     .addReg(NextAddrReg)
18139     .setMemRefs(MMOBegin, MMOEnd);
18140
18141   // If we branched, emit the PHI to the front of endMBB.
18142   if (offsetMBB) {
18143     BuildMI(*endMBB, endMBB->begin(), DL,
18144             TII->get(X86::PHI), DestReg)
18145       .addReg(OffsetDestReg).addMBB(offsetMBB)
18146       .addReg(OverflowDestReg).addMBB(overflowMBB);
18147   }
18148
18149   // Erase the pseudo instruction
18150   MI->eraseFromParent();
18151
18152   return endMBB;
18153 }
18154
18155 MachineBasicBlock *
18156 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18157                                                  MachineInstr *MI,
18158                                                  MachineBasicBlock *MBB) const {
18159   // Emit code to save XMM registers to the stack. The ABI says that the
18160   // number of registers to save is given in %al, so it's theoretically
18161   // possible to do an indirect jump trick to avoid saving all of them,
18162   // however this code takes a simpler approach and just executes all
18163   // of the stores if %al is non-zero. It's less code, and it's probably
18164   // easier on the hardware branch predictor, and stores aren't all that
18165   // expensive anyway.
18166
18167   // Create the new basic blocks. One block contains all the XMM stores,
18168   // and one block is the final destination regardless of whether any
18169   // stores were performed.
18170   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18171   MachineFunction *F = MBB->getParent();
18172   MachineFunction::iterator MBBIter = MBB;
18173   ++MBBIter;
18174   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18175   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18176   F->insert(MBBIter, XMMSaveMBB);
18177   F->insert(MBBIter, EndMBB);
18178
18179   // Transfer the remainder of MBB and its successor edges to EndMBB.
18180   EndMBB->splice(EndMBB->begin(), MBB,
18181                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18182   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18183
18184   // The original block will now fall through to the XMM save block.
18185   MBB->addSuccessor(XMMSaveMBB);
18186   // The XMMSaveMBB will fall through to the end block.
18187   XMMSaveMBB->addSuccessor(EndMBB);
18188
18189   // Now add the instructions.
18190   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18191   DebugLoc DL = MI->getDebugLoc();
18192
18193   unsigned CountReg = MI->getOperand(0).getReg();
18194   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18195   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18196
18197   if (!Subtarget->isTargetWin64()) {
18198     // If %al is 0, branch around the XMM save block.
18199     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18200     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18201     MBB->addSuccessor(EndMBB);
18202   }
18203
18204   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18205   // that was just emitted, but clearly shouldn't be "saved".
18206   assert((MI->getNumOperands() <= 3 ||
18207           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18208           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18209          && "Expected last argument to be EFLAGS");
18210   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18211   // In the XMM save block, save all the XMM argument registers.
18212   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18213     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18214     MachineMemOperand *MMO =
18215       F->getMachineMemOperand(
18216           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18217         MachineMemOperand::MOStore,
18218         /*Size=*/16, /*Align=*/16);
18219     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18220       .addFrameIndex(RegSaveFrameIndex)
18221       .addImm(/*Scale=*/1)
18222       .addReg(/*IndexReg=*/0)
18223       .addImm(/*Disp=*/Offset)
18224       .addReg(/*Segment=*/0)
18225       .addReg(MI->getOperand(i).getReg())
18226       .addMemOperand(MMO);
18227   }
18228
18229   MI->eraseFromParent();   // The pseudo instruction is gone now.
18230
18231   return EndMBB;
18232 }
18233
18234 // The EFLAGS operand of SelectItr might be missing a kill marker
18235 // because there were multiple uses of EFLAGS, and ISel didn't know
18236 // which to mark. Figure out whether SelectItr should have had a
18237 // kill marker, and set it if it should. Returns the correct kill
18238 // marker value.
18239 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18240                                      MachineBasicBlock* BB,
18241                                      const TargetRegisterInfo* TRI) {
18242   // Scan forward through BB for a use/def of EFLAGS.
18243   MachineBasicBlock::iterator miI(std::next(SelectItr));
18244   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18245     const MachineInstr& mi = *miI;
18246     if (mi.readsRegister(X86::EFLAGS))
18247       return false;
18248     if (mi.definesRegister(X86::EFLAGS))
18249       break; // Should have kill-flag - update below.
18250   }
18251
18252   // If we hit the end of the block, check whether EFLAGS is live into a
18253   // successor.
18254   if (miI == BB->end()) {
18255     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18256                                           sEnd = BB->succ_end();
18257          sItr != sEnd; ++sItr) {
18258       MachineBasicBlock* succ = *sItr;
18259       if (succ->isLiveIn(X86::EFLAGS))
18260         return false;
18261     }
18262   }
18263
18264   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18265   // out. SelectMI should have a kill flag on EFLAGS.
18266   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18267   return true;
18268 }
18269
18270 MachineBasicBlock *
18271 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18272                                      MachineBasicBlock *BB) const {
18273   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18274   DebugLoc DL = MI->getDebugLoc();
18275
18276   // To "insert" a SELECT_CC instruction, we actually have to insert the
18277   // diamond control-flow pattern.  The incoming instruction knows the
18278   // destination vreg to set, the condition code register to branch on, the
18279   // true/false values to select between, and a branch opcode to use.
18280   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18281   MachineFunction::iterator It = BB;
18282   ++It;
18283
18284   //  thisMBB:
18285   //  ...
18286   //   TrueVal = ...
18287   //   cmpTY ccX, r1, r2
18288   //   bCC copy1MBB
18289   //   fallthrough --> copy0MBB
18290   MachineBasicBlock *thisMBB = BB;
18291   MachineFunction *F = BB->getParent();
18292   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18293   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18294   F->insert(It, copy0MBB);
18295   F->insert(It, sinkMBB);
18296
18297   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18298   // live into the sink and copy blocks.
18299   const TargetRegisterInfo *TRI =
18300       BB->getParent()->getSubtarget().getRegisterInfo();
18301   if (!MI->killsRegister(X86::EFLAGS) &&
18302       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18303     copy0MBB->addLiveIn(X86::EFLAGS);
18304     sinkMBB->addLiveIn(X86::EFLAGS);
18305   }
18306
18307   // Transfer the remainder of BB and its successor edges to sinkMBB.
18308   sinkMBB->splice(sinkMBB->begin(), BB,
18309                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18310   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18311
18312   // Add the true and fallthrough blocks as its successors.
18313   BB->addSuccessor(copy0MBB);
18314   BB->addSuccessor(sinkMBB);
18315
18316   // Create the conditional branch instruction.
18317   unsigned Opc =
18318     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18319   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18320
18321   //  copy0MBB:
18322   //   %FalseValue = ...
18323   //   # fallthrough to sinkMBB
18324   copy0MBB->addSuccessor(sinkMBB);
18325
18326   //  sinkMBB:
18327   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18328   //  ...
18329   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18330           TII->get(X86::PHI), MI->getOperand(0).getReg())
18331     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18332     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18333
18334   MI->eraseFromParent();   // The pseudo instruction is gone now.
18335   return sinkMBB;
18336 }
18337
18338 MachineBasicBlock *
18339 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18340                                         bool Is64Bit) const {
18341   MachineFunction *MF = BB->getParent();
18342   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18343   DebugLoc DL = MI->getDebugLoc();
18344   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18345
18346   assert(MF->shouldSplitStack());
18347
18348   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18349   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18350
18351   // BB:
18352   //  ... [Till the alloca]
18353   // If stacklet is not large enough, jump to mallocMBB
18354   //
18355   // bumpMBB:
18356   //  Allocate by subtracting from RSP
18357   //  Jump to continueMBB
18358   //
18359   // mallocMBB:
18360   //  Allocate by call to runtime
18361   //
18362   // continueMBB:
18363   //  ...
18364   //  [rest of original BB]
18365   //
18366
18367   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18368   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18369   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18370
18371   MachineRegisterInfo &MRI = MF->getRegInfo();
18372   const TargetRegisterClass *AddrRegClass =
18373     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18374
18375   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18376     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18377     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18378     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18379     sizeVReg = MI->getOperand(1).getReg(),
18380     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18381
18382   MachineFunction::iterator MBBIter = BB;
18383   ++MBBIter;
18384
18385   MF->insert(MBBIter, bumpMBB);
18386   MF->insert(MBBIter, mallocMBB);
18387   MF->insert(MBBIter, continueMBB);
18388
18389   continueMBB->splice(continueMBB->begin(), BB,
18390                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18391   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18392
18393   // Add code to the main basic block to check if the stack limit has been hit,
18394   // and if so, jump to mallocMBB otherwise to bumpMBB.
18395   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18396   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18397     .addReg(tmpSPVReg).addReg(sizeVReg);
18398   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18399     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18400     .addReg(SPLimitVReg);
18401   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18402
18403   // bumpMBB simply decreases the stack pointer, since we know the current
18404   // stacklet has enough space.
18405   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18406     .addReg(SPLimitVReg);
18407   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18408     .addReg(SPLimitVReg);
18409   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18410
18411   // Calls into a routine in libgcc to allocate more space from the heap.
18412   const uint32_t *RegMask = MF->getTarget()
18413                                 .getSubtargetImpl()
18414                                 ->getRegisterInfo()
18415                                 ->getCallPreservedMask(CallingConv::C);
18416   if (Is64Bit) {
18417     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18418       .addReg(sizeVReg);
18419     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18420       .addExternalSymbol("__morestack_allocate_stack_space")
18421       .addRegMask(RegMask)
18422       .addReg(X86::RDI, RegState::Implicit)
18423       .addReg(X86::RAX, RegState::ImplicitDefine);
18424   } else {
18425     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18426       .addImm(12);
18427     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18428     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18429       .addExternalSymbol("__morestack_allocate_stack_space")
18430       .addRegMask(RegMask)
18431       .addReg(X86::EAX, RegState::ImplicitDefine);
18432   }
18433
18434   if (!Is64Bit)
18435     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18436       .addImm(16);
18437
18438   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18439     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18440   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18441
18442   // Set up the CFG correctly.
18443   BB->addSuccessor(bumpMBB);
18444   BB->addSuccessor(mallocMBB);
18445   mallocMBB->addSuccessor(continueMBB);
18446   bumpMBB->addSuccessor(continueMBB);
18447
18448   // Take care of the PHI nodes.
18449   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18450           MI->getOperand(0).getReg())
18451     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18452     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18453
18454   // Delete the original pseudo instruction.
18455   MI->eraseFromParent();
18456
18457   // And we're done.
18458   return continueMBB;
18459 }
18460
18461 MachineBasicBlock *
18462 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18463                                         MachineBasicBlock *BB) const {
18464   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18465   DebugLoc DL = MI->getDebugLoc();
18466
18467   assert(!Subtarget->isTargetMacho());
18468
18469   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18470   // non-trivial part is impdef of ESP.
18471
18472   if (Subtarget->isTargetWin64()) {
18473     if (Subtarget->isTargetCygMing()) {
18474       // ___chkstk(Mingw64):
18475       // Clobbers R10, R11, RAX and EFLAGS.
18476       // Updates RSP.
18477       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18478         .addExternalSymbol("___chkstk")
18479         .addReg(X86::RAX, RegState::Implicit)
18480         .addReg(X86::RSP, RegState::Implicit)
18481         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18482         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18483         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18484     } else {
18485       // __chkstk(MSVCRT): does not update stack pointer.
18486       // Clobbers R10, R11 and EFLAGS.
18487       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18488         .addExternalSymbol("__chkstk")
18489         .addReg(X86::RAX, RegState::Implicit)
18490         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18491       // RAX has the offset to be subtracted from RSP.
18492       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18493         .addReg(X86::RSP)
18494         .addReg(X86::RAX);
18495     }
18496   } else {
18497     const char *StackProbeSymbol =
18498       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18499
18500     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18501       .addExternalSymbol(StackProbeSymbol)
18502       .addReg(X86::EAX, RegState::Implicit)
18503       .addReg(X86::ESP, RegState::Implicit)
18504       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18505       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18506       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18507   }
18508
18509   MI->eraseFromParent();   // The pseudo instruction is gone now.
18510   return BB;
18511 }
18512
18513 MachineBasicBlock *
18514 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18515                                       MachineBasicBlock *BB) const {
18516   // This is pretty easy.  We're taking the value that we received from
18517   // our load from the relocation, sticking it in either RDI (x86-64)
18518   // or EAX and doing an indirect call.  The return value will then
18519   // be in the normal return register.
18520   MachineFunction *F = BB->getParent();
18521   const X86InstrInfo *TII =
18522       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18523   DebugLoc DL = MI->getDebugLoc();
18524
18525   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18526   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18527
18528   // Get a register mask for the lowered call.
18529   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18530   // proper register mask.
18531   const uint32_t *RegMask = F->getTarget()
18532                                 .getSubtargetImpl()
18533                                 ->getRegisterInfo()
18534                                 ->getCallPreservedMask(CallingConv::C);
18535   if (Subtarget->is64Bit()) {
18536     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18537                                       TII->get(X86::MOV64rm), X86::RDI)
18538     .addReg(X86::RIP)
18539     .addImm(0).addReg(0)
18540     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18541                       MI->getOperand(3).getTargetFlags())
18542     .addReg(0);
18543     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18544     addDirectMem(MIB, X86::RDI);
18545     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18546   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18547     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18548                                       TII->get(X86::MOV32rm), X86::EAX)
18549     .addReg(0)
18550     .addImm(0).addReg(0)
18551     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18552                       MI->getOperand(3).getTargetFlags())
18553     .addReg(0);
18554     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18555     addDirectMem(MIB, X86::EAX);
18556     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18557   } else {
18558     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18559                                       TII->get(X86::MOV32rm), X86::EAX)
18560     .addReg(TII->getGlobalBaseReg(F))
18561     .addImm(0).addReg(0)
18562     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18563                       MI->getOperand(3).getTargetFlags())
18564     .addReg(0);
18565     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18566     addDirectMem(MIB, X86::EAX);
18567     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18568   }
18569
18570   MI->eraseFromParent(); // The pseudo instruction is gone now.
18571   return BB;
18572 }
18573
18574 MachineBasicBlock *
18575 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18576                                     MachineBasicBlock *MBB) const {
18577   DebugLoc DL = MI->getDebugLoc();
18578   MachineFunction *MF = MBB->getParent();
18579   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18580   MachineRegisterInfo &MRI = MF->getRegInfo();
18581
18582   const BasicBlock *BB = MBB->getBasicBlock();
18583   MachineFunction::iterator I = MBB;
18584   ++I;
18585
18586   // Memory Reference
18587   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18588   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18589
18590   unsigned DstReg;
18591   unsigned MemOpndSlot = 0;
18592
18593   unsigned CurOp = 0;
18594
18595   DstReg = MI->getOperand(CurOp++).getReg();
18596   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18597   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18598   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18599   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18600
18601   MemOpndSlot = CurOp;
18602
18603   MVT PVT = getPointerTy();
18604   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18605          "Invalid Pointer Size!");
18606
18607   // For v = setjmp(buf), we generate
18608   //
18609   // thisMBB:
18610   //  buf[LabelOffset] = restoreMBB
18611   //  SjLjSetup restoreMBB
18612   //
18613   // mainMBB:
18614   //  v_main = 0
18615   //
18616   // sinkMBB:
18617   //  v = phi(main, restore)
18618   //
18619   // restoreMBB:
18620   //  v_restore = 1
18621
18622   MachineBasicBlock *thisMBB = MBB;
18623   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18624   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18625   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18626   MF->insert(I, mainMBB);
18627   MF->insert(I, sinkMBB);
18628   MF->push_back(restoreMBB);
18629
18630   MachineInstrBuilder MIB;
18631
18632   // Transfer the remainder of BB and its successor edges to sinkMBB.
18633   sinkMBB->splice(sinkMBB->begin(), MBB,
18634                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18635   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18636
18637   // thisMBB:
18638   unsigned PtrStoreOpc = 0;
18639   unsigned LabelReg = 0;
18640   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18641   Reloc::Model RM = MF->getTarget().getRelocationModel();
18642   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18643                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18644
18645   // Prepare IP either in reg or imm.
18646   if (!UseImmLabel) {
18647     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18648     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18649     LabelReg = MRI.createVirtualRegister(PtrRC);
18650     if (Subtarget->is64Bit()) {
18651       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18652               .addReg(X86::RIP)
18653               .addImm(0)
18654               .addReg(0)
18655               .addMBB(restoreMBB)
18656               .addReg(0);
18657     } else {
18658       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18659       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18660               .addReg(XII->getGlobalBaseReg(MF))
18661               .addImm(0)
18662               .addReg(0)
18663               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18664               .addReg(0);
18665     }
18666   } else
18667     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18668   // Store IP
18669   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18670   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18671     if (i == X86::AddrDisp)
18672       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18673     else
18674       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18675   }
18676   if (!UseImmLabel)
18677     MIB.addReg(LabelReg);
18678   else
18679     MIB.addMBB(restoreMBB);
18680   MIB.setMemRefs(MMOBegin, MMOEnd);
18681   // Setup
18682   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18683           .addMBB(restoreMBB);
18684
18685   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18686       MF->getSubtarget().getRegisterInfo());
18687   MIB.addRegMask(RegInfo->getNoPreservedMask());
18688   thisMBB->addSuccessor(mainMBB);
18689   thisMBB->addSuccessor(restoreMBB);
18690
18691   // mainMBB:
18692   //  EAX = 0
18693   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18694   mainMBB->addSuccessor(sinkMBB);
18695
18696   // sinkMBB:
18697   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18698           TII->get(X86::PHI), DstReg)
18699     .addReg(mainDstReg).addMBB(mainMBB)
18700     .addReg(restoreDstReg).addMBB(restoreMBB);
18701
18702   // restoreMBB:
18703   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18704   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18705   restoreMBB->addSuccessor(sinkMBB);
18706
18707   MI->eraseFromParent();
18708   return sinkMBB;
18709 }
18710
18711 MachineBasicBlock *
18712 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18713                                      MachineBasicBlock *MBB) const {
18714   DebugLoc DL = MI->getDebugLoc();
18715   MachineFunction *MF = MBB->getParent();
18716   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18717   MachineRegisterInfo &MRI = MF->getRegInfo();
18718
18719   // Memory Reference
18720   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18721   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18722
18723   MVT PVT = getPointerTy();
18724   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18725          "Invalid Pointer Size!");
18726
18727   const TargetRegisterClass *RC =
18728     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18729   unsigned Tmp = MRI.createVirtualRegister(RC);
18730   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18731   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18732       MF->getSubtarget().getRegisterInfo());
18733   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18734   unsigned SP = RegInfo->getStackRegister();
18735
18736   MachineInstrBuilder MIB;
18737
18738   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18739   const int64_t SPOffset = 2 * PVT.getStoreSize();
18740
18741   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18742   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18743
18744   // Reload FP
18745   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18746   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18747     MIB.addOperand(MI->getOperand(i));
18748   MIB.setMemRefs(MMOBegin, MMOEnd);
18749   // Reload IP
18750   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18751   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18752     if (i == X86::AddrDisp)
18753       MIB.addDisp(MI->getOperand(i), LabelOffset);
18754     else
18755       MIB.addOperand(MI->getOperand(i));
18756   }
18757   MIB.setMemRefs(MMOBegin, MMOEnd);
18758   // Reload SP
18759   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18760   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18761     if (i == X86::AddrDisp)
18762       MIB.addDisp(MI->getOperand(i), SPOffset);
18763     else
18764       MIB.addOperand(MI->getOperand(i));
18765   }
18766   MIB.setMemRefs(MMOBegin, MMOEnd);
18767   // Jump
18768   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18769
18770   MI->eraseFromParent();
18771   return MBB;
18772 }
18773
18774 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18775 // accumulator loops. Writing back to the accumulator allows the coalescer
18776 // to remove extra copies in the loop.   
18777 MachineBasicBlock *
18778 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18779                                  MachineBasicBlock *MBB) const {
18780   MachineOperand &AddendOp = MI->getOperand(3);
18781
18782   // Bail out early if the addend isn't a register - we can't switch these.
18783   if (!AddendOp.isReg())
18784     return MBB;
18785
18786   MachineFunction &MF = *MBB->getParent();
18787   MachineRegisterInfo &MRI = MF.getRegInfo();
18788
18789   // Check whether the addend is defined by a PHI:
18790   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18791   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18792   if (!AddendDef.isPHI())
18793     return MBB;
18794
18795   // Look for the following pattern:
18796   // loop:
18797   //   %addend = phi [%entry, 0], [%loop, %result]
18798   //   ...
18799   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18800
18801   // Replace with:
18802   //   loop:
18803   //   %addend = phi [%entry, 0], [%loop, %result]
18804   //   ...
18805   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18806
18807   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18808     assert(AddendDef.getOperand(i).isReg());
18809     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18810     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18811     if (&PHISrcInst == MI) {
18812       // Found a matching instruction.
18813       unsigned NewFMAOpc = 0;
18814       switch (MI->getOpcode()) {
18815         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18816         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18817         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18818         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18819         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18820         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18821         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18822         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18823         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18824         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18825         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18826         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18827         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18828         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18829         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18830         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18831         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18832         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18833         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18834         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18835         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18836         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18837         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18838         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18839         default: llvm_unreachable("Unrecognized FMA variant.");
18840       }
18841
18842       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18843       MachineInstrBuilder MIB =
18844         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18845         .addOperand(MI->getOperand(0))
18846         .addOperand(MI->getOperand(3))
18847         .addOperand(MI->getOperand(2))
18848         .addOperand(MI->getOperand(1));
18849       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18850       MI->eraseFromParent();
18851     }
18852   }
18853
18854   return MBB;
18855 }
18856
18857 MachineBasicBlock *
18858 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18859                                                MachineBasicBlock *BB) const {
18860   switch (MI->getOpcode()) {
18861   default: llvm_unreachable("Unexpected instr type to insert");
18862   case X86::TAILJMPd64:
18863   case X86::TAILJMPr64:
18864   case X86::TAILJMPm64:
18865     llvm_unreachable("TAILJMP64 would not be touched here.");
18866   case X86::TCRETURNdi64:
18867   case X86::TCRETURNri64:
18868   case X86::TCRETURNmi64:
18869     return BB;
18870   case X86::WIN_ALLOCA:
18871     return EmitLoweredWinAlloca(MI, BB);
18872   case X86::SEG_ALLOCA_32:
18873     return EmitLoweredSegAlloca(MI, BB, false);
18874   case X86::SEG_ALLOCA_64:
18875     return EmitLoweredSegAlloca(MI, BB, true);
18876   case X86::TLSCall_32:
18877   case X86::TLSCall_64:
18878     return EmitLoweredTLSCall(MI, BB);
18879   case X86::CMOV_GR8:
18880   case X86::CMOV_FR32:
18881   case X86::CMOV_FR64:
18882   case X86::CMOV_V4F32:
18883   case X86::CMOV_V2F64:
18884   case X86::CMOV_V2I64:
18885   case X86::CMOV_V8F32:
18886   case X86::CMOV_V4F64:
18887   case X86::CMOV_V4I64:
18888   case X86::CMOV_V16F32:
18889   case X86::CMOV_V8F64:
18890   case X86::CMOV_V8I64:
18891   case X86::CMOV_GR16:
18892   case X86::CMOV_GR32:
18893   case X86::CMOV_RFP32:
18894   case X86::CMOV_RFP64:
18895   case X86::CMOV_RFP80:
18896     return EmitLoweredSelect(MI, BB);
18897
18898   case X86::FP32_TO_INT16_IN_MEM:
18899   case X86::FP32_TO_INT32_IN_MEM:
18900   case X86::FP32_TO_INT64_IN_MEM:
18901   case X86::FP64_TO_INT16_IN_MEM:
18902   case X86::FP64_TO_INT32_IN_MEM:
18903   case X86::FP64_TO_INT64_IN_MEM:
18904   case X86::FP80_TO_INT16_IN_MEM:
18905   case X86::FP80_TO_INT32_IN_MEM:
18906   case X86::FP80_TO_INT64_IN_MEM: {
18907     MachineFunction *F = BB->getParent();
18908     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18909     DebugLoc DL = MI->getDebugLoc();
18910
18911     // Change the floating point control register to use "round towards zero"
18912     // mode when truncating to an integer value.
18913     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18914     addFrameReference(BuildMI(*BB, MI, DL,
18915                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18916
18917     // Load the old value of the high byte of the control word...
18918     unsigned OldCW =
18919       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18920     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18921                       CWFrameIdx);
18922
18923     // Set the high part to be round to zero...
18924     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18925       .addImm(0xC7F);
18926
18927     // Reload the modified control word now...
18928     addFrameReference(BuildMI(*BB, MI, DL,
18929                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18930
18931     // Restore the memory image of control word to original value
18932     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18933       .addReg(OldCW);
18934
18935     // Get the X86 opcode to use.
18936     unsigned Opc;
18937     switch (MI->getOpcode()) {
18938     default: llvm_unreachable("illegal opcode!");
18939     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18940     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18941     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18942     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18943     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18944     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18945     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18946     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18947     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18948     }
18949
18950     X86AddressMode AM;
18951     MachineOperand &Op = MI->getOperand(0);
18952     if (Op.isReg()) {
18953       AM.BaseType = X86AddressMode::RegBase;
18954       AM.Base.Reg = Op.getReg();
18955     } else {
18956       AM.BaseType = X86AddressMode::FrameIndexBase;
18957       AM.Base.FrameIndex = Op.getIndex();
18958     }
18959     Op = MI->getOperand(1);
18960     if (Op.isImm())
18961       AM.Scale = Op.getImm();
18962     Op = MI->getOperand(2);
18963     if (Op.isImm())
18964       AM.IndexReg = Op.getImm();
18965     Op = MI->getOperand(3);
18966     if (Op.isGlobal()) {
18967       AM.GV = Op.getGlobal();
18968     } else {
18969       AM.Disp = Op.getImm();
18970     }
18971     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18972                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18973
18974     // Reload the original control word now.
18975     addFrameReference(BuildMI(*BB, MI, DL,
18976                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18977
18978     MI->eraseFromParent();   // The pseudo instruction is gone now.
18979     return BB;
18980   }
18981     // String/text processing lowering.
18982   case X86::PCMPISTRM128REG:
18983   case X86::VPCMPISTRM128REG:
18984   case X86::PCMPISTRM128MEM:
18985   case X86::VPCMPISTRM128MEM:
18986   case X86::PCMPESTRM128REG:
18987   case X86::VPCMPESTRM128REG:
18988   case X86::PCMPESTRM128MEM:
18989   case X86::VPCMPESTRM128MEM:
18990     assert(Subtarget->hasSSE42() &&
18991            "Target must have SSE4.2 or AVX features enabled");
18992     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18993
18994   // String/text processing lowering.
18995   case X86::PCMPISTRIREG:
18996   case X86::VPCMPISTRIREG:
18997   case X86::PCMPISTRIMEM:
18998   case X86::VPCMPISTRIMEM:
18999   case X86::PCMPESTRIREG:
19000   case X86::VPCMPESTRIREG:
19001   case X86::PCMPESTRIMEM:
19002   case X86::VPCMPESTRIMEM:
19003     assert(Subtarget->hasSSE42() &&
19004            "Target must have SSE4.2 or AVX features enabled");
19005     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19006
19007   // Thread synchronization.
19008   case X86::MONITOR:
19009     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
19010                        Subtarget);
19011
19012   // xbegin
19013   case X86::XBEGIN:
19014     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19015
19016   case X86::VASTART_SAVE_XMM_REGS:
19017     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19018
19019   case X86::VAARG_64:
19020     return EmitVAARG64WithCustomInserter(MI, BB);
19021
19022   case X86::EH_SjLj_SetJmp32:
19023   case X86::EH_SjLj_SetJmp64:
19024     return emitEHSjLjSetJmp(MI, BB);
19025
19026   case X86::EH_SjLj_LongJmp32:
19027   case X86::EH_SjLj_LongJmp64:
19028     return emitEHSjLjLongJmp(MI, BB);
19029
19030   case TargetOpcode::STACKMAP:
19031   case TargetOpcode::PATCHPOINT:
19032     return emitPatchPoint(MI, BB);
19033
19034   case X86::VFMADDPDr213r:
19035   case X86::VFMADDPSr213r:
19036   case X86::VFMADDSDr213r:
19037   case X86::VFMADDSSr213r:
19038   case X86::VFMSUBPDr213r:
19039   case X86::VFMSUBPSr213r:
19040   case X86::VFMSUBSDr213r:
19041   case X86::VFMSUBSSr213r:
19042   case X86::VFNMADDPDr213r:
19043   case X86::VFNMADDPSr213r:
19044   case X86::VFNMADDSDr213r:
19045   case X86::VFNMADDSSr213r:
19046   case X86::VFNMSUBPDr213r:
19047   case X86::VFNMSUBPSr213r:
19048   case X86::VFNMSUBSDr213r:
19049   case X86::VFNMSUBSSr213r:
19050   case X86::VFMADDPDr213rY:
19051   case X86::VFMADDPSr213rY:
19052   case X86::VFMSUBPDr213rY:
19053   case X86::VFMSUBPSr213rY:
19054   case X86::VFNMADDPDr213rY:
19055   case X86::VFNMADDPSr213rY:
19056   case X86::VFNMSUBPDr213rY:
19057   case X86::VFNMSUBPSr213rY:
19058     return emitFMA3Instr(MI, BB);
19059   }
19060 }
19061
19062 //===----------------------------------------------------------------------===//
19063 //                           X86 Optimization Hooks
19064 //===----------------------------------------------------------------------===//
19065
19066 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19067                                                       APInt &KnownZero,
19068                                                       APInt &KnownOne,
19069                                                       const SelectionDAG &DAG,
19070                                                       unsigned Depth) const {
19071   unsigned BitWidth = KnownZero.getBitWidth();
19072   unsigned Opc = Op.getOpcode();
19073   assert((Opc >= ISD::BUILTIN_OP_END ||
19074           Opc == ISD::INTRINSIC_WO_CHAIN ||
19075           Opc == ISD::INTRINSIC_W_CHAIN ||
19076           Opc == ISD::INTRINSIC_VOID) &&
19077          "Should use MaskedValueIsZero if you don't know whether Op"
19078          " is a target node!");
19079
19080   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19081   switch (Opc) {
19082   default: break;
19083   case X86ISD::ADD:
19084   case X86ISD::SUB:
19085   case X86ISD::ADC:
19086   case X86ISD::SBB:
19087   case X86ISD::SMUL:
19088   case X86ISD::UMUL:
19089   case X86ISD::INC:
19090   case X86ISD::DEC:
19091   case X86ISD::OR:
19092   case X86ISD::XOR:
19093   case X86ISD::AND:
19094     // These nodes' second result is a boolean.
19095     if (Op.getResNo() == 0)
19096       break;
19097     // Fallthrough
19098   case X86ISD::SETCC:
19099     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19100     break;
19101   case ISD::INTRINSIC_WO_CHAIN: {
19102     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19103     unsigned NumLoBits = 0;
19104     switch (IntId) {
19105     default: break;
19106     case Intrinsic::x86_sse_movmsk_ps:
19107     case Intrinsic::x86_avx_movmsk_ps_256:
19108     case Intrinsic::x86_sse2_movmsk_pd:
19109     case Intrinsic::x86_avx_movmsk_pd_256:
19110     case Intrinsic::x86_mmx_pmovmskb:
19111     case Intrinsic::x86_sse2_pmovmskb_128:
19112     case Intrinsic::x86_avx2_pmovmskb: {
19113       // High bits of movmskp{s|d}, pmovmskb are known zero.
19114       switch (IntId) {
19115         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19116         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19117         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19118         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19119         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19120         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19121         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19122         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19123       }
19124       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19125       break;
19126     }
19127     }
19128     break;
19129   }
19130   }
19131 }
19132
19133 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19134   SDValue Op,
19135   const SelectionDAG &,
19136   unsigned Depth) const {
19137   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19138   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19139     return Op.getValueType().getScalarType().getSizeInBits();
19140
19141   // Fallback case.
19142   return 1;
19143 }
19144
19145 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19146 /// node is a GlobalAddress + offset.
19147 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19148                                        const GlobalValue* &GA,
19149                                        int64_t &Offset) const {
19150   if (N->getOpcode() == X86ISD::Wrapper) {
19151     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19152       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19153       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19154       return true;
19155     }
19156   }
19157   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19158 }
19159
19160 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19161 /// same as extracting the high 128-bit part of 256-bit vector and then
19162 /// inserting the result into the low part of a new 256-bit vector
19163 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19164   EVT VT = SVOp->getValueType(0);
19165   unsigned NumElems = VT.getVectorNumElements();
19166
19167   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19168   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19169     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19170         SVOp->getMaskElt(j) >= 0)
19171       return false;
19172
19173   return true;
19174 }
19175
19176 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19177 /// same as extracting the low 128-bit part of 256-bit vector and then
19178 /// inserting the result into the high part of a new 256-bit vector
19179 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19180   EVT VT = SVOp->getValueType(0);
19181   unsigned NumElems = VT.getVectorNumElements();
19182
19183   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19184   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19185     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19186         SVOp->getMaskElt(j) >= 0)
19187       return false;
19188
19189   return true;
19190 }
19191
19192 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19193 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19194                                         TargetLowering::DAGCombinerInfo &DCI,
19195                                         const X86Subtarget* Subtarget) {
19196   SDLoc dl(N);
19197   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19198   SDValue V1 = SVOp->getOperand(0);
19199   SDValue V2 = SVOp->getOperand(1);
19200   EVT VT = SVOp->getValueType(0);
19201   unsigned NumElems = VT.getVectorNumElements();
19202
19203   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19204       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19205     //
19206     //                   0,0,0,...
19207     //                      |
19208     //    V      UNDEF    BUILD_VECTOR    UNDEF
19209     //     \      /           \           /
19210     //  CONCAT_VECTOR         CONCAT_VECTOR
19211     //         \                  /
19212     //          \                /
19213     //          RESULT: V + zero extended
19214     //
19215     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19216         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19217         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19218       return SDValue();
19219
19220     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19221       return SDValue();
19222
19223     // To match the shuffle mask, the first half of the mask should
19224     // be exactly the first vector, and all the rest a splat with the
19225     // first element of the second one.
19226     for (unsigned i = 0; i != NumElems/2; ++i)
19227       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19228           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19229         return SDValue();
19230
19231     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19232     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19233       if (Ld->hasNUsesOfValue(1, 0)) {
19234         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19235         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19236         SDValue ResNode =
19237           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19238                                   Ld->getMemoryVT(),
19239                                   Ld->getPointerInfo(),
19240                                   Ld->getAlignment(),
19241                                   false/*isVolatile*/, true/*ReadMem*/,
19242                                   false/*WriteMem*/);
19243
19244         // Make sure the newly-created LOAD is in the same position as Ld in
19245         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19246         // and update uses of Ld's output chain to use the TokenFactor.
19247         if (Ld->hasAnyUseOfValue(1)) {
19248           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19249                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19250           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19251           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19252                                  SDValue(ResNode.getNode(), 1));
19253         }
19254
19255         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19256       }
19257     }
19258
19259     // Emit a zeroed vector and insert the desired subvector on its
19260     // first half.
19261     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19262     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19263     return DCI.CombineTo(N, InsV);
19264   }
19265
19266   //===--------------------------------------------------------------------===//
19267   // Combine some shuffles into subvector extracts and inserts:
19268   //
19269
19270   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19271   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19272     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19273     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19274     return DCI.CombineTo(N, InsV);
19275   }
19276
19277   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19278   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19279     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19280     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19281     return DCI.CombineTo(N, InsV);
19282   }
19283
19284   return SDValue();
19285 }
19286
19287 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19288 /// possible.
19289 ///
19290 /// This is the leaf of the recursive combinine below. When we have found some
19291 /// chain of single-use x86 shuffle instructions and accumulated the combined
19292 /// shuffle mask represented by them, this will try to pattern match that mask
19293 /// into either a single instruction if there is a special purpose instruction
19294 /// for this operation, or into a PSHUFB instruction which is a fully general
19295 /// instruction but should only be used to replace chains over a certain depth.
19296 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19297                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19298                                    TargetLowering::DAGCombinerInfo &DCI,
19299                                    const X86Subtarget *Subtarget) {
19300   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19301
19302   // Find the operand that enters the chain. Note that multiple uses are OK
19303   // here, we're not going to remove the operand we find.
19304   SDValue Input = Op.getOperand(0);
19305   while (Input.getOpcode() == ISD::BITCAST)
19306     Input = Input.getOperand(0);
19307
19308   MVT VT = Input.getSimpleValueType();
19309   MVT RootVT = Root.getSimpleValueType();
19310   SDLoc DL(Root);
19311
19312   // Just remove no-op shuffle masks.
19313   if (Mask.size() == 1) {
19314     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19315                   /*AddTo*/ true);
19316     return true;
19317   }
19318
19319   // Use the float domain if the operand type is a floating point type.
19320   bool FloatDomain = VT.isFloatingPoint();
19321
19322   // If we don't have access to VEX encodings, the generic PSHUF instructions
19323   // are preferable to some of the specialized forms despite requiring one more
19324   // byte to encode because they can implicitly copy.
19325   //
19326   // IF we *do* have VEX encodings, than we can use shorter, more specific
19327   // shuffle instructions freely as they can copy due to the extra register
19328   // operand.
19329   if (Subtarget->hasAVX()) {
19330     // We have both floating point and integer variants of shuffles that dup
19331     // either the low or high half of the vector.
19332     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19333       bool Lo = Mask.equals(0, 0);
19334       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19335                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19336       if (Depth == 1 && Root->getOpcode() == Shuffle)
19337         return false; // Nothing to do!
19338       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19339       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19340       DCI.AddToWorklist(Op.getNode());
19341       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19342       DCI.AddToWorklist(Op.getNode());
19343       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19344                     /*AddTo*/ true);
19345       return true;
19346     }
19347
19348     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19349
19350     // For the integer domain we have specialized instructions for duplicating
19351     // any element size from the low or high half.
19352     if (!FloatDomain &&
19353         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19354          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19355          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19356          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19357          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19358                      15))) {
19359       bool Lo = Mask[0] == 0;
19360       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19361       if (Depth == 1 && Root->getOpcode() == Shuffle)
19362         return false; // Nothing to do!
19363       MVT ShuffleVT;
19364       switch (Mask.size()) {
19365       case 4: ShuffleVT = MVT::v4i32; break;
19366       case 8: ShuffleVT = MVT::v8i16; break;
19367       case 16: ShuffleVT = MVT::v16i8; break;
19368       };
19369       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19370       DCI.AddToWorklist(Op.getNode());
19371       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19372       DCI.AddToWorklist(Op.getNode());
19373       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19374                     /*AddTo*/ true);
19375       return true;
19376     }
19377   }
19378
19379   // Don't try to re-form single instruction chains under any circumstances now
19380   // that we've done encoding canonicalization for them.
19381   if (Depth < 2)
19382     return false;
19383
19384   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19385   // can replace them with a single PSHUFB instruction profitably. Intel's
19386   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19387   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19388   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19389     SmallVector<SDValue, 16> PSHUFBMask;
19390     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19391     int Ratio = 16 / Mask.size();
19392     for (unsigned i = 0; i < 16; ++i) {
19393       int M = Mask[i / Ratio] != SM_SentinelZero
19394                   ? Ratio * Mask[i / Ratio] + i % Ratio
19395                   : 255;
19396       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19397     }
19398     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19399     DCI.AddToWorklist(Op.getNode());
19400     SDValue PSHUFBMaskOp =
19401         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19402     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19403     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19404     DCI.AddToWorklist(Op.getNode());
19405     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19406                   /*AddTo*/ true);
19407     return true;
19408   }
19409
19410   // Failed to find any combines.
19411   return false;
19412 }
19413
19414 /// \brief Fully generic combining of x86 shuffle instructions.
19415 ///
19416 /// This should be the last combine run over the x86 shuffle instructions. Once
19417 /// they have been fully optimized, this will recursively consider all chains
19418 /// of single-use shuffle instructions, build a generic model of the cumulative
19419 /// shuffle operation, and check for simpler instructions which implement this
19420 /// operation. We use this primarily for two purposes:
19421 ///
19422 /// 1) Collapse generic shuffles to specialized single instructions when
19423 ///    equivalent. In most cases, this is just an encoding size win, but
19424 ///    sometimes we will collapse multiple generic shuffles into a single
19425 ///    special-purpose shuffle.
19426 /// 2) Look for sequences of shuffle instructions with 3 or more total
19427 ///    instructions, and replace them with the slightly more expensive SSSE3
19428 ///    PSHUFB instruction if available. We do this as the last combining step
19429 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19430 ///    a suitable short sequence of other instructions. The PHUFB will either
19431 ///    use a register or have to read from memory and so is slightly (but only
19432 ///    slightly) more expensive than the other shuffle instructions.
19433 ///
19434 /// Because this is inherently a quadratic operation (for each shuffle in
19435 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19436 /// This should never be an issue in practice as the shuffle lowering doesn't
19437 /// produce sequences of more than 8 instructions.
19438 ///
19439 /// FIXME: We will currently miss some cases where the redundant shuffling
19440 /// would simplify under the threshold for PSHUFB formation because of
19441 /// combine-ordering. To fix this, we should do the redundant instruction
19442 /// combining in this recursive walk.
19443 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19444                                           ArrayRef<int> RootMask,
19445                                           int Depth, bool HasPSHUFB,
19446                                           SelectionDAG &DAG,
19447                                           TargetLowering::DAGCombinerInfo &DCI,
19448                                           const X86Subtarget *Subtarget) {
19449   // Bound the depth of our recursive combine because this is ultimately
19450   // quadratic in nature.
19451   if (Depth > 8)
19452     return false;
19453
19454   // Directly rip through bitcasts to find the underlying operand.
19455   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19456     Op = Op.getOperand(0);
19457
19458   MVT VT = Op.getSimpleValueType();
19459   if (!VT.isVector())
19460     return false; // Bail if we hit a non-vector.
19461   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19462   // version should be added.
19463   if (VT.getSizeInBits() != 128)
19464     return false;
19465
19466   assert(Root.getSimpleValueType().isVector() &&
19467          "Shuffles operate on vector types!");
19468   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19469          "Can only combine shuffles of the same vector register size.");
19470
19471   if (!isTargetShuffle(Op.getOpcode()))
19472     return false;
19473   SmallVector<int, 16> OpMask;
19474   bool IsUnary;
19475   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19476   // We only can combine unary shuffles which we can decode the mask for.
19477   if (!HaveMask || !IsUnary)
19478     return false;
19479
19480   assert(VT.getVectorNumElements() == OpMask.size() &&
19481          "Different mask size from vector size!");
19482   assert(((RootMask.size() > OpMask.size() &&
19483            RootMask.size() % OpMask.size() == 0) ||
19484           (OpMask.size() > RootMask.size() &&
19485            OpMask.size() % RootMask.size() == 0) ||
19486           OpMask.size() == RootMask.size()) &&
19487          "The smaller number of elements must divide the larger.");
19488   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19489   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19490   assert(((RootRatio == 1 && OpRatio == 1) ||
19491           (RootRatio == 1) != (OpRatio == 1)) &&
19492          "Must not have a ratio for both incoming and op masks!");
19493
19494   SmallVector<int, 16> Mask;
19495   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19496
19497   // Merge this shuffle operation's mask into our accumulated mask. Note that
19498   // this shuffle's mask will be the first applied to the input, followed by the
19499   // root mask to get us all the way to the root value arrangement. The reason
19500   // for this order is that we are recursing up the operation chain.
19501   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19502     int RootIdx = i / RootRatio;
19503     if (RootMask[RootIdx] == SM_SentinelZero) {
19504       // This is a zero-ed lane, we're done.
19505       Mask.push_back(SM_SentinelZero);
19506       continue;
19507     }
19508
19509     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19510     int OpIdx = RootMaskedIdx / OpRatio;
19511     if (OpMask[OpIdx] == SM_SentinelZero) {
19512       // The incoming lanes are zero, it doesn't matter which ones we are using.
19513       Mask.push_back(SM_SentinelZero);
19514       continue;
19515     }
19516
19517     // Ok, we have non-zero lanes, map them through.
19518     Mask.push_back(OpMask[OpIdx] * OpRatio +
19519                    RootMaskedIdx % OpRatio);
19520   }
19521
19522   // See if we can recurse into the operand to combine more things.
19523   switch (Op.getOpcode()) {
19524     case X86ISD::PSHUFB:
19525       HasPSHUFB = true;
19526     case X86ISD::PSHUFD:
19527     case X86ISD::PSHUFHW:
19528     case X86ISD::PSHUFLW:
19529       if (Op.getOperand(0).hasOneUse() &&
19530           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19531                                         HasPSHUFB, DAG, DCI, Subtarget))
19532         return true;
19533       break;
19534
19535     case X86ISD::UNPCKL:
19536     case X86ISD::UNPCKH:
19537       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19538       // We can't check for single use, we have to check that this shuffle is the only user.
19539       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19540           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19541                                         HasPSHUFB, DAG, DCI, Subtarget))
19542           return true;
19543       break;
19544   }
19545
19546   // Minor canonicalization of the accumulated shuffle mask to make it easier
19547   // to match below. All this does is detect masks with squential pairs of
19548   // elements, and shrink them to the half-width mask. It does this in a loop
19549   // so it will reduce the size of the mask to the minimal width mask which
19550   // performs an equivalent shuffle.
19551   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19552     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19553       Mask[i] = Mask[2 * i] / 2;
19554     Mask.resize(Mask.size() / 2);
19555   }
19556
19557   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19558                                 Subtarget);
19559 }
19560
19561 /// \brief Get the PSHUF-style mask from PSHUF node.
19562 ///
19563 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19564 /// PSHUF-style masks that can be reused with such instructions.
19565 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19566   SmallVector<int, 4> Mask;
19567   bool IsUnary;
19568   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19569   (void)HaveMask;
19570   assert(HaveMask);
19571
19572   switch (N.getOpcode()) {
19573   case X86ISD::PSHUFD:
19574     return Mask;
19575   case X86ISD::PSHUFLW:
19576     Mask.resize(4);
19577     return Mask;
19578   case X86ISD::PSHUFHW:
19579     Mask.erase(Mask.begin(), Mask.begin() + 4);
19580     for (int &M : Mask)
19581       M -= 4;
19582     return Mask;
19583   default:
19584     llvm_unreachable("No valid shuffle instruction found!");
19585   }
19586 }
19587
19588 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19589 ///
19590 /// We walk up the chain and look for a combinable shuffle, skipping over
19591 /// shuffles that we could hoist this shuffle's transformation past without
19592 /// altering anything.
19593 static SDValue
19594 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19595                              SelectionDAG &DAG,
19596                              TargetLowering::DAGCombinerInfo &DCI) {
19597   assert(N.getOpcode() == X86ISD::PSHUFD &&
19598          "Called with something other than an x86 128-bit half shuffle!");
19599   SDLoc DL(N);
19600
19601   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19602   // of the shuffles in the chain so that we can form a fresh chain to replace
19603   // this one.
19604   SmallVector<SDValue, 8> Chain;
19605   SDValue V = N.getOperand(0);
19606   for (; V.hasOneUse(); V = V.getOperand(0)) {
19607     switch (V.getOpcode()) {
19608     default:
19609       return SDValue(); // Nothing combined!
19610
19611     case ISD::BITCAST:
19612       // Skip bitcasts as we always know the type for the target specific
19613       // instructions.
19614       continue;
19615
19616     case X86ISD::PSHUFD:
19617       // Found another dword shuffle.
19618       break;
19619
19620     case X86ISD::PSHUFLW:
19621       // Check that the low words (being shuffled) are the identity in the
19622       // dword shuffle, and the high words are self-contained.
19623       if (Mask[0] != 0 || Mask[1] != 1 ||
19624           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19625         return SDValue();
19626
19627       Chain.push_back(V);
19628       continue;
19629
19630     case X86ISD::PSHUFHW:
19631       // Check that the high words (being shuffled) are the identity in the
19632       // dword shuffle, and the low words are self-contained.
19633       if (Mask[2] != 2 || Mask[3] != 3 ||
19634           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19635         return SDValue();
19636
19637       Chain.push_back(V);
19638       continue;
19639
19640     case X86ISD::UNPCKL:
19641     case X86ISD::UNPCKH:
19642       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19643       // shuffle into a preceding word shuffle.
19644       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19645         return SDValue();
19646
19647       // Search for a half-shuffle which we can combine with.
19648       unsigned CombineOp =
19649           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19650       if (V.getOperand(0) != V.getOperand(1) ||
19651           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19652         return SDValue();
19653       Chain.push_back(V);
19654       V = V.getOperand(0);
19655       do {
19656         switch (V.getOpcode()) {
19657         default:
19658           return SDValue(); // Nothing to combine.
19659
19660         case X86ISD::PSHUFLW:
19661         case X86ISD::PSHUFHW:
19662           if (V.getOpcode() == CombineOp)
19663             break;
19664
19665           Chain.push_back(V);
19666
19667           // Fallthrough!
19668         case ISD::BITCAST:
19669           V = V.getOperand(0);
19670           continue;
19671         }
19672         break;
19673       } while (V.hasOneUse());
19674       break;
19675     }
19676     // Break out of the loop if we break out of the switch.
19677     break;
19678   }
19679
19680   if (!V.hasOneUse())
19681     // We fell out of the loop without finding a viable combining instruction.
19682     return SDValue();
19683
19684   // Merge this node's mask and our incoming mask.
19685   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19686   for (int &M : Mask)
19687     M = VMask[M];
19688   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19689                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19690
19691   // Rebuild the chain around this new shuffle.
19692   while (!Chain.empty()) {
19693     SDValue W = Chain.pop_back_val();
19694
19695     if (V.getValueType() != W.getOperand(0).getValueType())
19696       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19697
19698     switch (W.getOpcode()) {
19699     default:
19700       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19701
19702     case X86ISD::UNPCKL:
19703     case X86ISD::UNPCKH:
19704       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19705       break;
19706
19707     case X86ISD::PSHUFD:
19708     case X86ISD::PSHUFLW:
19709     case X86ISD::PSHUFHW:
19710       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19711       break;
19712     }
19713   }
19714   if (V.getValueType() != N.getValueType())
19715     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19716
19717   // Return the new chain to replace N.
19718   return V;
19719 }
19720
19721 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19722 ///
19723 /// We walk up the chain, skipping shuffles of the other half and looking
19724 /// through shuffles which switch halves trying to find a shuffle of the same
19725 /// pair of dwords.
19726 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19727                                         SelectionDAG &DAG,
19728                                         TargetLowering::DAGCombinerInfo &DCI) {
19729   assert(
19730       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19731       "Called with something other than an x86 128-bit half shuffle!");
19732   SDLoc DL(N);
19733   unsigned CombineOpcode = N.getOpcode();
19734
19735   // Walk up a single-use chain looking for a combinable shuffle.
19736   SDValue V = N.getOperand(0);
19737   for (; V.hasOneUse(); V = V.getOperand(0)) {
19738     switch (V.getOpcode()) {
19739     default:
19740       return false; // Nothing combined!
19741
19742     case ISD::BITCAST:
19743       // Skip bitcasts as we always know the type for the target specific
19744       // instructions.
19745       continue;
19746
19747     case X86ISD::PSHUFLW:
19748     case X86ISD::PSHUFHW:
19749       if (V.getOpcode() == CombineOpcode)
19750         break;
19751
19752       // Other-half shuffles are no-ops.
19753       continue;
19754     }
19755     // Break out of the loop if we break out of the switch.
19756     break;
19757   }
19758
19759   if (!V.hasOneUse())
19760     // We fell out of the loop without finding a viable combining instruction.
19761     return false;
19762
19763   // Combine away the bottom node as its shuffle will be accumulated into
19764   // a preceding shuffle.
19765   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19766
19767   // Record the old value.
19768   SDValue Old = V;
19769
19770   // Merge this node's mask and our incoming mask (adjusted to account for all
19771   // the pshufd instructions encountered).
19772   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19773   for (int &M : Mask)
19774     M = VMask[M];
19775   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19776                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19777
19778   // Check that the shuffles didn't cancel each other out. If not, we need to
19779   // combine to the new one.
19780   if (Old != V)
19781     // Replace the combinable shuffle with the combined one, updating all users
19782     // so that we re-evaluate the chain here.
19783     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19784
19785   return true;
19786 }
19787
19788 /// \brief Try to combine x86 target specific shuffles.
19789 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19790                                            TargetLowering::DAGCombinerInfo &DCI,
19791                                            const X86Subtarget *Subtarget) {
19792   SDLoc DL(N);
19793   MVT VT = N.getSimpleValueType();
19794   SmallVector<int, 4> Mask;
19795
19796   switch (N.getOpcode()) {
19797   case X86ISD::PSHUFD:
19798   case X86ISD::PSHUFLW:
19799   case X86ISD::PSHUFHW:
19800     Mask = getPSHUFShuffleMask(N);
19801     assert(Mask.size() == 4);
19802     break;
19803   default:
19804     return SDValue();
19805   }
19806
19807   // Nuke no-op shuffles that show up after combining.
19808   if (isNoopShuffleMask(Mask))
19809     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19810
19811   // Look for simplifications involving one or two shuffle instructions.
19812   SDValue V = N.getOperand(0);
19813   switch (N.getOpcode()) {
19814   default:
19815     break;
19816   case X86ISD::PSHUFLW:
19817   case X86ISD::PSHUFHW:
19818     assert(VT == MVT::v8i16);
19819     (void)VT;
19820
19821     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19822       return SDValue(); // We combined away this shuffle, so we're done.
19823
19824     // See if this reduces to a PSHUFD which is no more expensive and can
19825     // combine with more operations.
19826     if (canWidenShuffleElements(Mask)) {
19827       int DMask[] = {-1, -1, -1, -1};
19828       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19829       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19830       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19831       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19832       DCI.AddToWorklist(V.getNode());
19833       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19834                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19835       DCI.AddToWorklist(V.getNode());
19836       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19837     }
19838
19839     // Look for shuffle patterns which can be implemented as a single unpack.
19840     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19841     // only works when we have a PSHUFD followed by two half-shuffles.
19842     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19843         (V.getOpcode() == X86ISD::PSHUFLW ||
19844          V.getOpcode() == X86ISD::PSHUFHW) &&
19845         V.getOpcode() != N.getOpcode() &&
19846         V.hasOneUse()) {
19847       SDValue D = V.getOperand(0);
19848       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19849         D = D.getOperand(0);
19850       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19851         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19852         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19853         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19854         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19855         int WordMask[8];
19856         for (int i = 0; i < 4; ++i) {
19857           WordMask[i + NOffset] = Mask[i] + NOffset;
19858           WordMask[i + VOffset] = VMask[i] + VOffset;
19859         }
19860         // Map the word mask through the DWord mask.
19861         int MappedMask[8];
19862         for (int i = 0; i < 8; ++i)
19863           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19864         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19865         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19866         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19867                        std::begin(UnpackLoMask)) ||
19868             std::equal(std::begin(MappedMask), std::end(MappedMask),
19869                        std::begin(UnpackHiMask))) {
19870           // We can replace all three shuffles with an unpack.
19871           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19872           DCI.AddToWorklist(V.getNode());
19873           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19874                                                 : X86ISD::UNPCKH,
19875                              DL, MVT::v8i16, V, V);
19876         }
19877       }
19878     }
19879
19880     break;
19881
19882   case X86ISD::PSHUFD:
19883     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19884       return NewN;
19885
19886     break;
19887   }
19888
19889   return SDValue();
19890 }
19891
19892 /// PerformShuffleCombine - Performs several different shuffle combines.
19893 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19894                                      TargetLowering::DAGCombinerInfo &DCI,
19895                                      const X86Subtarget *Subtarget) {
19896   SDLoc dl(N);
19897   SDValue N0 = N->getOperand(0);
19898   SDValue N1 = N->getOperand(1);
19899   EVT VT = N->getValueType(0);
19900
19901   // Don't create instructions with illegal types after legalize types has run.
19902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19903   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19904     return SDValue();
19905
19906   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19907   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19908       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19909     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19910
19911   // During Type Legalization, when promoting illegal vector types,
19912   // the backend might introduce new shuffle dag nodes and bitcasts.
19913   //
19914   // This code performs the following transformation:
19915   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19916   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19917   //
19918   // We do this only if both the bitcast and the BINOP dag nodes have
19919   // one use. Also, perform this transformation only if the new binary
19920   // operation is legal. This is to avoid introducing dag nodes that
19921   // potentially need to be further expanded (or custom lowered) into a
19922   // less optimal sequence of dag nodes.
19923   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19924       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19925       N0.getOpcode() == ISD::BITCAST) {
19926     SDValue BC0 = N0.getOperand(0);
19927     EVT SVT = BC0.getValueType();
19928     unsigned Opcode = BC0.getOpcode();
19929     unsigned NumElts = VT.getVectorNumElements();
19930     
19931     if (BC0.hasOneUse() && SVT.isVector() &&
19932         SVT.getVectorNumElements() * 2 == NumElts &&
19933         TLI.isOperationLegal(Opcode, VT)) {
19934       bool CanFold = false;
19935       switch (Opcode) {
19936       default : break;
19937       case ISD::ADD :
19938       case ISD::FADD :
19939       case ISD::SUB :
19940       case ISD::FSUB :
19941       case ISD::MUL :
19942       case ISD::FMUL :
19943         CanFold = true;
19944       }
19945
19946       unsigned SVTNumElts = SVT.getVectorNumElements();
19947       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19948       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19949         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19950       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19951         CanFold = SVOp->getMaskElt(i) < 0;
19952
19953       if (CanFold) {
19954         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19955         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19956         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19957         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19958       }
19959     }
19960   }
19961
19962   // Only handle 128 wide vector from here on.
19963   if (!VT.is128BitVector())
19964     return SDValue();
19965
19966   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19967   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19968   // consecutive, non-overlapping, and in the right order.
19969   SmallVector<SDValue, 16> Elts;
19970   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19971     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19972
19973   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19974   if (LD.getNode())
19975     return LD;
19976
19977   if (isTargetShuffle(N->getOpcode())) {
19978     SDValue Shuffle =
19979         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19980     if (Shuffle.getNode())
19981       return Shuffle;
19982
19983     // Try recursively combining arbitrary sequences of x86 shuffle
19984     // instructions into higher-order shuffles. We do this after combining
19985     // specific PSHUF instruction sequences into their minimal form so that we
19986     // can evaluate how many specialized shuffle instructions are involved in
19987     // a particular chain.
19988     SmallVector<int, 1> NonceMask; // Just a placeholder.
19989     NonceMask.push_back(0);
19990     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19991                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19992                                       DCI, Subtarget))
19993       return SDValue(); // This routine will use CombineTo to replace N.
19994   }
19995
19996   return SDValue();
19997 }
19998
19999 /// PerformTruncateCombine - Converts truncate operation to
20000 /// a sequence of vector shuffle operations.
20001 /// It is possible when we truncate 256-bit vector to 128-bit vector
20002 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20003                                       TargetLowering::DAGCombinerInfo &DCI,
20004                                       const X86Subtarget *Subtarget)  {
20005   return SDValue();
20006 }
20007
20008 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20009 /// specific shuffle of a load can be folded into a single element load.
20010 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20011 /// shuffles have been customed lowered so we need to handle those here.
20012 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20013                                          TargetLowering::DAGCombinerInfo &DCI) {
20014   if (DCI.isBeforeLegalizeOps())
20015     return SDValue();
20016
20017   SDValue InVec = N->getOperand(0);
20018   SDValue EltNo = N->getOperand(1);
20019
20020   if (!isa<ConstantSDNode>(EltNo))
20021     return SDValue();
20022
20023   EVT VT = InVec.getValueType();
20024
20025   if (InVec.getOpcode() == ISD::BITCAST) {
20026     // Don't duplicate a load with other uses.
20027     if (!InVec.hasOneUse())
20028       return SDValue();
20029     EVT BCVT = InVec.getOperand(0).getValueType();
20030     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
20031       return SDValue();
20032     InVec = InVec.getOperand(0);
20033   }
20034
20035   if (!isTargetShuffle(InVec.getOpcode()))
20036     return SDValue();
20037
20038   // Don't duplicate a load with other uses.
20039   if (!InVec.hasOneUse())
20040     return SDValue();
20041
20042   SmallVector<int, 16> ShuffleMask;
20043   bool UnaryShuffle;
20044   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
20045                             UnaryShuffle))
20046     return SDValue();
20047
20048   // Select the input vector, guarding against out of range extract vector.
20049   unsigned NumElems = VT.getVectorNumElements();
20050   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20051   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20052   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20053                                          : InVec.getOperand(1);
20054
20055   // If inputs to shuffle are the same for both ops, then allow 2 uses
20056   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20057
20058   if (LdNode.getOpcode() == ISD::BITCAST) {
20059     // Don't duplicate a load with other uses.
20060     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20061       return SDValue();
20062
20063     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20064     LdNode = LdNode.getOperand(0);
20065   }
20066
20067   if (!ISD::isNormalLoad(LdNode.getNode()))
20068     return SDValue();
20069
20070   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20071
20072   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20073     return SDValue();
20074
20075   EVT EltVT = N->getValueType(0);
20076   // If there's a bitcast before the shuffle, check if the load type and
20077   // alignment is valid.
20078   unsigned Align = LN0->getAlignment();
20079   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20080   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20081       EltVT.getTypeForEVT(*DAG.getContext()));
20082
20083   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20084     return SDValue();
20085
20086   // All checks match so transform back to vector_shuffle so that DAG combiner
20087   // can finish the job
20088   SDLoc dl(N);
20089
20090   // Create shuffle node taking into account the case that its a unary shuffle
20091   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
20092   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
20093                                  InVec.getOperand(0), Shuffle,
20094                                  &ShuffleMask[0]);
20095   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
20096   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20097                      EltNo);
20098 }
20099
20100 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20101 /// generation and convert it from being a bunch of shuffles and extracts
20102 /// to a simple store and scalar loads to extract the elements.
20103 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20104                                          TargetLowering::DAGCombinerInfo &DCI) {
20105   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20106   if (NewOp.getNode())
20107     return NewOp;
20108
20109   SDValue InputVector = N->getOperand(0);
20110
20111   // Detect whether we are trying to convert from mmx to i32 and the bitcast
20112   // from mmx to v2i32 has a single usage.
20113   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
20114       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
20115       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
20116     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20117                        N->getValueType(0),
20118                        InputVector.getNode()->getOperand(0));
20119
20120   // Only operate on vectors of 4 elements, where the alternative shuffling
20121   // gets to be more expensive.
20122   if (InputVector.getValueType() != MVT::v4i32)
20123     return SDValue();
20124
20125   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20126   // single use which is a sign-extend or zero-extend, and all elements are
20127   // used.
20128   SmallVector<SDNode *, 4> Uses;
20129   unsigned ExtractedElements = 0;
20130   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20131        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20132     if (UI.getUse().getResNo() != InputVector.getResNo())
20133       return SDValue();
20134
20135     SDNode *Extract = *UI;
20136     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20137       return SDValue();
20138
20139     if (Extract->getValueType(0) != MVT::i32)
20140       return SDValue();
20141     if (!Extract->hasOneUse())
20142       return SDValue();
20143     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20144         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20145       return SDValue();
20146     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20147       return SDValue();
20148
20149     // Record which element was extracted.
20150     ExtractedElements |=
20151       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20152
20153     Uses.push_back(Extract);
20154   }
20155
20156   // If not all the elements were used, this may not be worthwhile.
20157   if (ExtractedElements != 15)
20158     return SDValue();
20159
20160   // Ok, we've now decided to do the transformation.
20161   SDLoc dl(InputVector);
20162
20163   // Store the value to a temporary stack slot.
20164   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20165   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20166                             MachinePointerInfo(), false, false, 0);
20167
20168   // Replace each use (extract) with a load of the appropriate element.
20169   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20170        UE = Uses.end(); UI != UE; ++UI) {
20171     SDNode *Extract = *UI;
20172
20173     // cOMpute the element's address.
20174     SDValue Idx = Extract->getOperand(1);
20175     unsigned EltSize =
20176         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
20177     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
20178     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20179     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20180
20181     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20182                                      StackPtr, OffsetVal);
20183
20184     // Load the scalar.
20185     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
20186                                      ScalarAddr, MachinePointerInfo(),
20187                                      false, false, false, 0);
20188
20189     // Replace the exact with the load.
20190     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20191   }
20192
20193   // The replacement was made in place; don't return anything.
20194   return SDValue();
20195 }
20196
20197 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20198 static std::pair<unsigned, bool>
20199 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20200                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20201   if (!VT.isVector())
20202     return std::make_pair(0, false);
20203
20204   bool NeedSplit = false;
20205   switch (VT.getSimpleVT().SimpleTy) {
20206   default: return std::make_pair(0, false);
20207   case MVT::v32i8:
20208   case MVT::v16i16:
20209   case MVT::v8i32:
20210     if (!Subtarget->hasAVX2())
20211       NeedSplit = true;
20212     if (!Subtarget->hasAVX())
20213       return std::make_pair(0, false);
20214     break;
20215   case MVT::v16i8:
20216   case MVT::v8i16:
20217   case MVT::v4i32:
20218     if (!Subtarget->hasSSE2())
20219       return std::make_pair(0, false);
20220   }
20221
20222   // SSE2 has only a small subset of the operations.
20223   bool hasUnsigned = Subtarget->hasSSE41() ||
20224                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20225   bool hasSigned = Subtarget->hasSSE41() ||
20226                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20227
20228   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20229
20230   unsigned Opc = 0;
20231   // Check for x CC y ? x : y.
20232   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20233       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20234     switch (CC) {
20235     default: break;
20236     case ISD::SETULT:
20237     case ISD::SETULE:
20238       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20239     case ISD::SETUGT:
20240     case ISD::SETUGE:
20241       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20242     case ISD::SETLT:
20243     case ISD::SETLE:
20244       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20245     case ISD::SETGT:
20246     case ISD::SETGE:
20247       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20248     }
20249   // Check for x CC y ? y : x -- a min/max with reversed arms.
20250   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20251              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20252     switch (CC) {
20253     default: break;
20254     case ISD::SETULT:
20255     case ISD::SETULE:
20256       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20257     case ISD::SETUGT:
20258     case ISD::SETUGE:
20259       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20260     case ISD::SETLT:
20261     case ISD::SETLE:
20262       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20263     case ISD::SETGT:
20264     case ISD::SETGE:
20265       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20266     }
20267   }
20268
20269   return std::make_pair(Opc, NeedSplit);
20270 }
20271
20272 static SDValue
20273 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20274                                       const X86Subtarget *Subtarget) {
20275   SDLoc dl(N);
20276   SDValue Cond = N->getOperand(0);
20277   SDValue LHS = N->getOperand(1);
20278   SDValue RHS = N->getOperand(2);
20279
20280   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20281     SDValue CondSrc = Cond->getOperand(0);
20282     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20283       Cond = CondSrc->getOperand(0);
20284   }
20285
20286   MVT VT = N->getSimpleValueType(0);
20287   MVT EltVT = VT.getVectorElementType();
20288   unsigned NumElems = VT.getVectorNumElements();
20289   // There is no blend with immediate in AVX-512.
20290   if (VT.is512BitVector())
20291     return SDValue();
20292
20293   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20294     return SDValue();
20295   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20296     return SDValue();
20297
20298   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20299     return SDValue();
20300
20301   // A vselect where all conditions and data are constants can be optimized into
20302   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20303   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20304       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20305     return SDValue();
20306
20307   unsigned MaskValue = 0;
20308   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20309     return SDValue();
20310
20311   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20312   for (unsigned i = 0; i < NumElems; ++i) {
20313     // Be sure we emit undef where we can.
20314     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20315       ShuffleMask[i] = -1;
20316     else
20317       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20318   }
20319
20320   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20321 }
20322
20323 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20324 /// nodes.
20325 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20326                                     TargetLowering::DAGCombinerInfo &DCI,
20327                                     const X86Subtarget *Subtarget) {
20328   SDLoc DL(N);
20329   SDValue Cond = N->getOperand(0);
20330   // Get the LHS/RHS of the select.
20331   SDValue LHS = N->getOperand(1);
20332   SDValue RHS = N->getOperand(2);
20333   EVT VT = LHS.getValueType();
20334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20335
20336   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20337   // instructions match the semantics of the common C idiom x<y?x:y but not
20338   // x<=y?x:y, because of how they handle negative zero (which can be
20339   // ignored in unsafe-math mode).
20340   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20341       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20342       (Subtarget->hasSSE2() ||
20343        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20344     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20345
20346     unsigned Opcode = 0;
20347     // Check for x CC y ? x : y.
20348     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20349         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20350       switch (CC) {
20351       default: break;
20352       case ISD::SETULT:
20353         // Converting this to a min would handle NaNs incorrectly, and swapping
20354         // the operands would cause it to handle comparisons between positive
20355         // and negative zero incorrectly.
20356         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20357           if (!DAG.getTarget().Options.UnsafeFPMath &&
20358               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20359             break;
20360           std::swap(LHS, RHS);
20361         }
20362         Opcode = X86ISD::FMIN;
20363         break;
20364       case ISD::SETOLE:
20365         // Converting this to a min would handle comparisons between positive
20366         // and negative zero incorrectly.
20367         if (!DAG.getTarget().Options.UnsafeFPMath &&
20368             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20369           break;
20370         Opcode = X86ISD::FMIN;
20371         break;
20372       case ISD::SETULE:
20373         // Converting this to a min would handle both negative zeros and NaNs
20374         // incorrectly, but we can swap the operands to fix both.
20375         std::swap(LHS, RHS);
20376       case ISD::SETOLT:
20377       case ISD::SETLT:
20378       case ISD::SETLE:
20379         Opcode = X86ISD::FMIN;
20380         break;
20381
20382       case ISD::SETOGE:
20383         // Converting this to a max would handle comparisons between positive
20384         // and negative zero incorrectly.
20385         if (!DAG.getTarget().Options.UnsafeFPMath &&
20386             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20387           break;
20388         Opcode = X86ISD::FMAX;
20389         break;
20390       case ISD::SETUGT:
20391         // Converting this to a max would handle NaNs incorrectly, and swapping
20392         // the operands would cause it to handle comparisons between positive
20393         // and negative zero incorrectly.
20394         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20395           if (!DAG.getTarget().Options.UnsafeFPMath &&
20396               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20397             break;
20398           std::swap(LHS, RHS);
20399         }
20400         Opcode = X86ISD::FMAX;
20401         break;
20402       case ISD::SETUGE:
20403         // Converting this to a max would handle both negative zeros and NaNs
20404         // incorrectly, but we can swap the operands to fix both.
20405         std::swap(LHS, RHS);
20406       case ISD::SETOGT:
20407       case ISD::SETGT:
20408       case ISD::SETGE:
20409         Opcode = X86ISD::FMAX;
20410         break;
20411       }
20412     // Check for x CC y ? y : x -- a min/max with reversed arms.
20413     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20414                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20415       switch (CC) {
20416       default: break;
20417       case ISD::SETOGE:
20418         // Converting this to a min would handle comparisons between positive
20419         // and negative zero incorrectly, and swapping the operands would
20420         // cause it to handle NaNs incorrectly.
20421         if (!DAG.getTarget().Options.UnsafeFPMath &&
20422             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20423           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20424             break;
20425           std::swap(LHS, RHS);
20426         }
20427         Opcode = X86ISD::FMIN;
20428         break;
20429       case ISD::SETUGT:
20430         // Converting this to a min would handle NaNs incorrectly.
20431         if (!DAG.getTarget().Options.UnsafeFPMath &&
20432             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20433           break;
20434         Opcode = X86ISD::FMIN;
20435         break;
20436       case ISD::SETUGE:
20437         // Converting this to a min would handle both negative zeros and NaNs
20438         // incorrectly, but we can swap the operands to fix both.
20439         std::swap(LHS, RHS);
20440       case ISD::SETOGT:
20441       case ISD::SETGT:
20442       case ISD::SETGE:
20443         Opcode = X86ISD::FMIN;
20444         break;
20445
20446       case ISD::SETULT:
20447         // Converting this to a max would handle NaNs incorrectly.
20448         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20449           break;
20450         Opcode = X86ISD::FMAX;
20451         break;
20452       case ISD::SETOLE:
20453         // Converting this to a max would handle comparisons between positive
20454         // and negative zero incorrectly, and swapping the operands would
20455         // cause it to handle NaNs incorrectly.
20456         if (!DAG.getTarget().Options.UnsafeFPMath &&
20457             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20458           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20459             break;
20460           std::swap(LHS, RHS);
20461         }
20462         Opcode = X86ISD::FMAX;
20463         break;
20464       case ISD::SETULE:
20465         // Converting this to a max would handle both negative zeros and NaNs
20466         // incorrectly, but we can swap the operands to fix both.
20467         std::swap(LHS, RHS);
20468       case ISD::SETOLT:
20469       case ISD::SETLT:
20470       case ISD::SETLE:
20471         Opcode = X86ISD::FMAX;
20472         break;
20473       }
20474     }
20475
20476     if (Opcode)
20477       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20478   }
20479
20480   EVT CondVT = Cond.getValueType();
20481   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20482       CondVT.getVectorElementType() == MVT::i1) {
20483     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20484     // lowering on KNL. In this case we convert it to
20485     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20486     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20487     // Since SKX these selects have a proper lowering.
20488     EVT OpVT = LHS.getValueType();
20489     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20490         (OpVT.getVectorElementType() == MVT::i8 ||
20491          OpVT.getVectorElementType() == MVT::i16) &&
20492         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20493       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20494       DCI.AddToWorklist(Cond.getNode());
20495       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20496     }
20497   }
20498   // If this is a select between two integer constants, try to do some
20499   // optimizations.
20500   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20501     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20502       // Don't do this for crazy integer types.
20503       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20504         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20505         // so that TrueC (the true value) is larger than FalseC.
20506         bool NeedsCondInvert = false;
20507
20508         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20509             // Efficiently invertible.
20510             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20511              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20512               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20513           NeedsCondInvert = true;
20514           std::swap(TrueC, FalseC);
20515         }
20516
20517         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20518         if (FalseC->getAPIntValue() == 0 &&
20519             TrueC->getAPIntValue().isPowerOf2()) {
20520           if (NeedsCondInvert) // Invert the condition if needed.
20521             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20522                                DAG.getConstant(1, Cond.getValueType()));
20523
20524           // Zero extend the condition if needed.
20525           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20526
20527           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20528           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20529                              DAG.getConstant(ShAmt, MVT::i8));
20530         }
20531
20532         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20533         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20534           if (NeedsCondInvert) // Invert the condition if needed.
20535             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20536                                DAG.getConstant(1, Cond.getValueType()));
20537
20538           // Zero extend the condition if needed.
20539           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20540                              FalseC->getValueType(0), Cond);
20541           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20542                              SDValue(FalseC, 0));
20543         }
20544
20545         // Optimize cases that will turn into an LEA instruction.  This requires
20546         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20547         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20548           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20549           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20550
20551           bool isFastMultiplier = false;
20552           if (Diff < 10) {
20553             switch ((unsigned char)Diff) {
20554               default: break;
20555               case 1:  // result = add base, cond
20556               case 2:  // result = lea base(    , cond*2)
20557               case 3:  // result = lea base(cond, cond*2)
20558               case 4:  // result = lea base(    , cond*4)
20559               case 5:  // result = lea base(cond, cond*4)
20560               case 8:  // result = lea base(    , cond*8)
20561               case 9:  // result = lea base(cond, cond*8)
20562                 isFastMultiplier = true;
20563                 break;
20564             }
20565           }
20566
20567           if (isFastMultiplier) {
20568             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20569             if (NeedsCondInvert) // Invert the condition if needed.
20570               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20571                                  DAG.getConstant(1, Cond.getValueType()));
20572
20573             // Zero extend the condition if needed.
20574             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20575                                Cond);
20576             // Scale the condition by the difference.
20577             if (Diff != 1)
20578               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20579                                  DAG.getConstant(Diff, Cond.getValueType()));
20580
20581             // Add the base if non-zero.
20582             if (FalseC->getAPIntValue() != 0)
20583               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20584                                  SDValue(FalseC, 0));
20585             return Cond;
20586           }
20587         }
20588       }
20589   }
20590
20591   // Canonicalize max and min:
20592   // (x > y) ? x : y -> (x >= y) ? x : y
20593   // (x < y) ? x : y -> (x <= y) ? x : y
20594   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20595   // the need for an extra compare
20596   // against zero. e.g.
20597   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20598   // subl   %esi, %edi
20599   // testl  %edi, %edi
20600   // movl   $0, %eax
20601   // cmovgl %edi, %eax
20602   // =>
20603   // xorl   %eax, %eax
20604   // subl   %esi, $edi
20605   // cmovsl %eax, %edi
20606   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20607       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20608       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20609     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20610     switch (CC) {
20611     default: break;
20612     case ISD::SETLT:
20613     case ISD::SETGT: {
20614       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20615       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20616                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20617       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20618     }
20619     }
20620   }
20621
20622   // Early exit check
20623   if (!TLI.isTypeLegal(VT))
20624     return SDValue();
20625
20626   // Match VSELECTs into subs with unsigned saturation.
20627   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20628       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20629       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20630        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20631     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20632
20633     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20634     // left side invert the predicate to simplify logic below.
20635     SDValue Other;
20636     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20637       Other = RHS;
20638       CC = ISD::getSetCCInverse(CC, true);
20639     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20640       Other = LHS;
20641     }
20642
20643     if (Other.getNode() && Other->getNumOperands() == 2 &&
20644         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20645       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20646       SDValue CondRHS = Cond->getOperand(1);
20647
20648       // Look for a general sub with unsigned saturation first.
20649       // x >= y ? x-y : 0 --> subus x, y
20650       // x >  y ? x-y : 0 --> subus x, y
20651       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20652           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20653         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20654
20655       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20656         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20657           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20658             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20659               // If the RHS is a constant we have to reverse the const
20660               // canonicalization.
20661               // x > C-1 ? x+-C : 0 --> subus x, C
20662               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20663                   CondRHSConst->getAPIntValue() ==
20664                       (-OpRHSConst->getAPIntValue() - 1))
20665                 return DAG.getNode(
20666                     X86ISD::SUBUS, DL, VT, OpLHS,
20667                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20668
20669           // Another special case: If C was a sign bit, the sub has been
20670           // canonicalized into a xor.
20671           // FIXME: Would it be better to use computeKnownBits to determine
20672           //        whether it's safe to decanonicalize the xor?
20673           // x s< 0 ? x^C : 0 --> subus x, C
20674           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20675               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20676               OpRHSConst->getAPIntValue().isSignBit())
20677             // Note that we have to rebuild the RHS constant here to ensure we
20678             // don't rely on particular values of undef lanes.
20679             return DAG.getNode(
20680                 X86ISD::SUBUS, DL, VT, OpLHS,
20681                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20682         }
20683     }
20684   }
20685
20686   // Try to match a min/max vector operation.
20687   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20688     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20689     unsigned Opc = ret.first;
20690     bool NeedSplit = ret.second;
20691
20692     if (Opc && NeedSplit) {
20693       unsigned NumElems = VT.getVectorNumElements();
20694       // Extract the LHS vectors
20695       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20696       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20697
20698       // Extract the RHS vectors
20699       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20700       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20701
20702       // Create min/max for each subvector
20703       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20704       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20705
20706       // Merge the result
20707       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20708     } else if (Opc)
20709       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20710   }
20711
20712   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20713   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20714       // Check if SETCC has already been promoted
20715       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20716       // Check that condition value type matches vselect operand type
20717       CondVT == VT) { 
20718
20719     assert(Cond.getValueType().isVector() &&
20720            "vector select expects a vector selector!");
20721
20722     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20723     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20724
20725     if (!TValIsAllOnes && !FValIsAllZeros) {
20726       // Try invert the condition if true value is not all 1s and false value
20727       // is not all 0s.
20728       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20729       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20730
20731       if (TValIsAllZeros || FValIsAllOnes) {
20732         SDValue CC = Cond.getOperand(2);
20733         ISD::CondCode NewCC =
20734           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20735                                Cond.getOperand(0).getValueType().isInteger());
20736         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20737         std::swap(LHS, RHS);
20738         TValIsAllOnes = FValIsAllOnes;
20739         FValIsAllZeros = TValIsAllZeros;
20740       }
20741     }
20742
20743     if (TValIsAllOnes || FValIsAllZeros) {
20744       SDValue Ret;
20745
20746       if (TValIsAllOnes && FValIsAllZeros)
20747         Ret = Cond;
20748       else if (TValIsAllOnes)
20749         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20750                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20751       else if (FValIsAllZeros)
20752         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20753                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20754
20755       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20756     }
20757   }
20758
20759   // Try to fold this VSELECT into a MOVSS/MOVSD
20760   if (N->getOpcode() == ISD::VSELECT &&
20761       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20762     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20763         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20764       bool CanFold = false;
20765       unsigned NumElems = Cond.getNumOperands();
20766       SDValue A = LHS;
20767       SDValue B = RHS;
20768       
20769       if (isZero(Cond.getOperand(0))) {
20770         CanFold = true;
20771
20772         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20773         // fold (vselect <0,-1> -> (movsd A, B)
20774         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20775           CanFold = isAllOnes(Cond.getOperand(i));
20776       } else if (isAllOnes(Cond.getOperand(0))) {
20777         CanFold = true;
20778         std::swap(A, B);
20779
20780         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20781         // fold (vselect <-1,0> -> (movsd B, A)
20782         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20783           CanFold = isZero(Cond.getOperand(i));
20784       }
20785
20786       if (CanFold) {
20787         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20788           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20789         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20790       }
20791
20792       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20793         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20794         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20795         //                             (v2i64 (bitcast B)))))
20796         //
20797         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20798         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20799         //                             (v2f64 (bitcast B)))))
20800         //
20801         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20802         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20803         //                             (v2i64 (bitcast A)))))
20804         //
20805         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20806         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20807         //                             (v2f64 (bitcast A)))))
20808
20809         CanFold = (isZero(Cond.getOperand(0)) &&
20810                    isZero(Cond.getOperand(1)) &&
20811                    isAllOnes(Cond.getOperand(2)) &&
20812                    isAllOnes(Cond.getOperand(3)));
20813
20814         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20815             isAllOnes(Cond.getOperand(1)) &&
20816             isZero(Cond.getOperand(2)) &&
20817             isZero(Cond.getOperand(3))) {
20818           CanFold = true;
20819           std::swap(LHS, RHS);
20820         }
20821
20822         if (CanFold) {
20823           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20824           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20825           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20826           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20827                                                 NewB, DAG);
20828           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20829         }
20830       }
20831     }
20832   }
20833
20834   // If we know that this node is legal then we know that it is going to be
20835   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20836   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20837   // to simplify previous instructions.
20838   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20839       !DCI.isBeforeLegalize() &&
20840       // We explicitly check against v8i16 and v16i16 because, although
20841       // they're marked as Custom, they might only be legal when Cond is a
20842       // build_vector of constants. This will be taken care in a later
20843       // condition.
20844       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20845        VT != MVT::v8i16)) {
20846     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20847
20848     // Don't optimize vector selects that map to mask-registers.
20849     if (BitWidth == 1)
20850       return SDValue();
20851
20852     // Check all uses of that condition operand to check whether it will be
20853     // consumed by non-BLEND instructions, which may depend on all bits are set
20854     // properly.
20855     for (SDNode::use_iterator I = Cond->use_begin(),
20856                               E = Cond->use_end(); I != E; ++I)
20857       if (I->getOpcode() != ISD::VSELECT)
20858         // TODO: Add other opcodes eventually lowered into BLEND.
20859         return SDValue();
20860
20861     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20862     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20863
20864     APInt KnownZero, KnownOne;
20865     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20866                                           DCI.isBeforeLegalizeOps());
20867     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20868         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20869       DCI.CommitTargetLoweringOpt(TLO);
20870   }
20871
20872   // We should generate an X86ISD::BLENDI from a vselect if its argument
20873   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20874   // constants. This specific pattern gets generated when we split a
20875   // selector for a 512 bit vector in a machine without AVX512 (but with
20876   // 256-bit vectors), during legalization:
20877   //
20878   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20879   //
20880   // Iff we find this pattern and the build_vectors are built from
20881   // constants, we translate the vselect into a shuffle_vector that we
20882   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20883   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20884     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20885     if (Shuffle.getNode())
20886       return Shuffle;
20887   }
20888
20889   return SDValue();
20890 }
20891
20892 // Check whether a boolean test is testing a boolean value generated by
20893 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20894 // code.
20895 //
20896 // Simplify the following patterns:
20897 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20898 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20899 // to (Op EFLAGS Cond)
20900 //
20901 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20902 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20903 // to (Op EFLAGS !Cond)
20904 //
20905 // where Op could be BRCOND or CMOV.
20906 //
20907 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20908   // Quit if not CMP and SUB with its value result used.
20909   if (Cmp.getOpcode() != X86ISD::CMP &&
20910       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20911       return SDValue();
20912
20913   // Quit if not used as a boolean value.
20914   if (CC != X86::COND_E && CC != X86::COND_NE)
20915     return SDValue();
20916
20917   // Check CMP operands. One of them should be 0 or 1 and the other should be
20918   // an SetCC or extended from it.
20919   SDValue Op1 = Cmp.getOperand(0);
20920   SDValue Op2 = Cmp.getOperand(1);
20921
20922   SDValue SetCC;
20923   const ConstantSDNode* C = nullptr;
20924   bool needOppositeCond = (CC == X86::COND_E);
20925   bool checkAgainstTrue = false; // Is it a comparison against 1?
20926
20927   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20928     SetCC = Op2;
20929   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20930     SetCC = Op1;
20931   else // Quit if all operands are not constants.
20932     return SDValue();
20933
20934   if (C->getZExtValue() == 1) {
20935     needOppositeCond = !needOppositeCond;
20936     checkAgainstTrue = true;
20937   } else if (C->getZExtValue() != 0)
20938     // Quit if the constant is neither 0 or 1.
20939     return SDValue();
20940
20941   bool truncatedToBoolWithAnd = false;
20942   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20943   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20944          SetCC.getOpcode() == ISD::TRUNCATE ||
20945          SetCC.getOpcode() == ISD::AND) {
20946     if (SetCC.getOpcode() == ISD::AND) {
20947       int OpIdx = -1;
20948       ConstantSDNode *CS;
20949       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20950           CS->getZExtValue() == 1)
20951         OpIdx = 1;
20952       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20953           CS->getZExtValue() == 1)
20954         OpIdx = 0;
20955       if (OpIdx == -1)
20956         break;
20957       SetCC = SetCC.getOperand(OpIdx);
20958       truncatedToBoolWithAnd = true;
20959     } else
20960       SetCC = SetCC.getOperand(0);
20961   }
20962
20963   switch (SetCC.getOpcode()) {
20964   case X86ISD::SETCC_CARRY:
20965     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20966     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20967     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20968     // truncated to i1 using 'and'.
20969     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20970       break;
20971     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20972            "Invalid use of SETCC_CARRY!");
20973     // FALL THROUGH
20974   case X86ISD::SETCC:
20975     // Set the condition code or opposite one if necessary.
20976     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20977     if (needOppositeCond)
20978       CC = X86::GetOppositeBranchCondition(CC);
20979     return SetCC.getOperand(1);
20980   case X86ISD::CMOV: {
20981     // Check whether false/true value has canonical one, i.e. 0 or 1.
20982     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20983     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20984     // Quit if true value is not a constant.
20985     if (!TVal)
20986       return SDValue();
20987     // Quit if false value is not a constant.
20988     if (!FVal) {
20989       SDValue Op = SetCC.getOperand(0);
20990       // Skip 'zext' or 'trunc' node.
20991       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20992           Op.getOpcode() == ISD::TRUNCATE)
20993         Op = Op.getOperand(0);
20994       // A special case for rdrand/rdseed, where 0 is set if false cond is
20995       // found.
20996       if ((Op.getOpcode() != X86ISD::RDRAND &&
20997            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20998         return SDValue();
20999     }
21000     // Quit if false value is not the constant 0 or 1.
21001     bool FValIsFalse = true;
21002     if (FVal && FVal->getZExtValue() != 0) {
21003       if (FVal->getZExtValue() != 1)
21004         return SDValue();
21005       // If FVal is 1, opposite cond is needed.
21006       needOppositeCond = !needOppositeCond;
21007       FValIsFalse = false;
21008     }
21009     // Quit if TVal is not the constant opposite of FVal.
21010     if (FValIsFalse && TVal->getZExtValue() != 1)
21011       return SDValue();
21012     if (!FValIsFalse && TVal->getZExtValue() != 0)
21013       return SDValue();
21014     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21015     if (needOppositeCond)
21016       CC = X86::GetOppositeBranchCondition(CC);
21017     return SetCC.getOperand(3);
21018   }
21019   }
21020
21021   return SDValue();
21022 }
21023
21024 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21025 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21026                                   TargetLowering::DAGCombinerInfo &DCI,
21027                                   const X86Subtarget *Subtarget) {
21028   SDLoc DL(N);
21029
21030   // If the flag operand isn't dead, don't touch this CMOV.
21031   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21032     return SDValue();
21033
21034   SDValue FalseOp = N->getOperand(0);
21035   SDValue TrueOp = N->getOperand(1);
21036   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21037   SDValue Cond = N->getOperand(3);
21038
21039   if (CC == X86::COND_E || CC == X86::COND_NE) {
21040     switch (Cond.getOpcode()) {
21041     default: break;
21042     case X86ISD::BSR:
21043     case X86ISD::BSF:
21044       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21045       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21046         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21047     }
21048   }
21049
21050   SDValue Flags;
21051
21052   Flags = checkBoolTestSetCCCombine(Cond, CC);
21053   if (Flags.getNode() &&
21054       // Extra check as FCMOV only supports a subset of X86 cond.
21055       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21056     SDValue Ops[] = { FalseOp, TrueOp,
21057                       DAG.getConstant(CC, MVT::i8), Flags };
21058     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21059   }
21060
21061   // If this is a select between two integer constants, try to do some
21062   // optimizations.  Note that the operands are ordered the opposite of SELECT
21063   // operands.
21064   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21065     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21066       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21067       // larger than FalseC (the false value).
21068       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21069         CC = X86::GetOppositeBranchCondition(CC);
21070         std::swap(TrueC, FalseC);
21071         std::swap(TrueOp, FalseOp);
21072       }
21073
21074       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21075       // This is efficient for any integer data type (including i8/i16) and
21076       // shift amount.
21077       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21078         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21079                            DAG.getConstant(CC, MVT::i8), Cond);
21080
21081         // Zero extend the condition if needed.
21082         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21083
21084         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21085         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21086                            DAG.getConstant(ShAmt, MVT::i8));
21087         if (N->getNumValues() == 2)  // Dead flag value?
21088           return DCI.CombineTo(N, Cond, SDValue());
21089         return Cond;
21090       }
21091
21092       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21093       // for any integer data type, including i8/i16.
21094       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21095         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21096                            DAG.getConstant(CC, MVT::i8), Cond);
21097
21098         // Zero extend the condition if needed.
21099         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21100                            FalseC->getValueType(0), Cond);
21101         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21102                            SDValue(FalseC, 0));
21103
21104         if (N->getNumValues() == 2)  // Dead flag value?
21105           return DCI.CombineTo(N, Cond, SDValue());
21106         return Cond;
21107       }
21108
21109       // Optimize cases that will turn into an LEA instruction.  This requires
21110       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21111       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21112         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21113         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21114
21115         bool isFastMultiplier = false;
21116         if (Diff < 10) {
21117           switch ((unsigned char)Diff) {
21118           default: break;
21119           case 1:  // result = add base, cond
21120           case 2:  // result = lea base(    , cond*2)
21121           case 3:  // result = lea base(cond, cond*2)
21122           case 4:  // result = lea base(    , cond*4)
21123           case 5:  // result = lea base(cond, cond*4)
21124           case 8:  // result = lea base(    , cond*8)
21125           case 9:  // result = lea base(cond, cond*8)
21126             isFastMultiplier = true;
21127             break;
21128           }
21129         }
21130
21131         if (isFastMultiplier) {
21132           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21133           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21134                              DAG.getConstant(CC, MVT::i8), Cond);
21135           // Zero extend the condition if needed.
21136           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21137                              Cond);
21138           // Scale the condition by the difference.
21139           if (Diff != 1)
21140             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21141                                DAG.getConstant(Diff, Cond.getValueType()));
21142
21143           // Add the base if non-zero.
21144           if (FalseC->getAPIntValue() != 0)
21145             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21146                                SDValue(FalseC, 0));
21147           if (N->getNumValues() == 2)  // Dead flag value?
21148             return DCI.CombineTo(N, Cond, SDValue());
21149           return Cond;
21150         }
21151       }
21152     }
21153   }
21154
21155   // Handle these cases:
21156   //   (select (x != c), e, c) -> select (x != c), e, x),
21157   //   (select (x == c), c, e) -> select (x == c), x, e)
21158   // where the c is an integer constant, and the "select" is the combination
21159   // of CMOV and CMP.
21160   //
21161   // The rationale for this change is that the conditional-move from a constant
21162   // needs two instructions, however, conditional-move from a register needs
21163   // only one instruction.
21164   //
21165   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21166   //  some instruction-combining opportunities. This opt needs to be
21167   //  postponed as late as possible.
21168   //
21169   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21170     // the DCI.xxxx conditions are provided to postpone the optimization as
21171     // late as possible.
21172
21173     ConstantSDNode *CmpAgainst = nullptr;
21174     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21175         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21176         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21177
21178       if (CC == X86::COND_NE &&
21179           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21180         CC = X86::GetOppositeBranchCondition(CC);
21181         std::swap(TrueOp, FalseOp);
21182       }
21183
21184       if (CC == X86::COND_E &&
21185           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21186         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21187                           DAG.getConstant(CC, MVT::i8), Cond };
21188         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21189       }
21190     }
21191   }
21192
21193   return SDValue();
21194 }
21195
21196 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21197                                                 const X86Subtarget *Subtarget) {
21198   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21199   switch (IntNo) {
21200   default: return SDValue();
21201   // SSE/AVX/AVX2 blend intrinsics.
21202   case Intrinsic::x86_avx2_pblendvb:
21203   case Intrinsic::x86_avx2_pblendw:
21204   case Intrinsic::x86_avx2_pblendd_128:
21205   case Intrinsic::x86_avx2_pblendd_256:
21206     // Don't try to simplify this intrinsic if we don't have AVX2.
21207     if (!Subtarget->hasAVX2())
21208       return SDValue();
21209     // FALL-THROUGH
21210   case Intrinsic::x86_avx_blend_pd_256:
21211   case Intrinsic::x86_avx_blend_ps_256:
21212   case Intrinsic::x86_avx_blendv_pd_256:
21213   case Intrinsic::x86_avx_blendv_ps_256:
21214     // Don't try to simplify this intrinsic if we don't have AVX.
21215     if (!Subtarget->hasAVX())
21216       return SDValue();
21217     // FALL-THROUGH
21218   case Intrinsic::x86_sse41_pblendw:
21219   case Intrinsic::x86_sse41_blendpd:
21220   case Intrinsic::x86_sse41_blendps:
21221   case Intrinsic::x86_sse41_blendvps:
21222   case Intrinsic::x86_sse41_blendvpd:
21223   case Intrinsic::x86_sse41_pblendvb: {
21224     SDValue Op0 = N->getOperand(1);
21225     SDValue Op1 = N->getOperand(2);
21226     SDValue Mask = N->getOperand(3);
21227
21228     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21229     if (!Subtarget->hasSSE41())
21230       return SDValue();
21231
21232     // fold (blend A, A, Mask) -> A
21233     if (Op0 == Op1)
21234       return Op0;
21235     // fold (blend A, B, allZeros) -> A
21236     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21237       return Op0;
21238     // fold (blend A, B, allOnes) -> B
21239     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21240       return Op1;
21241     
21242     // Simplify the case where the mask is a constant i32 value.
21243     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21244       if (C->isNullValue())
21245         return Op0;
21246       if (C->isAllOnesValue())
21247         return Op1;
21248     }
21249
21250     return SDValue();
21251   }
21252
21253   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21254   case Intrinsic::x86_sse2_psrai_w:
21255   case Intrinsic::x86_sse2_psrai_d:
21256   case Intrinsic::x86_avx2_psrai_w:
21257   case Intrinsic::x86_avx2_psrai_d:
21258   case Intrinsic::x86_sse2_psra_w:
21259   case Intrinsic::x86_sse2_psra_d:
21260   case Intrinsic::x86_avx2_psra_w:
21261   case Intrinsic::x86_avx2_psra_d: {
21262     SDValue Op0 = N->getOperand(1);
21263     SDValue Op1 = N->getOperand(2);
21264     EVT VT = Op0.getValueType();
21265     assert(VT.isVector() && "Expected a vector type!");
21266
21267     if (isa<BuildVectorSDNode>(Op1))
21268       Op1 = Op1.getOperand(0);
21269
21270     if (!isa<ConstantSDNode>(Op1))
21271       return SDValue();
21272
21273     EVT SVT = VT.getVectorElementType();
21274     unsigned SVTBits = SVT.getSizeInBits();
21275
21276     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21277     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21278     uint64_t ShAmt = C.getZExtValue();
21279
21280     // Don't try to convert this shift into a ISD::SRA if the shift
21281     // count is bigger than or equal to the element size.
21282     if (ShAmt >= SVTBits)
21283       return SDValue();
21284
21285     // Trivial case: if the shift count is zero, then fold this
21286     // into the first operand.
21287     if (ShAmt == 0)
21288       return Op0;
21289
21290     // Replace this packed shift intrinsic with a target independent
21291     // shift dag node.
21292     SDValue Splat = DAG.getConstant(C, VT);
21293     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21294   }
21295   }
21296 }
21297
21298 /// PerformMulCombine - Optimize a single multiply with constant into two
21299 /// in order to implement it with two cheaper instructions, e.g.
21300 /// LEA + SHL, LEA + LEA.
21301 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21302                                  TargetLowering::DAGCombinerInfo &DCI) {
21303   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21304     return SDValue();
21305
21306   EVT VT = N->getValueType(0);
21307   if (VT != MVT::i64)
21308     return SDValue();
21309
21310   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21311   if (!C)
21312     return SDValue();
21313   uint64_t MulAmt = C->getZExtValue();
21314   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21315     return SDValue();
21316
21317   uint64_t MulAmt1 = 0;
21318   uint64_t MulAmt2 = 0;
21319   if ((MulAmt % 9) == 0) {
21320     MulAmt1 = 9;
21321     MulAmt2 = MulAmt / 9;
21322   } else if ((MulAmt % 5) == 0) {
21323     MulAmt1 = 5;
21324     MulAmt2 = MulAmt / 5;
21325   } else if ((MulAmt % 3) == 0) {
21326     MulAmt1 = 3;
21327     MulAmt2 = MulAmt / 3;
21328   }
21329   if (MulAmt2 &&
21330       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21331     SDLoc DL(N);
21332
21333     if (isPowerOf2_64(MulAmt2) &&
21334         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21335       // If second multiplifer is pow2, issue it first. We want the multiply by
21336       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21337       // is an add.
21338       std::swap(MulAmt1, MulAmt2);
21339
21340     SDValue NewMul;
21341     if (isPowerOf2_64(MulAmt1))
21342       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21343                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21344     else
21345       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21346                            DAG.getConstant(MulAmt1, VT));
21347
21348     if (isPowerOf2_64(MulAmt2))
21349       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21350                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21351     else
21352       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21353                            DAG.getConstant(MulAmt2, VT));
21354
21355     // Do not add new nodes to DAG combiner worklist.
21356     DCI.CombineTo(N, NewMul, false);
21357   }
21358   return SDValue();
21359 }
21360
21361 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21362   SDValue N0 = N->getOperand(0);
21363   SDValue N1 = N->getOperand(1);
21364   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21365   EVT VT = N0.getValueType();
21366
21367   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21368   // since the result of setcc_c is all zero's or all ones.
21369   if (VT.isInteger() && !VT.isVector() &&
21370       N1C && N0.getOpcode() == ISD::AND &&
21371       N0.getOperand(1).getOpcode() == ISD::Constant) {
21372     SDValue N00 = N0.getOperand(0);
21373     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21374         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21375           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21376          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21377       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21378       APInt ShAmt = N1C->getAPIntValue();
21379       Mask = Mask.shl(ShAmt);
21380       if (Mask != 0)
21381         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21382                            N00, DAG.getConstant(Mask, VT));
21383     }
21384   }
21385
21386   // Hardware support for vector shifts is sparse which makes us scalarize the
21387   // vector operations in many cases. Also, on sandybridge ADD is faster than
21388   // shl.
21389   // (shl V, 1) -> add V,V
21390   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21391     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21392       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21393       // We shift all of the values by one. In many cases we do not have
21394       // hardware support for this operation. This is better expressed as an ADD
21395       // of two values.
21396       if (N1SplatC->getZExtValue() == 1)
21397         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21398     }
21399
21400   return SDValue();
21401 }
21402
21403 /// \brief Returns a vector of 0s if the node in input is a vector logical
21404 /// shift by a constant amount which is known to be bigger than or equal
21405 /// to the vector element size in bits.
21406 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21407                                       const X86Subtarget *Subtarget) {
21408   EVT VT = N->getValueType(0);
21409
21410   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21411       (!Subtarget->hasInt256() ||
21412        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21413     return SDValue();
21414
21415   SDValue Amt = N->getOperand(1);
21416   SDLoc DL(N);
21417   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21418     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21419       APInt ShiftAmt = AmtSplat->getAPIntValue();
21420       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21421
21422       // SSE2/AVX2 logical shifts always return a vector of 0s
21423       // if the shift amount is bigger than or equal to
21424       // the element size. The constant shift amount will be
21425       // encoded as a 8-bit immediate.
21426       if (ShiftAmt.trunc(8).uge(MaxAmount))
21427         return getZeroVector(VT, Subtarget, DAG, DL);
21428     }
21429
21430   return SDValue();
21431 }
21432
21433 /// PerformShiftCombine - Combine shifts.
21434 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21435                                    TargetLowering::DAGCombinerInfo &DCI,
21436                                    const X86Subtarget *Subtarget) {
21437   if (N->getOpcode() == ISD::SHL) {
21438     SDValue V = PerformSHLCombine(N, DAG);
21439     if (V.getNode()) return V;
21440   }
21441
21442   if (N->getOpcode() != ISD::SRA) {
21443     // Try to fold this logical shift into a zero vector.
21444     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21445     if (V.getNode()) return V;
21446   }
21447
21448   return SDValue();
21449 }
21450
21451 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21452 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21453 // and friends.  Likewise for OR -> CMPNEQSS.
21454 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21455                             TargetLowering::DAGCombinerInfo &DCI,
21456                             const X86Subtarget *Subtarget) {
21457   unsigned opcode;
21458
21459   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21460   // we're requiring SSE2 for both.
21461   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21462     SDValue N0 = N->getOperand(0);
21463     SDValue N1 = N->getOperand(1);
21464     SDValue CMP0 = N0->getOperand(1);
21465     SDValue CMP1 = N1->getOperand(1);
21466     SDLoc DL(N);
21467
21468     // The SETCCs should both refer to the same CMP.
21469     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21470       return SDValue();
21471
21472     SDValue CMP00 = CMP0->getOperand(0);
21473     SDValue CMP01 = CMP0->getOperand(1);
21474     EVT     VT    = CMP00.getValueType();
21475
21476     if (VT == MVT::f32 || VT == MVT::f64) {
21477       bool ExpectingFlags = false;
21478       // Check for any users that want flags:
21479       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21480            !ExpectingFlags && UI != UE; ++UI)
21481         switch (UI->getOpcode()) {
21482         default:
21483         case ISD::BR_CC:
21484         case ISD::BRCOND:
21485         case ISD::SELECT:
21486           ExpectingFlags = true;
21487           break;
21488         case ISD::CopyToReg:
21489         case ISD::SIGN_EXTEND:
21490         case ISD::ZERO_EXTEND:
21491         case ISD::ANY_EXTEND:
21492           break;
21493         }
21494
21495       if (!ExpectingFlags) {
21496         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21497         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21498
21499         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21500           X86::CondCode tmp = cc0;
21501           cc0 = cc1;
21502           cc1 = tmp;
21503         }
21504
21505         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21506             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21507           // FIXME: need symbolic constants for these magic numbers.
21508           // See X86ATTInstPrinter.cpp:printSSECC().
21509           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21510           if (Subtarget->hasAVX512()) {
21511             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21512                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21513             if (N->getValueType(0) != MVT::i1)
21514               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21515                                  FSetCC);
21516             return FSetCC;
21517           }
21518           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21519                                               CMP00.getValueType(), CMP00, CMP01,
21520                                               DAG.getConstant(x86cc, MVT::i8));
21521
21522           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21523           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21524
21525           if (is64BitFP && !Subtarget->is64Bit()) {
21526             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21527             // 64-bit integer, since that's not a legal type. Since
21528             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21529             // bits, but can do this little dance to extract the lowest 32 bits
21530             // and work with those going forward.
21531             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21532                                            OnesOrZeroesF);
21533             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21534                                            Vector64);
21535             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21536                                         Vector32, DAG.getIntPtrConstant(0));
21537             IntVT = MVT::i32;
21538           }
21539
21540           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21541           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21542                                       DAG.getConstant(1, IntVT));
21543           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21544           return OneBitOfTruth;
21545         }
21546       }
21547     }
21548   }
21549   return SDValue();
21550 }
21551
21552 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21553 /// so it can be folded inside ANDNP.
21554 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21555   EVT VT = N->getValueType(0);
21556
21557   // Match direct AllOnes for 128 and 256-bit vectors
21558   if (ISD::isBuildVectorAllOnes(N))
21559     return true;
21560
21561   // Look through a bit convert.
21562   if (N->getOpcode() == ISD::BITCAST)
21563     N = N->getOperand(0).getNode();
21564
21565   // Sometimes the operand may come from a insert_subvector building a 256-bit
21566   // allones vector
21567   if (VT.is256BitVector() &&
21568       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21569     SDValue V1 = N->getOperand(0);
21570     SDValue V2 = N->getOperand(1);
21571
21572     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21573         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21574         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21575         ISD::isBuildVectorAllOnes(V2.getNode()))
21576       return true;
21577   }
21578
21579   return false;
21580 }
21581
21582 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21583 // register. In most cases we actually compare or select YMM-sized registers
21584 // and mixing the two types creates horrible code. This method optimizes
21585 // some of the transition sequences.
21586 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21587                                  TargetLowering::DAGCombinerInfo &DCI,
21588                                  const X86Subtarget *Subtarget) {
21589   EVT VT = N->getValueType(0);
21590   if (!VT.is256BitVector())
21591     return SDValue();
21592
21593   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21594           N->getOpcode() == ISD::ZERO_EXTEND ||
21595           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21596
21597   SDValue Narrow = N->getOperand(0);
21598   EVT NarrowVT = Narrow->getValueType(0);
21599   if (!NarrowVT.is128BitVector())
21600     return SDValue();
21601
21602   if (Narrow->getOpcode() != ISD::XOR &&
21603       Narrow->getOpcode() != ISD::AND &&
21604       Narrow->getOpcode() != ISD::OR)
21605     return SDValue();
21606
21607   SDValue N0  = Narrow->getOperand(0);
21608   SDValue N1  = Narrow->getOperand(1);
21609   SDLoc DL(Narrow);
21610
21611   // The Left side has to be a trunc.
21612   if (N0.getOpcode() != ISD::TRUNCATE)
21613     return SDValue();
21614
21615   // The type of the truncated inputs.
21616   EVT WideVT = N0->getOperand(0)->getValueType(0);
21617   if (WideVT != VT)
21618     return SDValue();
21619
21620   // The right side has to be a 'trunc' or a constant vector.
21621   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21622   ConstantSDNode *RHSConstSplat = nullptr;
21623   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21624     RHSConstSplat = RHSBV->getConstantSplatNode();
21625   if (!RHSTrunc && !RHSConstSplat)
21626     return SDValue();
21627
21628   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21629
21630   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21631     return SDValue();
21632
21633   // Set N0 and N1 to hold the inputs to the new wide operation.
21634   N0 = N0->getOperand(0);
21635   if (RHSConstSplat) {
21636     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21637                      SDValue(RHSConstSplat, 0));
21638     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21639     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21640   } else if (RHSTrunc) {
21641     N1 = N1->getOperand(0);
21642   }
21643
21644   // Generate the wide operation.
21645   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21646   unsigned Opcode = N->getOpcode();
21647   switch (Opcode) {
21648   case ISD::ANY_EXTEND:
21649     return Op;
21650   case ISD::ZERO_EXTEND: {
21651     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21652     APInt Mask = APInt::getAllOnesValue(InBits);
21653     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21654     return DAG.getNode(ISD::AND, DL, VT,
21655                        Op, DAG.getConstant(Mask, VT));
21656   }
21657   case ISD::SIGN_EXTEND:
21658     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21659                        Op, DAG.getValueType(NarrowVT));
21660   default:
21661     llvm_unreachable("Unexpected opcode");
21662   }
21663 }
21664
21665 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21666                                  TargetLowering::DAGCombinerInfo &DCI,
21667                                  const X86Subtarget *Subtarget) {
21668   EVT VT = N->getValueType(0);
21669   if (DCI.isBeforeLegalizeOps())
21670     return SDValue();
21671
21672   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21673   if (R.getNode())
21674     return R;
21675
21676   // Create BEXTR instructions
21677   // BEXTR is ((X >> imm) & (2**size-1))
21678   if (VT == MVT::i32 || VT == MVT::i64) {
21679     SDValue N0 = N->getOperand(0);
21680     SDValue N1 = N->getOperand(1);
21681     SDLoc DL(N);
21682
21683     // Check for BEXTR.
21684     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21685         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21686       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21687       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21688       if (MaskNode && ShiftNode) {
21689         uint64_t Mask = MaskNode->getZExtValue();
21690         uint64_t Shift = ShiftNode->getZExtValue();
21691         if (isMask_64(Mask)) {
21692           uint64_t MaskSize = CountPopulation_64(Mask);
21693           if (Shift + MaskSize <= VT.getSizeInBits())
21694             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21695                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21696         }
21697       }
21698     } // BEXTR
21699
21700     return SDValue();
21701   }
21702
21703   // Want to form ANDNP nodes:
21704   // 1) In the hopes of then easily combining them with OR and AND nodes
21705   //    to form PBLEND/PSIGN.
21706   // 2) To match ANDN packed intrinsics
21707   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21708     return SDValue();
21709
21710   SDValue N0 = N->getOperand(0);
21711   SDValue N1 = N->getOperand(1);
21712   SDLoc DL(N);
21713
21714   // Check LHS for vnot
21715   if (N0.getOpcode() == ISD::XOR &&
21716       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21717       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21718     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21719
21720   // Check RHS for vnot
21721   if (N1.getOpcode() == ISD::XOR &&
21722       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21723       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21724     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21725
21726   return SDValue();
21727 }
21728
21729 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21730                                 TargetLowering::DAGCombinerInfo &DCI,
21731                                 const X86Subtarget *Subtarget) {
21732   if (DCI.isBeforeLegalizeOps())
21733     return SDValue();
21734
21735   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21736   if (R.getNode())
21737     return R;
21738
21739   SDValue N0 = N->getOperand(0);
21740   SDValue N1 = N->getOperand(1);
21741   EVT VT = N->getValueType(0);
21742
21743   // look for psign/blend
21744   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21745     if (!Subtarget->hasSSSE3() ||
21746         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21747       return SDValue();
21748
21749     // Canonicalize pandn to RHS
21750     if (N0.getOpcode() == X86ISD::ANDNP)
21751       std::swap(N0, N1);
21752     // or (and (m, y), (pandn m, x))
21753     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21754       SDValue Mask = N1.getOperand(0);
21755       SDValue X    = N1.getOperand(1);
21756       SDValue Y;
21757       if (N0.getOperand(0) == Mask)
21758         Y = N0.getOperand(1);
21759       if (N0.getOperand(1) == Mask)
21760         Y = N0.getOperand(0);
21761
21762       // Check to see if the mask appeared in both the AND and ANDNP and
21763       if (!Y.getNode())
21764         return SDValue();
21765
21766       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21767       // Look through mask bitcast.
21768       if (Mask.getOpcode() == ISD::BITCAST)
21769         Mask = Mask.getOperand(0);
21770       if (X.getOpcode() == ISD::BITCAST)
21771         X = X.getOperand(0);
21772       if (Y.getOpcode() == ISD::BITCAST)
21773         Y = Y.getOperand(0);
21774
21775       EVT MaskVT = Mask.getValueType();
21776
21777       // Validate that the Mask operand is a vector sra node.
21778       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21779       // there is no psrai.b
21780       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21781       unsigned SraAmt = ~0;
21782       if (Mask.getOpcode() == ISD::SRA) {
21783         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21784           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21785             SraAmt = AmtConst->getZExtValue();
21786       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21787         SDValue SraC = Mask.getOperand(1);
21788         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21789       }
21790       if ((SraAmt + 1) != EltBits)
21791         return SDValue();
21792
21793       SDLoc DL(N);
21794
21795       // Now we know we at least have a plendvb with the mask val.  See if
21796       // we can form a psignb/w/d.
21797       // psign = x.type == y.type == mask.type && y = sub(0, x);
21798       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21799           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21800           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21801         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21802                "Unsupported VT for PSIGN");
21803         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21804         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21805       }
21806       // PBLENDVB only available on SSE 4.1
21807       if (!Subtarget->hasSSE41())
21808         return SDValue();
21809
21810       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21811
21812       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21813       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21814       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21815       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21816       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21817     }
21818   }
21819
21820   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21821     return SDValue();
21822
21823   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21824   MachineFunction &MF = DAG.getMachineFunction();
21825   bool OptForSize = MF.getFunction()->getAttributes().
21826     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21827
21828   // SHLD/SHRD instructions have lower register pressure, but on some
21829   // platforms they have higher latency than the equivalent
21830   // series of shifts/or that would otherwise be generated.
21831   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21832   // have higher latencies and we are not optimizing for size.
21833   if (!OptForSize && Subtarget->isSHLDSlow())
21834     return SDValue();
21835
21836   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21837     std::swap(N0, N1);
21838   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21839     return SDValue();
21840   if (!N0.hasOneUse() || !N1.hasOneUse())
21841     return SDValue();
21842
21843   SDValue ShAmt0 = N0.getOperand(1);
21844   if (ShAmt0.getValueType() != MVT::i8)
21845     return SDValue();
21846   SDValue ShAmt1 = N1.getOperand(1);
21847   if (ShAmt1.getValueType() != MVT::i8)
21848     return SDValue();
21849   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21850     ShAmt0 = ShAmt0.getOperand(0);
21851   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21852     ShAmt1 = ShAmt1.getOperand(0);
21853
21854   SDLoc DL(N);
21855   unsigned Opc = X86ISD::SHLD;
21856   SDValue Op0 = N0.getOperand(0);
21857   SDValue Op1 = N1.getOperand(0);
21858   if (ShAmt0.getOpcode() == ISD::SUB) {
21859     Opc = X86ISD::SHRD;
21860     std::swap(Op0, Op1);
21861     std::swap(ShAmt0, ShAmt1);
21862   }
21863
21864   unsigned Bits = VT.getSizeInBits();
21865   if (ShAmt1.getOpcode() == ISD::SUB) {
21866     SDValue Sum = ShAmt1.getOperand(0);
21867     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21868       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21869       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21870         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21871       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21872         return DAG.getNode(Opc, DL, VT,
21873                            Op0, Op1,
21874                            DAG.getNode(ISD::TRUNCATE, DL,
21875                                        MVT::i8, ShAmt0));
21876     }
21877   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21878     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21879     if (ShAmt0C &&
21880         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21881       return DAG.getNode(Opc, DL, VT,
21882                          N0.getOperand(0), N1.getOperand(0),
21883                          DAG.getNode(ISD::TRUNCATE, DL,
21884                                        MVT::i8, ShAmt0));
21885   }
21886
21887   return SDValue();
21888 }
21889
21890 // Generate NEG and CMOV for integer abs.
21891 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21892   EVT VT = N->getValueType(0);
21893
21894   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21895   // 8-bit integer abs to NEG and CMOV.
21896   if (VT.isInteger() && VT.getSizeInBits() == 8)
21897     return SDValue();
21898
21899   SDValue N0 = N->getOperand(0);
21900   SDValue N1 = N->getOperand(1);
21901   SDLoc DL(N);
21902
21903   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21904   // and change it to SUB and CMOV.
21905   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21906       N0.getOpcode() == ISD::ADD &&
21907       N0.getOperand(1) == N1 &&
21908       N1.getOpcode() == ISD::SRA &&
21909       N1.getOperand(0) == N0.getOperand(0))
21910     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21911       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21912         // Generate SUB & CMOV.
21913         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21914                                   DAG.getConstant(0, VT), N0.getOperand(0));
21915
21916         SDValue Ops[] = { N0.getOperand(0), Neg,
21917                           DAG.getConstant(X86::COND_GE, MVT::i8),
21918                           SDValue(Neg.getNode(), 1) };
21919         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21920       }
21921   return SDValue();
21922 }
21923
21924 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21925 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21926                                  TargetLowering::DAGCombinerInfo &DCI,
21927                                  const X86Subtarget *Subtarget) {
21928   if (DCI.isBeforeLegalizeOps())
21929     return SDValue();
21930
21931   if (Subtarget->hasCMov()) {
21932     SDValue RV = performIntegerAbsCombine(N, DAG);
21933     if (RV.getNode())
21934       return RV;
21935   }
21936
21937   return SDValue();
21938 }
21939
21940 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21941 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21942                                   TargetLowering::DAGCombinerInfo &DCI,
21943                                   const X86Subtarget *Subtarget) {
21944   LoadSDNode *Ld = cast<LoadSDNode>(N);
21945   EVT RegVT = Ld->getValueType(0);
21946   EVT MemVT = Ld->getMemoryVT();
21947   SDLoc dl(Ld);
21948   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21949
21950   // On Sandybridge unaligned 256bit loads are inefficient.
21951   ISD::LoadExtType Ext = Ld->getExtensionType();
21952   unsigned Alignment = Ld->getAlignment();
21953   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21954   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21955       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21956     unsigned NumElems = RegVT.getVectorNumElements();
21957     if (NumElems < 2)
21958       return SDValue();
21959
21960     SDValue Ptr = Ld->getBasePtr();
21961     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21962
21963     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21964                                   NumElems/2);
21965     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21966                                 Ld->getPointerInfo(), Ld->isVolatile(),
21967                                 Ld->isNonTemporal(), Ld->isInvariant(),
21968                                 Alignment);
21969     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21970     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21971                                 Ld->getPointerInfo(), Ld->isVolatile(),
21972                                 Ld->isNonTemporal(), Ld->isInvariant(),
21973                                 std::min(16U, Alignment));
21974     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21975                              Load1.getValue(1),
21976                              Load2.getValue(1));
21977
21978     SDValue NewVec = DAG.getUNDEF(RegVT);
21979     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21980     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21981     return DCI.CombineTo(N, NewVec, TF, true);
21982   }
21983
21984   return SDValue();
21985 }
21986
21987 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21988 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21989                                    const X86Subtarget *Subtarget) {
21990   StoreSDNode *St = cast<StoreSDNode>(N);
21991   EVT VT = St->getValue().getValueType();
21992   EVT StVT = St->getMemoryVT();
21993   SDLoc dl(St);
21994   SDValue StoredVal = St->getOperand(1);
21995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21996
21997   // If we are saving a concatenation of two XMM registers, perform two stores.
21998   // On Sandy Bridge, 256-bit memory operations are executed by two
21999   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
22000   // memory  operation.
22001   unsigned Alignment = St->getAlignment();
22002   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22003   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
22004       StVT == VT && !IsAligned) {
22005     unsigned NumElems = VT.getVectorNumElements();
22006     if (NumElems < 2)
22007       return SDValue();
22008
22009     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22010     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22011
22012     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22013     SDValue Ptr0 = St->getBasePtr();
22014     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22015
22016     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22017                                 St->getPointerInfo(), St->isVolatile(),
22018                                 St->isNonTemporal(), Alignment);
22019     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22020                                 St->getPointerInfo(), St->isVolatile(),
22021                                 St->isNonTemporal(),
22022                                 std::min(16U, Alignment));
22023     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22024   }
22025
22026   // Optimize trunc store (of multiple scalars) to shuffle and store.
22027   // First, pack all of the elements in one place. Next, store to memory
22028   // in fewer chunks.
22029   if (St->isTruncatingStore() && VT.isVector()) {
22030     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22031     unsigned NumElems = VT.getVectorNumElements();
22032     assert(StVT != VT && "Cannot truncate to the same type");
22033     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22034     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22035
22036     // From, To sizes and ElemCount must be pow of two
22037     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22038     // We are going to use the original vector elt for storing.
22039     // Accumulated smaller vector elements must be a multiple of the store size.
22040     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22041
22042     unsigned SizeRatio  = FromSz / ToSz;
22043
22044     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22045
22046     // Create a type on which we perform the shuffle
22047     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22048             StVT.getScalarType(), NumElems*SizeRatio);
22049
22050     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22051
22052     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22053     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22054     for (unsigned i = 0; i != NumElems; ++i)
22055       ShuffleVec[i] = i * SizeRatio;
22056
22057     // Can't shuffle using an illegal type.
22058     if (!TLI.isTypeLegal(WideVecVT))
22059       return SDValue();
22060
22061     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22062                                          DAG.getUNDEF(WideVecVT),
22063                                          &ShuffleVec[0]);
22064     // At this point all of the data is stored at the bottom of the
22065     // register. We now need to save it to mem.
22066
22067     // Find the largest store unit
22068     MVT StoreType = MVT::i8;
22069     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
22070          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
22071       MVT Tp = (MVT::SimpleValueType)tp;
22072       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22073         StoreType = Tp;
22074     }
22075
22076     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22077     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22078         (64 <= NumElems * ToSz))
22079       StoreType = MVT::f64;
22080
22081     // Bitcast the original vector into a vector of store-size units
22082     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22083             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22084     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22085     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22086     SmallVector<SDValue, 8> Chains;
22087     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22088                                         TLI.getPointerTy());
22089     SDValue Ptr = St->getBasePtr();
22090
22091     // Perform one or more big stores into memory.
22092     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22093       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22094                                    StoreType, ShuffWide,
22095                                    DAG.getIntPtrConstant(i));
22096       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22097                                 St->getPointerInfo(), St->isVolatile(),
22098                                 St->isNonTemporal(), St->getAlignment());
22099       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22100       Chains.push_back(Ch);
22101     }
22102
22103     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22104   }
22105
22106   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22107   // the FP state in cases where an emms may be missing.
22108   // A preferable solution to the general problem is to figure out the right
22109   // places to insert EMMS.  This qualifies as a quick hack.
22110
22111   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22112   if (VT.getSizeInBits() != 64)
22113     return SDValue();
22114
22115   const Function *F = DAG.getMachineFunction().getFunction();
22116   bool NoImplicitFloatOps = F->getAttributes().
22117     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
22118   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22119                      && Subtarget->hasSSE2();
22120   if ((VT.isVector() ||
22121        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22122       isa<LoadSDNode>(St->getValue()) &&
22123       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22124       St->getChain().hasOneUse() && !St->isVolatile()) {
22125     SDNode* LdVal = St->getValue().getNode();
22126     LoadSDNode *Ld = nullptr;
22127     int TokenFactorIndex = -1;
22128     SmallVector<SDValue, 8> Ops;
22129     SDNode* ChainVal = St->getChain().getNode();
22130     // Must be a store of a load.  We currently handle two cases:  the load
22131     // is a direct child, and it's under an intervening TokenFactor.  It is
22132     // possible to dig deeper under nested TokenFactors.
22133     if (ChainVal == LdVal)
22134       Ld = cast<LoadSDNode>(St->getChain());
22135     else if (St->getValue().hasOneUse() &&
22136              ChainVal->getOpcode() == ISD::TokenFactor) {
22137       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22138         if (ChainVal->getOperand(i).getNode() == LdVal) {
22139           TokenFactorIndex = i;
22140           Ld = cast<LoadSDNode>(St->getValue());
22141         } else
22142           Ops.push_back(ChainVal->getOperand(i));
22143       }
22144     }
22145
22146     if (!Ld || !ISD::isNormalLoad(Ld))
22147       return SDValue();
22148
22149     // If this is not the MMX case, i.e. we are just turning i64 load/store
22150     // into f64 load/store, avoid the transformation if there are multiple
22151     // uses of the loaded value.
22152     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22153       return SDValue();
22154
22155     SDLoc LdDL(Ld);
22156     SDLoc StDL(N);
22157     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22158     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22159     // pair instead.
22160     if (Subtarget->is64Bit() || F64IsLegal) {
22161       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22162       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22163                                   Ld->getPointerInfo(), Ld->isVolatile(),
22164                                   Ld->isNonTemporal(), Ld->isInvariant(),
22165                                   Ld->getAlignment());
22166       SDValue NewChain = NewLd.getValue(1);
22167       if (TokenFactorIndex != -1) {
22168         Ops.push_back(NewChain);
22169         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22170       }
22171       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22172                           St->getPointerInfo(),
22173                           St->isVolatile(), St->isNonTemporal(),
22174                           St->getAlignment());
22175     }
22176
22177     // Otherwise, lower to two pairs of 32-bit loads / stores.
22178     SDValue LoAddr = Ld->getBasePtr();
22179     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22180                                  DAG.getConstant(4, MVT::i32));
22181
22182     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22183                                Ld->getPointerInfo(),
22184                                Ld->isVolatile(), Ld->isNonTemporal(),
22185                                Ld->isInvariant(), Ld->getAlignment());
22186     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22187                                Ld->getPointerInfo().getWithOffset(4),
22188                                Ld->isVolatile(), Ld->isNonTemporal(),
22189                                Ld->isInvariant(),
22190                                MinAlign(Ld->getAlignment(), 4));
22191
22192     SDValue NewChain = LoLd.getValue(1);
22193     if (TokenFactorIndex != -1) {
22194       Ops.push_back(LoLd);
22195       Ops.push_back(HiLd);
22196       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22197     }
22198
22199     LoAddr = St->getBasePtr();
22200     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22201                          DAG.getConstant(4, MVT::i32));
22202
22203     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22204                                 St->getPointerInfo(),
22205                                 St->isVolatile(), St->isNonTemporal(),
22206                                 St->getAlignment());
22207     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22208                                 St->getPointerInfo().getWithOffset(4),
22209                                 St->isVolatile(),
22210                                 St->isNonTemporal(),
22211                                 MinAlign(St->getAlignment(), 4));
22212     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22213   }
22214   return SDValue();
22215 }
22216
22217 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22218 /// and return the operands for the horizontal operation in LHS and RHS.  A
22219 /// horizontal operation performs the binary operation on successive elements
22220 /// of its first operand, then on successive elements of its second operand,
22221 /// returning the resulting values in a vector.  For example, if
22222 ///   A = < float a0, float a1, float a2, float a3 >
22223 /// and
22224 ///   B = < float b0, float b1, float b2, float b3 >
22225 /// then the result of doing a horizontal operation on A and B is
22226 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22227 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22228 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22229 /// set to A, RHS to B, and the routine returns 'true'.
22230 /// Note that the binary operation should have the property that if one of the
22231 /// operands is UNDEF then the result is UNDEF.
22232 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22233   // Look for the following pattern: if
22234   //   A = < float a0, float a1, float a2, float a3 >
22235   //   B = < float b0, float b1, float b2, float b3 >
22236   // and
22237   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22238   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22239   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22240   // which is A horizontal-op B.
22241
22242   // At least one of the operands should be a vector shuffle.
22243   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22244       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22245     return false;
22246
22247   MVT VT = LHS.getSimpleValueType();
22248
22249   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22250          "Unsupported vector type for horizontal add/sub");
22251
22252   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22253   // operate independently on 128-bit lanes.
22254   unsigned NumElts = VT.getVectorNumElements();
22255   unsigned NumLanes = VT.getSizeInBits()/128;
22256   unsigned NumLaneElts = NumElts / NumLanes;
22257   assert((NumLaneElts % 2 == 0) &&
22258          "Vector type should have an even number of elements in each lane");
22259   unsigned HalfLaneElts = NumLaneElts/2;
22260
22261   // View LHS in the form
22262   //   LHS = VECTOR_SHUFFLE A, B, LMask
22263   // If LHS is not a shuffle then pretend it is the shuffle
22264   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22265   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22266   // type VT.
22267   SDValue A, B;
22268   SmallVector<int, 16> LMask(NumElts);
22269   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22270     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22271       A = LHS.getOperand(0);
22272     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22273       B = LHS.getOperand(1);
22274     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22275     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22276   } else {
22277     if (LHS.getOpcode() != ISD::UNDEF)
22278       A = LHS;
22279     for (unsigned i = 0; i != NumElts; ++i)
22280       LMask[i] = i;
22281   }
22282
22283   // Likewise, view RHS in the form
22284   //   RHS = VECTOR_SHUFFLE C, D, RMask
22285   SDValue C, D;
22286   SmallVector<int, 16> RMask(NumElts);
22287   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22288     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22289       C = RHS.getOperand(0);
22290     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22291       D = RHS.getOperand(1);
22292     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22293     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22294   } else {
22295     if (RHS.getOpcode() != ISD::UNDEF)
22296       C = RHS;
22297     for (unsigned i = 0; i != NumElts; ++i)
22298       RMask[i] = i;
22299   }
22300
22301   // Check that the shuffles are both shuffling the same vectors.
22302   if (!(A == C && B == D) && !(A == D && B == C))
22303     return false;
22304
22305   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22306   if (!A.getNode() && !B.getNode())
22307     return false;
22308
22309   // If A and B occur in reverse order in RHS, then "swap" them (which means
22310   // rewriting the mask).
22311   if (A != C)
22312     CommuteVectorShuffleMask(RMask, NumElts);
22313
22314   // At this point LHS and RHS are equivalent to
22315   //   LHS = VECTOR_SHUFFLE A, B, LMask
22316   //   RHS = VECTOR_SHUFFLE A, B, RMask
22317   // Check that the masks correspond to performing a horizontal operation.
22318   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22319     for (unsigned i = 0; i != NumLaneElts; ++i) {
22320       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22321
22322       // Ignore any UNDEF components.
22323       if (LIdx < 0 || RIdx < 0 ||
22324           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22325           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22326         continue;
22327
22328       // Check that successive elements are being operated on.  If not, this is
22329       // not a horizontal operation.
22330       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22331       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22332       if (!(LIdx == Index && RIdx == Index + 1) &&
22333           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22334         return false;
22335     }
22336   }
22337
22338   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22339   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22340   return true;
22341 }
22342
22343 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22344 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22345                                   const X86Subtarget *Subtarget) {
22346   EVT VT = N->getValueType(0);
22347   SDValue LHS = N->getOperand(0);
22348   SDValue RHS = N->getOperand(1);
22349
22350   // Try to synthesize horizontal adds from adds of shuffles.
22351   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22352        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22353       isHorizontalBinOp(LHS, RHS, true))
22354     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22355   return SDValue();
22356 }
22357
22358 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22359 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22360                                   const X86Subtarget *Subtarget) {
22361   EVT VT = N->getValueType(0);
22362   SDValue LHS = N->getOperand(0);
22363   SDValue RHS = N->getOperand(1);
22364
22365   // Try to synthesize horizontal subs from subs of shuffles.
22366   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22367        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22368       isHorizontalBinOp(LHS, RHS, false))
22369     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22370   return SDValue();
22371 }
22372
22373 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22374 /// X86ISD::FXOR nodes.
22375 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22376   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22377   // F[X]OR(0.0, x) -> x
22378   // F[X]OR(x, 0.0) -> x
22379   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22380     if (C->getValueAPF().isPosZero())
22381       return N->getOperand(1);
22382   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22383     if (C->getValueAPF().isPosZero())
22384       return N->getOperand(0);
22385   return SDValue();
22386 }
22387
22388 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22389 /// X86ISD::FMAX nodes.
22390 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22391   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22392
22393   // Only perform optimizations if UnsafeMath is used.
22394   if (!DAG.getTarget().Options.UnsafeFPMath)
22395     return SDValue();
22396
22397   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22398   // into FMINC and FMAXC, which are Commutative operations.
22399   unsigned NewOp = 0;
22400   switch (N->getOpcode()) {
22401     default: llvm_unreachable("unknown opcode");
22402     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22403     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22404   }
22405
22406   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22407                      N->getOperand(0), N->getOperand(1));
22408 }
22409
22410 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22411 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22412   // FAND(0.0, x) -> 0.0
22413   // FAND(x, 0.0) -> 0.0
22414   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22415     if (C->getValueAPF().isPosZero())
22416       return N->getOperand(0);
22417   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22418     if (C->getValueAPF().isPosZero())
22419       return N->getOperand(1);
22420   return SDValue();
22421 }
22422
22423 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22424 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22425   // FANDN(x, 0.0) -> 0.0
22426   // FANDN(0.0, x) -> x
22427   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22428     if (C->getValueAPF().isPosZero())
22429       return N->getOperand(1);
22430   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22431     if (C->getValueAPF().isPosZero())
22432       return N->getOperand(1);
22433   return SDValue();
22434 }
22435
22436 static SDValue PerformBTCombine(SDNode *N,
22437                                 SelectionDAG &DAG,
22438                                 TargetLowering::DAGCombinerInfo &DCI) {
22439   // BT ignores high bits in the bit index operand.
22440   SDValue Op1 = N->getOperand(1);
22441   if (Op1.hasOneUse()) {
22442     unsigned BitWidth = Op1.getValueSizeInBits();
22443     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22444     APInt KnownZero, KnownOne;
22445     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22446                                           !DCI.isBeforeLegalizeOps());
22447     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22448     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22449         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22450       DCI.CommitTargetLoweringOpt(TLO);
22451   }
22452   return SDValue();
22453 }
22454
22455 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22456   SDValue Op = N->getOperand(0);
22457   if (Op.getOpcode() == ISD::BITCAST)
22458     Op = Op.getOperand(0);
22459   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22460   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22461       VT.getVectorElementType().getSizeInBits() ==
22462       OpVT.getVectorElementType().getSizeInBits()) {
22463     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22464   }
22465   return SDValue();
22466 }
22467
22468 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22469                                                const X86Subtarget *Subtarget) {
22470   EVT VT = N->getValueType(0);
22471   if (!VT.isVector())
22472     return SDValue();
22473
22474   SDValue N0 = N->getOperand(0);
22475   SDValue N1 = N->getOperand(1);
22476   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22477   SDLoc dl(N);
22478
22479   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22480   // both SSE and AVX2 since there is no sign-extended shift right
22481   // operation on a vector with 64-bit elements.
22482   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22483   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22484   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22485       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22486     SDValue N00 = N0.getOperand(0);
22487
22488     // EXTLOAD has a better solution on AVX2,
22489     // it may be replaced with X86ISD::VSEXT node.
22490     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22491       if (!ISD::isNormalLoad(N00.getNode()))
22492         return SDValue();
22493
22494     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22495         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22496                                   N00, N1);
22497       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22498     }
22499   }
22500   return SDValue();
22501 }
22502
22503 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22504                                   TargetLowering::DAGCombinerInfo &DCI,
22505                                   const X86Subtarget *Subtarget) {
22506   if (!DCI.isBeforeLegalizeOps())
22507     return SDValue();
22508
22509   if (!Subtarget->hasFp256())
22510     return SDValue();
22511
22512   EVT VT = N->getValueType(0);
22513   if (VT.isVector() && VT.getSizeInBits() == 256) {
22514     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22515     if (R.getNode())
22516       return R;
22517   }
22518
22519   return SDValue();
22520 }
22521
22522 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22523                                  const X86Subtarget* Subtarget) {
22524   SDLoc dl(N);
22525   EVT VT = N->getValueType(0);
22526
22527   // Let legalize expand this if it isn't a legal type yet.
22528   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22529     return SDValue();
22530
22531   EVT ScalarVT = VT.getScalarType();
22532   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22533       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22534     return SDValue();
22535
22536   SDValue A = N->getOperand(0);
22537   SDValue B = N->getOperand(1);
22538   SDValue C = N->getOperand(2);
22539
22540   bool NegA = (A.getOpcode() == ISD::FNEG);
22541   bool NegB = (B.getOpcode() == ISD::FNEG);
22542   bool NegC = (C.getOpcode() == ISD::FNEG);
22543
22544   // Negative multiplication when NegA xor NegB
22545   bool NegMul = (NegA != NegB);
22546   if (NegA)
22547     A = A.getOperand(0);
22548   if (NegB)
22549     B = B.getOperand(0);
22550   if (NegC)
22551     C = C.getOperand(0);
22552
22553   unsigned Opcode;
22554   if (!NegMul)
22555     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22556   else
22557     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22558
22559   return DAG.getNode(Opcode, dl, VT, A, B, C);
22560 }
22561
22562 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22563                                   TargetLowering::DAGCombinerInfo &DCI,
22564                                   const X86Subtarget *Subtarget) {
22565   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22566   //           (and (i32 x86isd::setcc_carry), 1)
22567   // This eliminates the zext. This transformation is necessary because
22568   // ISD::SETCC is always legalized to i8.
22569   SDLoc dl(N);
22570   SDValue N0 = N->getOperand(0);
22571   EVT VT = N->getValueType(0);
22572
22573   if (N0.getOpcode() == ISD::AND &&
22574       N0.hasOneUse() &&
22575       N0.getOperand(0).hasOneUse()) {
22576     SDValue N00 = N0.getOperand(0);
22577     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22578       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22579       if (!C || C->getZExtValue() != 1)
22580         return SDValue();
22581       return DAG.getNode(ISD::AND, dl, VT,
22582                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22583                                      N00.getOperand(0), N00.getOperand(1)),
22584                          DAG.getConstant(1, VT));
22585     }
22586   }
22587
22588   if (N0.getOpcode() == ISD::TRUNCATE &&
22589       N0.hasOneUse() &&
22590       N0.getOperand(0).hasOneUse()) {
22591     SDValue N00 = N0.getOperand(0);
22592     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22593       return DAG.getNode(ISD::AND, dl, VT,
22594                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22595                                      N00.getOperand(0), N00.getOperand(1)),
22596                          DAG.getConstant(1, VT));
22597     }
22598   }
22599   if (VT.is256BitVector()) {
22600     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22601     if (R.getNode())
22602       return R;
22603   }
22604
22605   return SDValue();
22606 }
22607
22608 // Optimize x == -y --> x+y == 0
22609 //          x != -y --> x+y != 0
22610 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22611                                       const X86Subtarget* Subtarget) {
22612   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22613   SDValue LHS = N->getOperand(0);
22614   SDValue RHS = N->getOperand(1);
22615   EVT VT = N->getValueType(0);
22616   SDLoc DL(N);
22617
22618   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22619     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22620       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22621         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22622                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22623         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22624                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22625       }
22626   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22627     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22628       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22629         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22630                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22631         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22632                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22633       }
22634
22635   if (VT.getScalarType() == MVT::i1) {
22636     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22637       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22638     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22639     if (!IsSEXT0 && !IsVZero0)
22640       return SDValue();
22641     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22642       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22643     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22644
22645     if (!IsSEXT1 && !IsVZero1)
22646       return SDValue();
22647
22648     if (IsSEXT0 && IsVZero1) {
22649       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22650       if (CC == ISD::SETEQ)
22651         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22652       return LHS.getOperand(0);
22653     }
22654     if (IsSEXT1 && IsVZero0) {
22655       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22656       if (CC == ISD::SETEQ)
22657         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22658       return RHS.getOperand(0);
22659     }
22660   }
22661
22662   return SDValue();
22663 }
22664
22665 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22666                                       const X86Subtarget *Subtarget) {
22667   SDLoc dl(N);
22668   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22669   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22670          "X86insertps is only defined for v4x32");
22671
22672   SDValue Ld = N->getOperand(1);
22673   if (MayFoldLoad(Ld)) {
22674     // Extract the countS bits from the immediate so we can get the proper
22675     // address when narrowing the vector load to a specific element.
22676     // When the second source op is a memory address, interps doesn't use
22677     // countS and just gets an f32 from that address.
22678     unsigned DestIndex =
22679         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22680     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22681   } else
22682     return SDValue();
22683
22684   // Create this as a scalar to vector to match the instruction pattern.
22685   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22686   // countS bits are ignored when loading from memory on insertps, which
22687   // means we don't need to explicitly set them to 0.
22688   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22689                      LoadScalarToVector, N->getOperand(2));
22690 }
22691
22692 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22693 // as "sbb reg,reg", since it can be extended without zext and produces
22694 // an all-ones bit which is more useful than 0/1 in some cases.
22695 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22696                                MVT VT) {
22697   if (VT == MVT::i8)
22698     return DAG.getNode(ISD::AND, DL, VT,
22699                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22700                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22701                        DAG.getConstant(1, VT));
22702   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22703   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22704                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22705                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22706 }
22707
22708 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22709 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22710                                    TargetLowering::DAGCombinerInfo &DCI,
22711                                    const X86Subtarget *Subtarget) {
22712   SDLoc DL(N);
22713   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22714   SDValue EFLAGS = N->getOperand(1);
22715
22716   if (CC == X86::COND_A) {
22717     // Try to convert COND_A into COND_B in an attempt to facilitate
22718     // materializing "setb reg".
22719     //
22720     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22721     // cannot take an immediate as its first operand.
22722     //
22723     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22724         EFLAGS.getValueType().isInteger() &&
22725         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22726       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22727                                    EFLAGS.getNode()->getVTList(),
22728                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22729       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22730       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22731     }
22732   }
22733
22734   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22735   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22736   // cases.
22737   if (CC == X86::COND_B)
22738     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22739
22740   SDValue Flags;
22741
22742   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22743   if (Flags.getNode()) {
22744     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22745     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22746   }
22747
22748   return SDValue();
22749 }
22750
22751 // Optimize branch condition evaluation.
22752 //
22753 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22754                                     TargetLowering::DAGCombinerInfo &DCI,
22755                                     const X86Subtarget *Subtarget) {
22756   SDLoc DL(N);
22757   SDValue Chain = N->getOperand(0);
22758   SDValue Dest = N->getOperand(1);
22759   SDValue EFLAGS = N->getOperand(3);
22760   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22761
22762   SDValue Flags;
22763
22764   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22765   if (Flags.getNode()) {
22766     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22767     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22768                        Flags);
22769   }
22770
22771   return SDValue();
22772 }
22773
22774 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22775                                                          SelectionDAG &DAG) {
22776   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22777   // optimize away operation when it's from a constant.
22778   //
22779   // The general transformation is:
22780   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22781   //       AND(VECTOR_CMP(x,y), constant2)
22782   //    constant2 = UNARYOP(constant)
22783
22784   // Early exit if this isn't a vector operation, the operand of the
22785   // unary operation isn't a bitwise AND, or if the sizes of the operations
22786   // aren't the same.
22787   EVT VT = N->getValueType(0);
22788   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22789       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22790       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22791     return SDValue();
22792
22793   // Now check that the other operand of the AND is a constant. We could
22794   // make the transformation for non-constant splats as well, but it's unclear
22795   // that would be a benefit as it would not eliminate any operations, just
22796   // perform one more step in scalar code before moving to the vector unit.
22797   if (BuildVectorSDNode *BV =
22798           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22799     // Bail out if the vector isn't a constant.
22800     if (!BV->isConstant())
22801       return SDValue();
22802
22803     // Everything checks out. Build up the new and improved node.
22804     SDLoc DL(N);
22805     EVT IntVT = BV->getValueType(0);
22806     // Create a new constant of the appropriate type for the transformed
22807     // DAG.
22808     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22809     // The AND node needs bitcasts to/from an integer vector type around it.
22810     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22811     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22812                                  N->getOperand(0)->getOperand(0), MaskConst);
22813     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22814     return Res;
22815   }
22816
22817   return SDValue();
22818 }
22819
22820 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22821                                         const X86TargetLowering *XTLI) {
22822   // First try to optimize away the conversion entirely when it's
22823   // conditionally from a constant. Vectors only.
22824   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22825   if (Res != SDValue())
22826     return Res;
22827
22828   // Now move on to more general possibilities.
22829   SDValue Op0 = N->getOperand(0);
22830   EVT InVT = Op0->getValueType(0);
22831
22832   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22833   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22834     SDLoc dl(N);
22835     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22836     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22837     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22838   }
22839
22840   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22841   // a 32-bit target where SSE doesn't support i64->FP operations.
22842   if (Op0.getOpcode() == ISD::LOAD) {
22843     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22844     EVT VT = Ld->getValueType(0);
22845     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22846         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22847         !XTLI->getSubtarget()->is64Bit() &&
22848         VT == MVT::i64) {
22849       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22850                                           Ld->getChain(), Op0, DAG);
22851       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22852       return FILDChain;
22853     }
22854   }
22855   return SDValue();
22856 }
22857
22858 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22859 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22860                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22861   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22862   // the result is either zero or one (depending on the input carry bit).
22863   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22864   if (X86::isZeroNode(N->getOperand(0)) &&
22865       X86::isZeroNode(N->getOperand(1)) &&
22866       // We don't have a good way to replace an EFLAGS use, so only do this when
22867       // dead right now.
22868       SDValue(N, 1).use_empty()) {
22869     SDLoc DL(N);
22870     EVT VT = N->getValueType(0);
22871     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22872     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22873                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22874                                            DAG.getConstant(X86::COND_B,MVT::i8),
22875                                            N->getOperand(2)),
22876                                DAG.getConstant(1, VT));
22877     return DCI.CombineTo(N, Res1, CarryOut);
22878   }
22879
22880   return SDValue();
22881 }
22882
22883 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22884 //      (add Y, (setne X, 0)) -> sbb -1, Y
22885 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22886 //      (sub (setne X, 0), Y) -> adc -1, Y
22887 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22888   SDLoc DL(N);
22889
22890   // Look through ZExts.
22891   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22892   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22893     return SDValue();
22894
22895   SDValue SetCC = Ext.getOperand(0);
22896   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22897     return SDValue();
22898
22899   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22900   if (CC != X86::COND_E && CC != X86::COND_NE)
22901     return SDValue();
22902
22903   SDValue Cmp = SetCC.getOperand(1);
22904   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22905       !X86::isZeroNode(Cmp.getOperand(1)) ||
22906       !Cmp.getOperand(0).getValueType().isInteger())
22907     return SDValue();
22908
22909   SDValue CmpOp0 = Cmp.getOperand(0);
22910   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22911                                DAG.getConstant(1, CmpOp0.getValueType()));
22912
22913   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22914   if (CC == X86::COND_NE)
22915     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22916                        DL, OtherVal.getValueType(), OtherVal,
22917                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22918   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22919                      DL, OtherVal.getValueType(), OtherVal,
22920                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22921 }
22922
22923 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22924 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22925                                  const X86Subtarget *Subtarget) {
22926   EVT VT = N->getValueType(0);
22927   SDValue Op0 = N->getOperand(0);
22928   SDValue Op1 = N->getOperand(1);
22929
22930   // Try to synthesize horizontal adds from adds of shuffles.
22931   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22932        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22933       isHorizontalBinOp(Op0, Op1, true))
22934     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22935
22936   return OptimizeConditionalInDecrement(N, DAG);
22937 }
22938
22939 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22940                                  const X86Subtarget *Subtarget) {
22941   SDValue Op0 = N->getOperand(0);
22942   SDValue Op1 = N->getOperand(1);
22943
22944   // X86 can't encode an immediate LHS of a sub. See if we can push the
22945   // negation into a preceding instruction.
22946   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22947     // If the RHS of the sub is a XOR with one use and a constant, invert the
22948     // immediate. Then add one to the LHS of the sub so we can turn
22949     // X-Y -> X+~Y+1, saving one register.
22950     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22951         isa<ConstantSDNode>(Op1.getOperand(1))) {
22952       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22953       EVT VT = Op0.getValueType();
22954       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22955                                    Op1.getOperand(0),
22956                                    DAG.getConstant(~XorC, VT));
22957       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22958                          DAG.getConstant(C->getAPIntValue()+1, VT));
22959     }
22960   }
22961
22962   // Try to synthesize horizontal adds from adds of shuffles.
22963   EVT VT = N->getValueType(0);
22964   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22965        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22966       isHorizontalBinOp(Op0, Op1, true))
22967     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22968
22969   return OptimizeConditionalInDecrement(N, DAG);
22970 }
22971
22972 /// performVZEXTCombine - Performs build vector combines
22973 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22974                                         TargetLowering::DAGCombinerInfo &DCI,
22975                                         const X86Subtarget *Subtarget) {
22976   // (vzext (bitcast (vzext (x)) -> (vzext x)
22977   SDValue In = N->getOperand(0);
22978   while (In.getOpcode() == ISD::BITCAST)
22979     In = In.getOperand(0);
22980
22981   if (In.getOpcode() != X86ISD::VZEXT)
22982     return SDValue();
22983
22984   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22985                      In.getOperand(0));
22986 }
22987
22988 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22989                                              DAGCombinerInfo &DCI) const {
22990   SelectionDAG &DAG = DCI.DAG;
22991   switch (N->getOpcode()) {
22992   default: break;
22993   case ISD::EXTRACT_VECTOR_ELT:
22994     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22995   case ISD::VSELECT:
22996   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22997   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22998   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22999   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23000   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23001   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23002   case ISD::SHL:
23003   case ISD::SRA:
23004   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23005   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23006   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23007   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23008   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23009   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23010   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
23011   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23012   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23013   case X86ISD::FXOR:
23014   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23015   case X86ISD::FMIN:
23016   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23017   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23018   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23019   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23020   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23021   case ISD::ANY_EXTEND:
23022   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23023   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23024   case ISD::SIGN_EXTEND_INREG:
23025     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23026   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23027   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23028   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23029   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23030   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23031   case X86ISD::SHUFP:       // Handle all target specific shuffles
23032   case X86ISD::PALIGNR:
23033   case X86ISD::UNPCKH:
23034   case X86ISD::UNPCKL:
23035   case X86ISD::MOVHLPS:
23036   case X86ISD::MOVLHPS:
23037   case X86ISD::PSHUFB:
23038   case X86ISD::PSHUFD:
23039   case X86ISD::PSHUFHW:
23040   case X86ISD::PSHUFLW:
23041   case X86ISD::MOVSS:
23042   case X86ISD::MOVSD:
23043   case X86ISD::VPERMILP:
23044   case X86ISD::VPERM2X128:
23045   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23046   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23047   case ISD::INTRINSIC_WO_CHAIN:
23048     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23049   case X86ISD::INSERTPS:
23050     return PerformINSERTPSCombine(N, DAG, Subtarget);
23051   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23052   }
23053
23054   return SDValue();
23055 }
23056
23057 /// isTypeDesirableForOp - Return true if the target has native support for
23058 /// the specified value type and it is 'desirable' to use the type for the
23059 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23060 /// instruction encodings are longer and some i16 instructions are slow.
23061 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23062   if (!isTypeLegal(VT))
23063     return false;
23064   if (VT != MVT::i16)
23065     return true;
23066
23067   switch (Opc) {
23068   default:
23069     return true;
23070   case ISD::LOAD:
23071   case ISD::SIGN_EXTEND:
23072   case ISD::ZERO_EXTEND:
23073   case ISD::ANY_EXTEND:
23074   case ISD::SHL:
23075   case ISD::SRL:
23076   case ISD::SUB:
23077   case ISD::ADD:
23078   case ISD::MUL:
23079   case ISD::AND:
23080   case ISD::OR:
23081   case ISD::XOR:
23082     return false;
23083   }
23084 }
23085
23086 /// IsDesirableToPromoteOp - This method query the target whether it is
23087 /// beneficial for dag combiner to promote the specified node. If true, it
23088 /// should return the desired promotion type by reference.
23089 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23090   EVT VT = Op.getValueType();
23091   if (VT != MVT::i16)
23092     return false;
23093
23094   bool Promote = false;
23095   bool Commute = false;
23096   switch (Op.getOpcode()) {
23097   default: break;
23098   case ISD::LOAD: {
23099     LoadSDNode *LD = cast<LoadSDNode>(Op);
23100     // If the non-extending load has a single use and it's not live out, then it
23101     // might be folded.
23102     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23103                                                      Op.hasOneUse()*/) {
23104       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23105              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23106         // The only case where we'd want to promote LOAD (rather then it being
23107         // promoted as an operand is when it's only use is liveout.
23108         if (UI->getOpcode() != ISD::CopyToReg)
23109           return false;
23110       }
23111     }
23112     Promote = true;
23113     break;
23114   }
23115   case ISD::SIGN_EXTEND:
23116   case ISD::ZERO_EXTEND:
23117   case ISD::ANY_EXTEND:
23118     Promote = true;
23119     break;
23120   case ISD::SHL:
23121   case ISD::SRL: {
23122     SDValue N0 = Op.getOperand(0);
23123     // Look out for (store (shl (load), x)).
23124     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23125       return false;
23126     Promote = true;
23127     break;
23128   }
23129   case ISD::ADD:
23130   case ISD::MUL:
23131   case ISD::AND:
23132   case ISD::OR:
23133   case ISD::XOR:
23134     Commute = true;
23135     // fallthrough
23136   case ISD::SUB: {
23137     SDValue N0 = Op.getOperand(0);
23138     SDValue N1 = Op.getOperand(1);
23139     if (!Commute && MayFoldLoad(N1))
23140       return false;
23141     // Avoid disabling potential load folding opportunities.
23142     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23143       return false;
23144     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23145       return false;
23146     Promote = true;
23147   }
23148   }
23149
23150   PVT = MVT::i32;
23151   return Promote;
23152 }
23153
23154 //===----------------------------------------------------------------------===//
23155 //                           X86 Inline Assembly Support
23156 //===----------------------------------------------------------------------===//
23157
23158 namespace {
23159   // Helper to match a string separated by whitespace.
23160   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23161     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23162
23163     for (unsigned i = 0, e = args.size(); i != e; ++i) {
23164       StringRef piece(*args[i]);
23165       if (!s.startswith(piece)) // Check if the piece matches.
23166         return false;
23167
23168       s = s.substr(piece.size());
23169       StringRef::size_type pos = s.find_first_not_of(" \t");
23170       if (pos == 0) // We matched a prefix.
23171         return false;
23172
23173       s = s.substr(pos);
23174     }
23175
23176     return s.empty();
23177   }
23178   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23179 }
23180
23181 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23182
23183   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23184     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23185         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23186         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23187
23188       if (AsmPieces.size() == 3)
23189         return true;
23190       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23191         return true;
23192     }
23193   }
23194   return false;
23195 }
23196
23197 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23198   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23199
23200   std::string AsmStr = IA->getAsmString();
23201
23202   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23203   if (!Ty || Ty->getBitWidth() % 16 != 0)
23204     return false;
23205
23206   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23207   SmallVector<StringRef, 4> AsmPieces;
23208   SplitString(AsmStr, AsmPieces, ";\n");
23209
23210   switch (AsmPieces.size()) {
23211   default: return false;
23212   case 1:
23213     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23214     // we will turn this bswap into something that will be lowered to logical
23215     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23216     // lower so don't worry about this.
23217     // bswap $0
23218     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23219         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23220         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23221         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23222         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23223         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23224       // No need to check constraints, nothing other than the equivalent of
23225       // "=r,0" would be valid here.
23226       return IntrinsicLowering::LowerToByteSwap(CI);
23227     }
23228
23229     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23230     if (CI->getType()->isIntegerTy(16) &&
23231         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23232         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23233          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23234       AsmPieces.clear();
23235       const std::string &ConstraintsStr = IA->getConstraintString();
23236       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23237       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23238       if (clobbersFlagRegisters(AsmPieces))
23239         return IntrinsicLowering::LowerToByteSwap(CI);
23240     }
23241     break;
23242   case 3:
23243     if (CI->getType()->isIntegerTy(32) &&
23244         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23245         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23246         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23247         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23248       AsmPieces.clear();
23249       const std::string &ConstraintsStr = IA->getConstraintString();
23250       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23251       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23252       if (clobbersFlagRegisters(AsmPieces))
23253         return IntrinsicLowering::LowerToByteSwap(CI);
23254     }
23255
23256     if (CI->getType()->isIntegerTy(64)) {
23257       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23258       if (Constraints.size() >= 2 &&
23259           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23260           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23261         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23262         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23263             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23264             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23265           return IntrinsicLowering::LowerToByteSwap(CI);
23266       }
23267     }
23268     break;
23269   }
23270   return false;
23271 }
23272
23273 /// getConstraintType - Given a constraint letter, return the type of
23274 /// constraint it is for this target.
23275 X86TargetLowering::ConstraintType
23276 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23277   if (Constraint.size() == 1) {
23278     switch (Constraint[0]) {
23279     case 'R':
23280     case 'q':
23281     case 'Q':
23282     case 'f':
23283     case 't':
23284     case 'u':
23285     case 'y':
23286     case 'x':
23287     case 'Y':
23288     case 'l':
23289       return C_RegisterClass;
23290     case 'a':
23291     case 'b':
23292     case 'c':
23293     case 'd':
23294     case 'S':
23295     case 'D':
23296     case 'A':
23297       return C_Register;
23298     case 'I':
23299     case 'J':
23300     case 'K':
23301     case 'L':
23302     case 'M':
23303     case 'N':
23304     case 'G':
23305     case 'C':
23306     case 'e':
23307     case 'Z':
23308       return C_Other;
23309     default:
23310       break;
23311     }
23312   }
23313   return TargetLowering::getConstraintType(Constraint);
23314 }
23315
23316 /// Examine constraint type and operand type and determine a weight value.
23317 /// This object must already have been set up with the operand type
23318 /// and the current alternative constraint selected.
23319 TargetLowering::ConstraintWeight
23320   X86TargetLowering::getSingleConstraintMatchWeight(
23321     AsmOperandInfo &info, const char *constraint) const {
23322   ConstraintWeight weight = CW_Invalid;
23323   Value *CallOperandVal = info.CallOperandVal;
23324     // If we don't have a value, we can't do a match,
23325     // but allow it at the lowest weight.
23326   if (!CallOperandVal)
23327     return CW_Default;
23328   Type *type = CallOperandVal->getType();
23329   // Look at the constraint type.
23330   switch (*constraint) {
23331   default:
23332     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23333   case 'R':
23334   case 'q':
23335   case 'Q':
23336   case 'a':
23337   case 'b':
23338   case 'c':
23339   case 'd':
23340   case 'S':
23341   case 'D':
23342   case 'A':
23343     if (CallOperandVal->getType()->isIntegerTy())
23344       weight = CW_SpecificReg;
23345     break;
23346   case 'f':
23347   case 't':
23348   case 'u':
23349     if (type->isFloatingPointTy())
23350       weight = CW_SpecificReg;
23351     break;
23352   case 'y':
23353     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23354       weight = CW_SpecificReg;
23355     break;
23356   case 'x':
23357   case 'Y':
23358     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23359         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23360       weight = CW_Register;
23361     break;
23362   case 'I':
23363     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23364       if (C->getZExtValue() <= 31)
23365         weight = CW_Constant;
23366     }
23367     break;
23368   case 'J':
23369     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23370       if (C->getZExtValue() <= 63)
23371         weight = CW_Constant;
23372     }
23373     break;
23374   case 'K':
23375     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23376       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23377         weight = CW_Constant;
23378     }
23379     break;
23380   case 'L':
23381     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23382       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23383         weight = CW_Constant;
23384     }
23385     break;
23386   case 'M':
23387     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23388       if (C->getZExtValue() <= 3)
23389         weight = CW_Constant;
23390     }
23391     break;
23392   case 'N':
23393     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23394       if (C->getZExtValue() <= 0xff)
23395         weight = CW_Constant;
23396     }
23397     break;
23398   case 'G':
23399   case 'C':
23400     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23401       weight = CW_Constant;
23402     }
23403     break;
23404   case 'e':
23405     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23406       if ((C->getSExtValue() >= -0x80000000LL) &&
23407           (C->getSExtValue() <= 0x7fffffffLL))
23408         weight = CW_Constant;
23409     }
23410     break;
23411   case 'Z':
23412     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23413       if (C->getZExtValue() <= 0xffffffff)
23414         weight = CW_Constant;
23415     }
23416     break;
23417   }
23418   return weight;
23419 }
23420
23421 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23422 /// with another that has more specific requirements based on the type of the
23423 /// corresponding operand.
23424 const char *X86TargetLowering::
23425 LowerXConstraint(EVT ConstraintVT) const {
23426   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23427   // 'f' like normal targets.
23428   if (ConstraintVT.isFloatingPoint()) {
23429     if (Subtarget->hasSSE2())
23430       return "Y";
23431     if (Subtarget->hasSSE1())
23432       return "x";
23433   }
23434
23435   return TargetLowering::LowerXConstraint(ConstraintVT);
23436 }
23437
23438 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23439 /// vector.  If it is invalid, don't add anything to Ops.
23440 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23441                                                      std::string &Constraint,
23442                                                      std::vector<SDValue>&Ops,
23443                                                      SelectionDAG &DAG) const {
23444   SDValue Result;
23445
23446   // Only support length 1 constraints for now.
23447   if (Constraint.length() > 1) return;
23448
23449   char ConstraintLetter = Constraint[0];
23450   switch (ConstraintLetter) {
23451   default: break;
23452   case 'I':
23453     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23454       if (C->getZExtValue() <= 31) {
23455         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23456         break;
23457       }
23458     }
23459     return;
23460   case 'J':
23461     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23462       if (C->getZExtValue() <= 63) {
23463         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23464         break;
23465       }
23466     }
23467     return;
23468   case 'K':
23469     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23470       if (isInt<8>(C->getSExtValue())) {
23471         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23472         break;
23473       }
23474     }
23475     return;
23476   case 'N':
23477     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23478       if (C->getZExtValue() <= 255) {
23479         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23480         break;
23481       }
23482     }
23483     return;
23484   case 'e': {
23485     // 32-bit signed value
23486     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23487       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23488                                            C->getSExtValue())) {
23489         // Widen to 64 bits here to get it sign extended.
23490         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23491         break;
23492       }
23493     // FIXME gcc accepts some relocatable values here too, but only in certain
23494     // memory models; it's complicated.
23495     }
23496     return;
23497   }
23498   case 'Z': {
23499     // 32-bit unsigned value
23500     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23501       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23502                                            C->getZExtValue())) {
23503         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23504         break;
23505       }
23506     }
23507     // FIXME gcc accepts some relocatable values here too, but only in certain
23508     // memory models; it's complicated.
23509     return;
23510   }
23511   case 'i': {
23512     // Literal immediates are always ok.
23513     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23514       // Widen to 64 bits here to get it sign extended.
23515       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23516       break;
23517     }
23518
23519     // In any sort of PIC mode addresses need to be computed at runtime by
23520     // adding in a register or some sort of table lookup.  These can't
23521     // be used as immediates.
23522     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23523       return;
23524
23525     // If we are in non-pic codegen mode, we allow the address of a global (with
23526     // an optional displacement) to be used with 'i'.
23527     GlobalAddressSDNode *GA = nullptr;
23528     int64_t Offset = 0;
23529
23530     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23531     while (1) {
23532       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23533         Offset += GA->getOffset();
23534         break;
23535       } else if (Op.getOpcode() == ISD::ADD) {
23536         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23537           Offset += C->getZExtValue();
23538           Op = Op.getOperand(0);
23539           continue;
23540         }
23541       } else if (Op.getOpcode() == ISD::SUB) {
23542         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23543           Offset += -C->getZExtValue();
23544           Op = Op.getOperand(0);
23545           continue;
23546         }
23547       }
23548
23549       // Otherwise, this isn't something we can handle, reject it.
23550       return;
23551     }
23552
23553     const GlobalValue *GV = GA->getGlobal();
23554     // If we require an extra load to get this address, as in PIC mode, we
23555     // can't accept it.
23556     if (isGlobalStubReference(
23557             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23558       return;
23559
23560     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23561                                         GA->getValueType(0), Offset);
23562     break;
23563   }
23564   }
23565
23566   if (Result.getNode()) {
23567     Ops.push_back(Result);
23568     return;
23569   }
23570   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23571 }
23572
23573 std::pair<unsigned, const TargetRegisterClass*>
23574 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23575                                                 MVT VT) const {
23576   // First, see if this is a constraint that directly corresponds to an LLVM
23577   // register class.
23578   if (Constraint.size() == 1) {
23579     // GCC Constraint Letters
23580     switch (Constraint[0]) {
23581     default: break;
23582       // TODO: Slight differences here in allocation order and leaving
23583       // RIP in the class. Do they matter any more here than they do
23584       // in the normal allocation?
23585     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23586       if (Subtarget->is64Bit()) {
23587         if (VT == MVT::i32 || VT == MVT::f32)
23588           return std::make_pair(0U, &X86::GR32RegClass);
23589         if (VT == MVT::i16)
23590           return std::make_pair(0U, &X86::GR16RegClass);
23591         if (VT == MVT::i8 || VT == MVT::i1)
23592           return std::make_pair(0U, &X86::GR8RegClass);
23593         if (VT == MVT::i64 || VT == MVT::f64)
23594           return std::make_pair(0U, &X86::GR64RegClass);
23595         break;
23596       }
23597       // 32-bit fallthrough
23598     case 'Q':   // Q_REGS
23599       if (VT == MVT::i32 || VT == MVT::f32)
23600         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23601       if (VT == MVT::i16)
23602         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23603       if (VT == MVT::i8 || VT == MVT::i1)
23604         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23605       if (VT == MVT::i64)
23606         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23607       break;
23608     case 'r':   // GENERAL_REGS
23609     case 'l':   // INDEX_REGS
23610       if (VT == MVT::i8 || VT == MVT::i1)
23611         return std::make_pair(0U, &X86::GR8RegClass);
23612       if (VT == MVT::i16)
23613         return std::make_pair(0U, &X86::GR16RegClass);
23614       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23615         return std::make_pair(0U, &X86::GR32RegClass);
23616       return std::make_pair(0U, &X86::GR64RegClass);
23617     case 'R':   // LEGACY_REGS
23618       if (VT == MVT::i8 || VT == MVT::i1)
23619         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23620       if (VT == MVT::i16)
23621         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23622       if (VT == MVT::i32 || !Subtarget->is64Bit())
23623         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23624       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23625     case 'f':  // FP Stack registers.
23626       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23627       // value to the correct fpstack register class.
23628       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23629         return std::make_pair(0U, &X86::RFP32RegClass);
23630       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23631         return std::make_pair(0U, &X86::RFP64RegClass);
23632       return std::make_pair(0U, &X86::RFP80RegClass);
23633     case 'y':   // MMX_REGS if MMX allowed.
23634       if (!Subtarget->hasMMX()) break;
23635       return std::make_pair(0U, &X86::VR64RegClass);
23636     case 'Y':   // SSE_REGS if SSE2 allowed
23637       if (!Subtarget->hasSSE2()) break;
23638       // FALL THROUGH.
23639     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23640       if (!Subtarget->hasSSE1()) break;
23641
23642       switch (VT.SimpleTy) {
23643       default: break;
23644       // Scalar SSE types.
23645       case MVT::f32:
23646       case MVT::i32:
23647         return std::make_pair(0U, &X86::FR32RegClass);
23648       case MVT::f64:
23649       case MVT::i64:
23650         return std::make_pair(0U, &X86::FR64RegClass);
23651       // Vector types.
23652       case MVT::v16i8:
23653       case MVT::v8i16:
23654       case MVT::v4i32:
23655       case MVT::v2i64:
23656       case MVT::v4f32:
23657       case MVT::v2f64:
23658         return std::make_pair(0U, &X86::VR128RegClass);
23659       // AVX types.
23660       case MVT::v32i8:
23661       case MVT::v16i16:
23662       case MVT::v8i32:
23663       case MVT::v4i64:
23664       case MVT::v8f32:
23665       case MVT::v4f64:
23666         return std::make_pair(0U, &X86::VR256RegClass);
23667       case MVT::v8f64:
23668       case MVT::v16f32:
23669       case MVT::v16i32:
23670       case MVT::v8i64:
23671         return std::make_pair(0U, &X86::VR512RegClass);
23672       }
23673       break;
23674     }
23675   }
23676
23677   // Use the default implementation in TargetLowering to convert the register
23678   // constraint into a member of a register class.
23679   std::pair<unsigned, const TargetRegisterClass*> Res;
23680   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23681
23682   // Not found as a standard register?
23683   if (!Res.second) {
23684     // Map st(0) -> st(7) -> ST0
23685     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23686         tolower(Constraint[1]) == 's' &&
23687         tolower(Constraint[2]) == 't' &&
23688         Constraint[3] == '(' &&
23689         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23690         Constraint[5] == ')' &&
23691         Constraint[6] == '}') {
23692
23693       Res.first = X86::FP0+Constraint[4]-'0';
23694       Res.second = &X86::RFP80RegClass;
23695       return Res;
23696     }
23697
23698     // GCC allows "st(0)" to be called just plain "st".
23699     if (StringRef("{st}").equals_lower(Constraint)) {
23700       Res.first = X86::FP0;
23701       Res.second = &X86::RFP80RegClass;
23702       return Res;
23703     }
23704
23705     // flags -> EFLAGS
23706     if (StringRef("{flags}").equals_lower(Constraint)) {
23707       Res.first = X86::EFLAGS;
23708       Res.second = &X86::CCRRegClass;
23709       return Res;
23710     }
23711
23712     // 'A' means EAX + EDX.
23713     if (Constraint == "A") {
23714       Res.first = X86::EAX;
23715       Res.second = &X86::GR32_ADRegClass;
23716       return Res;
23717     }
23718     return Res;
23719   }
23720
23721   // Otherwise, check to see if this is a register class of the wrong value
23722   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23723   // turn into {ax},{dx}.
23724   if (Res.second->hasType(VT))
23725     return Res;   // Correct type already, nothing to do.
23726
23727   // All of the single-register GCC register classes map their values onto
23728   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23729   // really want an 8-bit or 32-bit register, map to the appropriate register
23730   // class and return the appropriate register.
23731   if (Res.second == &X86::GR16RegClass) {
23732     if (VT == MVT::i8 || VT == MVT::i1) {
23733       unsigned DestReg = 0;
23734       switch (Res.first) {
23735       default: break;
23736       case X86::AX: DestReg = X86::AL; break;
23737       case X86::DX: DestReg = X86::DL; break;
23738       case X86::CX: DestReg = X86::CL; break;
23739       case X86::BX: DestReg = X86::BL; break;
23740       }
23741       if (DestReg) {
23742         Res.first = DestReg;
23743         Res.second = &X86::GR8RegClass;
23744       }
23745     } else if (VT == MVT::i32 || VT == MVT::f32) {
23746       unsigned DestReg = 0;
23747       switch (Res.first) {
23748       default: break;
23749       case X86::AX: DestReg = X86::EAX; break;
23750       case X86::DX: DestReg = X86::EDX; break;
23751       case X86::CX: DestReg = X86::ECX; break;
23752       case X86::BX: DestReg = X86::EBX; break;
23753       case X86::SI: DestReg = X86::ESI; break;
23754       case X86::DI: DestReg = X86::EDI; break;
23755       case X86::BP: DestReg = X86::EBP; break;
23756       case X86::SP: DestReg = X86::ESP; break;
23757       }
23758       if (DestReg) {
23759         Res.first = DestReg;
23760         Res.second = &X86::GR32RegClass;
23761       }
23762     } else if (VT == MVT::i64 || VT == MVT::f64) {
23763       unsigned DestReg = 0;
23764       switch (Res.first) {
23765       default: break;
23766       case X86::AX: DestReg = X86::RAX; break;
23767       case X86::DX: DestReg = X86::RDX; break;
23768       case X86::CX: DestReg = X86::RCX; break;
23769       case X86::BX: DestReg = X86::RBX; break;
23770       case X86::SI: DestReg = X86::RSI; break;
23771       case X86::DI: DestReg = X86::RDI; break;
23772       case X86::BP: DestReg = X86::RBP; break;
23773       case X86::SP: DestReg = X86::RSP; break;
23774       }
23775       if (DestReg) {
23776         Res.first = DestReg;
23777         Res.second = &X86::GR64RegClass;
23778       }
23779     }
23780   } else if (Res.second == &X86::FR32RegClass ||
23781              Res.second == &X86::FR64RegClass ||
23782              Res.second == &X86::VR128RegClass ||
23783              Res.second == &X86::VR256RegClass ||
23784              Res.second == &X86::FR32XRegClass ||
23785              Res.second == &X86::FR64XRegClass ||
23786              Res.second == &X86::VR128XRegClass ||
23787              Res.second == &X86::VR256XRegClass ||
23788              Res.second == &X86::VR512RegClass) {
23789     // Handle references to XMM physical registers that got mapped into the
23790     // wrong class.  This can happen with constraints like {xmm0} where the
23791     // target independent register mapper will just pick the first match it can
23792     // find, ignoring the required type.
23793
23794     if (VT == MVT::f32 || VT == MVT::i32)
23795       Res.second = &X86::FR32RegClass;
23796     else if (VT == MVT::f64 || VT == MVT::i64)
23797       Res.second = &X86::FR64RegClass;
23798     else if (X86::VR128RegClass.hasType(VT))
23799       Res.second = &X86::VR128RegClass;
23800     else if (X86::VR256RegClass.hasType(VT))
23801       Res.second = &X86::VR256RegClass;
23802     else if (X86::VR512RegClass.hasType(VT))
23803       Res.second = &X86::VR512RegClass;
23804   }
23805
23806   return Res;
23807 }
23808
23809 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23810                                             Type *Ty) const {
23811   // Scaling factors are not free at all.
23812   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23813   // will take 2 allocations in the out of order engine instead of 1
23814   // for plain addressing mode, i.e. inst (reg1).
23815   // E.g.,
23816   // vaddps (%rsi,%drx), %ymm0, %ymm1
23817   // Requires two allocations (one for the load, one for the computation)
23818   // whereas:
23819   // vaddps (%rsi), %ymm0, %ymm1
23820   // Requires just 1 allocation, i.e., freeing allocations for other operations
23821   // and having less micro operations to execute.
23822   //
23823   // For some X86 architectures, this is even worse because for instance for
23824   // stores, the complex addressing mode forces the instruction to use the
23825   // "load" ports instead of the dedicated "store" port.
23826   // E.g., on Haswell:
23827   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23828   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23829   if (isLegalAddressingMode(AM, Ty))
23830     // Scale represents reg2 * scale, thus account for 1
23831     // as soon as we use a second register.
23832     return AM.Scale != 0;
23833   return -1;
23834 }
23835
23836 bool X86TargetLowering::isTargetFTOL() const {
23837   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23838 }