CodeGen: don't form illegail EXTLOAD operations.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
523     setOperationAction(ISD::FP32_TO_FP16, MVT::i16, Expand);
524   }
525
526   if (Subtarget->hasPOPCNT()) {
527     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
528   } else {
529     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
530     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
531     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
532     if (Subtarget->is64Bit())
533       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
534   }
535
536   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
537
538   if (!Subtarget->hasMOVBE())
539     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
540
541   // These should be promoted to a larger select which is supported.
542   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
543   // X86 wants to expand cmov itself.
544   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
545   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
546   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
547   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
548   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
549   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
550   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
551   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
552   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
553   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
554   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
555   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
556   if (Subtarget->is64Bit()) {
557     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
558     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
559   }
560   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
561   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
562   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
563   // support continuation, user-level threading, and etc.. As a result, no
564   // other SjLj exception interfaces are implemented and please don't build
565   // your own exception handling based on them.
566   // LLVM/Clang supports zero-cost DWARF exception handling.
567   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
568   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
569
570   // Darwin ABI issue.
571   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
572   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
573   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
574   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
575   if (Subtarget->is64Bit())
576     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
577   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
578   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
579   if (Subtarget->is64Bit()) {
580     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
581     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
582     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
583     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
584     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
585   }
586   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
587   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
588   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
589   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
592     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
593     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
594   }
595
596   if (Subtarget->hasSSE1())
597     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
598
599   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
600
601   // Expand certain atomics
602   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
603     MVT VT = IntVTs[i];
604     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
605     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
606     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
607   }
608
609   if (Subtarget->hasCmpxchg16b()) {
610     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
611   }
612
613   // FIXME - use subtarget debug flags
614   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
615       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
616     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
617   }
618
619   if (Subtarget->is64Bit()) {
620     setExceptionPointerRegister(X86::RAX);
621     setExceptionSelectorRegister(X86::RDX);
622   } else {
623     setExceptionPointerRegister(X86::EAX);
624     setExceptionSelectorRegister(X86::EDX);
625   }
626   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
627   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
628
629   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
630   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
631
632   setOperationAction(ISD::TRAP, MVT::Other, Legal);
633   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
634
635   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
636   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
637   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
638   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
639     // TargetInfo::X86_64ABIBuiltinVaList
640     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
641     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
642   } else {
643     // TargetInfo::CharPtrBuiltinVaList
644     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
645     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
646   }
647
648   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
649   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
650
651   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
652                      MVT::i64 : MVT::i32, Custom);
653
654   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
655     // f32 and f64 use SSE.
656     // Set up the FP register classes.
657     addRegisterClass(MVT::f32, &X86::FR32RegClass);
658     addRegisterClass(MVT::f64, &X86::FR64RegClass);
659
660     // Use ANDPD to simulate FABS.
661     setOperationAction(ISD::FABS , MVT::f64, Custom);
662     setOperationAction(ISD::FABS , MVT::f32, Custom);
663
664     // Use XORP to simulate FNEG.
665     setOperationAction(ISD::FNEG , MVT::f64, Custom);
666     setOperationAction(ISD::FNEG , MVT::f32, Custom);
667
668     // Use ANDPD and ORPD to simulate FCOPYSIGN.
669     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
670     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
671
672     // Lower this to FGETSIGNx86 plus an AND.
673     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
674     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
675
676     // We don't support sin/cos/fmod
677     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
678     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
679     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
680     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
681     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
682     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
683
684     // Expand FP immediates into loads from the stack, except for the special
685     // cases we handle.
686     addLegalFPImmediate(APFloat(+0.0)); // xorpd
687     addLegalFPImmediate(APFloat(+0.0f)); // xorps
688   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
689     // Use SSE for f32, x87 for f64.
690     // Set up the FP register classes.
691     addRegisterClass(MVT::f32, &X86::FR32RegClass);
692     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
693
694     // Use ANDPS to simulate FABS.
695     setOperationAction(ISD::FABS , MVT::f32, Custom);
696
697     // Use XORP to simulate FNEG.
698     setOperationAction(ISD::FNEG , MVT::f32, Custom);
699
700     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
701
702     // Use ANDPS and ORPS to simulate FCOPYSIGN.
703     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
704     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
705
706     // We don't support sin/cos/fmod
707     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
708     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
709     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
710
711     // Special cases we handle for FP constants.
712     addLegalFPImmediate(APFloat(+0.0f)); // xorps
713     addLegalFPImmediate(APFloat(+0.0)); // FLD0
714     addLegalFPImmediate(APFloat(+1.0)); // FLD1
715     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
716     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
717
718     if (!TM.Options.UnsafeFPMath) {
719       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
720       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
721       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
722     }
723   } else if (!TM.Options.UseSoftFloat) {
724     // f32 and f64 in x87.
725     // Set up the FP register classes.
726     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
727     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
728
729     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
730     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
731     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
732     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
733
734     if (!TM.Options.UnsafeFPMath) {
735       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
736       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
737       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
738       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
739       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
740       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
741     }
742     addLegalFPImmediate(APFloat(+0.0)); // FLD0
743     addLegalFPImmediate(APFloat(+1.0)); // FLD1
744     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
745     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
746     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
747     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
748     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
749     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
750   }
751
752   // We don't support FMA.
753   setOperationAction(ISD::FMA, MVT::f64, Expand);
754   setOperationAction(ISD::FMA, MVT::f32, Expand);
755
756   // Long double always uses X87.
757   if (!TM.Options.UseSoftFloat) {
758     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
759     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
760     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
761     {
762       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
763       addLegalFPImmediate(TmpFlt);  // FLD0
764       TmpFlt.changeSign();
765       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
766
767       bool ignored;
768       APFloat TmpFlt2(+1.0);
769       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
770                       &ignored);
771       addLegalFPImmediate(TmpFlt2);  // FLD1
772       TmpFlt2.changeSign();
773       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
774     }
775
776     if (!TM.Options.UnsafeFPMath) {
777       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
778       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
779       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
780     }
781
782     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
783     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
784     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
785     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
786     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
787     setOperationAction(ISD::FMA, MVT::f80, Expand);
788   }
789
790   // Always use a library call for pow.
791   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
792   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
793   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
794
795   setOperationAction(ISD::FLOG, MVT::f80, Expand);
796   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
797   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
798   setOperationAction(ISD::FEXP, MVT::f80, Expand);
799   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
800
801   // First set operation action for all vector types to either promote
802   // (for widening) or expand (for scalarization). Then we will selectively
803   // turn on ones that can be effectively codegen'd.
804   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
805            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
806     MVT VT = (MVT::SimpleValueType)i;
807     setOperationAction(ISD::ADD , VT, Expand);
808     setOperationAction(ISD::SUB , VT, Expand);
809     setOperationAction(ISD::FADD, VT, Expand);
810     setOperationAction(ISD::FNEG, VT, Expand);
811     setOperationAction(ISD::FSUB, VT, Expand);
812     setOperationAction(ISD::MUL , VT, Expand);
813     setOperationAction(ISD::FMUL, VT, Expand);
814     setOperationAction(ISD::SDIV, VT, Expand);
815     setOperationAction(ISD::UDIV, VT, Expand);
816     setOperationAction(ISD::FDIV, VT, Expand);
817     setOperationAction(ISD::SREM, VT, Expand);
818     setOperationAction(ISD::UREM, VT, Expand);
819     setOperationAction(ISD::LOAD, VT, Expand);
820     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
821     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
822     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
823     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
824     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
825     setOperationAction(ISD::FABS, VT, Expand);
826     setOperationAction(ISD::FSIN, VT, Expand);
827     setOperationAction(ISD::FSINCOS, VT, Expand);
828     setOperationAction(ISD::FCOS, VT, Expand);
829     setOperationAction(ISD::FSINCOS, VT, Expand);
830     setOperationAction(ISD::FREM, VT, Expand);
831     setOperationAction(ISD::FMA,  VT, Expand);
832     setOperationAction(ISD::FPOWI, VT, Expand);
833     setOperationAction(ISD::FSQRT, VT, Expand);
834     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
835     setOperationAction(ISD::FFLOOR, VT, Expand);
836     setOperationAction(ISD::FCEIL, VT, Expand);
837     setOperationAction(ISD::FTRUNC, VT, Expand);
838     setOperationAction(ISD::FRINT, VT, Expand);
839     setOperationAction(ISD::FNEARBYINT, VT, Expand);
840     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841     setOperationAction(ISD::MULHS, VT, Expand);
842     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
843     setOperationAction(ISD::MULHU, VT, Expand);
844     setOperationAction(ISD::SDIVREM, VT, Expand);
845     setOperationAction(ISD::UDIVREM, VT, Expand);
846     setOperationAction(ISD::FPOW, VT, Expand);
847     setOperationAction(ISD::CTPOP, VT, Expand);
848     setOperationAction(ISD::CTTZ, VT, Expand);
849     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
850     setOperationAction(ISD::CTLZ, VT, Expand);
851     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
852     setOperationAction(ISD::SHL, VT, Expand);
853     setOperationAction(ISD::SRA, VT, Expand);
854     setOperationAction(ISD::SRL, VT, Expand);
855     setOperationAction(ISD::ROTL, VT, Expand);
856     setOperationAction(ISD::ROTR, VT, Expand);
857     setOperationAction(ISD::BSWAP, VT, Expand);
858     setOperationAction(ISD::SETCC, VT, Expand);
859     setOperationAction(ISD::FLOG, VT, Expand);
860     setOperationAction(ISD::FLOG2, VT, Expand);
861     setOperationAction(ISD::FLOG10, VT, Expand);
862     setOperationAction(ISD::FEXP, VT, Expand);
863     setOperationAction(ISD::FEXP2, VT, Expand);
864     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
865     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
866     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
867     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
868     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
869     setOperationAction(ISD::TRUNCATE, VT, Expand);
870     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
871     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
872     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
873     setOperationAction(ISD::VSELECT, VT, Expand);
874     setOperationAction(ISD::SELECT_CC, VT, Expand);
875     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
876              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
877       setTruncStoreAction(VT,
878                           (MVT::SimpleValueType)InnerVT, Expand);
879     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
880     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
881
882     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
883     // we have to deal with them whether we ask for Expansion or not. Setting
884     // Expand causes its own optimisation problems though, so leave them legal.
885     if (VT.getVectorElementType() == MVT::i1)
886       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
887   }
888
889   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
890   // with -msoft-float, disable use of MMX as well.
891   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
892     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
893     // No operations on x86mmx supported, everything uses intrinsics.
894   }
895
896   // MMX-sized vectors (other than x86mmx) are expected to be expanded
897   // into smaller operations.
898   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
899   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
900   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
901   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
902   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
903   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
904   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
905   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
906   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
907   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
908   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
909   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
910   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
911   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
912   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
913   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
914   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
915   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
916   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
917   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
918   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
919   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
920   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
921   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
922   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
923   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
924   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
925   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
926   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
927
928   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
929     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
930
931     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
932     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
933     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
934     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
935     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
936     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
937     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
938     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
939     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
940     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
942     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
943   }
944
945   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
946     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
947
948     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
949     // registers cannot be used even for integer operations.
950     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
951     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
952     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
953     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
954
955     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
956     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
957     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
958     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
959     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
960     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
961     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
962     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
963     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
964     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
965     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
966     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
967     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
968     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
969     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
970     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
971     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
972     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
973     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
974     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
975     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
976     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
977
978     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
979     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
980     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
981     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
982
983     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
984     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
988
989     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
990     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
991       MVT VT = (MVT::SimpleValueType)i;
992       // Do not attempt to custom lower non-power-of-2 vectors
993       if (!isPowerOf2_32(VT.getVectorNumElements()))
994         continue;
995       // Do not attempt to custom lower non-128-bit vectors
996       if (!VT.is128BitVector())
997         continue;
998       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
999       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1000       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1001     }
1002
1003     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1004     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1005     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1006     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1007     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1008     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1009
1010     if (Subtarget->is64Bit()) {
1011       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1012       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1013     }
1014
1015     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1016     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1017       MVT VT = (MVT::SimpleValueType)i;
1018
1019       // Do not attempt to promote non-128-bit vectors
1020       if (!VT.is128BitVector())
1021         continue;
1022
1023       setOperationAction(ISD::AND,    VT, Promote);
1024       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1025       setOperationAction(ISD::OR,     VT, Promote);
1026       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1027       setOperationAction(ISD::XOR,    VT, Promote);
1028       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1029       setOperationAction(ISD::LOAD,   VT, Promote);
1030       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1031       setOperationAction(ISD::SELECT, VT, Promote);
1032       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1033     }
1034
1035     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1036
1037     // Custom lower v2i64 and v2f64 selects.
1038     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1039     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1040     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1041     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1042
1043     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1044     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1045
1046     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1047     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1048     // As there is no 64-bit GPR available, we need build a special custom
1049     // sequence to convert from v2i32 to v2f32.
1050     if (!Subtarget->is64Bit())
1051       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1052
1053     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1054     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1055
1056     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1057
1058     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1059     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1060     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1061   }
1062
1063   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1064     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1065     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1066     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1067     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1068     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1072     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1074
1075     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1076     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1077     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1078     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1079     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1080     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1081     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1082     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1083     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1084     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1085
1086     // FIXME: Do we need to handle scalar-to-vector here?
1087     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1088
1089     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1090     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1091     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1092     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1093     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1094     // There is no BLENDI for byte vectors. We don't need to custom lower
1095     // some vselects for now.
1096     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1097
1098     // i8 and i16 vectors are custom , because the source register and source
1099     // source memory operand types are not the same width.  f32 vectors are
1100     // custom since the immediate controlling the insert encodes additional
1101     // information.
1102     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1103     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1104     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1105     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1106
1107     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1108     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1109     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1110     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1111
1112     // FIXME: these should be Legal but thats only for the case where
1113     // the index is constant.  For now custom expand to deal with that.
1114     if (Subtarget->is64Bit()) {
1115       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1116       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1117     }
1118   }
1119
1120   if (Subtarget->hasSSE2()) {
1121     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1122     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1123
1124     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1125     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1126
1127     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1128     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1129
1130     // In the customized shift lowering, the legal cases in AVX2 will be
1131     // recognized.
1132     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1133     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1134
1135     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1136     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1137
1138     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1139   }
1140
1141   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1142     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1143     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1144     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1145     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1146     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1147     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1148
1149     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1150     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1151     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1152
1153     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1154     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1155     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1156     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1157     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1158     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1159     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1160     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1161     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1162     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1163     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1164     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1165
1166     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1167     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1168     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1169     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1170     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1171     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1172     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1173     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1174     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1175     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1176     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1177     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1178
1179     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1180     // even though v8i16 is a legal type.
1181     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1182     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1183     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1184
1185     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1186     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1187     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1188
1189     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1190     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1191
1192     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1193
1194     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1195     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1196
1197     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1198     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1199
1200     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1201     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1202
1203     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1204     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1205     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1206     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1207
1208     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1209     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1210     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1211
1212     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1213     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1214     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1215     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1216
1217     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1218     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1219     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1220     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1221     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1222     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1223     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1224     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1225     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1226     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1227     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1228     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1229
1230     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1231       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1232       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1233       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1234       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1235       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1236       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1237     }
1238
1239     if (Subtarget->hasInt256()) {
1240       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1241       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1242       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1243       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1244
1245       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1246       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1247       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1248       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1249
1250       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1251       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1252       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1253       // Don't lower v32i8 because there is no 128-bit byte mul
1254
1255       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1256       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1257       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1258       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1259
1260       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1261       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1262     } else {
1263       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1264       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1265       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1266       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1267
1268       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1269       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1270       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1271       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1272
1273       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1274       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1275       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1276       // Don't lower v32i8 because there is no 128-bit byte mul
1277     }
1278
1279     // In the customized shift lowering, the legal cases in AVX2 will be
1280     // recognized.
1281     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1282     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1283
1284     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1285     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1286
1287     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1288
1289     // Custom lower several nodes for 256-bit types.
1290     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1291              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1292       MVT VT = (MVT::SimpleValueType)i;
1293
1294       // Extract subvector is special because the value type
1295       // (result) is 128-bit but the source is 256-bit wide.
1296       if (VT.is128BitVector())
1297         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1298
1299       // Do not attempt to custom lower other non-256-bit vectors
1300       if (!VT.is256BitVector())
1301         continue;
1302
1303       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1304       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1305       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1306       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1307       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1308       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1309       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1310     }
1311
1312     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1313     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1314       MVT VT = (MVT::SimpleValueType)i;
1315
1316       // Do not attempt to promote non-256-bit vectors
1317       if (!VT.is256BitVector())
1318         continue;
1319
1320       setOperationAction(ISD::AND,    VT, Promote);
1321       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1322       setOperationAction(ISD::OR,     VT, Promote);
1323       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1324       setOperationAction(ISD::XOR,    VT, Promote);
1325       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1326       setOperationAction(ISD::LOAD,   VT, Promote);
1327       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1328       setOperationAction(ISD::SELECT, VT, Promote);
1329       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1330     }
1331   }
1332
1333   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1334     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1335     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1336     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1337     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1338
1339     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1340     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1341     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1342
1343     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1344     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1345     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1346     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1347     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1348     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1349     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1350     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1351     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1352     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1353     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1354
1355     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1356     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1357     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1358     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1359     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1360     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1361
1362     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1363     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1364     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1365     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1366     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1367     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1368     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1369     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1370
1371     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1372     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1374     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1375     if (Subtarget->is64Bit()) {
1376       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1377       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1378       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1379       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1380     }
1381     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1382     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1383     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1384     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1385     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1386     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1387     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1388     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1389     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1390     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1391
1392     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1393     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1394     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1395     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1396     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1397     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1398     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1399     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1400     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1401     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1402     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1403     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1404     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1405
1406     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1407     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1408     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1409     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1410     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1411     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1412
1413     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1414     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1415
1416     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1417
1418     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1419     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1420     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1421     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1422     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1423     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1424     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1425     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1426     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1427
1428     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1429     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1430
1431     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1432     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1433
1434     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1435
1436     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1437     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1438
1439     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1440     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1441
1442     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1443     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1444
1445     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1446     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1447     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1448     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1449     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1450     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1451
1452     if (Subtarget->hasCDI()) {
1453       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1454       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1455     }
1456
1457     // Custom lower several nodes.
1458     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1459              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1460       MVT VT = (MVT::SimpleValueType)i;
1461
1462       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1463       // Extract subvector is special because the value type
1464       // (result) is 256/128-bit but the source is 512-bit wide.
1465       if (VT.is128BitVector() || VT.is256BitVector())
1466         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1467
1468       if (VT.getVectorElementType() == MVT::i1)
1469         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1470
1471       // Do not attempt to custom lower other non-512-bit vectors
1472       if (!VT.is512BitVector())
1473         continue;
1474
1475       if ( EltSize >= 32) {
1476         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1477         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1478         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1479         setOperationAction(ISD::VSELECT,             VT, Legal);
1480         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1481         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1482         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1483       }
1484     }
1485     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1486       MVT VT = (MVT::SimpleValueType)i;
1487
1488       // Do not attempt to promote non-256-bit vectors
1489       if (!VT.is512BitVector())
1490         continue;
1491
1492       setOperationAction(ISD::SELECT, VT, Promote);
1493       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1494     }
1495   }// has  AVX-512
1496
1497   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1498   // of this type with custom code.
1499   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1500            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1501     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1502                        Custom);
1503   }
1504
1505   // We want to custom lower some of our intrinsics.
1506   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1507   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1508   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1509   if (!Subtarget->is64Bit())
1510     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1511
1512   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1513   // handle type legalization for these operations here.
1514   //
1515   // FIXME: We really should do custom legalization for addition and
1516   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1517   // than generic legalization for 64-bit multiplication-with-overflow, though.
1518   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1519     // Add/Sub/Mul with overflow operations are custom lowered.
1520     MVT VT = IntVTs[i];
1521     setOperationAction(ISD::SADDO, VT, Custom);
1522     setOperationAction(ISD::UADDO, VT, Custom);
1523     setOperationAction(ISD::SSUBO, VT, Custom);
1524     setOperationAction(ISD::USUBO, VT, Custom);
1525     setOperationAction(ISD::SMULO, VT, Custom);
1526     setOperationAction(ISD::UMULO, VT, Custom);
1527   }
1528
1529   // There are no 8-bit 3-address imul/mul instructions
1530   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1531   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1532
1533   if (!Subtarget->is64Bit()) {
1534     // These libcalls are not available in 32-bit.
1535     setLibcallName(RTLIB::SHL_I128, nullptr);
1536     setLibcallName(RTLIB::SRL_I128, nullptr);
1537     setLibcallName(RTLIB::SRA_I128, nullptr);
1538   }
1539
1540   // Combine sin / cos into one node or libcall if possible.
1541   if (Subtarget->hasSinCos()) {
1542     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1543     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1544     if (Subtarget->isTargetDarwin()) {
1545       // For MacOSX, we don't want to the normal expansion of a libcall to
1546       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1547       // traffic.
1548       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1549       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1550     }
1551   }
1552
1553   if (Subtarget->isTargetWin64()) {
1554     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1555     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1556     setOperationAction(ISD::SREM, MVT::i128, Custom);
1557     setOperationAction(ISD::UREM, MVT::i128, Custom);
1558     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1559     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1560   }
1561
1562   // We have target-specific dag combine patterns for the following nodes:
1563   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1564   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1565   setTargetDAGCombine(ISD::VSELECT);
1566   setTargetDAGCombine(ISD::SELECT);
1567   setTargetDAGCombine(ISD::SHL);
1568   setTargetDAGCombine(ISD::SRA);
1569   setTargetDAGCombine(ISD::SRL);
1570   setTargetDAGCombine(ISD::OR);
1571   setTargetDAGCombine(ISD::AND);
1572   setTargetDAGCombine(ISD::ADD);
1573   setTargetDAGCombine(ISD::FADD);
1574   setTargetDAGCombine(ISD::FSUB);
1575   setTargetDAGCombine(ISD::FMA);
1576   setTargetDAGCombine(ISD::SUB);
1577   setTargetDAGCombine(ISD::LOAD);
1578   setTargetDAGCombine(ISD::STORE);
1579   setTargetDAGCombine(ISD::ZERO_EXTEND);
1580   setTargetDAGCombine(ISD::ANY_EXTEND);
1581   setTargetDAGCombine(ISD::SIGN_EXTEND);
1582   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1583   setTargetDAGCombine(ISD::TRUNCATE);
1584   setTargetDAGCombine(ISD::SINT_TO_FP);
1585   setTargetDAGCombine(ISD::SETCC);
1586   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1587   setTargetDAGCombine(ISD::BUILD_VECTOR);
1588   if (Subtarget->is64Bit())
1589     setTargetDAGCombine(ISD::MUL);
1590   setTargetDAGCombine(ISD::XOR);
1591
1592   computeRegisterProperties();
1593
1594   // On Darwin, -Os means optimize for size without hurting performance,
1595   // do not reduce the limit.
1596   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1597   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1598   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1599   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1600   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1601   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1602   setPrefLoopAlignment(4); // 2^4 bytes.
1603
1604   // Predictable cmov don't hurt on atom because it's in-order.
1605   PredictableSelectIsExpensive = !Subtarget->isAtom();
1606
1607   setPrefFunctionAlignment(4); // 2^4 bytes.
1608 }
1609
1610 TargetLoweringBase::LegalizeTypeAction
1611 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1612   if (ExperimentalVectorWideningLegalization &&
1613       VT.getVectorNumElements() != 1 &&
1614       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1615     return TypeWidenVector;
1616
1617   return TargetLoweringBase::getPreferredVectorAction(VT);
1618 }
1619
1620 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1621   if (!VT.isVector())
1622     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1623
1624   if (Subtarget->hasAVX512())
1625     switch(VT.getVectorNumElements()) {
1626     case  8: return MVT::v8i1;
1627     case 16: return MVT::v16i1;
1628   }
1629
1630   return VT.changeVectorElementTypeToInteger();
1631 }
1632
1633 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1634 /// the desired ByVal argument alignment.
1635 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1636   if (MaxAlign == 16)
1637     return;
1638   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1639     if (VTy->getBitWidth() == 128)
1640       MaxAlign = 16;
1641   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1642     unsigned EltAlign = 0;
1643     getMaxByValAlign(ATy->getElementType(), EltAlign);
1644     if (EltAlign > MaxAlign)
1645       MaxAlign = EltAlign;
1646   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1647     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1648       unsigned EltAlign = 0;
1649       getMaxByValAlign(STy->getElementType(i), EltAlign);
1650       if (EltAlign > MaxAlign)
1651         MaxAlign = EltAlign;
1652       if (MaxAlign == 16)
1653         break;
1654     }
1655   }
1656 }
1657
1658 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1659 /// function arguments in the caller parameter area. For X86, aggregates
1660 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1661 /// are at 4-byte boundaries.
1662 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1663   if (Subtarget->is64Bit()) {
1664     // Max of 8 and alignment of type.
1665     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1666     if (TyAlign > 8)
1667       return TyAlign;
1668     return 8;
1669   }
1670
1671   unsigned Align = 4;
1672   if (Subtarget->hasSSE1())
1673     getMaxByValAlign(Ty, Align);
1674   return Align;
1675 }
1676
1677 /// getOptimalMemOpType - Returns the target specific optimal type for load
1678 /// and store operations as a result of memset, memcpy, and memmove
1679 /// lowering. If DstAlign is zero that means it's safe to destination
1680 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1681 /// means there isn't a need to check it against alignment requirement,
1682 /// probably because the source does not need to be loaded. If 'IsMemset' is
1683 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1684 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1685 /// source is constant so it does not need to be loaded.
1686 /// It returns EVT::Other if the type should be determined using generic
1687 /// target-independent logic.
1688 EVT
1689 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1690                                        unsigned DstAlign, unsigned SrcAlign,
1691                                        bool IsMemset, bool ZeroMemset,
1692                                        bool MemcpyStrSrc,
1693                                        MachineFunction &MF) const {
1694   const Function *F = MF.getFunction();
1695   if ((!IsMemset || ZeroMemset) &&
1696       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1697                                        Attribute::NoImplicitFloat)) {
1698     if (Size >= 16 &&
1699         (Subtarget->isUnalignedMemAccessFast() ||
1700          ((DstAlign == 0 || DstAlign >= 16) &&
1701           (SrcAlign == 0 || SrcAlign >= 16)))) {
1702       if (Size >= 32) {
1703         if (Subtarget->hasInt256())
1704           return MVT::v8i32;
1705         if (Subtarget->hasFp256())
1706           return MVT::v8f32;
1707       }
1708       if (Subtarget->hasSSE2())
1709         return MVT::v4i32;
1710       if (Subtarget->hasSSE1())
1711         return MVT::v4f32;
1712     } else if (!MemcpyStrSrc && Size >= 8 &&
1713                !Subtarget->is64Bit() &&
1714                Subtarget->hasSSE2()) {
1715       // Do not use f64 to lower memcpy if source is string constant. It's
1716       // better to use i32 to avoid the loads.
1717       return MVT::f64;
1718     }
1719   }
1720   if (Subtarget->is64Bit() && Size >= 8)
1721     return MVT::i64;
1722   return MVT::i32;
1723 }
1724
1725 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1726   if (VT == MVT::f32)
1727     return X86ScalarSSEf32;
1728   else if (VT == MVT::f64)
1729     return X86ScalarSSEf64;
1730   return true;
1731 }
1732
1733 bool
1734 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1735                                                  unsigned,
1736                                                  bool *Fast) const {
1737   if (Fast)
1738     *Fast = Subtarget->isUnalignedMemAccessFast();
1739   return true;
1740 }
1741
1742 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1743 /// current function.  The returned value is a member of the
1744 /// MachineJumpTableInfo::JTEntryKind enum.
1745 unsigned X86TargetLowering::getJumpTableEncoding() const {
1746   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1747   // symbol.
1748   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1749       Subtarget->isPICStyleGOT())
1750     return MachineJumpTableInfo::EK_Custom32;
1751
1752   // Otherwise, use the normal jump table encoding heuristics.
1753   return TargetLowering::getJumpTableEncoding();
1754 }
1755
1756 const MCExpr *
1757 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1758                                              const MachineBasicBlock *MBB,
1759                                              unsigned uid,MCContext &Ctx) const{
1760   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1761          Subtarget->isPICStyleGOT());
1762   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1763   // entries.
1764   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1765                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1766 }
1767
1768 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1769 /// jumptable.
1770 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1771                                                     SelectionDAG &DAG) const {
1772   if (!Subtarget->is64Bit())
1773     // This doesn't have SDLoc associated with it, but is not really the
1774     // same as a Register.
1775     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1776   return Table;
1777 }
1778
1779 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1780 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1781 /// MCExpr.
1782 const MCExpr *X86TargetLowering::
1783 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1784                              MCContext &Ctx) const {
1785   // X86-64 uses RIP relative addressing based on the jump table label.
1786   if (Subtarget->isPICStyleRIPRel())
1787     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1788
1789   // Otherwise, the reference is relative to the PIC base.
1790   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1791 }
1792
1793 // FIXME: Why this routine is here? Move to RegInfo!
1794 std::pair<const TargetRegisterClass*, uint8_t>
1795 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1796   const TargetRegisterClass *RRC = nullptr;
1797   uint8_t Cost = 1;
1798   switch (VT.SimpleTy) {
1799   default:
1800     return TargetLowering::findRepresentativeClass(VT);
1801   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1802     RRC = Subtarget->is64Bit() ?
1803       (const TargetRegisterClass*)&X86::GR64RegClass :
1804       (const TargetRegisterClass*)&X86::GR32RegClass;
1805     break;
1806   case MVT::x86mmx:
1807     RRC = &X86::VR64RegClass;
1808     break;
1809   case MVT::f32: case MVT::f64:
1810   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1811   case MVT::v4f32: case MVT::v2f64:
1812   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1813   case MVT::v4f64:
1814     RRC = &X86::VR128RegClass;
1815     break;
1816   }
1817   return std::make_pair(RRC, Cost);
1818 }
1819
1820 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1821                                                unsigned &Offset) const {
1822   if (!Subtarget->isTargetLinux())
1823     return false;
1824
1825   if (Subtarget->is64Bit()) {
1826     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1827     Offset = 0x28;
1828     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1829       AddressSpace = 256;
1830     else
1831       AddressSpace = 257;
1832   } else {
1833     // %gs:0x14 on i386
1834     Offset = 0x14;
1835     AddressSpace = 256;
1836   }
1837   return true;
1838 }
1839
1840 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1841                                             unsigned DestAS) const {
1842   assert(SrcAS != DestAS && "Expected different address spaces!");
1843
1844   return SrcAS < 256 && DestAS < 256;
1845 }
1846
1847 //===----------------------------------------------------------------------===//
1848 //               Return Value Calling Convention Implementation
1849 //===----------------------------------------------------------------------===//
1850
1851 #include "X86GenCallingConv.inc"
1852
1853 bool
1854 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1855                                   MachineFunction &MF, bool isVarArg,
1856                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1857                         LLVMContext &Context) const {
1858   SmallVector<CCValAssign, 16> RVLocs;
1859   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1860                  RVLocs, Context);
1861   return CCInfo.CheckReturn(Outs, RetCC_X86);
1862 }
1863
1864 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1865   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1866   return ScratchRegs;
1867 }
1868
1869 SDValue
1870 X86TargetLowering::LowerReturn(SDValue Chain,
1871                                CallingConv::ID CallConv, bool isVarArg,
1872                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1873                                const SmallVectorImpl<SDValue> &OutVals,
1874                                SDLoc dl, SelectionDAG &DAG) const {
1875   MachineFunction &MF = DAG.getMachineFunction();
1876   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1877
1878   SmallVector<CCValAssign, 16> RVLocs;
1879   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1880                  RVLocs, *DAG.getContext());
1881   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1882
1883   SDValue Flag;
1884   SmallVector<SDValue, 6> RetOps;
1885   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1886   // Operand #1 = Bytes To Pop
1887   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1888                    MVT::i16));
1889
1890   // Copy the result values into the output registers.
1891   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1892     CCValAssign &VA = RVLocs[i];
1893     assert(VA.isRegLoc() && "Can only return in registers!");
1894     SDValue ValToCopy = OutVals[i];
1895     EVT ValVT = ValToCopy.getValueType();
1896
1897     // Promote values to the appropriate types
1898     if (VA.getLocInfo() == CCValAssign::SExt)
1899       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1900     else if (VA.getLocInfo() == CCValAssign::ZExt)
1901       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1902     else if (VA.getLocInfo() == CCValAssign::AExt)
1903       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1904     else if (VA.getLocInfo() == CCValAssign::BCvt)
1905       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1906
1907     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1908            "Unexpected FP-extend for return value.");  
1909
1910     // If this is x86-64, and we disabled SSE, we can't return FP values,
1911     // or SSE or MMX vectors.
1912     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1913          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1914           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1915       report_fatal_error("SSE register return with SSE disabled");
1916     }
1917     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1918     // llvm-gcc has never done it right and no one has noticed, so this
1919     // should be OK for now.
1920     if (ValVT == MVT::f64 &&
1921         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1922       report_fatal_error("SSE2 register return with SSE2 disabled");
1923
1924     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1925     // the RET instruction and handled by the FP Stackifier.
1926     if (VA.getLocReg() == X86::ST0 ||
1927         VA.getLocReg() == X86::ST1) {
1928       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1929       // change the value to the FP stack register class.
1930       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1931         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1932       RetOps.push_back(ValToCopy);
1933       // Don't emit a copytoreg.
1934       continue;
1935     }
1936
1937     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1938     // which is returned in RAX / RDX.
1939     if (Subtarget->is64Bit()) {
1940       if (ValVT == MVT::x86mmx) {
1941         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1942           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1943           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1944                                   ValToCopy);
1945           // If we don't have SSE2 available, convert to v4f32 so the generated
1946           // register is legal.
1947           if (!Subtarget->hasSSE2())
1948             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1949         }
1950       }
1951     }
1952
1953     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1954     Flag = Chain.getValue(1);
1955     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1956   }
1957
1958   // The x86-64 ABIs require that for returning structs by value we copy
1959   // the sret argument into %rax/%eax (depending on ABI) for the return.
1960   // Win32 requires us to put the sret argument to %eax as well.
1961   // We saved the argument into a virtual register in the entry block,
1962   // so now we copy the value out and into %rax/%eax.
1963   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1964       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1965     MachineFunction &MF = DAG.getMachineFunction();
1966     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1967     unsigned Reg = FuncInfo->getSRetReturnReg();
1968     assert(Reg &&
1969            "SRetReturnReg should have been set in LowerFormalArguments().");
1970     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1971
1972     unsigned RetValReg
1973         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1974           X86::RAX : X86::EAX;
1975     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1976     Flag = Chain.getValue(1);
1977
1978     // RAX/EAX now acts like a return value.
1979     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1980   }
1981
1982   RetOps[0] = Chain;  // Update chain.
1983
1984   // Add the flag if we have it.
1985   if (Flag.getNode())
1986     RetOps.push_back(Flag);
1987
1988   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1989 }
1990
1991 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1992   if (N->getNumValues() != 1)
1993     return false;
1994   if (!N->hasNUsesOfValue(1, 0))
1995     return false;
1996
1997   SDValue TCChain = Chain;
1998   SDNode *Copy = *N->use_begin();
1999   if (Copy->getOpcode() == ISD::CopyToReg) {
2000     // If the copy has a glue operand, we conservatively assume it isn't safe to
2001     // perform a tail call.
2002     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2003       return false;
2004     TCChain = Copy->getOperand(0);
2005   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2006     return false;
2007
2008   bool HasRet = false;
2009   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2010        UI != UE; ++UI) {
2011     if (UI->getOpcode() != X86ISD::RET_FLAG)
2012       return false;
2013     HasRet = true;
2014   }
2015
2016   if (!HasRet)
2017     return false;
2018
2019   Chain = TCChain;
2020   return true;
2021 }
2022
2023 MVT
2024 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2025                                             ISD::NodeType ExtendKind) const {
2026   MVT ReturnMVT;
2027   // TODO: Is this also valid on 32-bit?
2028   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2029     ReturnMVT = MVT::i8;
2030   else
2031     ReturnMVT = MVT::i32;
2032
2033   MVT MinVT = getRegisterType(ReturnMVT);
2034   return VT.bitsLT(MinVT) ? MinVT : VT;
2035 }
2036
2037 /// LowerCallResult - Lower the result values of a call into the
2038 /// appropriate copies out of appropriate physical registers.
2039 ///
2040 SDValue
2041 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2042                                    CallingConv::ID CallConv, bool isVarArg,
2043                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2044                                    SDLoc dl, SelectionDAG &DAG,
2045                                    SmallVectorImpl<SDValue> &InVals) const {
2046
2047   // Assign locations to each value returned by this call.
2048   SmallVector<CCValAssign, 16> RVLocs;
2049   bool Is64Bit = Subtarget->is64Bit();
2050   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2051                  DAG.getTarget(), RVLocs, *DAG.getContext());
2052   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2053
2054   // Copy all of the result registers out of their specified physreg.
2055   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2056     CCValAssign &VA = RVLocs[i];
2057     EVT CopyVT = VA.getValVT();
2058
2059     // If this is x86-64, and we disabled SSE, we can't return FP values
2060     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2061         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2062       report_fatal_error("SSE register return with SSE disabled");
2063     }
2064
2065     SDValue Val;
2066
2067     // If this is a call to a function that returns an fp value on the floating
2068     // point stack, we must guarantee the value is popped from the stack, so
2069     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2070     // if the return value is not used. We use the FpPOP_RETVAL instruction
2071     // instead.
2072     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2073       // If we prefer to use the value in xmm registers, copy it out as f80 and
2074       // use a truncate to move it from fp stack reg to xmm reg.
2075       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2076       SDValue Ops[] = { Chain, InFlag };
2077       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2078                                          MVT::Other, MVT::Glue, Ops), 1);
2079       Val = Chain.getValue(0);
2080
2081       // Round the f80 to the right size, which also moves it to the appropriate
2082       // xmm register.
2083       if (CopyVT != VA.getValVT())
2084         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2085                           // This truncation won't change the value.
2086                           DAG.getIntPtrConstant(1));
2087     } else {
2088       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2089                                  CopyVT, InFlag).getValue(1);
2090       Val = Chain.getValue(0);
2091     }
2092     InFlag = Chain.getValue(2);
2093     InVals.push_back(Val);
2094   }
2095
2096   return Chain;
2097 }
2098
2099 //===----------------------------------------------------------------------===//
2100 //                C & StdCall & Fast Calling Convention implementation
2101 //===----------------------------------------------------------------------===//
2102 //  StdCall calling convention seems to be standard for many Windows' API
2103 //  routines and around. It differs from C calling convention just a little:
2104 //  callee should clean up the stack, not caller. Symbols should be also
2105 //  decorated in some fancy way :) It doesn't support any vector arguments.
2106 //  For info on fast calling convention see Fast Calling Convention (tail call)
2107 //  implementation LowerX86_32FastCCCallTo.
2108
2109 /// CallIsStructReturn - Determines whether a call uses struct return
2110 /// semantics.
2111 enum StructReturnType {
2112   NotStructReturn,
2113   RegStructReturn,
2114   StackStructReturn
2115 };
2116 static StructReturnType
2117 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2118   if (Outs.empty())
2119     return NotStructReturn;
2120
2121   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2122   if (!Flags.isSRet())
2123     return NotStructReturn;
2124   if (Flags.isInReg())
2125     return RegStructReturn;
2126   return StackStructReturn;
2127 }
2128
2129 /// ArgsAreStructReturn - Determines whether a function uses struct
2130 /// return semantics.
2131 static StructReturnType
2132 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2133   if (Ins.empty())
2134     return NotStructReturn;
2135
2136   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2137   if (!Flags.isSRet())
2138     return NotStructReturn;
2139   if (Flags.isInReg())
2140     return RegStructReturn;
2141   return StackStructReturn;
2142 }
2143
2144 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2145 /// by "Src" to address "Dst" with size and alignment information specified by
2146 /// the specific parameter attribute. The copy will be passed as a byval
2147 /// function parameter.
2148 static SDValue
2149 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2150                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2151                           SDLoc dl) {
2152   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2153
2154   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2155                        /*isVolatile*/false, /*AlwaysInline=*/true,
2156                        MachinePointerInfo(), MachinePointerInfo());
2157 }
2158
2159 /// IsTailCallConvention - Return true if the calling convention is one that
2160 /// supports tail call optimization.
2161 static bool IsTailCallConvention(CallingConv::ID CC) {
2162   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2163           CC == CallingConv::HiPE);
2164 }
2165
2166 /// \brief Return true if the calling convention is a C calling convention.
2167 static bool IsCCallConvention(CallingConv::ID CC) {
2168   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2169           CC == CallingConv::X86_64_SysV);
2170 }
2171
2172 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2173   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2174     return false;
2175
2176   CallSite CS(CI);
2177   CallingConv::ID CalleeCC = CS.getCallingConv();
2178   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2179     return false;
2180
2181   return true;
2182 }
2183
2184 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2185 /// a tailcall target by changing its ABI.
2186 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2187                                    bool GuaranteedTailCallOpt) {
2188   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2189 }
2190
2191 SDValue
2192 X86TargetLowering::LowerMemArgument(SDValue Chain,
2193                                     CallingConv::ID CallConv,
2194                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2195                                     SDLoc dl, SelectionDAG &DAG,
2196                                     const CCValAssign &VA,
2197                                     MachineFrameInfo *MFI,
2198                                     unsigned i) const {
2199   // Create the nodes corresponding to a load from this parameter slot.
2200   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2201   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2202       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2203   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2204   EVT ValVT;
2205
2206   // If value is passed by pointer we have address passed instead of the value
2207   // itself.
2208   if (VA.getLocInfo() == CCValAssign::Indirect)
2209     ValVT = VA.getLocVT();
2210   else
2211     ValVT = VA.getValVT();
2212
2213   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2214   // changed with more analysis.
2215   // In case of tail call optimization mark all arguments mutable. Since they
2216   // could be overwritten by lowering of arguments in case of a tail call.
2217   if (Flags.isByVal()) {
2218     unsigned Bytes = Flags.getByValSize();
2219     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2220     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2221     return DAG.getFrameIndex(FI, getPointerTy());
2222   } else {
2223     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2224                                     VA.getLocMemOffset(), isImmutable);
2225     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2226     return DAG.getLoad(ValVT, dl, Chain, FIN,
2227                        MachinePointerInfo::getFixedStack(FI),
2228                        false, false, false, 0);
2229   }
2230 }
2231
2232 SDValue
2233 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2234                                         CallingConv::ID CallConv,
2235                                         bool isVarArg,
2236                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2237                                         SDLoc dl,
2238                                         SelectionDAG &DAG,
2239                                         SmallVectorImpl<SDValue> &InVals)
2240                                           const {
2241   MachineFunction &MF = DAG.getMachineFunction();
2242   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2243
2244   const Function* Fn = MF.getFunction();
2245   if (Fn->hasExternalLinkage() &&
2246       Subtarget->isTargetCygMing() &&
2247       Fn->getName() == "main")
2248     FuncInfo->setForceFramePointer(true);
2249
2250   MachineFrameInfo *MFI = MF.getFrameInfo();
2251   bool Is64Bit = Subtarget->is64Bit();
2252   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2253
2254   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2255          "Var args not supported with calling convention fastcc, ghc or hipe");
2256
2257   // Assign locations to all of the incoming arguments.
2258   SmallVector<CCValAssign, 16> ArgLocs;
2259   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2260                  ArgLocs, *DAG.getContext());
2261
2262   // Allocate shadow area for Win64
2263   if (IsWin64)
2264     CCInfo.AllocateStack(32, 8);
2265
2266   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2267
2268   unsigned LastVal = ~0U;
2269   SDValue ArgValue;
2270   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2271     CCValAssign &VA = ArgLocs[i];
2272     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2273     // places.
2274     assert(VA.getValNo() != LastVal &&
2275            "Don't support value assigned to multiple locs yet");
2276     (void)LastVal;
2277     LastVal = VA.getValNo();
2278
2279     if (VA.isRegLoc()) {
2280       EVT RegVT = VA.getLocVT();
2281       const TargetRegisterClass *RC;
2282       if (RegVT == MVT::i32)
2283         RC = &X86::GR32RegClass;
2284       else if (Is64Bit && RegVT == MVT::i64)
2285         RC = &X86::GR64RegClass;
2286       else if (RegVT == MVT::f32)
2287         RC = &X86::FR32RegClass;
2288       else if (RegVT == MVT::f64)
2289         RC = &X86::FR64RegClass;
2290       else if (RegVT.is512BitVector())
2291         RC = &X86::VR512RegClass;
2292       else if (RegVT.is256BitVector())
2293         RC = &X86::VR256RegClass;
2294       else if (RegVT.is128BitVector())
2295         RC = &X86::VR128RegClass;
2296       else if (RegVT == MVT::x86mmx)
2297         RC = &X86::VR64RegClass;
2298       else if (RegVT == MVT::i1)
2299         RC = &X86::VK1RegClass;
2300       else if (RegVT == MVT::v8i1)
2301         RC = &X86::VK8RegClass;
2302       else if (RegVT == MVT::v16i1)
2303         RC = &X86::VK16RegClass;
2304       else
2305         llvm_unreachable("Unknown argument type!");
2306
2307       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2308       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2309
2310       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2311       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2312       // right size.
2313       if (VA.getLocInfo() == CCValAssign::SExt)
2314         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2315                                DAG.getValueType(VA.getValVT()));
2316       else if (VA.getLocInfo() == CCValAssign::ZExt)
2317         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2318                                DAG.getValueType(VA.getValVT()));
2319       else if (VA.getLocInfo() == CCValAssign::BCvt)
2320         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2321
2322       if (VA.isExtInLoc()) {
2323         // Handle MMX values passed in XMM regs.
2324         if (RegVT.isVector())
2325           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2326         else
2327           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2328       }
2329     } else {
2330       assert(VA.isMemLoc());
2331       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2332     }
2333
2334     // If value is passed via pointer - do a load.
2335     if (VA.getLocInfo() == CCValAssign::Indirect)
2336       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2337                              MachinePointerInfo(), false, false, false, 0);
2338
2339     InVals.push_back(ArgValue);
2340   }
2341
2342   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2343     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2344       // The x86-64 ABIs require that for returning structs by value we copy
2345       // the sret argument into %rax/%eax (depending on ABI) for the return.
2346       // Win32 requires us to put the sret argument to %eax as well.
2347       // Save the argument into a virtual register so that we can access it
2348       // from the return points.
2349       if (Ins[i].Flags.isSRet()) {
2350         unsigned Reg = FuncInfo->getSRetReturnReg();
2351         if (!Reg) {
2352           MVT PtrTy = getPointerTy();
2353           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2354           FuncInfo->setSRetReturnReg(Reg);
2355         }
2356         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2357         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2358         break;
2359       }
2360     }
2361   }
2362
2363   unsigned StackSize = CCInfo.getNextStackOffset();
2364   // Align stack specially for tail calls.
2365   if (FuncIsMadeTailCallSafe(CallConv,
2366                              MF.getTarget().Options.GuaranteedTailCallOpt))
2367     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2368
2369   // If the function takes variable number of arguments, make a frame index for
2370   // the start of the first vararg value... for expansion of llvm.va_start.
2371   if (isVarArg) {
2372     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2373                     CallConv != CallingConv::X86_ThisCall)) {
2374       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2375     }
2376     if (Is64Bit) {
2377       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2378
2379       // FIXME: We should really autogenerate these arrays
2380       static const MCPhysReg GPR64ArgRegsWin64[] = {
2381         X86::RCX, X86::RDX, X86::R8,  X86::R9
2382       };
2383       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2384         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2385       };
2386       static const MCPhysReg XMMArgRegs64Bit[] = {
2387         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2388         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2389       };
2390       const MCPhysReg *GPR64ArgRegs;
2391       unsigned NumXMMRegs = 0;
2392
2393       if (IsWin64) {
2394         // The XMM registers which might contain var arg parameters are shadowed
2395         // in their paired GPR.  So we only need to save the GPR to their home
2396         // slots.
2397         TotalNumIntRegs = 4;
2398         GPR64ArgRegs = GPR64ArgRegsWin64;
2399       } else {
2400         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2401         GPR64ArgRegs = GPR64ArgRegs64Bit;
2402
2403         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2404                                                 TotalNumXMMRegs);
2405       }
2406       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2407                                                        TotalNumIntRegs);
2408
2409       bool NoImplicitFloatOps = Fn->getAttributes().
2410         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2411       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2412              "SSE register cannot be used when SSE is disabled!");
2413       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2414                NoImplicitFloatOps) &&
2415              "SSE register cannot be used when SSE is disabled!");
2416       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2417           !Subtarget->hasSSE1())
2418         // Kernel mode asks for SSE to be disabled, so don't push them
2419         // on the stack.
2420         TotalNumXMMRegs = 0;
2421
2422       if (IsWin64) {
2423         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2424         // Get to the caller-allocated home save location.  Add 8 to account
2425         // for the return address.
2426         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2427         FuncInfo->setRegSaveFrameIndex(
2428           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2429         // Fixup to set vararg frame on shadow area (4 x i64).
2430         if (NumIntRegs < 4)
2431           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2432       } else {
2433         // For X86-64, if there are vararg parameters that are passed via
2434         // registers, then we must store them to their spots on the stack so
2435         // they may be loaded by deferencing the result of va_next.
2436         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2437         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2438         FuncInfo->setRegSaveFrameIndex(
2439           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2440                                false));
2441       }
2442
2443       // Store the integer parameter registers.
2444       SmallVector<SDValue, 8> MemOps;
2445       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2446                                         getPointerTy());
2447       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2448       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2449         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2450                                   DAG.getIntPtrConstant(Offset));
2451         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2452                                      &X86::GR64RegClass);
2453         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2454         SDValue Store =
2455           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2456                        MachinePointerInfo::getFixedStack(
2457                          FuncInfo->getRegSaveFrameIndex(), Offset),
2458                        false, false, 0);
2459         MemOps.push_back(Store);
2460         Offset += 8;
2461       }
2462
2463       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2464         // Now store the XMM (fp + vector) parameter registers.
2465         SmallVector<SDValue, 11> SaveXMMOps;
2466         SaveXMMOps.push_back(Chain);
2467
2468         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2469         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2470         SaveXMMOps.push_back(ALVal);
2471
2472         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2473                                FuncInfo->getRegSaveFrameIndex()));
2474         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2475                                FuncInfo->getVarArgsFPOffset()));
2476
2477         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2478           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2479                                        &X86::VR128RegClass);
2480           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2481           SaveXMMOps.push_back(Val);
2482         }
2483         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2484                                      MVT::Other, SaveXMMOps));
2485       }
2486
2487       if (!MemOps.empty())
2488         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2489     }
2490   }
2491
2492   // Some CCs need callee pop.
2493   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2494                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2495     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2496   } else {
2497     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2498     // If this is an sret function, the return should pop the hidden pointer.
2499     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2500         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2501         argsAreStructReturn(Ins) == StackStructReturn)
2502       FuncInfo->setBytesToPopOnReturn(4);
2503   }
2504
2505   if (!Is64Bit) {
2506     // RegSaveFrameIndex is X86-64 only.
2507     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2508     if (CallConv == CallingConv::X86_FastCall ||
2509         CallConv == CallingConv::X86_ThisCall)
2510       // fastcc functions can't have varargs.
2511       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2512   }
2513
2514   FuncInfo->setArgumentStackSize(StackSize);
2515
2516   return Chain;
2517 }
2518
2519 SDValue
2520 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2521                                     SDValue StackPtr, SDValue Arg,
2522                                     SDLoc dl, SelectionDAG &DAG,
2523                                     const CCValAssign &VA,
2524                                     ISD::ArgFlagsTy Flags) const {
2525   unsigned LocMemOffset = VA.getLocMemOffset();
2526   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2527   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2528   if (Flags.isByVal())
2529     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2530
2531   return DAG.getStore(Chain, dl, Arg, PtrOff,
2532                       MachinePointerInfo::getStack(LocMemOffset),
2533                       false, false, 0);
2534 }
2535
2536 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2537 /// optimization is performed and it is required.
2538 SDValue
2539 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2540                                            SDValue &OutRetAddr, SDValue Chain,
2541                                            bool IsTailCall, bool Is64Bit,
2542                                            int FPDiff, SDLoc dl) const {
2543   // Adjust the Return address stack slot.
2544   EVT VT = getPointerTy();
2545   OutRetAddr = getReturnAddressFrameIndex(DAG);
2546
2547   // Load the "old" Return address.
2548   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2549                            false, false, false, 0);
2550   return SDValue(OutRetAddr.getNode(), 1);
2551 }
2552
2553 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2554 /// optimization is performed and it is required (FPDiff!=0).
2555 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2556                                         SDValue Chain, SDValue RetAddrFrIdx,
2557                                         EVT PtrVT, unsigned SlotSize,
2558                                         int FPDiff, SDLoc dl) {
2559   // Store the return address to the appropriate stack slot.
2560   if (!FPDiff) return Chain;
2561   // Calculate the new stack slot for the return address.
2562   int NewReturnAddrFI =
2563     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2564                                          false);
2565   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2566   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2567                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2568                        false, false, 0);
2569   return Chain;
2570 }
2571
2572 SDValue
2573 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2574                              SmallVectorImpl<SDValue> &InVals) const {
2575   SelectionDAG &DAG                     = CLI.DAG;
2576   SDLoc &dl                             = CLI.DL;
2577   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2578   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2579   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2580   SDValue Chain                         = CLI.Chain;
2581   SDValue Callee                        = CLI.Callee;
2582   CallingConv::ID CallConv              = CLI.CallConv;
2583   bool &isTailCall                      = CLI.IsTailCall;
2584   bool isVarArg                         = CLI.IsVarArg;
2585
2586   MachineFunction &MF = DAG.getMachineFunction();
2587   bool Is64Bit        = Subtarget->is64Bit();
2588   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2589   StructReturnType SR = callIsStructReturn(Outs);
2590   bool IsSibcall      = false;
2591
2592   if (MF.getTarget().Options.DisableTailCalls)
2593     isTailCall = false;
2594
2595   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2596   if (IsMustTail) {
2597     // Force this to be a tail call.  The verifier rules are enough to ensure
2598     // that we can lower this successfully without moving the return address
2599     // around.
2600     isTailCall = true;
2601   } else if (isTailCall) {
2602     // Check if it's really possible to do a tail call.
2603     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2604                     isVarArg, SR != NotStructReturn,
2605                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2606                     Outs, OutVals, Ins, DAG);
2607
2608     // Sibcalls are automatically detected tailcalls which do not require
2609     // ABI changes.
2610     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2611       IsSibcall = true;
2612
2613     if (isTailCall)
2614       ++NumTailCalls;
2615   }
2616
2617   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2618          "Var args not supported with calling convention fastcc, ghc or hipe");
2619
2620   // Analyze operands of the call, assigning locations to each operand.
2621   SmallVector<CCValAssign, 16> ArgLocs;
2622   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2623                  ArgLocs, *DAG.getContext());
2624
2625   // Allocate shadow area for Win64
2626   if (IsWin64)
2627     CCInfo.AllocateStack(32, 8);
2628
2629   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2630
2631   // Get a count of how many bytes are to be pushed on the stack.
2632   unsigned NumBytes = CCInfo.getNextStackOffset();
2633   if (IsSibcall)
2634     // This is a sibcall. The memory operands are available in caller's
2635     // own caller's stack.
2636     NumBytes = 0;
2637   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2638            IsTailCallConvention(CallConv))
2639     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2640
2641   int FPDiff = 0;
2642   if (isTailCall && !IsSibcall && !IsMustTail) {
2643     // Lower arguments at fp - stackoffset + fpdiff.
2644     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2645     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2646
2647     FPDiff = NumBytesCallerPushed - NumBytes;
2648
2649     // Set the delta of movement of the returnaddr stackslot.
2650     // But only set if delta is greater than previous delta.
2651     if (FPDiff < X86Info->getTCReturnAddrDelta())
2652       X86Info->setTCReturnAddrDelta(FPDiff);
2653   }
2654
2655   unsigned NumBytesToPush = NumBytes;
2656   unsigned NumBytesToPop = NumBytes;
2657
2658   // If we have an inalloca argument, all stack space has already been allocated
2659   // for us and be right at the top of the stack.  We don't support multiple
2660   // arguments passed in memory when using inalloca.
2661   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2662     NumBytesToPush = 0;
2663     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2664            "an inalloca argument must be the only memory argument");
2665   }
2666
2667   if (!IsSibcall)
2668     Chain = DAG.getCALLSEQ_START(
2669         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2670
2671   SDValue RetAddrFrIdx;
2672   // Load return address for tail calls.
2673   if (isTailCall && FPDiff)
2674     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2675                                     Is64Bit, FPDiff, dl);
2676
2677   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2678   SmallVector<SDValue, 8> MemOpChains;
2679   SDValue StackPtr;
2680
2681   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2682   // of tail call optimization arguments are handle later.
2683   const X86RegisterInfo *RegInfo =
2684     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2685   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2686     // Skip inalloca arguments, they have already been written.
2687     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2688     if (Flags.isInAlloca())
2689       continue;
2690
2691     CCValAssign &VA = ArgLocs[i];
2692     EVT RegVT = VA.getLocVT();
2693     SDValue Arg = OutVals[i];
2694     bool isByVal = Flags.isByVal();
2695
2696     // Promote the value if needed.
2697     switch (VA.getLocInfo()) {
2698     default: llvm_unreachable("Unknown loc info!");
2699     case CCValAssign::Full: break;
2700     case CCValAssign::SExt:
2701       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2702       break;
2703     case CCValAssign::ZExt:
2704       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2705       break;
2706     case CCValAssign::AExt:
2707       if (RegVT.is128BitVector()) {
2708         // Special case: passing MMX values in XMM registers.
2709         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2710         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2711         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2712       } else
2713         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2714       break;
2715     case CCValAssign::BCvt:
2716       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2717       break;
2718     case CCValAssign::Indirect: {
2719       // Store the argument.
2720       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2721       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2722       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2723                            MachinePointerInfo::getFixedStack(FI),
2724                            false, false, 0);
2725       Arg = SpillSlot;
2726       break;
2727     }
2728     }
2729
2730     if (VA.isRegLoc()) {
2731       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2732       if (isVarArg && IsWin64) {
2733         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2734         // shadow reg if callee is a varargs function.
2735         unsigned ShadowReg = 0;
2736         switch (VA.getLocReg()) {
2737         case X86::XMM0: ShadowReg = X86::RCX; break;
2738         case X86::XMM1: ShadowReg = X86::RDX; break;
2739         case X86::XMM2: ShadowReg = X86::R8; break;
2740         case X86::XMM3: ShadowReg = X86::R9; break;
2741         }
2742         if (ShadowReg)
2743           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2744       }
2745     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2746       assert(VA.isMemLoc());
2747       if (!StackPtr.getNode())
2748         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2749                                       getPointerTy());
2750       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2751                                              dl, DAG, VA, Flags));
2752     }
2753   }
2754
2755   if (!MemOpChains.empty())
2756     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2757
2758   if (Subtarget->isPICStyleGOT()) {
2759     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2760     // GOT pointer.
2761     if (!isTailCall) {
2762       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2763                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2764     } else {
2765       // If we are tail calling and generating PIC/GOT style code load the
2766       // address of the callee into ECX. The value in ecx is used as target of
2767       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2768       // for tail calls on PIC/GOT architectures. Normally we would just put the
2769       // address of GOT into ebx and then call target@PLT. But for tail calls
2770       // ebx would be restored (since ebx is callee saved) before jumping to the
2771       // target@PLT.
2772
2773       // Note: The actual moving to ECX is done further down.
2774       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2775       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2776           !G->getGlobal()->hasProtectedVisibility())
2777         Callee = LowerGlobalAddress(Callee, DAG);
2778       else if (isa<ExternalSymbolSDNode>(Callee))
2779         Callee = LowerExternalSymbol(Callee, DAG);
2780     }
2781   }
2782
2783   if (Is64Bit && isVarArg && !IsWin64) {
2784     // From AMD64 ABI document:
2785     // For calls that may call functions that use varargs or stdargs
2786     // (prototype-less calls or calls to functions containing ellipsis (...) in
2787     // the declaration) %al is used as hidden argument to specify the number
2788     // of SSE registers used. The contents of %al do not need to match exactly
2789     // the number of registers, but must be an ubound on the number of SSE
2790     // registers used and is in the range 0 - 8 inclusive.
2791
2792     // Count the number of XMM registers allocated.
2793     static const MCPhysReg XMMArgRegs[] = {
2794       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2795       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2796     };
2797     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2798     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2799            && "SSE registers cannot be used when SSE is disabled");
2800
2801     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2802                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2803   }
2804
2805   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2806   // don't need this because the eligibility check rejects calls that require
2807   // shuffling arguments passed in memory.
2808   if (!IsSibcall && isTailCall) {
2809     // Force all the incoming stack arguments to be loaded from the stack
2810     // before any new outgoing arguments are stored to the stack, because the
2811     // outgoing stack slots may alias the incoming argument stack slots, and
2812     // the alias isn't otherwise explicit. This is slightly more conservative
2813     // than necessary, because it means that each store effectively depends
2814     // on every argument instead of just those arguments it would clobber.
2815     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2816
2817     SmallVector<SDValue, 8> MemOpChains2;
2818     SDValue FIN;
2819     int FI = 0;
2820     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2821       CCValAssign &VA = ArgLocs[i];
2822       if (VA.isRegLoc())
2823         continue;
2824       assert(VA.isMemLoc());
2825       SDValue Arg = OutVals[i];
2826       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2827       // Skip inalloca arguments.  They don't require any work.
2828       if (Flags.isInAlloca())
2829         continue;
2830       // Create frame index.
2831       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2832       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2833       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2834       FIN = DAG.getFrameIndex(FI, getPointerTy());
2835
2836       if (Flags.isByVal()) {
2837         // Copy relative to framepointer.
2838         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2839         if (!StackPtr.getNode())
2840           StackPtr = DAG.getCopyFromReg(Chain, dl,
2841                                         RegInfo->getStackRegister(),
2842                                         getPointerTy());
2843         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2844
2845         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2846                                                          ArgChain,
2847                                                          Flags, DAG, dl));
2848       } else {
2849         // Store relative to framepointer.
2850         MemOpChains2.push_back(
2851           DAG.getStore(ArgChain, dl, Arg, FIN,
2852                        MachinePointerInfo::getFixedStack(FI),
2853                        false, false, 0));
2854       }
2855     }
2856
2857     if (!MemOpChains2.empty())
2858       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2859
2860     // Store the return address to the appropriate stack slot.
2861     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2862                                      getPointerTy(), RegInfo->getSlotSize(),
2863                                      FPDiff, dl);
2864   }
2865
2866   // Build a sequence of copy-to-reg nodes chained together with token chain
2867   // and flag operands which copy the outgoing args into registers.
2868   SDValue InFlag;
2869   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2870     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2871                              RegsToPass[i].second, InFlag);
2872     InFlag = Chain.getValue(1);
2873   }
2874
2875   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2876     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2877     // In the 64-bit large code model, we have to make all calls
2878     // through a register, since the call instruction's 32-bit
2879     // pc-relative offset may not be large enough to hold the whole
2880     // address.
2881   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2882     // If the callee is a GlobalAddress node (quite common, every direct call
2883     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2884     // it.
2885
2886     // We should use extra load for direct calls to dllimported functions in
2887     // non-JIT mode.
2888     const GlobalValue *GV = G->getGlobal();
2889     if (!GV->hasDLLImportStorageClass()) {
2890       unsigned char OpFlags = 0;
2891       bool ExtraLoad = false;
2892       unsigned WrapperKind = ISD::DELETED_NODE;
2893
2894       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2895       // external symbols most go through the PLT in PIC mode.  If the symbol
2896       // has hidden or protected visibility, or if it is static or local, then
2897       // we don't need to use the PLT - we can directly call it.
2898       if (Subtarget->isTargetELF() &&
2899           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2900           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2901         OpFlags = X86II::MO_PLT;
2902       } else if (Subtarget->isPICStyleStubAny() &&
2903                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2904                  (!Subtarget->getTargetTriple().isMacOSX() ||
2905                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2906         // PC-relative references to external symbols should go through $stub,
2907         // unless we're building with the leopard linker or later, which
2908         // automatically synthesizes these stubs.
2909         OpFlags = X86II::MO_DARWIN_STUB;
2910       } else if (Subtarget->isPICStyleRIPRel() &&
2911                  isa<Function>(GV) &&
2912                  cast<Function>(GV)->getAttributes().
2913                    hasAttribute(AttributeSet::FunctionIndex,
2914                                 Attribute::NonLazyBind)) {
2915         // If the function is marked as non-lazy, generate an indirect call
2916         // which loads from the GOT directly. This avoids runtime overhead
2917         // at the cost of eager binding (and one extra byte of encoding).
2918         OpFlags = X86II::MO_GOTPCREL;
2919         WrapperKind = X86ISD::WrapperRIP;
2920         ExtraLoad = true;
2921       }
2922
2923       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2924                                           G->getOffset(), OpFlags);
2925
2926       // Add a wrapper if needed.
2927       if (WrapperKind != ISD::DELETED_NODE)
2928         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2929       // Add extra indirection if needed.
2930       if (ExtraLoad)
2931         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2932                              MachinePointerInfo::getGOT(),
2933                              false, false, false, 0);
2934     }
2935   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2936     unsigned char OpFlags = 0;
2937
2938     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2939     // external symbols should go through the PLT.
2940     if (Subtarget->isTargetELF() &&
2941         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2942       OpFlags = X86II::MO_PLT;
2943     } else if (Subtarget->isPICStyleStubAny() &&
2944                (!Subtarget->getTargetTriple().isMacOSX() ||
2945                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2946       // PC-relative references to external symbols should go through $stub,
2947       // unless we're building with the leopard linker or later, which
2948       // automatically synthesizes these stubs.
2949       OpFlags = X86II::MO_DARWIN_STUB;
2950     }
2951
2952     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2953                                          OpFlags);
2954   }
2955
2956   // Returns a chain & a flag for retval copy to use.
2957   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2958   SmallVector<SDValue, 8> Ops;
2959
2960   if (!IsSibcall && isTailCall) {
2961     Chain = DAG.getCALLSEQ_END(Chain,
2962                                DAG.getIntPtrConstant(NumBytesToPop, true),
2963                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2964     InFlag = Chain.getValue(1);
2965   }
2966
2967   Ops.push_back(Chain);
2968   Ops.push_back(Callee);
2969
2970   if (isTailCall)
2971     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2972
2973   // Add argument registers to the end of the list so that they are known live
2974   // into the call.
2975   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2976     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2977                                   RegsToPass[i].second.getValueType()));
2978
2979   // Add a register mask operand representing the call-preserved registers.
2980   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2981   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2982   assert(Mask && "Missing call preserved mask for calling convention");
2983   Ops.push_back(DAG.getRegisterMask(Mask));
2984
2985   if (InFlag.getNode())
2986     Ops.push_back(InFlag);
2987
2988   if (isTailCall) {
2989     // We used to do:
2990     //// If this is the first return lowered for this function, add the regs
2991     //// to the liveout set for the function.
2992     // This isn't right, although it's probably harmless on x86; liveouts
2993     // should be computed from returns not tail calls.  Consider a void
2994     // function making a tail call to a function returning int.
2995     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2996   }
2997
2998   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2999   InFlag = Chain.getValue(1);
3000
3001   // Create the CALLSEQ_END node.
3002   unsigned NumBytesForCalleeToPop;
3003   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3004                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3005     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3006   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3007            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3008            SR == StackStructReturn)
3009     // If this is a call to a struct-return function, the callee
3010     // pops the hidden struct pointer, so we have to push it back.
3011     // This is common for Darwin/X86, Linux & Mingw32 targets.
3012     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3013     NumBytesForCalleeToPop = 4;
3014   else
3015     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3016
3017   // Returns a flag for retval copy to use.
3018   if (!IsSibcall) {
3019     Chain = DAG.getCALLSEQ_END(Chain,
3020                                DAG.getIntPtrConstant(NumBytesToPop, true),
3021                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3022                                                      true),
3023                                InFlag, dl);
3024     InFlag = Chain.getValue(1);
3025   }
3026
3027   // Handle result values, copying them out of physregs into vregs that we
3028   // return.
3029   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3030                          Ins, dl, DAG, InVals);
3031 }
3032
3033 //===----------------------------------------------------------------------===//
3034 //                Fast Calling Convention (tail call) implementation
3035 //===----------------------------------------------------------------------===//
3036
3037 //  Like std call, callee cleans arguments, convention except that ECX is
3038 //  reserved for storing the tail called function address. Only 2 registers are
3039 //  free for argument passing (inreg). Tail call optimization is performed
3040 //  provided:
3041 //                * tailcallopt is enabled
3042 //                * caller/callee are fastcc
3043 //  On X86_64 architecture with GOT-style position independent code only local
3044 //  (within module) calls are supported at the moment.
3045 //  To keep the stack aligned according to platform abi the function
3046 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3047 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3048 //  If a tail called function callee has more arguments than the caller the
3049 //  caller needs to make sure that there is room to move the RETADDR to. This is
3050 //  achieved by reserving an area the size of the argument delta right after the
3051 //  original RETADDR, but before the saved framepointer or the spilled registers
3052 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3053 //  stack layout:
3054 //    arg1
3055 //    arg2
3056 //    RETADDR
3057 //    [ new RETADDR
3058 //      move area ]
3059 //    (possible EBP)
3060 //    ESI
3061 //    EDI
3062 //    local1 ..
3063
3064 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3065 /// for a 16 byte align requirement.
3066 unsigned
3067 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3068                                                SelectionDAG& DAG) const {
3069   MachineFunction &MF = DAG.getMachineFunction();
3070   const TargetMachine &TM = MF.getTarget();
3071   const X86RegisterInfo *RegInfo =
3072     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3073   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3074   unsigned StackAlignment = TFI.getStackAlignment();
3075   uint64_t AlignMask = StackAlignment - 1;
3076   int64_t Offset = StackSize;
3077   unsigned SlotSize = RegInfo->getSlotSize();
3078   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3079     // Number smaller than 12 so just add the difference.
3080     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3081   } else {
3082     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3083     Offset = ((~AlignMask) & Offset) + StackAlignment +
3084       (StackAlignment-SlotSize);
3085   }
3086   return Offset;
3087 }
3088
3089 /// MatchingStackOffset - Return true if the given stack call argument is
3090 /// already available in the same position (relatively) of the caller's
3091 /// incoming argument stack.
3092 static
3093 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3094                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3095                          const X86InstrInfo *TII) {
3096   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3097   int FI = INT_MAX;
3098   if (Arg.getOpcode() == ISD::CopyFromReg) {
3099     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3100     if (!TargetRegisterInfo::isVirtualRegister(VR))
3101       return false;
3102     MachineInstr *Def = MRI->getVRegDef(VR);
3103     if (!Def)
3104       return false;
3105     if (!Flags.isByVal()) {
3106       if (!TII->isLoadFromStackSlot(Def, FI))
3107         return false;
3108     } else {
3109       unsigned Opcode = Def->getOpcode();
3110       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3111           Def->getOperand(1).isFI()) {
3112         FI = Def->getOperand(1).getIndex();
3113         Bytes = Flags.getByValSize();
3114       } else
3115         return false;
3116     }
3117   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3118     if (Flags.isByVal())
3119       // ByVal argument is passed in as a pointer but it's now being
3120       // dereferenced. e.g.
3121       // define @foo(%struct.X* %A) {
3122       //   tail call @bar(%struct.X* byval %A)
3123       // }
3124       return false;
3125     SDValue Ptr = Ld->getBasePtr();
3126     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3127     if (!FINode)
3128       return false;
3129     FI = FINode->getIndex();
3130   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3131     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3132     FI = FINode->getIndex();
3133     Bytes = Flags.getByValSize();
3134   } else
3135     return false;
3136
3137   assert(FI != INT_MAX);
3138   if (!MFI->isFixedObjectIndex(FI))
3139     return false;
3140   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3141 }
3142
3143 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3144 /// for tail call optimization. Targets which want to do tail call
3145 /// optimization should implement this function.
3146 bool
3147 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3148                                                      CallingConv::ID CalleeCC,
3149                                                      bool isVarArg,
3150                                                      bool isCalleeStructRet,
3151                                                      bool isCallerStructRet,
3152                                                      Type *RetTy,
3153                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3154                                     const SmallVectorImpl<SDValue> &OutVals,
3155                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3156                                                      SelectionDAG &DAG) const {
3157   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3158     return false;
3159
3160   // If -tailcallopt is specified, make fastcc functions tail-callable.
3161   const MachineFunction &MF = DAG.getMachineFunction();
3162   const Function *CallerF = MF.getFunction();
3163
3164   // If the function return type is x86_fp80 and the callee return type is not,
3165   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3166   // perform a tailcall optimization here.
3167   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3168     return false;
3169
3170   CallingConv::ID CallerCC = CallerF->getCallingConv();
3171   bool CCMatch = CallerCC == CalleeCC;
3172   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3173   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3174
3175   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3176     if (IsTailCallConvention(CalleeCC) && CCMatch)
3177       return true;
3178     return false;
3179   }
3180
3181   // Look for obvious safe cases to perform tail call optimization that do not
3182   // require ABI changes. This is what gcc calls sibcall.
3183
3184   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3185   // emit a special epilogue.
3186   const X86RegisterInfo *RegInfo =
3187     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3188   if (RegInfo->needsStackRealignment(MF))
3189     return false;
3190
3191   // Also avoid sibcall optimization if either caller or callee uses struct
3192   // return semantics.
3193   if (isCalleeStructRet || isCallerStructRet)
3194     return false;
3195
3196   // An stdcall/thiscall caller is expected to clean up its arguments; the
3197   // callee isn't going to do that.
3198   // FIXME: this is more restrictive than needed. We could produce a tailcall
3199   // when the stack adjustment matches. For example, with a thiscall that takes
3200   // only one argument.
3201   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3202                    CallerCC == CallingConv::X86_ThisCall))
3203     return false;
3204
3205   // Do not sibcall optimize vararg calls unless all arguments are passed via
3206   // registers.
3207   if (isVarArg && !Outs.empty()) {
3208
3209     // Optimizing for varargs on Win64 is unlikely to be safe without
3210     // additional testing.
3211     if (IsCalleeWin64 || IsCallerWin64)
3212       return false;
3213
3214     SmallVector<CCValAssign, 16> ArgLocs;
3215     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3216                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3217
3218     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3219     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3220       if (!ArgLocs[i].isRegLoc())
3221         return false;
3222   }
3223
3224   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3225   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3226   // this into a sibcall.
3227   bool Unused = false;
3228   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3229     if (!Ins[i].Used) {
3230       Unused = true;
3231       break;
3232     }
3233   }
3234   if (Unused) {
3235     SmallVector<CCValAssign, 16> RVLocs;
3236     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3237                    DAG.getTarget(), RVLocs, *DAG.getContext());
3238     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3239     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3240       CCValAssign &VA = RVLocs[i];
3241       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3242         return false;
3243     }
3244   }
3245
3246   // If the calling conventions do not match, then we'd better make sure the
3247   // results are returned in the same way as what the caller expects.
3248   if (!CCMatch) {
3249     SmallVector<CCValAssign, 16> RVLocs1;
3250     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3251                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3252     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3253
3254     SmallVector<CCValAssign, 16> RVLocs2;
3255     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3256                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3257     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3258
3259     if (RVLocs1.size() != RVLocs2.size())
3260       return false;
3261     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3262       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3263         return false;
3264       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3265         return false;
3266       if (RVLocs1[i].isRegLoc()) {
3267         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3268           return false;
3269       } else {
3270         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3271           return false;
3272       }
3273     }
3274   }
3275
3276   // If the callee takes no arguments then go on to check the results of the
3277   // call.
3278   if (!Outs.empty()) {
3279     // Check if stack adjustment is needed. For now, do not do this if any
3280     // argument is passed on the stack.
3281     SmallVector<CCValAssign, 16> ArgLocs;
3282     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3283                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3284
3285     // Allocate shadow area for Win64
3286     if (IsCalleeWin64)
3287       CCInfo.AllocateStack(32, 8);
3288
3289     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3290     if (CCInfo.getNextStackOffset()) {
3291       MachineFunction &MF = DAG.getMachineFunction();
3292       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3293         return false;
3294
3295       // Check if the arguments are already laid out in the right way as
3296       // the caller's fixed stack objects.
3297       MachineFrameInfo *MFI = MF.getFrameInfo();
3298       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3299       const X86InstrInfo *TII =
3300           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3301       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3302         CCValAssign &VA = ArgLocs[i];
3303         SDValue Arg = OutVals[i];
3304         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3305         if (VA.getLocInfo() == CCValAssign::Indirect)
3306           return false;
3307         if (!VA.isRegLoc()) {
3308           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3309                                    MFI, MRI, TII))
3310             return false;
3311         }
3312       }
3313     }
3314
3315     // If the tailcall address may be in a register, then make sure it's
3316     // possible to register allocate for it. In 32-bit, the call address can
3317     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3318     // callee-saved registers are restored. These happen to be the same
3319     // registers used to pass 'inreg' arguments so watch out for those.
3320     if (!Subtarget->is64Bit() &&
3321         ((!isa<GlobalAddressSDNode>(Callee) &&
3322           !isa<ExternalSymbolSDNode>(Callee)) ||
3323          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3324       unsigned NumInRegs = 0;
3325       // In PIC we need an extra register to formulate the address computation
3326       // for the callee.
3327       unsigned MaxInRegs =
3328         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3329
3330       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3331         CCValAssign &VA = ArgLocs[i];
3332         if (!VA.isRegLoc())
3333           continue;
3334         unsigned Reg = VA.getLocReg();
3335         switch (Reg) {
3336         default: break;
3337         case X86::EAX: case X86::EDX: case X86::ECX:
3338           if (++NumInRegs == MaxInRegs)
3339             return false;
3340           break;
3341         }
3342       }
3343     }
3344   }
3345
3346   return true;
3347 }
3348
3349 FastISel *
3350 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3351                                   const TargetLibraryInfo *libInfo) const {
3352   return X86::createFastISel(funcInfo, libInfo);
3353 }
3354
3355 //===----------------------------------------------------------------------===//
3356 //                           Other Lowering Hooks
3357 //===----------------------------------------------------------------------===//
3358
3359 static bool MayFoldLoad(SDValue Op) {
3360   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3361 }
3362
3363 static bool MayFoldIntoStore(SDValue Op) {
3364   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3365 }
3366
3367 static bool isTargetShuffle(unsigned Opcode) {
3368   switch(Opcode) {
3369   default: return false;
3370   case X86ISD::PSHUFD:
3371   case X86ISD::PSHUFHW:
3372   case X86ISD::PSHUFLW:
3373   case X86ISD::SHUFP:
3374   case X86ISD::PALIGNR:
3375   case X86ISD::MOVLHPS:
3376   case X86ISD::MOVLHPD:
3377   case X86ISD::MOVHLPS:
3378   case X86ISD::MOVLPS:
3379   case X86ISD::MOVLPD:
3380   case X86ISD::MOVSHDUP:
3381   case X86ISD::MOVSLDUP:
3382   case X86ISD::MOVDDUP:
3383   case X86ISD::MOVSS:
3384   case X86ISD::MOVSD:
3385   case X86ISD::UNPCKL:
3386   case X86ISD::UNPCKH:
3387   case X86ISD::VPERMILP:
3388   case X86ISD::VPERM2X128:
3389   case X86ISD::VPERMI:
3390     return true;
3391   }
3392 }
3393
3394 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3395                                     SDValue V1, SelectionDAG &DAG) {
3396   switch(Opc) {
3397   default: llvm_unreachable("Unknown x86 shuffle node");
3398   case X86ISD::MOVSHDUP:
3399   case X86ISD::MOVSLDUP:
3400   case X86ISD::MOVDDUP:
3401     return DAG.getNode(Opc, dl, VT, V1);
3402   }
3403 }
3404
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406                                     SDValue V1, unsigned TargetMask,
3407                                     SelectionDAG &DAG) {
3408   switch(Opc) {
3409   default: llvm_unreachable("Unknown x86 shuffle node");
3410   case X86ISD::PSHUFD:
3411   case X86ISD::PSHUFHW:
3412   case X86ISD::PSHUFLW:
3413   case X86ISD::VPERMILP:
3414   case X86ISD::VPERMI:
3415     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3416   }
3417 }
3418
3419 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3420                                     SDValue V1, SDValue V2, unsigned TargetMask,
3421                                     SelectionDAG &DAG) {
3422   switch(Opc) {
3423   default: llvm_unreachable("Unknown x86 shuffle node");
3424   case X86ISD::PALIGNR:
3425   case X86ISD::SHUFP:
3426   case X86ISD::VPERM2X128:
3427     return DAG.getNode(Opc, dl, VT, V1, V2,
3428                        DAG.getConstant(TargetMask, MVT::i8));
3429   }
3430 }
3431
3432 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3433                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3434   switch(Opc) {
3435   default: llvm_unreachable("Unknown x86 shuffle node");
3436   case X86ISD::MOVLHPS:
3437   case X86ISD::MOVLHPD:
3438   case X86ISD::MOVHLPS:
3439   case X86ISD::MOVLPS:
3440   case X86ISD::MOVLPD:
3441   case X86ISD::MOVSS:
3442   case X86ISD::MOVSD:
3443   case X86ISD::UNPCKL:
3444   case X86ISD::UNPCKH:
3445     return DAG.getNode(Opc, dl, VT, V1, V2);
3446   }
3447 }
3448
3449 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3450   MachineFunction &MF = DAG.getMachineFunction();
3451   const X86RegisterInfo *RegInfo =
3452     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3453   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3454   int ReturnAddrIndex = FuncInfo->getRAIndex();
3455
3456   if (ReturnAddrIndex == 0) {
3457     // Set up a frame object for the return address.
3458     unsigned SlotSize = RegInfo->getSlotSize();
3459     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3460                                                            -(int64_t)SlotSize,
3461                                                            false);
3462     FuncInfo->setRAIndex(ReturnAddrIndex);
3463   }
3464
3465   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3466 }
3467
3468 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3469                                        bool hasSymbolicDisplacement) {
3470   // Offset should fit into 32 bit immediate field.
3471   if (!isInt<32>(Offset))
3472     return false;
3473
3474   // If we don't have a symbolic displacement - we don't have any extra
3475   // restrictions.
3476   if (!hasSymbolicDisplacement)
3477     return true;
3478
3479   // FIXME: Some tweaks might be needed for medium code model.
3480   if (M != CodeModel::Small && M != CodeModel::Kernel)
3481     return false;
3482
3483   // For small code model we assume that latest object is 16MB before end of 31
3484   // bits boundary. We may also accept pretty large negative constants knowing
3485   // that all objects are in the positive half of address space.
3486   if (M == CodeModel::Small && Offset < 16*1024*1024)
3487     return true;
3488
3489   // For kernel code model we know that all object resist in the negative half
3490   // of 32bits address space. We may not accept negative offsets, since they may
3491   // be just off and we may accept pretty large positive ones.
3492   if (M == CodeModel::Kernel && Offset > 0)
3493     return true;
3494
3495   return false;
3496 }
3497
3498 /// isCalleePop - Determines whether the callee is required to pop its
3499 /// own arguments. Callee pop is necessary to support tail calls.
3500 bool X86::isCalleePop(CallingConv::ID CallingConv,
3501                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3502   if (IsVarArg)
3503     return false;
3504
3505   switch (CallingConv) {
3506   default:
3507     return false;
3508   case CallingConv::X86_StdCall:
3509     return !is64Bit;
3510   case CallingConv::X86_FastCall:
3511     return !is64Bit;
3512   case CallingConv::X86_ThisCall:
3513     return !is64Bit;
3514   case CallingConv::Fast:
3515     return TailCallOpt;
3516   case CallingConv::GHC:
3517     return TailCallOpt;
3518   case CallingConv::HiPE:
3519     return TailCallOpt;
3520   }
3521 }
3522
3523 /// \brief Return true if the condition is an unsigned comparison operation.
3524 static bool isX86CCUnsigned(unsigned X86CC) {
3525   switch (X86CC) {
3526   default: llvm_unreachable("Invalid integer condition!");
3527   case X86::COND_E:     return true;
3528   case X86::COND_G:     return false;
3529   case X86::COND_GE:    return false;
3530   case X86::COND_L:     return false;
3531   case X86::COND_LE:    return false;
3532   case X86::COND_NE:    return true;
3533   case X86::COND_B:     return true;
3534   case X86::COND_A:     return true;
3535   case X86::COND_BE:    return true;
3536   case X86::COND_AE:    return true;
3537   }
3538   llvm_unreachable("covered switch fell through?!");
3539 }
3540
3541 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3542 /// specific condition code, returning the condition code and the LHS/RHS of the
3543 /// comparison to make.
3544 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3545                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3546   if (!isFP) {
3547     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3548       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3549         // X > -1   -> X == 0, jump !sign.
3550         RHS = DAG.getConstant(0, RHS.getValueType());
3551         return X86::COND_NS;
3552       }
3553       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3554         // X < 0   -> X == 0, jump on sign.
3555         return X86::COND_S;
3556       }
3557       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3558         // X < 1   -> X <= 0
3559         RHS = DAG.getConstant(0, RHS.getValueType());
3560         return X86::COND_LE;
3561       }
3562     }
3563
3564     switch (SetCCOpcode) {
3565     default: llvm_unreachable("Invalid integer condition!");
3566     case ISD::SETEQ:  return X86::COND_E;
3567     case ISD::SETGT:  return X86::COND_G;
3568     case ISD::SETGE:  return X86::COND_GE;
3569     case ISD::SETLT:  return X86::COND_L;
3570     case ISD::SETLE:  return X86::COND_LE;
3571     case ISD::SETNE:  return X86::COND_NE;
3572     case ISD::SETULT: return X86::COND_B;
3573     case ISD::SETUGT: return X86::COND_A;
3574     case ISD::SETULE: return X86::COND_BE;
3575     case ISD::SETUGE: return X86::COND_AE;
3576     }
3577   }
3578
3579   // First determine if it is required or is profitable to flip the operands.
3580
3581   // If LHS is a foldable load, but RHS is not, flip the condition.
3582   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3583       !ISD::isNON_EXTLoad(RHS.getNode())) {
3584     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3585     std::swap(LHS, RHS);
3586   }
3587
3588   switch (SetCCOpcode) {
3589   default: break;
3590   case ISD::SETOLT:
3591   case ISD::SETOLE:
3592   case ISD::SETUGT:
3593   case ISD::SETUGE:
3594     std::swap(LHS, RHS);
3595     break;
3596   }
3597
3598   // On a floating point condition, the flags are set as follows:
3599   // ZF  PF  CF   op
3600   //  0 | 0 | 0 | X > Y
3601   //  0 | 0 | 1 | X < Y
3602   //  1 | 0 | 0 | X == Y
3603   //  1 | 1 | 1 | unordered
3604   switch (SetCCOpcode) {
3605   default: llvm_unreachable("Condcode should be pre-legalized away");
3606   case ISD::SETUEQ:
3607   case ISD::SETEQ:   return X86::COND_E;
3608   case ISD::SETOLT:              // flipped
3609   case ISD::SETOGT:
3610   case ISD::SETGT:   return X86::COND_A;
3611   case ISD::SETOLE:              // flipped
3612   case ISD::SETOGE:
3613   case ISD::SETGE:   return X86::COND_AE;
3614   case ISD::SETUGT:              // flipped
3615   case ISD::SETULT:
3616   case ISD::SETLT:   return X86::COND_B;
3617   case ISD::SETUGE:              // flipped
3618   case ISD::SETULE:
3619   case ISD::SETLE:   return X86::COND_BE;
3620   case ISD::SETONE:
3621   case ISD::SETNE:   return X86::COND_NE;
3622   case ISD::SETUO:   return X86::COND_P;
3623   case ISD::SETO:    return X86::COND_NP;
3624   case ISD::SETOEQ:
3625   case ISD::SETUNE:  return X86::COND_INVALID;
3626   }
3627 }
3628
3629 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3630 /// code. Current x86 isa includes the following FP cmov instructions:
3631 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3632 static bool hasFPCMov(unsigned X86CC) {
3633   switch (X86CC) {
3634   default:
3635     return false;
3636   case X86::COND_B:
3637   case X86::COND_BE:
3638   case X86::COND_E:
3639   case X86::COND_P:
3640   case X86::COND_A:
3641   case X86::COND_AE:
3642   case X86::COND_NE:
3643   case X86::COND_NP:
3644     return true;
3645   }
3646 }
3647
3648 /// isFPImmLegal - Returns true if the target can instruction select the
3649 /// specified FP immediate natively. If false, the legalizer will
3650 /// materialize the FP immediate as a load from a constant pool.
3651 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3652   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3653     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3654       return true;
3655   }
3656   return false;
3657 }
3658
3659 /// \brief Returns true if it is beneficial to convert a load of a constant
3660 /// to just the constant itself.
3661 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3662                                                           Type *Ty) const {
3663   assert(Ty->isIntegerTy());
3664
3665   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3666   if (BitSize == 0 || BitSize > 64)
3667     return false;
3668   return true;
3669 }
3670
3671 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3672 /// the specified range (L, H].
3673 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3674   return (Val < 0) || (Val >= Low && Val < Hi);
3675 }
3676
3677 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3678 /// specified value.
3679 static bool isUndefOrEqual(int Val, int CmpVal) {
3680   return (Val < 0 || Val == CmpVal);
3681 }
3682
3683 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3684 /// from position Pos and ending in Pos+Size, falls within the specified
3685 /// sequential range (L, L+Pos]. or is undef.
3686 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3687                                        unsigned Pos, unsigned Size, int Low) {
3688   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3689     if (!isUndefOrEqual(Mask[i], Low))
3690       return false;
3691   return true;
3692 }
3693
3694 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3695 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3696 /// the second operand.
3697 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3698   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3699     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3700   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3701     return (Mask[0] < 2 && Mask[1] < 2);
3702   return false;
3703 }
3704
3705 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3706 /// is suitable for input to PSHUFHW.
3707 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3708   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3709     return false;
3710
3711   // Lower quadword copied in order or undef.
3712   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3713     return false;
3714
3715   // Upper quadword shuffled.
3716   for (unsigned i = 4; i != 8; ++i)
3717     if (!isUndefOrInRange(Mask[i], 4, 8))
3718       return false;
3719
3720   if (VT == MVT::v16i16) {
3721     // Lower quadword copied in order or undef.
3722     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3723       return false;
3724
3725     // Upper quadword shuffled.
3726     for (unsigned i = 12; i != 16; ++i)
3727       if (!isUndefOrInRange(Mask[i], 12, 16))
3728         return false;
3729   }
3730
3731   return true;
3732 }
3733
3734 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3735 /// is suitable for input to PSHUFLW.
3736 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3737   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3738     return false;
3739
3740   // Upper quadword copied in order.
3741   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3742     return false;
3743
3744   // Lower quadword shuffled.
3745   for (unsigned i = 0; i != 4; ++i)
3746     if (!isUndefOrInRange(Mask[i], 0, 4))
3747       return false;
3748
3749   if (VT == MVT::v16i16) {
3750     // Upper quadword copied in order.
3751     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3752       return false;
3753
3754     // Lower quadword shuffled.
3755     for (unsigned i = 8; i != 12; ++i)
3756       if (!isUndefOrInRange(Mask[i], 8, 12))
3757         return false;
3758   }
3759
3760   return true;
3761 }
3762
3763 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3764 /// is suitable for input to PALIGNR.
3765 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3766                           const X86Subtarget *Subtarget) {
3767   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3768       (VT.is256BitVector() && !Subtarget->hasInt256()))
3769     return false;
3770
3771   unsigned NumElts = VT.getVectorNumElements();
3772   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3773   unsigned NumLaneElts = NumElts/NumLanes;
3774
3775   // Do not handle 64-bit element shuffles with palignr.
3776   if (NumLaneElts == 2)
3777     return false;
3778
3779   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3780     unsigned i;
3781     for (i = 0; i != NumLaneElts; ++i) {
3782       if (Mask[i+l] >= 0)
3783         break;
3784     }
3785
3786     // Lane is all undef, go to next lane
3787     if (i == NumLaneElts)
3788       continue;
3789
3790     int Start = Mask[i+l];
3791
3792     // Make sure its in this lane in one of the sources
3793     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3794         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3795       return false;
3796
3797     // If not lane 0, then we must match lane 0
3798     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3799       return false;
3800
3801     // Correct second source to be contiguous with first source
3802     if (Start >= (int)NumElts)
3803       Start -= NumElts - NumLaneElts;
3804
3805     // Make sure we're shifting in the right direction.
3806     if (Start <= (int)(i+l))
3807       return false;
3808
3809     Start -= i;
3810
3811     // Check the rest of the elements to see if they are consecutive.
3812     for (++i; i != NumLaneElts; ++i) {
3813       int Idx = Mask[i+l];
3814
3815       // Make sure its in this lane
3816       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3817           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3818         return false;
3819
3820       // If not lane 0, then we must match lane 0
3821       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3822         return false;
3823
3824       if (Idx >= (int)NumElts)
3825         Idx -= NumElts - NumLaneElts;
3826
3827       if (!isUndefOrEqual(Idx, Start+i))
3828         return false;
3829
3830     }
3831   }
3832
3833   return true;
3834 }
3835
3836 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3837 /// the two vector operands have swapped position.
3838 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3839                                      unsigned NumElems) {
3840   for (unsigned i = 0; i != NumElems; ++i) {
3841     int idx = Mask[i];
3842     if (idx < 0)
3843       continue;
3844     else if (idx < (int)NumElems)
3845       Mask[i] = idx + NumElems;
3846     else
3847       Mask[i] = idx - NumElems;
3848   }
3849 }
3850
3851 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3852 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3853 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3854 /// reverse of what x86 shuffles want.
3855 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3856
3857   unsigned NumElems = VT.getVectorNumElements();
3858   unsigned NumLanes = VT.getSizeInBits()/128;
3859   unsigned NumLaneElems = NumElems/NumLanes;
3860
3861   if (NumLaneElems != 2 && NumLaneElems != 4)
3862     return false;
3863
3864   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3865   bool symetricMaskRequired =
3866     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3867
3868   // VSHUFPSY divides the resulting vector into 4 chunks.
3869   // The sources are also splitted into 4 chunks, and each destination
3870   // chunk must come from a different source chunk.
3871   //
3872   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3873   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3874   //
3875   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3876   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3877   //
3878   // VSHUFPDY divides the resulting vector into 4 chunks.
3879   // The sources are also splitted into 4 chunks, and each destination
3880   // chunk must come from a different source chunk.
3881   //
3882   //  SRC1 =>      X3       X2       X1       X0
3883   //  SRC2 =>      Y3       Y2       Y1       Y0
3884   //
3885   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3886   //
3887   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3888   unsigned HalfLaneElems = NumLaneElems/2;
3889   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3890     for (unsigned i = 0; i != NumLaneElems; ++i) {
3891       int Idx = Mask[i+l];
3892       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3893       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3894         return false;
3895       // For VSHUFPSY, the mask of the second half must be the same as the
3896       // first but with the appropriate offsets. This works in the same way as
3897       // VPERMILPS works with masks.
3898       if (!symetricMaskRequired || Idx < 0)
3899         continue;
3900       if (MaskVal[i] < 0) {
3901         MaskVal[i] = Idx - l;
3902         continue;
3903       }
3904       if ((signed)(Idx - l) != MaskVal[i])
3905         return false;
3906     }
3907   }
3908
3909   return true;
3910 }
3911
3912 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3914 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3915   if (!VT.is128BitVector())
3916     return false;
3917
3918   unsigned NumElems = VT.getVectorNumElements();
3919
3920   if (NumElems != 4)
3921     return false;
3922
3923   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3924   return isUndefOrEqual(Mask[0], 6) &&
3925          isUndefOrEqual(Mask[1], 7) &&
3926          isUndefOrEqual(Mask[2], 2) &&
3927          isUndefOrEqual(Mask[3], 3);
3928 }
3929
3930 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3931 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3932 /// <2, 3, 2, 3>
3933 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3934   if (!VT.is128BitVector())
3935     return false;
3936
3937   unsigned NumElems = VT.getVectorNumElements();
3938
3939   if (NumElems != 4)
3940     return false;
3941
3942   return isUndefOrEqual(Mask[0], 2) &&
3943          isUndefOrEqual(Mask[1], 3) &&
3944          isUndefOrEqual(Mask[2], 2) &&
3945          isUndefOrEqual(Mask[3], 3);
3946 }
3947
3948 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3949 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3950 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3951   if (!VT.is128BitVector())
3952     return false;
3953
3954   unsigned NumElems = VT.getVectorNumElements();
3955
3956   if (NumElems != 2 && NumElems != 4)
3957     return false;
3958
3959   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3960     if (!isUndefOrEqual(Mask[i], i + NumElems))
3961       return false;
3962
3963   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3964     if (!isUndefOrEqual(Mask[i], i))
3965       return false;
3966
3967   return true;
3968 }
3969
3970 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3971 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3972 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3973   if (!VT.is128BitVector())
3974     return false;
3975
3976   unsigned NumElems = VT.getVectorNumElements();
3977
3978   if (NumElems != 2 && NumElems != 4)
3979     return false;
3980
3981   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3982     if (!isUndefOrEqual(Mask[i], i))
3983       return false;
3984
3985   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3986     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3987       return false;
3988
3989   return true;
3990 }
3991
3992 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3993 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3994 /// i. e: If all but one element come from the same vector.
3995 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3996   // TODO: Deal with AVX's VINSERTPS
3997   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3998     return false;
3999
4000   unsigned CorrectPosV1 = 0;
4001   unsigned CorrectPosV2 = 0;
4002   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4003     if (Mask[i] == -1) {
4004       ++CorrectPosV1;
4005       ++CorrectPosV2;
4006       continue;
4007     }
4008
4009     if (Mask[i] == i)
4010       ++CorrectPosV1;
4011     else if (Mask[i] == i + 4)
4012       ++CorrectPosV2;
4013   }
4014
4015   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4016     // We have 3 elements (undefs count as elements from any vector) from one
4017     // vector, and one from another.
4018     return true;
4019
4020   return false;
4021 }
4022
4023 //
4024 // Some special combinations that can be optimized.
4025 //
4026 static
4027 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4028                                SelectionDAG &DAG) {
4029   MVT VT = SVOp->getSimpleValueType(0);
4030   SDLoc dl(SVOp);
4031
4032   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4033     return SDValue();
4034
4035   ArrayRef<int> Mask = SVOp->getMask();
4036
4037   // These are the special masks that may be optimized.
4038   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4039   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4040   bool MatchEvenMask = true;
4041   bool MatchOddMask  = true;
4042   for (int i=0; i<8; ++i) {
4043     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4044       MatchEvenMask = false;
4045     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4046       MatchOddMask = false;
4047   }
4048
4049   if (!MatchEvenMask && !MatchOddMask)
4050     return SDValue();
4051
4052   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4053
4054   SDValue Op0 = SVOp->getOperand(0);
4055   SDValue Op1 = SVOp->getOperand(1);
4056
4057   if (MatchEvenMask) {
4058     // Shift the second operand right to 32 bits.
4059     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4060     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4061   } else {
4062     // Shift the first operand left to 32 bits.
4063     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4064     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4065   }
4066   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4067   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4068 }
4069
4070 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4071 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4072 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4073                          bool HasInt256, bool V2IsSplat = false) {
4074
4075   assert(VT.getSizeInBits() >= 128 &&
4076          "Unsupported vector type for unpckl");
4077
4078   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4079   unsigned NumLanes;
4080   unsigned NumOf256BitLanes;
4081   unsigned NumElts = VT.getVectorNumElements();
4082   if (VT.is256BitVector()) {
4083     if (NumElts != 4 && NumElts != 8 &&
4084         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4085     return false;
4086     NumLanes = 2;
4087     NumOf256BitLanes = 1;
4088   } else if (VT.is512BitVector()) {
4089     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4090            "Unsupported vector type for unpckh");
4091     NumLanes = 2;
4092     NumOf256BitLanes = 2;
4093   } else {
4094     NumLanes = 1;
4095     NumOf256BitLanes = 1;
4096   }
4097
4098   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4099   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4100
4101   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4102     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4103       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4104         int BitI  = Mask[l256*NumEltsInStride+l+i];
4105         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4106         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4107           return false;
4108         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4109           return false;
4110         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4111           return false;
4112       }
4113     }
4114   }
4115   return true;
4116 }
4117
4118 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4119 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4120 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4121                          bool HasInt256, bool V2IsSplat = false) {
4122   assert(VT.getSizeInBits() >= 128 &&
4123          "Unsupported vector type for unpckh");
4124
4125   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4126   unsigned NumLanes;
4127   unsigned NumOf256BitLanes;
4128   unsigned NumElts = VT.getVectorNumElements();
4129   if (VT.is256BitVector()) {
4130     if (NumElts != 4 && NumElts != 8 &&
4131         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4132     return false;
4133     NumLanes = 2;
4134     NumOf256BitLanes = 1;
4135   } else if (VT.is512BitVector()) {
4136     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4137            "Unsupported vector type for unpckh");
4138     NumLanes = 2;
4139     NumOf256BitLanes = 2;
4140   } else {
4141     NumLanes = 1;
4142     NumOf256BitLanes = 1;
4143   }
4144
4145   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4146   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4147
4148   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4149     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4150       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4151         int BitI  = Mask[l256*NumEltsInStride+l+i];
4152         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4153         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4154           return false;
4155         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4156           return false;
4157         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4158           return false;
4159       }
4160     }
4161   }
4162   return true;
4163 }
4164
4165 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4166 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4167 /// <0, 0, 1, 1>
4168 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4169   unsigned NumElts = VT.getVectorNumElements();
4170   bool Is256BitVec = VT.is256BitVector();
4171
4172   if (VT.is512BitVector())
4173     return false;
4174   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4175          "Unsupported vector type for unpckh");
4176
4177   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4178       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4179     return false;
4180
4181   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4182   // FIXME: Need a better way to get rid of this, there's no latency difference
4183   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4184   // the former later. We should also remove the "_undef" special mask.
4185   if (NumElts == 4 && Is256BitVec)
4186     return false;
4187
4188   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4189   // independently on 128-bit lanes.
4190   unsigned NumLanes = VT.getSizeInBits()/128;
4191   unsigned NumLaneElts = NumElts/NumLanes;
4192
4193   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4194     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4195       int BitI  = Mask[l+i];
4196       int BitI1 = Mask[l+i+1];
4197
4198       if (!isUndefOrEqual(BitI, j))
4199         return false;
4200       if (!isUndefOrEqual(BitI1, j))
4201         return false;
4202     }
4203   }
4204
4205   return true;
4206 }
4207
4208 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4209 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4210 /// <2, 2, 3, 3>
4211 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4212   unsigned NumElts = VT.getVectorNumElements();
4213
4214   if (VT.is512BitVector())
4215     return false;
4216
4217   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4218          "Unsupported vector type for unpckh");
4219
4220   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4221       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4222     return false;
4223
4224   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4225   // independently on 128-bit lanes.
4226   unsigned NumLanes = VT.getSizeInBits()/128;
4227   unsigned NumLaneElts = NumElts/NumLanes;
4228
4229   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4230     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4231       int BitI  = Mask[l+i];
4232       int BitI1 = Mask[l+i+1];
4233       if (!isUndefOrEqual(BitI, j))
4234         return false;
4235       if (!isUndefOrEqual(BitI1, j))
4236         return false;
4237     }
4238   }
4239   return true;
4240 }
4241
4242 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4243 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4244 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4245   if (!VT.is512BitVector())
4246     return false;
4247
4248   unsigned NumElts = VT.getVectorNumElements();
4249   unsigned HalfSize = NumElts/2;
4250   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4251     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4252       *Imm = 1;
4253       return true;
4254     }
4255   }
4256   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4257     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4258       *Imm = 0;
4259       return true;
4260     }
4261   }
4262   return false;
4263 }
4264
4265 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4266 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4267 /// MOVSD, and MOVD, i.e. setting the lowest element.
4268 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4269   if (VT.getVectorElementType().getSizeInBits() < 32)
4270     return false;
4271   if (!VT.is128BitVector())
4272     return false;
4273
4274   unsigned NumElts = VT.getVectorNumElements();
4275
4276   if (!isUndefOrEqual(Mask[0], NumElts))
4277     return false;
4278
4279   for (unsigned i = 1; i != NumElts; ++i)
4280     if (!isUndefOrEqual(Mask[i], i))
4281       return false;
4282
4283   return true;
4284 }
4285
4286 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4287 /// as permutations between 128-bit chunks or halves. As an example: this
4288 /// shuffle bellow:
4289 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4290 /// The first half comes from the second half of V1 and the second half from the
4291 /// the second half of V2.
4292 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4293   if (!HasFp256 || !VT.is256BitVector())
4294     return false;
4295
4296   // The shuffle result is divided into half A and half B. In total the two
4297   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4298   // B must come from C, D, E or F.
4299   unsigned HalfSize = VT.getVectorNumElements()/2;
4300   bool MatchA = false, MatchB = false;
4301
4302   // Check if A comes from one of C, D, E, F.
4303   for (unsigned Half = 0; Half != 4; ++Half) {
4304     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4305       MatchA = true;
4306       break;
4307     }
4308   }
4309
4310   // Check if B comes from one of C, D, E, F.
4311   for (unsigned Half = 0; Half != 4; ++Half) {
4312     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4313       MatchB = true;
4314       break;
4315     }
4316   }
4317
4318   return MatchA && MatchB;
4319 }
4320
4321 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4322 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4323 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4324   MVT VT = SVOp->getSimpleValueType(0);
4325
4326   unsigned HalfSize = VT.getVectorNumElements()/2;
4327
4328   unsigned FstHalf = 0, SndHalf = 0;
4329   for (unsigned i = 0; i < HalfSize; ++i) {
4330     if (SVOp->getMaskElt(i) > 0) {
4331       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4332       break;
4333     }
4334   }
4335   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4336     if (SVOp->getMaskElt(i) > 0) {
4337       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4338       break;
4339     }
4340   }
4341
4342   return (FstHalf | (SndHalf << 4));
4343 }
4344
4345 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4346 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4347   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4348   if (EltSize < 32)
4349     return false;
4350
4351   unsigned NumElts = VT.getVectorNumElements();
4352   Imm8 = 0;
4353   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4354     for (unsigned i = 0; i != NumElts; ++i) {
4355       if (Mask[i] < 0)
4356         continue;
4357       Imm8 |= Mask[i] << (i*2);
4358     }
4359     return true;
4360   }
4361
4362   unsigned LaneSize = 4;
4363   SmallVector<int, 4> MaskVal(LaneSize, -1);
4364
4365   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4366     for (unsigned i = 0; i != LaneSize; ++i) {
4367       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4368         return false;
4369       if (Mask[i+l] < 0)
4370         continue;
4371       if (MaskVal[i] < 0) {
4372         MaskVal[i] = Mask[i+l] - l;
4373         Imm8 |= MaskVal[i] << (i*2);
4374         continue;
4375       }
4376       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4377         return false;
4378     }
4379   }
4380   return true;
4381 }
4382
4383 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4384 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4385 /// Note that VPERMIL mask matching is different depending whether theunderlying
4386 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4387 /// to the same elements of the low, but to the higher half of the source.
4388 /// In VPERMILPD the two lanes could be shuffled independently of each other
4389 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4390 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4391   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4392   if (VT.getSizeInBits() < 256 || EltSize < 32)
4393     return false;
4394   bool symetricMaskRequired = (EltSize == 32);
4395   unsigned NumElts = VT.getVectorNumElements();
4396
4397   unsigned NumLanes = VT.getSizeInBits()/128;
4398   unsigned LaneSize = NumElts/NumLanes;
4399   // 2 or 4 elements in one lane
4400
4401   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4402   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4403     for (unsigned i = 0; i != LaneSize; ++i) {
4404       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4405         return false;
4406       if (symetricMaskRequired) {
4407         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4408           ExpectedMaskVal[i] = Mask[i+l] - l;
4409           continue;
4410         }
4411         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4412           return false;
4413       }
4414     }
4415   }
4416   return true;
4417 }
4418
4419 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4420 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4421 /// element of vector 2 and the other elements to come from vector 1 in order.
4422 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4423                                bool V2IsSplat = false, bool V2IsUndef = false) {
4424   if (!VT.is128BitVector())
4425     return false;
4426
4427   unsigned NumOps = VT.getVectorNumElements();
4428   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4429     return false;
4430
4431   if (!isUndefOrEqual(Mask[0], 0))
4432     return false;
4433
4434   for (unsigned i = 1; i != NumOps; ++i)
4435     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4436           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4437           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4438       return false;
4439
4440   return true;
4441 }
4442
4443 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4444 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4445 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4446 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4447                            const X86Subtarget *Subtarget) {
4448   if (!Subtarget->hasSSE3())
4449     return false;
4450
4451   unsigned NumElems = VT.getVectorNumElements();
4452
4453   if ((VT.is128BitVector() && NumElems != 4) ||
4454       (VT.is256BitVector() && NumElems != 8) ||
4455       (VT.is512BitVector() && NumElems != 16))
4456     return false;
4457
4458   // "i+1" is the value the indexed mask element must have
4459   for (unsigned i = 0; i != NumElems; i += 2)
4460     if (!isUndefOrEqual(Mask[i], i+1) ||
4461         !isUndefOrEqual(Mask[i+1], i+1))
4462       return false;
4463
4464   return true;
4465 }
4466
4467 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4468 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4469 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4470 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4471                            const X86Subtarget *Subtarget) {
4472   if (!Subtarget->hasSSE3())
4473     return false;
4474
4475   unsigned NumElems = VT.getVectorNumElements();
4476
4477   if ((VT.is128BitVector() && NumElems != 4) ||
4478       (VT.is256BitVector() && NumElems != 8) ||
4479       (VT.is512BitVector() && NumElems != 16))
4480     return false;
4481
4482   // "i" is the value the indexed mask element must have
4483   for (unsigned i = 0; i != NumElems; i += 2)
4484     if (!isUndefOrEqual(Mask[i], i) ||
4485         !isUndefOrEqual(Mask[i+1], i))
4486       return false;
4487
4488   return true;
4489 }
4490
4491 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4492 /// specifies a shuffle of elements that is suitable for input to 256-bit
4493 /// version of MOVDDUP.
4494 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4495   if (!HasFp256 || !VT.is256BitVector())
4496     return false;
4497
4498   unsigned NumElts = VT.getVectorNumElements();
4499   if (NumElts != 4)
4500     return false;
4501
4502   for (unsigned i = 0; i != NumElts/2; ++i)
4503     if (!isUndefOrEqual(Mask[i], 0))
4504       return false;
4505   for (unsigned i = NumElts/2; i != NumElts; ++i)
4506     if (!isUndefOrEqual(Mask[i], NumElts/2))
4507       return false;
4508   return true;
4509 }
4510
4511 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4512 /// specifies a shuffle of elements that is suitable for input to 128-bit
4513 /// version of MOVDDUP.
4514 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4515   if (!VT.is128BitVector())
4516     return false;
4517
4518   unsigned e = VT.getVectorNumElements() / 2;
4519   for (unsigned i = 0; i != e; ++i)
4520     if (!isUndefOrEqual(Mask[i], i))
4521       return false;
4522   for (unsigned i = 0; i != e; ++i)
4523     if (!isUndefOrEqual(Mask[e+i], i))
4524       return false;
4525   return true;
4526 }
4527
4528 /// isVEXTRACTIndex - Return true if the specified
4529 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4530 /// suitable for instruction that extract 128 or 256 bit vectors
4531 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4532   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4533   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4534     return false;
4535
4536   // The index should be aligned on a vecWidth-bit boundary.
4537   uint64_t Index =
4538     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4539
4540   MVT VT = N->getSimpleValueType(0);
4541   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4542   bool Result = (Index * ElSize) % vecWidth == 0;
4543
4544   return Result;
4545 }
4546
4547 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4548 /// operand specifies a subvector insert that is suitable for input to
4549 /// insertion of 128 or 256-bit subvectors
4550 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4551   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4552   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4553     return false;
4554   // The index should be aligned on a vecWidth-bit boundary.
4555   uint64_t Index =
4556     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4557
4558   MVT VT = N->getSimpleValueType(0);
4559   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4560   bool Result = (Index * ElSize) % vecWidth == 0;
4561
4562   return Result;
4563 }
4564
4565 bool X86::isVINSERT128Index(SDNode *N) {
4566   return isVINSERTIndex(N, 128);
4567 }
4568
4569 bool X86::isVINSERT256Index(SDNode *N) {
4570   return isVINSERTIndex(N, 256);
4571 }
4572
4573 bool X86::isVEXTRACT128Index(SDNode *N) {
4574   return isVEXTRACTIndex(N, 128);
4575 }
4576
4577 bool X86::isVEXTRACT256Index(SDNode *N) {
4578   return isVEXTRACTIndex(N, 256);
4579 }
4580
4581 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4582 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4583 /// Handles 128-bit and 256-bit.
4584 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4585   MVT VT = N->getSimpleValueType(0);
4586
4587   assert((VT.getSizeInBits() >= 128) &&
4588          "Unsupported vector type for PSHUF/SHUFP");
4589
4590   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4591   // independently on 128-bit lanes.
4592   unsigned NumElts = VT.getVectorNumElements();
4593   unsigned NumLanes = VT.getSizeInBits()/128;
4594   unsigned NumLaneElts = NumElts/NumLanes;
4595
4596   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4597          "Only supports 2, 4 or 8 elements per lane");
4598
4599   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4600   unsigned Mask = 0;
4601   for (unsigned i = 0; i != NumElts; ++i) {
4602     int Elt = N->getMaskElt(i);
4603     if (Elt < 0) continue;
4604     Elt &= NumLaneElts - 1;
4605     unsigned ShAmt = (i << Shift) % 8;
4606     Mask |= Elt << ShAmt;
4607   }
4608
4609   return Mask;
4610 }
4611
4612 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4613 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4614 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4615   MVT VT = N->getSimpleValueType(0);
4616
4617   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4618          "Unsupported vector type for PSHUFHW");
4619
4620   unsigned NumElts = VT.getVectorNumElements();
4621
4622   unsigned Mask = 0;
4623   for (unsigned l = 0; l != NumElts; l += 8) {
4624     // 8 nodes per lane, but we only care about the last 4.
4625     for (unsigned i = 0; i < 4; ++i) {
4626       int Elt = N->getMaskElt(l+i+4);
4627       if (Elt < 0) continue;
4628       Elt &= 0x3; // only 2-bits.
4629       Mask |= Elt << (i * 2);
4630     }
4631   }
4632
4633   return Mask;
4634 }
4635
4636 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4637 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4638 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4639   MVT VT = N->getSimpleValueType(0);
4640
4641   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4642          "Unsupported vector type for PSHUFHW");
4643
4644   unsigned NumElts = VT.getVectorNumElements();
4645
4646   unsigned Mask = 0;
4647   for (unsigned l = 0; l != NumElts; l += 8) {
4648     // 8 nodes per lane, but we only care about the first 4.
4649     for (unsigned i = 0; i < 4; ++i) {
4650       int Elt = N->getMaskElt(l+i);
4651       if (Elt < 0) continue;
4652       Elt &= 0x3; // only 2-bits
4653       Mask |= Elt << (i * 2);
4654     }
4655   }
4656
4657   return Mask;
4658 }
4659
4660 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4661 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4662 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4663   MVT VT = SVOp->getSimpleValueType(0);
4664   unsigned EltSize = VT.is512BitVector() ? 1 :
4665     VT.getVectorElementType().getSizeInBits() >> 3;
4666
4667   unsigned NumElts = VT.getVectorNumElements();
4668   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4669   unsigned NumLaneElts = NumElts/NumLanes;
4670
4671   int Val = 0;
4672   unsigned i;
4673   for (i = 0; i != NumElts; ++i) {
4674     Val = SVOp->getMaskElt(i);
4675     if (Val >= 0)
4676       break;
4677   }
4678   if (Val >= (int)NumElts)
4679     Val -= NumElts - NumLaneElts;
4680
4681   assert(Val - i > 0 && "PALIGNR imm should be positive");
4682   return (Val - i) * EltSize;
4683 }
4684
4685 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4686   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4687   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4688     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4689
4690   uint64_t Index =
4691     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4692
4693   MVT VecVT = N->getOperand(0).getSimpleValueType();
4694   MVT ElVT = VecVT.getVectorElementType();
4695
4696   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4697   return Index / NumElemsPerChunk;
4698 }
4699
4700 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4701   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4702   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4703     llvm_unreachable("Illegal insert subvector for VINSERT");
4704
4705   uint64_t Index =
4706     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4707
4708   MVT VecVT = N->getSimpleValueType(0);
4709   MVT ElVT = VecVT.getVectorElementType();
4710
4711   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4712   return Index / NumElemsPerChunk;
4713 }
4714
4715 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4716 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4717 /// and VINSERTI128 instructions.
4718 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4719   return getExtractVEXTRACTImmediate(N, 128);
4720 }
4721
4722 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4723 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4724 /// and VINSERTI64x4 instructions.
4725 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4726   return getExtractVEXTRACTImmediate(N, 256);
4727 }
4728
4729 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4730 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4731 /// and VINSERTI128 instructions.
4732 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4733   return getInsertVINSERTImmediate(N, 128);
4734 }
4735
4736 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4737 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4738 /// and VINSERTI64x4 instructions.
4739 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4740   return getInsertVINSERTImmediate(N, 256);
4741 }
4742
4743 /// isZero - Returns true if Elt is a constant integer zero
4744 static bool isZero(SDValue V) {
4745   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4746   return C && C->isNullValue();
4747 }
4748
4749 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4750 /// constant +0.0.
4751 bool X86::isZeroNode(SDValue Elt) {
4752   if (isZero(Elt))
4753     return true;
4754   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4755     return CFP->getValueAPF().isPosZero();
4756   return false;
4757 }
4758
4759 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4760 /// their permute mask.
4761 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4762                                     SelectionDAG &DAG) {
4763   MVT VT = SVOp->getSimpleValueType(0);
4764   unsigned NumElems = VT.getVectorNumElements();
4765   SmallVector<int, 8> MaskVec;
4766
4767   for (unsigned i = 0; i != NumElems; ++i) {
4768     int Idx = SVOp->getMaskElt(i);
4769     if (Idx >= 0) {
4770       if (Idx < (int)NumElems)
4771         Idx += NumElems;
4772       else
4773         Idx -= NumElems;
4774     }
4775     MaskVec.push_back(Idx);
4776   }
4777   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4778                               SVOp->getOperand(0), &MaskVec[0]);
4779 }
4780
4781 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4782 /// match movhlps. The lower half elements should come from upper half of
4783 /// V1 (and in order), and the upper half elements should come from the upper
4784 /// half of V2 (and in order).
4785 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4786   if (!VT.is128BitVector())
4787     return false;
4788   if (VT.getVectorNumElements() != 4)
4789     return false;
4790   for (unsigned i = 0, e = 2; i != e; ++i)
4791     if (!isUndefOrEqual(Mask[i], i+2))
4792       return false;
4793   for (unsigned i = 2; i != 4; ++i)
4794     if (!isUndefOrEqual(Mask[i], i+4))
4795       return false;
4796   return true;
4797 }
4798
4799 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4800 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4801 /// required.
4802 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4803   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4804     return false;
4805   N = N->getOperand(0).getNode();
4806   if (!ISD::isNON_EXTLoad(N))
4807     return false;
4808   if (LD)
4809     *LD = cast<LoadSDNode>(N);
4810   return true;
4811 }
4812
4813 // Test whether the given value is a vector value which will be legalized
4814 // into a load.
4815 static bool WillBeConstantPoolLoad(SDNode *N) {
4816   if (N->getOpcode() != ISD::BUILD_VECTOR)
4817     return false;
4818
4819   // Check for any non-constant elements.
4820   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4821     switch (N->getOperand(i).getNode()->getOpcode()) {
4822     case ISD::UNDEF:
4823     case ISD::ConstantFP:
4824     case ISD::Constant:
4825       break;
4826     default:
4827       return false;
4828     }
4829
4830   // Vectors of all-zeros and all-ones are materialized with special
4831   // instructions rather than being loaded.
4832   return !ISD::isBuildVectorAllZeros(N) &&
4833          !ISD::isBuildVectorAllOnes(N);
4834 }
4835
4836 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4837 /// match movlp{s|d}. The lower half elements should come from lower half of
4838 /// V1 (and in order), and the upper half elements should come from the upper
4839 /// half of V2 (and in order). And since V1 will become the source of the
4840 /// MOVLP, it must be either a vector load or a scalar load to vector.
4841 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4842                                ArrayRef<int> Mask, MVT VT) {
4843   if (!VT.is128BitVector())
4844     return false;
4845
4846   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4847     return false;
4848   // Is V2 is a vector load, don't do this transformation. We will try to use
4849   // load folding shufps op.
4850   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4851     return false;
4852
4853   unsigned NumElems = VT.getVectorNumElements();
4854
4855   if (NumElems != 2 && NumElems != 4)
4856     return false;
4857   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4858     if (!isUndefOrEqual(Mask[i], i))
4859       return false;
4860   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4861     if (!isUndefOrEqual(Mask[i], i+NumElems))
4862       return false;
4863   return true;
4864 }
4865
4866 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4867 /// to an zero vector.
4868 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4869 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4870   SDValue V1 = N->getOperand(0);
4871   SDValue V2 = N->getOperand(1);
4872   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4873   for (unsigned i = 0; i != NumElems; ++i) {
4874     int Idx = N->getMaskElt(i);
4875     if (Idx >= (int)NumElems) {
4876       unsigned Opc = V2.getOpcode();
4877       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4878         continue;
4879       if (Opc != ISD::BUILD_VECTOR ||
4880           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4881         return false;
4882     } else if (Idx >= 0) {
4883       unsigned Opc = V1.getOpcode();
4884       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4885         continue;
4886       if (Opc != ISD::BUILD_VECTOR ||
4887           !X86::isZeroNode(V1.getOperand(Idx)))
4888         return false;
4889     }
4890   }
4891   return true;
4892 }
4893
4894 /// getZeroVector - Returns a vector of specified type with all zero elements.
4895 ///
4896 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4897                              SelectionDAG &DAG, SDLoc dl) {
4898   assert(VT.isVector() && "Expected a vector type");
4899
4900   // Always build SSE zero vectors as <4 x i32> bitcasted
4901   // to their dest type. This ensures they get CSE'd.
4902   SDValue Vec;
4903   if (VT.is128BitVector()) {  // SSE
4904     if (Subtarget->hasSSE2()) {  // SSE2
4905       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4906       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4907     } else { // SSE1
4908       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4909       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4910     }
4911   } else if (VT.is256BitVector()) { // AVX
4912     if (Subtarget->hasInt256()) { // AVX2
4913       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4914       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4915       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4916     } else {
4917       // 256-bit logic and arithmetic instructions in AVX are all
4918       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4919       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4920       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4921       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4922     }
4923   } else if (VT.is512BitVector()) { // AVX-512
4924       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4925       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4926                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4927       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4928   } else if (VT.getScalarType() == MVT::i1) {
4929     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4930     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4931     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4932     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4933   } else
4934     llvm_unreachable("Unexpected vector type");
4935
4936   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4937 }
4938
4939 /// getOnesVector - Returns a vector of specified type with all bits set.
4940 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4941 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4942 /// Then bitcast to their original type, ensuring they get CSE'd.
4943 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4944                              SDLoc dl) {
4945   assert(VT.isVector() && "Expected a vector type");
4946
4947   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4948   SDValue Vec;
4949   if (VT.is256BitVector()) {
4950     if (HasInt256) { // AVX2
4951       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4952       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4953     } else { // AVX
4954       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4955       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4956     }
4957   } else if (VT.is128BitVector()) {
4958     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4959   } else
4960     llvm_unreachable("Unexpected vector type");
4961
4962   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4963 }
4964
4965 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4966 /// that point to V2 points to its first element.
4967 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4968   for (unsigned i = 0; i != NumElems; ++i) {
4969     if (Mask[i] > (int)NumElems) {
4970       Mask[i] = NumElems;
4971     }
4972   }
4973 }
4974
4975 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4976 /// operation of specified width.
4977 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4978                        SDValue V2) {
4979   unsigned NumElems = VT.getVectorNumElements();
4980   SmallVector<int, 8> Mask;
4981   Mask.push_back(NumElems);
4982   for (unsigned i = 1; i != NumElems; ++i)
4983     Mask.push_back(i);
4984   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4985 }
4986
4987 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4988 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4989                           SDValue V2) {
4990   unsigned NumElems = VT.getVectorNumElements();
4991   SmallVector<int, 8> Mask;
4992   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4993     Mask.push_back(i);
4994     Mask.push_back(i + NumElems);
4995   }
4996   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4997 }
4998
4999 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5000 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5001                           SDValue V2) {
5002   unsigned NumElems = VT.getVectorNumElements();
5003   SmallVector<int, 8> Mask;
5004   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5005     Mask.push_back(i + Half);
5006     Mask.push_back(i + NumElems + Half);
5007   }
5008   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5009 }
5010
5011 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5012 // a generic shuffle instruction because the target has no such instructions.
5013 // Generate shuffles which repeat i16 and i8 several times until they can be
5014 // represented by v4f32 and then be manipulated by target suported shuffles.
5015 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5016   MVT VT = V.getSimpleValueType();
5017   int NumElems = VT.getVectorNumElements();
5018   SDLoc dl(V);
5019
5020   while (NumElems > 4) {
5021     if (EltNo < NumElems/2) {
5022       V = getUnpackl(DAG, dl, VT, V, V);
5023     } else {
5024       V = getUnpackh(DAG, dl, VT, V, V);
5025       EltNo -= NumElems/2;
5026     }
5027     NumElems >>= 1;
5028   }
5029   return V;
5030 }
5031
5032 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5033 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5034   MVT VT = V.getSimpleValueType();
5035   SDLoc dl(V);
5036
5037   if (VT.is128BitVector()) {
5038     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5039     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5040     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5041                              &SplatMask[0]);
5042   } else if (VT.is256BitVector()) {
5043     // To use VPERMILPS to splat scalars, the second half of indicies must
5044     // refer to the higher part, which is a duplication of the lower one,
5045     // because VPERMILPS can only handle in-lane permutations.
5046     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5047                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5048
5049     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5050     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5051                              &SplatMask[0]);
5052   } else
5053     llvm_unreachable("Vector size not supported");
5054
5055   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5056 }
5057
5058 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5059 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5060   MVT SrcVT = SV->getSimpleValueType(0);
5061   SDValue V1 = SV->getOperand(0);
5062   SDLoc dl(SV);
5063
5064   int EltNo = SV->getSplatIndex();
5065   int NumElems = SrcVT.getVectorNumElements();
5066   bool Is256BitVec = SrcVT.is256BitVector();
5067
5068   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5069          "Unknown how to promote splat for type");
5070
5071   // Extract the 128-bit part containing the splat element and update
5072   // the splat element index when it refers to the higher register.
5073   if (Is256BitVec) {
5074     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5075     if (EltNo >= NumElems/2)
5076       EltNo -= NumElems/2;
5077   }
5078
5079   // All i16 and i8 vector types can't be used directly by a generic shuffle
5080   // instruction because the target has no such instruction. Generate shuffles
5081   // which repeat i16 and i8 several times until they fit in i32, and then can
5082   // be manipulated by target suported shuffles.
5083   MVT EltVT = SrcVT.getVectorElementType();
5084   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5085     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5086
5087   // Recreate the 256-bit vector and place the same 128-bit vector
5088   // into the low and high part. This is necessary because we want
5089   // to use VPERM* to shuffle the vectors
5090   if (Is256BitVec) {
5091     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5092   }
5093
5094   return getLegalSplat(DAG, V1, EltNo);
5095 }
5096
5097 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5098 /// vector of zero or undef vector.  This produces a shuffle where the low
5099 /// element of V2 is swizzled into the zero/undef vector, landing at element
5100 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5101 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5102                                            bool IsZero,
5103                                            const X86Subtarget *Subtarget,
5104                                            SelectionDAG &DAG) {
5105   MVT VT = V2.getSimpleValueType();
5106   SDValue V1 = IsZero
5107     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5108   unsigned NumElems = VT.getVectorNumElements();
5109   SmallVector<int, 16> MaskVec;
5110   for (unsigned i = 0; i != NumElems; ++i)
5111     // If this is the insertion idx, put the low elt of V2 here.
5112     MaskVec.push_back(i == Idx ? NumElems : i);
5113   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5114 }
5115
5116 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5117 /// target specific opcode. Returns true if the Mask could be calculated.
5118 /// Sets IsUnary to true if only uses one source.
5119 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5120                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5121   unsigned NumElems = VT.getVectorNumElements();
5122   SDValue ImmN;
5123
5124   IsUnary = false;
5125   switch(N->getOpcode()) {
5126   case X86ISD::SHUFP:
5127     ImmN = N->getOperand(N->getNumOperands()-1);
5128     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5129     break;
5130   case X86ISD::UNPCKH:
5131     DecodeUNPCKHMask(VT, Mask);
5132     break;
5133   case X86ISD::UNPCKL:
5134     DecodeUNPCKLMask(VT, Mask);
5135     break;
5136   case X86ISD::MOVHLPS:
5137     DecodeMOVHLPSMask(NumElems, Mask);
5138     break;
5139   case X86ISD::MOVLHPS:
5140     DecodeMOVLHPSMask(NumElems, Mask);
5141     break;
5142   case X86ISD::PALIGNR:
5143     ImmN = N->getOperand(N->getNumOperands()-1);
5144     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5145     break;
5146   case X86ISD::PSHUFD:
5147   case X86ISD::VPERMILP:
5148     ImmN = N->getOperand(N->getNumOperands()-1);
5149     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5150     IsUnary = true;
5151     break;
5152   case X86ISD::PSHUFHW:
5153     ImmN = N->getOperand(N->getNumOperands()-1);
5154     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5155     IsUnary = true;
5156     break;
5157   case X86ISD::PSHUFLW:
5158     ImmN = N->getOperand(N->getNumOperands()-1);
5159     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5160     IsUnary = true;
5161     break;
5162   case X86ISD::VPERMI:
5163     ImmN = N->getOperand(N->getNumOperands()-1);
5164     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5165     IsUnary = true;
5166     break;
5167   case X86ISD::MOVSS:
5168   case X86ISD::MOVSD: {
5169     // The index 0 always comes from the first element of the second source,
5170     // this is why MOVSS and MOVSD are used in the first place. The other
5171     // elements come from the other positions of the first source vector
5172     Mask.push_back(NumElems);
5173     for (unsigned i = 1; i != NumElems; ++i) {
5174       Mask.push_back(i);
5175     }
5176     break;
5177   }
5178   case X86ISD::VPERM2X128:
5179     ImmN = N->getOperand(N->getNumOperands()-1);
5180     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5181     if (Mask.empty()) return false;
5182     break;
5183   case X86ISD::MOVDDUP:
5184   case X86ISD::MOVLHPD:
5185   case X86ISD::MOVLPD:
5186   case X86ISD::MOVLPS:
5187   case X86ISD::MOVSHDUP:
5188   case X86ISD::MOVSLDUP:
5189     // Not yet implemented
5190     return false;
5191   default: llvm_unreachable("unknown target shuffle node");
5192   }
5193
5194   return true;
5195 }
5196
5197 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5198 /// element of the result of the vector shuffle.
5199 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5200                                    unsigned Depth) {
5201   if (Depth == 6)
5202     return SDValue();  // Limit search depth.
5203
5204   SDValue V = SDValue(N, 0);
5205   EVT VT = V.getValueType();
5206   unsigned Opcode = V.getOpcode();
5207
5208   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5209   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5210     int Elt = SV->getMaskElt(Index);
5211
5212     if (Elt < 0)
5213       return DAG.getUNDEF(VT.getVectorElementType());
5214
5215     unsigned NumElems = VT.getVectorNumElements();
5216     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5217                                          : SV->getOperand(1);
5218     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5219   }
5220
5221   // Recurse into target specific vector shuffles to find scalars.
5222   if (isTargetShuffle(Opcode)) {
5223     MVT ShufVT = V.getSimpleValueType();
5224     unsigned NumElems = ShufVT.getVectorNumElements();
5225     SmallVector<int, 16> ShuffleMask;
5226     bool IsUnary;
5227
5228     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5229       return SDValue();
5230
5231     int Elt = ShuffleMask[Index];
5232     if (Elt < 0)
5233       return DAG.getUNDEF(ShufVT.getVectorElementType());
5234
5235     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5236                                          : N->getOperand(1);
5237     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5238                                Depth+1);
5239   }
5240
5241   // Actual nodes that may contain scalar elements
5242   if (Opcode == ISD::BITCAST) {
5243     V = V.getOperand(0);
5244     EVT SrcVT = V.getValueType();
5245     unsigned NumElems = VT.getVectorNumElements();
5246
5247     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5248       return SDValue();
5249   }
5250
5251   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5252     return (Index == 0) ? V.getOperand(0)
5253                         : DAG.getUNDEF(VT.getVectorElementType());
5254
5255   if (V.getOpcode() == ISD::BUILD_VECTOR)
5256     return V.getOperand(Index);
5257
5258   return SDValue();
5259 }
5260
5261 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5262 /// shuffle operation which come from a consecutively from a zero. The
5263 /// search can start in two different directions, from left or right.
5264 /// We count undefs as zeros until PreferredNum is reached.
5265 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5266                                          unsigned NumElems, bool ZerosFromLeft,
5267                                          SelectionDAG &DAG,
5268                                          unsigned PreferredNum = -1U) {
5269   unsigned NumZeros = 0;
5270   for (unsigned i = 0; i != NumElems; ++i) {
5271     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5272     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5273     if (!Elt.getNode())
5274       break;
5275
5276     if (X86::isZeroNode(Elt))
5277       ++NumZeros;
5278     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5279       NumZeros = std::min(NumZeros + 1, PreferredNum);
5280     else
5281       break;
5282   }
5283
5284   return NumZeros;
5285 }
5286
5287 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5288 /// correspond consecutively to elements from one of the vector operands,
5289 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5290 static
5291 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5292                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5293                               unsigned NumElems, unsigned &OpNum) {
5294   bool SeenV1 = false;
5295   bool SeenV2 = false;
5296
5297   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5298     int Idx = SVOp->getMaskElt(i);
5299     // Ignore undef indicies
5300     if (Idx < 0)
5301       continue;
5302
5303     if (Idx < (int)NumElems)
5304       SeenV1 = true;
5305     else
5306       SeenV2 = true;
5307
5308     // Only accept consecutive elements from the same vector
5309     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5310       return false;
5311   }
5312
5313   OpNum = SeenV1 ? 0 : 1;
5314   return true;
5315 }
5316
5317 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5318 /// logical left shift of a vector.
5319 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5320                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5321   unsigned NumElems =
5322     SVOp->getSimpleValueType(0).getVectorNumElements();
5323   unsigned NumZeros = getNumOfConsecutiveZeros(
5324       SVOp, NumElems, false /* check zeros from right */, DAG,
5325       SVOp->getMaskElt(0));
5326   unsigned OpSrc;
5327
5328   if (!NumZeros)
5329     return false;
5330
5331   // Considering the elements in the mask that are not consecutive zeros,
5332   // check if they consecutively come from only one of the source vectors.
5333   //
5334   //               V1 = {X, A, B, C}     0
5335   //                         \  \  \    /
5336   //   vector_shuffle V1, V2 <1, 2, 3, X>
5337   //
5338   if (!isShuffleMaskConsecutive(SVOp,
5339             0,                   // Mask Start Index
5340             NumElems-NumZeros,   // Mask End Index(exclusive)
5341             NumZeros,            // Where to start looking in the src vector
5342             NumElems,            // Number of elements in vector
5343             OpSrc))              // Which source operand ?
5344     return false;
5345
5346   isLeft = false;
5347   ShAmt = NumZeros;
5348   ShVal = SVOp->getOperand(OpSrc);
5349   return true;
5350 }
5351
5352 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5353 /// logical left shift of a vector.
5354 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5355                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5356   unsigned NumElems =
5357     SVOp->getSimpleValueType(0).getVectorNumElements();
5358   unsigned NumZeros = getNumOfConsecutiveZeros(
5359       SVOp, NumElems, true /* check zeros from left */, DAG,
5360       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5361   unsigned OpSrc;
5362
5363   if (!NumZeros)
5364     return false;
5365
5366   // Considering the elements in the mask that are not consecutive zeros,
5367   // check if they consecutively come from only one of the source vectors.
5368   //
5369   //                           0    { A, B, X, X } = V2
5370   //                          / \    /  /
5371   //   vector_shuffle V1, V2 <X, X, 4, 5>
5372   //
5373   if (!isShuffleMaskConsecutive(SVOp,
5374             NumZeros,     // Mask Start Index
5375             NumElems,     // Mask End Index(exclusive)
5376             0,            // Where to start looking in the src vector
5377             NumElems,     // Number of elements in vector
5378             OpSrc))       // Which source operand ?
5379     return false;
5380
5381   isLeft = true;
5382   ShAmt = NumZeros;
5383   ShVal = SVOp->getOperand(OpSrc);
5384   return true;
5385 }
5386
5387 /// isVectorShift - Returns true if the shuffle can be implemented as a
5388 /// logical left or right shift of a vector.
5389 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5390                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5391   // Although the logic below support any bitwidth size, there are no
5392   // shift instructions which handle more than 128-bit vectors.
5393   if (!SVOp->getSimpleValueType(0).is128BitVector())
5394     return false;
5395
5396   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5397       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5398     return true;
5399
5400   return false;
5401 }
5402
5403 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5404 ///
5405 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5406                                        unsigned NumNonZero, unsigned NumZero,
5407                                        SelectionDAG &DAG,
5408                                        const X86Subtarget* Subtarget,
5409                                        const TargetLowering &TLI) {
5410   if (NumNonZero > 8)
5411     return SDValue();
5412
5413   SDLoc dl(Op);
5414   SDValue V;
5415   bool First = true;
5416   for (unsigned i = 0; i < 16; ++i) {
5417     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5418     if (ThisIsNonZero && First) {
5419       if (NumZero)
5420         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5421       else
5422         V = DAG.getUNDEF(MVT::v8i16);
5423       First = false;
5424     }
5425
5426     if ((i & 1) != 0) {
5427       SDValue ThisElt, LastElt;
5428       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5429       if (LastIsNonZero) {
5430         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5431                               MVT::i16, Op.getOperand(i-1));
5432       }
5433       if (ThisIsNonZero) {
5434         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5435         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5436                               ThisElt, DAG.getConstant(8, MVT::i8));
5437         if (LastIsNonZero)
5438           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5439       } else
5440         ThisElt = LastElt;
5441
5442       if (ThisElt.getNode())
5443         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5444                         DAG.getIntPtrConstant(i/2));
5445     }
5446   }
5447
5448   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5449 }
5450
5451 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5452 ///
5453 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5454                                      unsigned NumNonZero, unsigned NumZero,
5455                                      SelectionDAG &DAG,
5456                                      const X86Subtarget* Subtarget,
5457                                      const TargetLowering &TLI) {
5458   if (NumNonZero > 4)
5459     return SDValue();
5460
5461   SDLoc dl(Op);
5462   SDValue V;
5463   bool First = true;
5464   for (unsigned i = 0; i < 8; ++i) {
5465     bool isNonZero = (NonZeros & (1 << i)) != 0;
5466     if (isNonZero) {
5467       if (First) {
5468         if (NumZero)
5469           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5470         else
5471           V = DAG.getUNDEF(MVT::v8i16);
5472         First = false;
5473       }
5474       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5475                       MVT::v8i16, V, Op.getOperand(i),
5476                       DAG.getIntPtrConstant(i));
5477     }
5478   }
5479
5480   return V;
5481 }
5482
5483 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5484 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5485                                      unsigned NonZeros, unsigned NumNonZero,
5486                                      unsigned NumZero, SelectionDAG &DAG,
5487                                      const X86Subtarget *Subtarget,
5488                                      const TargetLowering &TLI) {
5489   // We know there's at least one non-zero element
5490   unsigned FirstNonZeroIdx = 0;
5491   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5492   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5493          X86::isZeroNode(FirstNonZero)) {
5494     ++FirstNonZeroIdx;
5495     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5496   }
5497
5498   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5499       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5500     return SDValue();
5501
5502   SDValue V = FirstNonZero.getOperand(0);
5503   MVT VVT = V.getSimpleValueType();
5504   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5505     return SDValue();
5506
5507   unsigned FirstNonZeroDst =
5508       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5509   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5510   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5511   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5512
5513   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5514     SDValue Elem = Op.getOperand(Idx);
5515     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5516       continue;
5517
5518     // TODO: What else can be here? Deal with it.
5519     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5520       return SDValue();
5521
5522     // TODO: Some optimizations are still possible here
5523     // ex: Getting one element from a vector, and the rest from another.
5524     if (Elem.getOperand(0) != V)
5525       return SDValue();
5526
5527     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5528     if (Dst == Idx)
5529       ++CorrectIdx;
5530     else if (IncorrectIdx == -1U) {
5531       IncorrectIdx = Idx;
5532       IncorrectDst = Dst;
5533     } else
5534       // There was already one element with an incorrect index.
5535       // We can't optimize this case to an insertps.
5536       return SDValue();
5537   }
5538
5539   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5540     SDLoc dl(Op);
5541     EVT VT = Op.getSimpleValueType();
5542     unsigned ElementMoveMask = 0;
5543     if (IncorrectIdx == -1U)
5544       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5545     else
5546       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5547
5548     SDValue InsertpsMask =
5549         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5550     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5551   }
5552
5553   return SDValue();
5554 }
5555
5556 /// getVShift - Return a vector logical shift node.
5557 ///
5558 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5559                          unsigned NumBits, SelectionDAG &DAG,
5560                          const TargetLowering &TLI, SDLoc dl) {
5561   assert(VT.is128BitVector() && "Unknown type for VShift");
5562   EVT ShVT = MVT::v2i64;
5563   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5564   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5565   return DAG.getNode(ISD::BITCAST, dl, VT,
5566                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5567                              DAG.getConstant(NumBits,
5568                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5569 }
5570
5571 static SDValue
5572 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5573
5574   // Check if the scalar load can be widened into a vector load. And if
5575   // the address is "base + cst" see if the cst can be "absorbed" into
5576   // the shuffle mask.
5577   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5578     SDValue Ptr = LD->getBasePtr();
5579     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5580       return SDValue();
5581     EVT PVT = LD->getValueType(0);
5582     if (PVT != MVT::i32 && PVT != MVT::f32)
5583       return SDValue();
5584
5585     int FI = -1;
5586     int64_t Offset = 0;
5587     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5588       FI = FINode->getIndex();
5589       Offset = 0;
5590     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5591                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5592       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5593       Offset = Ptr.getConstantOperandVal(1);
5594       Ptr = Ptr.getOperand(0);
5595     } else {
5596       return SDValue();
5597     }
5598
5599     // FIXME: 256-bit vector instructions don't require a strict alignment,
5600     // improve this code to support it better.
5601     unsigned RequiredAlign = VT.getSizeInBits()/8;
5602     SDValue Chain = LD->getChain();
5603     // Make sure the stack object alignment is at least 16 or 32.
5604     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5605     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5606       if (MFI->isFixedObjectIndex(FI)) {
5607         // Can't change the alignment. FIXME: It's possible to compute
5608         // the exact stack offset and reference FI + adjust offset instead.
5609         // If someone *really* cares about this. That's the way to implement it.
5610         return SDValue();
5611       } else {
5612         MFI->setObjectAlignment(FI, RequiredAlign);
5613       }
5614     }
5615
5616     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5617     // Ptr + (Offset & ~15).
5618     if (Offset < 0)
5619       return SDValue();
5620     if ((Offset % RequiredAlign) & 3)
5621       return SDValue();
5622     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5623     if (StartOffset)
5624       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5625                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5626
5627     int EltNo = (Offset - StartOffset) >> 2;
5628     unsigned NumElems = VT.getVectorNumElements();
5629
5630     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5631     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5632                              LD->getPointerInfo().getWithOffset(StartOffset),
5633                              false, false, false, 0);
5634
5635     SmallVector<int, 8> Mask;
5636     for (unsigned i = 0; i != NumElems; ++i)
5637       Mask.push_back(EltNo);
5638
5639     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5640   }
5641
5642   return SDValue();
5643 }
5644
5645 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5646 /// vector of type 'VT', see if the elements can be replaced by a single large
5647 /// load which has the same value as a build_vector whose operands are 'elts'.
5648 ///
5649 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5650 ///
5651 /// FIXME: we'd also like to handle the case where the last elements are zero
5652 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5653 /// There's even a handy isZeroNode for that purpose.
5654 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5655                                         SDLoc &DL, SelectionDAG &DAG,
5656                                         bool isAfterLegalize) {
5657   EVT EltVT = VT.getVectorElementType();
5658   unsigned NumElems = Elts.size();
5659
5660   LoadSDNode *LDBase = nullptr;
5661   unsigned LastLoadedElt = -1U;
5662
5663   // For each element in the initializer, see if we've found a load or an undef.
5664   // If we don't find an initial load element, or later load elements are
5665   // non-consecutive, bail out.
5666   for (unsigned i = 0; i < NumElems; ++i) {
5667     SDValue Elt = Elts[i];
5668
5669     if (!Elt.getNode() ||
5670         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5671       return SDValue();
5672     if (!LDBase) {
5673       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5674         return SDValue();
5675       LDBase = cast<LoadSDNode>(Elt.getNode());
5676       LastLoadedElt = i;
5677       continue;
5678     }
5679     if (Elt.getOpcode() == ISD::UNDEF)
5680       continue;
5681
5682     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5683     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5684       return SDValue();
5685     LastLoadedElt = i;
5686   }
5687
5688   // If we have found an entire vector of loads and undefs, then return a large
5689   // load of the entire vector width starting at the base pointer.  If we found
5690   // consecutive loads for the low half, generate a vzext_load node.
5691   if (LastLoadedElt == NumElems - 1) {
5692
5693     if (isAfterLegalize &&
5694         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5695       return SDValue();
5696
5697     SDValue NewLd = SDValue();
5698
5699     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5700       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5701                           LDBase->getPointerInfo(),
5702                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5703                           LDBase->isInvariant(), 0);
5704     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5705                         LDBase->getPointerInfo(),
5706                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5707                         LDBase->isInvariant(), LDBase->getAlignment());
5708
5709     if (LDBase->hasAnyUseOfValue(1)) {
5710       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5711                                      SDValue(LDBase, 1),
5712                                      SDValue(NewLd.getNode(), 1));
5713       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5714       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5715                              SDValue(NewLd.getNode(), 1));
5716     }
5717
5718     return NewLd;
5719   }
5720   if (NumElems == 4 && LastLoadedElt == 1 &&
5721       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5722     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5723     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5724     SDValue ResNode =
5725         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5726                                 LDBase->getPointerInfo(),
5727                                 LDBase->getAlignment(),
5728                                 false/*isVolatile*/, true/*ReadMem*/,
5729                                 false/*WriteMem*/);
5730
5731     // Make sure the newly-created LOAD is in the same position as LDBase in
5732     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5733     // update uses of LDBase's output chain to use the TokenFactor.
5734     if (LDBase->hasAnyUseOfValue(1)) {
5735       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5736                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5737       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5738       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5739                              SDValue(ResNode.getNode(), 1));
5740     }
5741
5742     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5743   }
5744   return SDValue();
5745 }
5746
5747 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5748 /// to generate a splat value for the following cases:
5749 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5750 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5751 /// a scalar load, or a constant.
5752 /// The VBROADCAST node is returned when a pattern is found,
5753 /// or SDValue() otherwise.
5754 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5755                                     SelectionDAG &DAG) {
5756   if (!Subtarget->hasFp256())
5757     return SDValue();
5758
5759   MVT VT = Op.getSimpleValueType();
5760   SDLoc dl(Op);
5761
5762   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5763          "Unsupported vector type for broadcast.");
5764
5765   SDValue Ld;
5766   bool ConstSplatVal;
5767
5768   switch (Op.getOpcode()) {
5769     default:
5770       // Unknown pattern found.
5771       return SDValue();
5772
5773     case ISD::BUILD_VECTOR: {
5774       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5775       BitVector UndefElements;
5776       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5777
5778       // We need a splat of a single value to use broadcast, and it doesn't
5779       // make any sense if the value is only in one element of the vector.
5780       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5781         return SDValue();
5782
5783       Ld = Splat;
5784       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5785                        Ld.getOpcode() == ISD::ConstantFP);
5786
5787       // Make sure that all of the users of a non-constant load are from the
5788       // BUILD_VECTOR node.
5789       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5790         return SDValue();
5791       break;
5792     }
5793
5794     case ISD::VECTOR_SHUFFLE: {
5795       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5796
5797       // Shuffles must have a splat mask where the first element is
5798       // broadcasted.
5799       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5800         return SDValue();
5801
5802       SDValue Sc = Op.getOperand(0);
5803       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5804           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5805
5806         if (!Subtarget->hasInt256())
5807           return SDValue();
5808
5809         // Use the register form of the broadcast instruction available on AVX2.
5810         if (VT.getSizeInBits() >= 256)
5811           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5812         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5813       }
5814
5815       Ld = Sc.getOperand(0);
5816       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5817                        Ld.getOpcode() == ISD::ConstantFP);
5818
5819       // The scalar_to_vector node and the suspected
5820       // load node must have exactly one user.
5821       // Constants may have multiple users.
5822
5823       // AVX-512 has register version of the broadcast
5824       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5825         Ld.getValueType().getSizeInBits() >= 32;
5826       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5827           !hasRegVer))
5828         return SDValue();
5829       break;
5830     }
5831   }
5832
5833   bool IsGE256 = (VT.getSizeInBits() >= 256);
5834
5835   // Handle the broadcasting a single constant scalar from the constant pool
5836   // into a vector. On Sandybridge it is still better to load a constant vector
5837   // from the constant pool and not to broadcast it from a scalar.
5838   if (ConstSplatVal && Subtarget->hasInt256()) {
5839     EVT CVT = Ld.getValueType();
5840     assert(!CVT.isVector() && "Must not broadcast a vector type");
5841     unsigned ScalarSize = CVT.getSizeInBits();
5842
5843     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5844       const Constant *C = nullptr;
5845       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5846         C = CI->getConstantIntValue();
5847       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5848         C = CF->getConstantFPValue();
5849
5850       assert(C && "Invalid constant type");
5851
5852       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5853       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5854       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5855       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5856                        MachinePointerInfo::getConstantPool(),
5857                        false, false, false, Alignment);
5858
5859       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5860     }
5861   }
5862
5863   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5864   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5865
5866   // Handle AVX2 in-register broadcasts.
5867   if (!IsLoad && Subtarget->hasInt256() &&
5868       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5869     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5870
5871   // The scalar source must be a normal load.
5872   if (!IsLoad)
5873     return SDValue();
5874
5875   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5876     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5877
5878   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5879   // double since there is no vbroadcastsd xmm
5880   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5881     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5882       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5883   }
5884
5885   // Unsupported broadcast.
5886   return SDValue();
5887 }
5888
5889 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5890 /// underlying vector and index.
5891 ///
5892 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5893 /// index.
5894 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5895                                          SDValue ExtIdx) {
5896   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5897   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5898     return Idx;
5899
5900   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5901   // lowered this:
5902   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5903   // to:
5904   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5905   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5906   //                           undef)
5907   //                       Constant<0>)
5908   // In this case the vector is the extract_subvector expression and the index
5909   // is 2, as specified by the shuffle.
5910   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5911   SDValue ShuffleVec = SVOp->getOperand(0);
5912   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5913   assert(ShuffleVecVT.getVectorElementType() ==
5914          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5915
5916   int ShuffleIdx = SVOp->getMaskElt(Idx);
5917   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5918     ExtractedFromVec = ShuffleVec;
5919     return ShuffleIdx;
5920   }
5921   return Idx;
5922 }
5923
5924 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5925   MVT VT = Op.getSimpleValueType();
5926
5927   // Skip if insert_vec_elt is not supported.
5928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5929   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5930     return SDValue();
5931
5932   SDLoc DL(Op);
5933   unsigned NumElems = Op.getNumOperands();
5934
5935   SDValue VecIn1;
5936   SDValue VecIn2;
5937   SmallVector<unsigned, 4> InsertIndices;
5938   SmallVector<int, 8> Mask(NumElems, -1);
5939
5940   for (unsigned i = 0; i != NumElems; ++i) {
5941     unsigned Opc = Op.getOperand(i).getOpcode();
5942
5943     if (Opc == ISD::UNDEF)
5944       continue;
5945
5946     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5947       // Quit if more than 1 elements need inserting.
5948       if (InsertIndices.size() > 1)
5949         return SDValue();
5950
5951       InsertIndices.push_back(i);
5952       continue;
5953     }
5954
5955     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5956     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5957     // Quit if non-constant index.
5958     if (!isa<ConstantSDNode>(ExtIdx))
5959       return SDValue();
5960     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5961
5962     // Quit if extracted from vector of different type.
5963     if (ExtractedFromVec.getValueType() != VT)
5964       return SDValue();
5965
5966     if (!VecIn1.getNode())
5967       VecIn1 = ExtractedFromVec;
5968     else if (VecIn1 != ExtractedFromVec) {
5969       if (!VecIn2.getNode())
5970         VecIn2 = ExtractedFromVec;
5971       else if (VecIn2 != ExtractedFromVec)
5972         // Quit if more than 2 vectors to shuffle
5973         return SDValue();
5974     }
5975
5976     if (ExtractedFromVec == VecIn1)
5977       Mask[i] = Idx;
5978     else if (ExtractedFromVec == VecIn2)
5979       Mask[i] = Idx + NumElems;
5980   }
5981
5982   if (!VecIn1.getNode())
5983     return SDValue();
5984
5985   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5986   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5987   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5988     unsigned Idx = InsertIndices[i];
5989     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5990                      DAG.getIntPtrConstant(Idx));
5991   }
5992
5993   return NV;
5994 }
5995
5996 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5997 SDValue
5998 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5999
6000   MVT VT = Op.getSimpleValueType();
6001   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6002          "Unexpected type in LowerBUILD_VECTORvXi1!");
6003
6004   SDLoc dl(Op);
6005   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6006     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6007     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6008     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6009   }
6010
6011   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6012     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6013     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6014     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6015   }
6016
6017   bool AllContants = true;
6018   uint64_t Immediate = 0;
6019   int NonConstIdx = -1;
6020   bool IsSplat = true;
6021   unsigned NumNonConsts = 0;
6022   unsigned NumConsts = 0;
6023   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6024     SDValue In = Op.getOperand(idx);
6025     if (In.getOpcode() == ISD::UNDEF)
6026       continue;
6027     if (!isa<ConstantSDNode>(In)) {
6028       AllContants = false;
6029       NonConstIdx = idx;
6030       NumNonConsts++;
6031     }
6032     else {
6033       NumConsts++;
6034       if (cast<ConstantSDNode>(In)->getZExtValue())
6035       Immediate |= (1ULL << idx);
6036     }
6037     if (In != Op.getOperand(0))
6038       IsSplat = false;
6039   }
6040
6041   if (AllContants) {
6042     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6043       DAG.getConstant(Immediate, MVT::i16));
6044     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6045                        DAG.getIntPtrConstant(0));
6046   }
6047
6048   if (NumNonConsts == 1 && NonConstIdx != 0) {
6049     SDValue DstVec;
6050     if (NumConsts) {
6051       SDValue VecAsImm = DAG.getConstant(Immediate,
6052                                          MVT::getIntegerVT(VT.getSizeInBits()));
6053       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6054     }
6055     else 
6056       DstVec = DAG.getUNDEF(VT);
6057     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6058                        Op.getOperand(NonConstIdx),
6059                        DAG.getIntPtrConstant(NonConstIdx));
6060   }
6061   if (!IsSplat && (NonConstIdx != 0))
6062     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6063   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6064   SDValue Select;
6065   if (IsSplat)
6066     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6067                           DAG.getConstant(-1, SelectVT),
6068                           DAG.getConstant(0, SelectVT));
6069   else
6070     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6071                          DAG.getConstant((Immediate | 1), SelectVT),
6072                          DAG.getConstant(Immediate, SelectVT));
6073   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6074 }
6075
6076 /// \brief Return true if \p N implements a horizontal binop and return the
6077 /// operands for the horizontal binop into V0 and V1.
6078 /// 
6079 /// This is a helper function of PerformBUILD_VECTORCombine.
6080 /// This function checks that the build_vector \p N in input implements a
6081 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6082 /// operation to match.
6083 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6084 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6085 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6086 /// arithmetic sub.
6087 ///
6088 /// This function only analyzes elements of \p N whose indices are
6089 /// in range [BaseIdx, LastIdx).
6090 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6091                               SelectionDAG &DAG,
6092                               unsigned BaseIdx, unsigned LastIdx,
6093                               SDValue &V0, SDValue &V1) {
6094   EVT VT = N->getValueType(0);
6095
6096   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6097   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6098          "Invalid Vector in input!");
6099   
6100   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6101   bool CanFold = true;
6102   unsigned ExpectedVExtractIdx = BaseIdx;
6103   unsigned NumElts = LastIdx - BaseIdx;
6104   V0 = DAG.getUNDEF(VT);
6105   V1 = DAG.getUNDEF(VT);
6106
6107   // Check if N implements a horizontal binop.
6108   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6109     SDValue Op = N->getOperand(i + BaseIdx);
6110
6111     // Skip UNDEFs.
6112     if (Op->getOpcode() == ISD::UNDEF) {
6113       // Update the expected vector extract index.
6114       if (i * 2 == NumElts)
6115         ExpectedVExtractIdx = BaseIdx;
6116       ExpectedVExtractIdx += 2;
6117       continue;
6118     }
6119
6120     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6121
6122     if (!CanFold)
6123       break;
6124
6125     SDValue Op0 = Op.getOperand(0);
6126     SDValue Op1 = Op.getOperand(1);
6127
6128     // Try to match the following pattern:
6129     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6130     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6131         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6132         Op0.getOperand(0) == Op1.getOperand(0) &&
6133         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6134         isa<ConstantSDNode>(Op1.getOperand(1)));
6135     if (!CanFold)
6136       break;
6137
6138     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6139     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6140
6141     if (i * 2 < NumElts) {
6142       if (V0.getOpcode() == ISD::UNDEF)
6143         V0 = Op0.getOperand(0);
6144     } else {
6145       if (V1.getOpcode() == ISD::UNDEF)
6146         V1 = Op0.getOperand(0);
6147       if (i * 2 == NumElts)
6148         ExpectedVExtractIdx = BaseIdx;
6149     }
6150
6151     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6152     if (I0 == ExpectedVExtractIdx)
6153       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6154     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6155       // Try to match the following dag sequence:
6156       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6157       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6158     } else
6159       CanFold = false;
6160
6161     ExpectedVExtractIdx += 2;
6162   }
6163
6164   return CanFold;
6165 }
6166
6167 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6168 /// a concat_vector. 
6169 ///
6170 /// This is a helper function of PerformBUILD_VECTORCombine.
6171 /// This function expects two 256-bit vectors called V0 and V1.
6172 /// At first, each vector is split into two separate 128-bit vectors.
6173 /// Then, the resulting 128-bit vectors are used to implement two
6174 /// horizontal binary operations. 
6175 ///
6176 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6177 ///
6178 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6179 /// the two new horizontal binop.
6180 /// When Mode is set, the first horizontal binop dag node would take as input
6181 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6182 /// horizontal binop dag node would take as input the lower 128-bit of V1
6183 /// and the upper 128-bit of V1.
6184 ///   Example:
6185 ///     HADD V0_LO, V0_HI
6186 ///     HADD V1_LO, V1_HI
6187 ///
6188 /// Otherwise, the first horizontal binop dag node takes as input the lower
6189 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6190 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6191 ///   Example:
6192 ///     HADD V0_LO, V1_LO
6193 ///     HADD V0_HI, V1_HI
6194 ///
6195 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6196 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6197 /// the upper 128-bits of the result.
6198 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6199                                      SDLoc DL, SelectionDAG &DAG,
6200                                      unsigned X86Opcode, bool Mode,
6201                                      bool isUndefLO, bool isUndefHI) {
6202   EVT VT = V0.getValueType();
6203   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6204          "Invalid nodes in input!");
6205
6206   unsigned NumElts = VT.getVectorNumElements();
6207   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6208   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6209   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6210   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6211   EVT NewVT = V0_LO.getValueType();
6212
6213   SDValue LO = DAG.getUNDEF(NewVT);
6214   SDValue HI = DAG.getUNDEF(NewVT);
6215
6216   if (Mode) {
6217     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6218     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6219       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6220     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6221       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6222   } else {
6223     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6224     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6225                        V1_LO->getOpcode() != ISD::UNDEF))
6226       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6227
6228     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6229                        V1_HI->getOpcode() != ISD::UNDEF))
6230       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6231   }
6232
6233   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6234 }
6235
6236 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6237 /// sequence of 'vadd + vsub + blendi'.
6238 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6239                            const X86Subtarget *Subtarget) {
6240   SDLoc DL(BV);
6241   EVT VT = BV->getValueType(0);
6242   unsigned NumElts = VT.getVectorNumElements();
6243   SDValue InVec0 = DAG.getUNDEF(VT);
6244   SDValue InVec1 = DAG.getUNDEF(VT);
6245
6246   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6247           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6248
6249   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6251   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6252     return SDValue();
6253
6254   // Odd-numbered elements in the input build vector are obtained from
6255   // adding two integer/float elements.
6256   // Even-numbered elements in the input build vector are obtained from
6257   // subtracting two integer/float elements.
6258   unsigned ExpectedOpcode = ISD::FSUB;
6259   unsigned NextExpectedOpcode = ISD::FADD;
6260   bool AddFound = false;
6261   bool SubFound = false;
6262
6263   for (unsigned i = 0, e = NumElts; i != e; i++) {
6264     SDValue Op = BV->getOperand(i);
6265       
6266     // Skip 'undef' values.
6267     unsigned Opcode = Op.getOpcode();
6268     if (Opcode == ISD::UNDEF) {
6269       std::swap(ExpectedOpcode, NextExpectedOpcode);
6270       continue;
6271     }
6272       
6273     // Early exit if we found an unexpected opcode.
6274     if (Opcode != ExpectedOpcode)
6275       return SDValue();
6276
6277     SDValue Op0 = Op.getOperand(0);
6278     SDValue Op1 = Op.getOperand(1);
6279
6280     // Try to match the following pattern:
6281     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6282     // Early exit if we cannot match that sequence.
6283     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6284         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6285         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6286         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6287         Op0.getOperand(1) != Op1.getOperand(1))
6288       return SDValue();
6289
6290     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6291     if (I0 != i)
6292       return SDValue();
6293
6294     // We found a valid add/sub node. Update the information accordingly.
6295     if (i & 1)
6296       AddFound = true;
6297     else
6298       SubFound = true;
6299
6300     // Update InVec0 and InVec1.
6301     if (InVec0.getOpcode() == ISD::UNDEF)
6302       InVec0 = Op0.getOperand(0);
6303     if (InVec1.getOpcode() == ISD::UNDEF)
6304       InVec1 = Op1.getOperand(0);
6305
6306     // Make sure that operands in input to each add/sub node always
6307     // come from a same pair of vectors.
6308     if (InVec0 != Op0.getOperand(0)) {
6309       if (ExpectedOpcode == ISD::FSUB)
6310         return SDValue();
6311
6312       // FADD is commutable. Try to commute the operands
6313       // and then test again.
6314       std::swap(Op0, Op1);
6315       if (InVec0 != Op0.getOperand(0))
6316         return SDValue();
6317     }
6318
6319     if (InVec1 != Op1.getOperand(0))
6320       return SDValue();
6321
6322     // Update the pair of expected opcodes.
6323     std::swap(ExpectedOpcode, NextExpectedOpcode);
6324   }
6325
6326   // Don't try to fold this build_vector into a VSELECT if it has
6327   // too many UNDEF operands.
6328   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6329       InVec1.getOpcode() != ISD::UNDEF) {
6330     // Emit a sequence of vector add and sub followed by a VSELECT.
6331     // The new VSELECT will be lowered into a BLENDI.
6332     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6333     // and emit a single ADDSUB instruction.
6334     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6335     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6336
6337     // Construct the VSELECT mask.
6338     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6339     EVT SVT = MaskVT.getVectorElementType();
6340     unsigned SVTBits = SVT.getSizeInBits();
6341     SmallVector<SDValue, 8> Ops;
6342
6343     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6344       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6345                             APInt::getAllOnesValue(SVTBits);
6346       SDValue Constant = DAG.getConstant(Value, SVT);
6347       Ops.push_back(Constant);
6348     }
6349
6350     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6351     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6352   }
6353   
6354   return SDValue();
6355 }
6356
6357 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6358                                           const X86Subtarget *Subtarget) {
6359   SDLoc DL(N);
6360   EVT VT = N->getValueType(0);
6361   unsigned NumElts = VT.getVectorNumElements();
6362   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6363   SDValue InVec0, InVec1;
6364
6365   // Try to match an ADDSUB.
6366   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6367       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6368     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6369     if (Value.getNode())
6370       return Value;
6371   }
6372
6373   // Try to match horizontal ADD/SUB.
6374   unsigned NumUndefsLO = 0;
6375   unsigned NumUndefsHI = 0;
6376   unsigned Half = NumElts/2;
6377
6378   // Count the number of UNDEF operands in the build_vector in input.
6379   for (unsigned i = 0, e = Half; i != e; ++i)
6380     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6381       NumUndefsLO++;
6382
6383   for (unsigned i = Half, e = NumElts; i != e; ++i)
6384     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6385       NumUndefsHI++;
6386
6387   // Early exit if this is either a build_vector of all UNDEFs or all the
6388   // operands but one are UNDEF.
6389   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6390     return SDValue();
6391
6392   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6393     // Try to match an SSE3 float HADD/HSUB.
6394     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6395       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6396     
6397     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6398       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6399   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6400     // Try to match an SSSE3 integer HADD/HSUB.
6401     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6402       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6403     
6404     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6405       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6406   }
6407   
6408   if (!Subtarget->hasAVX())
6409     return SDValue();
6410
6411   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6412     // Try to match an AVX horizontal add/sub of packed single/double
6413     // precision floating point values from 256-bit vectors.
6414     SDValue InVec2, InVec3;
6415     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6416         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6417         ((InVec0.getOpcode() == ISD::UNDEF ||
6418           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6419         ((InVec1.getOpcode() == ISD::UNDEF ||
6420           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6421       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6422
6423     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6424         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6425         ((InVec0.getOpcode() == ISD::UNDEF ||
6426           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6427         ((InVec1.getOpcode() == ISD::UNDEF ||
6428           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6429       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6430   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6431     // Try to match an AVX2 horizontal add/sub of signed integers.
6432     SDValue InVec2, InVec3;
6433     unsigned X86Opcode;
6434     bool CanFold = true;
6435
6436     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6437         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6438         ((InVec0.getOpcode() == ISD::UNDEF ||
6439           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6440         ((InVec1.getOpcode() == ISD::UNDEF ||
6441           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6442       X86Opcode = X86ISD::HADD;
6443     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6444         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6445         ((InVec0.getOpcode() == ISD::UNDEF ||
6446           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6447         ((InVec1.getOpcode() == ISD::UNDEF ||
6448           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6449       X86Opcode = X86ISD::HSUB;
6450     else
6451       CanFold = false;
6452
6453     if (CanFold) {
6454       // Fold this build_vector into a single horizontal add/sub.
6455       // Do this only if the target has AVX2.
6456       if (Subtarget->hasAVX2())
6457         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6458  
6459       // Do not try to expand this build_vector into a pair of horizontal
6460       // add/sub if we can emit a pair of scalar add/sub.
6461       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6462         return SDValue();
6463
6464       // Convert this build_vector into a pair of horizontal binop followed by
6465       // a concat vector.
6466       bool isUndefLO = NumUndefsLO == Half;
6467       bool isUndefHI = NumUndefsHI == Half;
6468       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6469                                    isUndefLO, isUndefHI);
6470     }
6471   }
6472
6473   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6474        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6475     unsigned X86Opcode;
6476     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6477       X86Opcode = X86ISD::HADD;
6478     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6479       X86Opcode = X86ISD::HSUB;
6480     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6481       X86Opcode = X86ISD::FHADD;
6482     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6483       X86Opcode = X86ISD::FHSUB;
6484     else
6485       return SDValue();
6486
6487     // Don't try to expand this build_vector into a pair of horizontal add/sub
6488     // if we can simply emit a pair of scalar add/sub.
6489     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6490       return SDValue();
6491
6492     // Convert this build_vector into two horizontal add/sub followed by
6493     // a concat vector.
6494     bool isUndefLO = NumUndefsLO == Half;
6495     bool isUndefHI = NumUndefsHI == Half;
6496     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6497                                  isUndefLO, isUndefHI);
6498   }
6499
6500   return SDValue();
6501 }
6502
6503 SDValue
6504 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6505   SDLoc dl(Op);
6506
6507   MVT VT = Op.getSimpleValueType();
6508   MVT ExtVT = VT.getVectorElementType();
6509   unsigned NumElems = Op.getNumOperands();
6510
6511   // Generate vectors for predicate vectors.
6512   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6513     return LowerBUILD_VECTORvXi1(Op, DAG);
6514
6515   // Vectors containing all zeros can be matched by pxor and xorps later
6516   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6517     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6518     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6519     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6520       return Op;
6521
6522     return getZeroVector(VT, Subtarget, DAG, dl);
6523   }
6524
6525   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6526   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6527   // vpcmpeqd on 256-bit vectors.
6528   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6529     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6530       return Op;
6531
6532     if (!VT.is512BitVector())
6533       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6534   }
6535
6536   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6537   if (Broadcast.getNode())
6538     return Broadcast;
6539
6540   unsigned EVTBits = ExtVT.getSizeInBits();
6541
6542   unsigned NumZero  = 0;
6543   unsigned NumNonZero = 0;
6544   unsigned NonZeros = 0;
6545   bool IsAllConstants = true;
6546   SmallSet<SDValue, 8> Values;
6547   for (unsigned i = 0; i < NumElems; ++i) {
6548     SDValue Elt = Op.getOperand(i);
6549     if (Elt.getOpcode() == ISD::UNDEF)
6550       continue;
6551     Values.insert(Elt);
6552     if (Elt.getOpcode() != ISD::Constant &&
6553         Elt.getOpcode() != ISD::ConstantFP)
6554       IsAllConstants = false;
6555     if (X86::isZeroNode(Elt))
6556       NumZero++;
6557     else {
6558       NonZeros |= (1 << i);
6559       NumNonZero++;
6560     }
6561   }
6562
6563   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6564   if (NumNonZero == 0)
6565     return DAG.getUNDEF(VT);
6566
6567   // Special case for single non-zero, non-undef, element.
6568   if (NumNonZero == 1) {
6569     unsigned Idx = countTrailingZeros(NonZeros);
6570     SDValue Item = Op.getOperand(Idx);
6571
6572     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6573     // the value are obviously zero, truncate the value to i32 and do the
6574     // insertion that way.  Only do this if the value is non-constant or if the
6575     // value is a constant being inserted into element 0.  It is cheaper to do
6576     // a constant pool load than it is to do a movd + shuffle.
6577     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6578         (!IsAllConstants || Idx == 0)) {
6579       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6580         // Handle SSE only.
6581         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6582         EVT VecVT = MVT::v4i32;
6583         unsigned VecElts = 4;
6584
6585         // Truncate the value (which may itself be a constant) to i32, and
6586         // convert it to a vector with movd (S2V+shuffle to zero extend).
6587         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6588         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6589         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6590
6591         // Now we have our 32-bit value zero extended in the low element of
6592         // a vector.  If Idx != 0, swizzle it into place.
6593         if (Idx != 0) {
6594           SmallVector<int, 4> Mask;
6595           Mask.push_back(Idx);
6596           for (unsigned i = 1; i != VecElts; ++i)
6597             Mask.push_back(i);
6598           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6599                                       &Mask[0]);
6600         }
6601         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6602       }
6603     }
6604
6605     // If we have a constant or non-constant insertion into the low element of
6606     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6607     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6608     // depending on what the source datatype is.
6609     if (Idx == 0) {
6610       if (NumZero == 0)
6611         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6612
6613       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6614           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6615         if (VT.is256BitVector() || VT.is512BitVector()) {
6616           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6617           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6618                              Item, DAG.getIntPtrConstant(0));
6619         }
6620         assert(VT.is128BitVector() && "Expected an SSE value type!");
6621         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6622         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6623         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6624       }
6625
6626       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6627         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6628         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6629         if (VT.is256BitVector()) {
6630           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6631           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6632         } else {
6633           assert(VT.is128BitVector() && "Expected an SSE value type!");
6634           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6635         }
6636         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6637       }
6638     }
6639
6640     // Is it a vector logical left shift?
6641     if (NumElems == 2 && Idx == 1 &&
6642         X86::isZeroNode(Op.getOperand(0)) &&
6643         !X86::isZeroNode(Op.getOperand(1))) {
6644       unsigned NumBits = VT.getSizeInBits();
6645       return getVShift(true, VT,
6646                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6647                                    VT, Op.getOperand(1)),
6648                        NumBits/2, DAG, *this, dl);
6649     }
6650
6651     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6652       return SDValue();
6653
6654     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6655     // is a non-constant being inserted into an element other than the low one,
6656     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6657     // movd/movss) to move this into the low element, then shuffle it into
6658     // place.
6659     if (EVTBits == 32) {
6660       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6661
6662       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6663       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6664       SmallVector<int, 8> MaskVec;
6665       for (unsigned i = 0; i != NumElems; ++i)
6666         MaskVec.push_back(i == Idx ? 0 : 1);
6667       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6668     }
6669   }
6670
6671   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6672   if (Values.size() == 1) {
6673     if (EVTBits == 32) {
6674       // Instead of a shuffle like this:
6675       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6676       // Check if it's possible to issue this instead.
6677       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6678       unsigned Idx = countTrailingZeros(NonZeros);
6679       SDValue Item = Op.getOperand(Idx);
6680       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6681         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6682     }
6683     return SDValue();
6684   }
6685
6686   // A vector full of immediates; various special cases are already
6687   // handled, so this is best done with a single constant-pool load.
6688   if (IsAllConstants)
6689     return SDValue();
6690
6691   // For AVX-length vectors, build the individual 128-bit pieces and use
6692   // shuffles to put them in place.
6693   if (VT.is256BitVector() || VT.is512BitVector()) {
6694     SmallVector<SDValue, 64> V;
6695     for (unsigned i = 0; i != NumElems; ++i)
6696       V.push_back(Op.getOperand(i));
6697
6698     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6699
6700     // Build both the lower and upper subvector.
6701     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6702                                 makeArrayRef(&V[0], NumElems/2));
6703     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6704                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6705
6706     // Recreate the wider vector with the lower and upper part.
6707     if (VT.is256BitVector())
6708       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6709     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6710   }
6711
6712   // Let legalizer expand 2-wide build_vectors.
6713   if (EVTBits == 64) {
6714     if (NumNonZero == 1) {
6715       // One half is zero or undef.
6716       unsigned Idx = countTrailingZeros(NonZeros);
6717       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6718                                  Op.getOperand(Idx));
6719       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6720     }
6721     return SDValue();
6722   }
6723
6724   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6725   if (EVTBits == 8 && NumElems == 16) {
6726     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6727                                         Subtarget, *this);
6728     if (V.getNode()) return V;
6729   }
6730
6731   if (EVTBits == 16 && NumElems == 8) {
6732     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6733                                       Subtarget, *this);
6734     if (V.getNode()) return V;
6735   }
6736
6737   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6738   if (EVTBits == 32 && NumElems == 4) {
6739     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6740                                       NumZero, DAG, Subtarget, *this);
6741     if (V.getNode())
6742       return V;
6743   }
6744
6745   // If element VT is == 32 bits, turn it into a number of shuffles.
6746   SmallVector<SDValue, 8> V(NumElems);
6747   if (NumElems == 4 && NumZero > 0) {
6748     for (unsigned i = 0; i < 4; ++i) {
6749       bool isZero = !(NonZeros & (1 << i));
6750       if (isZero)
6751         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6752       else
6753         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6754     }
6755
6756     for (unsigned i = 0; i < 2; ++i) {
6757       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6758         default: break;
6759         case 0:
6760           V[i] = V[i*2];  // Must be a zero vector.
6761           break;
6762         case 1:
6763           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6764           break;
6765         case 2:
6766           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6767           break;
6768         case 3:
6769           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6770           break;
6771       }
6772     }
6773
6774     bool Reverse1 = (NonZeros & 0x3) == 2;
6775     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6776     int MaskVec[] = {
6777       Reverse1 ? 1 : 0,
6778       Reverse1 ? 0 : 1,
6779       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6780       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6781     };
6782     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6783   }
6784
6785   if (Values.size() > 1 && VT.is128BitVector()) {
6786     // Check for a build vector of consecutive loads.
6787     for (unsigned i = 0; i < NumElems; ++i)
6788       V[i] = Op.getOperand(i);
6789
6790     // Check for elements which are consecutive loads.
6791     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6792     if (LD.getNode())
6793       return LD;
6794
6795     // Check for a build vector from mostly shuffle plus few inserting.
6796     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6797     if (Sh.getNode())
6798       return Sh;
6799
6800     // For SSE 4.1, use insertps to put the high elements into the low element.
6801     if (getSubtarget()->hasSSE41()) {
6802       SDValue Result;
6803       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6804         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6805       else
6806         Result = DAG.getUNDEF(VT);
6807
6808       for (unsigned i = 1; i < NumElems; ++i) {
6809         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6810         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6811                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6812       }
6813       return Result;
6814     }
6815
6816     // Otherwise, expand into a number of unpckl*, start by extending each of
6817     // our (non-undef) elements to the full vector width with the element in the
6818     // bottom slot of the vector (which generates no code for SSE).
6819     for (unsigned i = 0; i < NumElems; ++i) {
6820       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6821         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6822       else
6823         V[i] = DAG.getUNDEF(VT);
6824     }
6825
6826     // Next, we iteratively mix elements, e.g. for v4f32:
6827     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6828     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6829     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6830     unsigned EltStride = NumElems >> 1;
6831     while (EltStride != 0) {
6832       for (unsigned i = 0; i < EltStride; ++i) {
6833         // If V[i+EltStride] is undef and this is the first round of mixing,
6834         // then it is safe to just drop this shuffle: V[i] is already in the
6835         // right place, the one element (since it's the first round) being
6836         // inserted as undef can be dropped.  This isn't safe for successive
6837         // rounds because they will permute elements within both vectors.
6838         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6839             EltStride == NumElems/2)
6840           continue;
6841
6842         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6843       }
6844       EltStride >>= 1;
6845     }
6846     return V[0];
6847   }
6848   return SDValue();
6849 }
6850
6851 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6852 // to create 256-bit vectors from two other 128-bit ones.
6853 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6854   SDLoc dl(Op);
6855   MVT ResVT = Op.getSimpleValueType();
6856
6857   assert((ResVT.is256BitVector() ||
6858           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6859
6860   SDValue V1 = Op.getOperand(0);
6861   SDValue V2 = Op.getOperand(1);
6862   unsigned NumElems = ResVT.getVectorNumElements();
6863   if(ResVT.is256BitVector())
6864     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6865
6866   if (Op.getNumOperands() == 4) {
6867     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6868                                 ResVT.getVectorNumElements()/2);
6869     SDValue V3 = Op.getOperand(2);
6870     SDValue V4 = Op.getOperand(3);
6871     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6872       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6873   }
6874   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6875 }
6876
6877 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6878   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6879   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6880          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6881           Op.getNumOperands() == 4)));
6882
6883   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6884   // from two other 128-bit ones.
6885
6886   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6887   return LowerAVXCONCAT_VECTORS(Op, DAG);
6888 }
6889
6890
6891 //===----------------------------------------------------------------------===//
6892 // Vector shuffle lowering
6893 //
6894 // This is an experimental code path for lowering vector shuffles on x86. It is
6895 // designed to handle arbitrary vector shuffles and blends, gracefully
6896 // degrading performance as necessary. It works hard to recognize idiomatic
6897 // shuffles and lower them to optimal instruction patterns without leaving
6898 // a framework that allows reasonably efficient handling of all vector shuffle
6899 // patterns.
6900 //===----------------------------------------------------------------------===//
6901
6902 /// \brief Tiny helper function to identify a no-op mask.
6903 ///
6904 /// This is a somewhat boring predicate function. It checks whether the mask
6905 /// array input, which is assumed to be a single-input shuffle mask of the kind
6906 /// used by the X86 shuffle instructions (not a fully general
6907 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6908 /// in-place shuffle are 'no-op's.
6909 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6910   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6911     if (Mask[i] != -1 && Mask[i] != i)
6912       return false;
6913   return true;
6914 }
6915
6916 /// \brief Helper function to classify a mask as a single-input mask.
6917 ///
6918 /// This isn't a generic single-input test because in the vector shuffle
6919 /// lowering we canonicalize single inputs to be the first input operand. This
6920 /// means we can more quickly test for a single input by only checking whether
6921 /// an input from the second operand exists. We also assume that the size of
6922 /// mask corresponds to the size of the input vectors which isn't true in the
6923 /// fully general case.
6924 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6925   for (int M : Mask)
6926     if (M >= (int)Mask.size())
6927       return false;
6928   return true;
6929 }
6930
6931 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6932 ///
6933 /// This helper function produces an 8-bit shuffle immediate corresponding to
6934 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6935 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6936 /// example.
6937 ///
6938 /// NB: We rely heavily on "undef" masks preserving the input lane.
6939 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6940                                           SelectionDAG &DAG) {
6941   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6942   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6943   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6944   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6945   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6946
6947   unsigned Imm = 0;
6948   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6949   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6950   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6951   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6952   return DAG.getConstant(Imm, MVT::i8);
6953 }
6954
6955 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6956 ///
6957 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6958 /// support for floating point shuffles but not integer shuffles. These
6959 /// instructions will incur a domain crossing penalty on some chips though so
6960 /// it is better to avoid lowering through this for integer vectors where
6961 /// possible.
6962 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6963                                        const X86Subtarget *Subtarget,
6964                                        SelectionDAG &DAG) {
6965   SDLoc DL(Op);
6966   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6967   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6968   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6969   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6970   ArrayRef<int> Mask = SVOp->getMask();
6971   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6972
6973   if (isSingleInputShuffleMask(Mask)) {
6974     // Straight shuffle of a single input vector. Simulate this by using the
6975     // single input as both of the "inputs" to this instruction..
6976     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6977     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6978                        DAG.getConstant(SHUFPDMask, MVT::i8));
6979   }
6980   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6981   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6982
6983   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6984   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6985                      DAG.getConstant(SHUFPDMask, MVT::i8));
6986 }
6987
6988 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6989 ///
6990 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6991 /// the integer unit to minimize domain crossing penalties. However, for blends
6992 /// it falls back to the floating point shuffle operation with appropriate bit
6993 /// casting.
6994 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6995                                        const X86Subtarget *Subtarget,
6996                                        SelectionDAG &DAG) {
6997   SDLoc DL(Op);
6998   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6999   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7000   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7001   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7002   ArrayRef<int> Mask = SVOp->getMask();
7003   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7004
7005   if (isSingleInputShuffleMask(Mask)) {
7006     // Straight shuffle of a single input vector. For everything from SSE2
7007     // onward this has a single fast instruction with no scary immediates.
7008     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7009     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7010     int WidenedMask[4] = {
7011         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7012         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7013     return DAG.getNode(
7014         ISD::BITCAST, DL, MVT::v2i64,
7015         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7016                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7017   }
7018
7019   // We implement this with SHUFPD which is pretty lame because it will likely
7020   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7021   // However, all the alternatives are still more cycles and newer chips don't
7022   // have this problem. It would be really nice if x86 had better shuffles here.
7023   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7024   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7025   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7026                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7027 }
7028
7029 /// \brief Lower 4-lane 32-bit floating point shuffles.
7030 ///
7031 /// Uses instructions exclusively from the floating point unit to minimize
7032 /// domain crossing penalties, as these are sufficient to implement all v4f32
7033 /// shuffles.
7034 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7035                                        const X86Subtarget *Subtarget,
7036                                        SelectionDAG &DAG) {
7037   SDLoc DL(Op);
7038   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7039   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7040   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7041   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7042   ArrayRef<int> Mask = SVOp->getMask();
7043   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7044
7045   SDValue LowV = V1, HighV = V2;
7046   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7047
7048   int NumV2Elements =
7049       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7050
7051   if (NumV2Elements == 0)
7052     // Straight shuffle of a single input vector. We pass the input vector to
7053     // both operands to simulate this with a SHUFPS.
7054     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7055                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7056
7057   if (NumV2Elements == 1) {
7058     int V2Index =
7059         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7060         Mask.begin();
7061     // Compute the index adjacent to V2Index and in the same half by toggling
7062     // the low bit.
7063     int V2AdjIndex = V2Index ^ 1;
7064
7065     if (Mask[V2AdjIndex] == -1) {
7066       // Handles all the cases where we have a single V2 element and an undef.
7067       // This will only ever happen in the high lanes because we commute the
7068       // vector otherwise.
7069       if (V2Index < 2)
7070         std::swap(LowV, HighV);
7071       NewMask[V2Index] -= 4;
7072     } else {
7073       // Handle the case where the V2 element ends up adjacent to a V1 element.
7074       // To make this work, blend them together as the first step.
7075       int V1Index = V2AdjIndex;
7076       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7077       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7078                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7079
7080       // Now proceed to reconstruct the final blend as we have the necessary
7081       // high or low half formed.
7082       if (V2Index < 2) {
7083         LowV = V2;
7084         HighV = V1;
7085       } else {
7086         HighV = V2;
7087       }
7088       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7089       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7090     }
7091   } else if (NumV2Elements == 2) {
7092     if (Mask[0] < 4 && Mask[1] < 4) {
7093       // Handle the easy case where we have V1 in the low lanes and V2 in the
7094       // high lanes. We never see this reversed because we sort the shuffle.
7095       NewMask[2] -= 4;
7096       NewMask[3] -= 4;
7097     } else {
7098       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7099       // trying to place elements directly, just blend them and set up the final
7100       // shuffle to place them.
7101
7102       // The first two blend mask elements are for V1, the second two are for
7103       // V2.
7104       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7105                           Mask[2] < 4 ? Mask[2] : Mask[3],
7106                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7107                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7108       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7109                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7110
7111       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7112       // a blend.
7113       LowV = HighV = V1;
7114       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7115       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7116       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7117       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7118     }
7119   }
7120   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7121                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7122 }
7123
7124 /// \brief Lower 4-lane i32 vector shuffles.
7125 ///
7126 /// We try to handle these with integer-domain shuffles where we can, but for
7127 /// blends we use the floating point domain blend instructions.
7128 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7129                                        const X86Subtarget *Subtarget,
7130                                        SelectionDAG &DAG) {
7131   SDLoc DL(Op);
7132   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7133   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7134   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7135   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7136   ArrayRef<int> Mask = SVOp->getMask();
7137   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7138
7139   if (isSingleInputShuffleMask(Mask))
7140     // Straight shuffle of a single input vector. For everything from SSE2
7141     // onward this has a single fast instruction with no scary immediates.
7142     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7143                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7144
7145   // We implement this with SHUFPS because it can blend from two vectors.
7146   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7147   // up the inputs, bypassing domain shift penalties that we would encur if we
7148   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7149   // relevant.
7150   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7151                      DAG.getVectorShuffle(
7152                          MVT::v4f32, DL,
7153                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7154                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7155 }
7156
7157 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7158 /// shuffle lowering, and the most complex part.
7159 ///
7160 /// The lowering strategy is to try to form pairs of input lanes which are
7161 /// targeted at the same half of the final vector, and then use a dword shuffle
7162 /// to place them onto the right half, and finally unpack the paired lanes into
7163 /// their final position.
7164 ///
7165 /// The exact breakdown of how to form these dword pairs and align them on the
7166 /// correct sides is really tricky. See the comments within the function for
7167 /// more of the details.
7168 static SDValue lowerV8I16SingleInputVectorShuffle(
7169     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7170     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7171   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7172   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7173   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7174
7175   SmallVector<int, 4> LoInputs;
7176   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7177                [](int M) { return M >= 0; });
7178   std::sort(LoInputs.begin(), LoInputs.end());
7179   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7180   SmallVector<int, 4> HiInputs;
7181   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7182                [](int M) { return M >= 0; });
7183   std::sort(HiInputs.begin(), HiInputs.end());
7184   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7185   int NumLToL =
7186       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7187   int NumHToL = LoInputs.size() - NumLToL;
7188   int NumLToH =
7189       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7190   int NumHToH = HiInputs.size() - NumLToH;
7191   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7192   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7193   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7194   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7195
7196   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7197   // such inputs we can swap two of the dwords across the half mark and end up
7198   // with <=2 inputs to each half in each half. Once there, we can fall through
7199   // to the generic code below. For example:
7200   //
7201   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7202   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7203   //
7204   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7205   // and 2-2.
7206   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7207                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7208     // Compute the index of dword with only one word among the three inputs in
7209     // a half by taking the sum of the half with three inputs and subtracting
7210     // the sum of the actual three inputs. The difference is the remaining
7211     // slot.
7212     int DWordA = (ThreeInputHalfSum -
7213                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7214                  2;
7215     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7216
7217     int PSHUFDMask[] = {0, 1, 2, 3};
7218     PSHUFDMask[DWordA] = DWordB;
7219     PSHUFDMask[DWordB] = DWordA;
7220     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7221                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7222                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7223                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7224
7225     // Adjust the mask to match the new locations of A and B.
7226     for (int &M : Mask)
7227       if (M != -1 && M/2 == DWordA)
7228         M = 2 * DWordB + M % 2;
7229       else if (M != -1 && M/2 == DWordB)
7230         M = 2 * DWordA + M % 2;
7231
7232     // Recurse back into this routine to re-compute state now that this isn't
7233     // a 3 and 1 problem.
7234     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7235                                 Mask);
7236   };
7237   if (NumLToL == 3 && NumHToL == 1)
7238     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7239   else if (NumLToL == 1 && NumHToL == 3)
7240     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7241   else if (NumLToH == 1 && NumHToH == 3)
7242     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7243   else if (NumLToH == 3 && NumHToH == 1)
7244     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7245
7246   // At this point there are at most two inputs to the low and high halves from
7247   // each half. That means the inputs can always be grouped into dwords and
7248   // those dwords can then be moved to the correct half with a dword shuffle.
7249   // We use at most one low and one high word shuffle to collect these paired
7250   // inputs into dwords, and finally a dword shuffle to place them.
7251   int PSHUFLMask[4] = {-1, -1, -1, -1};
7252   int PSHUFHMask[4] = {-1, -1, -1, -1};
7253   int PSHUFDMask[4] = {-1, -1, -1, -1};
7254
7255   // First fix the masks for all the inputs that are staying in their
7256   // original halves. This will then dictate the targets of the cross-half
7257   // shuffles.
7258   auto fixInPlaceInputs = [&PSHUFDMask](
7259       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7260       MutableArrayRef<int> HalfMask, int HalfOffset) {
7261     if (InPlaceInputs.empty())
7262       return;
7263     if (InPlaceInputs.size() == 1) {
7264       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7265           InPlaceInputs[0] - HalfOffset;
7266       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7267       return;
7268     }
7269
7270     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7271     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7272         InPlaceInputs[0] - HalfOffset;
7273     // Put the second input next to the first so that they are packed into
7274     // a dword. We find the adjacent index by toggling the low bit.
7275     int AdjIndex = InPlaceInputs[0] ^ 1;
7276     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7277     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7278     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7279   };
7280   if (!HToLInputs.empty())
7281     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7282   if (!LToHInputs.empty())
7283     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7284
7285   // Now gather the cross-half inputs and place them into a free dword of
7286   // their target half.
7287   // FIXME: This operation could almost certainly be simplified dramatically to
7288   // look more like the 3-1 fixing operation.
7289   auto moveInputsToRightHalf = [&PSHUFDMask](
7290       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7291       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7292       int SourceOffset, int DestOffset) {
7293     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7294       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7295     };
7296     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7297                                                int Word) {
7298       int LowWord = Word & ~1;
7299       int HighWord = Word | 1;
7300       return isWordClobbered(SourceHalfMask, LowWord) ||
7301              isWordClobbered(SourceHalfMask, HighWord);
7302     };
7303
7304     if (IncomingInputs.empty())
7305       return;
7306
7307     if (ExistingInputs.empty()) {
7308       // Map any dwords with inputs from them into the right half.
7309       for (int Input : IncomingInputs) {
7310         // If the source half mask maps over the inputs, turn those into
7311         // swaps and use the swapped lane.
7312         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7313           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7314             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7315                 Input - SourceOffset;
7316             // We have to swap the uses in our half mask in one sweep.
7317             for (int &M : HalfMask)
7318               if (M == SourceHalfMask[Input - SourceOffset])
7319                 M = Input;
7320               else if (M == Input)
7321                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7322           } else {
7323             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7324                        Input - SourceOffset &&
7325                    "Previous placement doesn't match!");
7326           }
7327           // Note that this correctly re-maps both when we do a swap and when
7328           // we observe the other side of the swap above. We rely on that to
7329           // avoid swapping the members of the input list directly.
7330           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7331         }
7332
7333         // Map the input's dword into the correct half.
7334         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7335           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7336         else
7337           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7338                      Input / 2 &&
7339                  "Previous placement doesn't match!");
7340       }
7341
7342       // And just directly shift any other-half mask elements to be same-half
7343       // as we will have mirrored the dword containing the element into the
7344       // same position within that half.
7345       for (int &M : HalfMask)
7346         if (M >= SourceOffset && M < SourceOffset + 4) {
7347           M = M - SourceOffset + DestOffset;
7348           assert(M >= 0 && "This should never wrap below zero!");
7349         }
7350       return;
7351     }
7352
7353     // Ensure we have the input in a viable dword of its current half. This
7354     // is particularly tricky because the original position may be clobbered
7355     // by inputs being moved and *staying* in that half.
7356     if (IncomingInputs.size() == 1) {
7357       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7358         int InputFixed = std::find(std::begin(SourceHalfMask),
7359                                    std::end(SourceHalfMask), -1) -
7360                          std::begin(SourceHalfMask) + SourceOffset;
7361         SourceHalfMask[InputFixed - SourceOffset] =
7362             IncomingInputs[0] - SourceOffset;
7363         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7364                      InputFixed);
7365         IncomingInputs[0] = InputFixed;
7366       }
7367     } else if (IncomingInputs.size() == 2) {
7368       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7369           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7370         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7371         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7372                "Not all dwords can be clobbered!");
7373         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7374         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7375         for (int &M : HalfMask)
7376           if (M == IncomingInputs[0])
7377             M = SourceDWordBase + SourceOffset;
7378           else if (M == IncomingInputs[1])
7379             M = SourceDWordBase + 1 + SourceOffset;
7380         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7381         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7382       }
7383     } else {
7384       llvm_unreachable("Unhandled input size!");
7385     }
7386
7387     // Now hoist the DWord down to the right half.
7388     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7389     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7390     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7391     for (int Input : IncomingInputs)
7392       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7393                    FreeDWord * 2 + Input % 2);
7394   };
7395   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7396                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7397   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7398                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7399
7400   // Now enact all the shuffles we've computed to move the inputs into their
7401   // target half.
7402   if (!isNoopShuffleMask(PSHUFLMask))
7403     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7404                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7405   if (!isNoopShuffleMask(PSHUFHMask))
7406     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7407                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7408   if (!isNoopShuffleMask(PSHUFDMask))
7409     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7410                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7411                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7412                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7413
7414   // At this point, each half should contain all its inputs, and we can then
7415   // just shuffle them into their final position.
7416   assert(std::count_if(LoMask.begin(), LoMask.end(),
7417                        [](int M) { return M >= 4; }) == 0 &&
7418          "Failed to lift all the high half inputs to the low mask!");
7419   assert(std::count_if(HiMask.begin(), HiMask.end(),
7420                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7421          "Failed to lift all the low half inputs to the high mask!");
7422
7423   // Do a half shuffle for the low mask.
7424   if (!isNoopShuffleMask(LoMask))
7425     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7426                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7427
7428   // Do a half shuffle with the high mask after shifting its values down.
7429   for (int &M : HiMask)
7430     if (M >= 0)
7431       M -= 4;
7432   if (!isNoopShuffleMask(HiMask))
7433     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7434                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7435
7436   return V;
7437 }
7438
7439 /// \brief Detect whether the mask pattern should be lowered through
7440 /// interleaving.
7441 ///
7442 /// This essentially tests whether viewing the mask as an interleaving of two
7443 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7444 /// lowering it through interleaving is a significantly better strategy.
7445 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7446   int NumEvenInputs[2] = {0, 0};
7447   int NumOddInputs[2] = {0, 0};
7448   int NumLoInputs[2] = {0, 0};
7449   int NumHiInputs[2] = {0, 0};
7450   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7451     if (Mask[i] < 0)
7452       continue;
7453
7454     int InputIdx = Mask[i] >= Size;
7455
7456     if (i < Size / 2)
7457       ++NumLoInputs[InputIdx];
7458     else
7459       ++NumHiInputs[InputIdx];
7460
7461     if ((i % 2) == 0)
7462       ++NumEvenInputs[InputIdx];
7463     else
7464       ++NumOddInputs[InputIdx];
7465   }
7466
7467   // The minimum number of cross-input results for both the interleaved and
7468   // split cases. If interleaving results in fewer cross-input results, return
7469   // true.
7470   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7471                                     NumEvenInputs[0] + NumOddInputs[1]);
7472   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7473                               NumLoInputs[0] + NumHiInputs[1]);
7474   return InterleavedCrosses < SplitCrosses;
7475 }
7476
7477 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7478 ///
7479 /// This strategy only works when the inputs from each vector fit into a single
7480 /// half of that vector, and generally there are not so many inputs as to leave
7481 /// the in-place shuffles required highly constrained (and thus expensive). It
7482 /// shifts all the inputs into a single side of both input vectors and then
7483 /// uses an unpack to interleave these inputs in a single vector. At that
7484 /// point, we will fall back on the generic single input shuffle lowering.
7485 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7486                                                  SDValue V2,
7487                                                  MutableArrayRef<int> Mask,
7488                                                  const X86Subtarget *Subtarget,
7489                                                  SelectionDAG &DAG) {
7490   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7491   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7492   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7493   for (int i = 0; i < 8; ++i)
7494     if (Mask[i] >= 0 && Mask[i] < 4)
7495       LoV1Inputs.push_back(i);
7496     else if (Mask[i] >= 4 && Mask[i] < 8)
7497       HiV1Inputs.push_back(i);
7498     else if (Mask[i] >= 8 && Mask[i] < 12)
7499       LoV2Inputs.push_back(i);
7500     else if (Mask[i] >= 12)
7501       HiV2Inputs.push_back(i);
7502
7503   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7504   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7505   (void)NumV1Inputs;
7506   (void)NumV2Inputs;
7507   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7508   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7509   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7510
7511   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7512                      HiV1Inputs.size() + HiV2Inputs.size();
7513
7514   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7515                               ArrayRef<int> HiInputs, bool MoveToLo,
7516                               int MaskOffset) {
7517     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7518     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7519     if (BadInputs.empty())
7520       return V;
7521
7522     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7523     int MoveOffset = MoveToLo ? 0 : 4;
7524
7525     if (GoodInputs.empty()) {
7526       for (int BadInput : BadInputs) {
7527         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7528         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7529       }
7530     } else {
7531       if (GoodInputs.size() == 2) {
7532         // If the low inputs are spread across two dwords, pack them into
7533         // a single dword.
7534         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7535             Mask[GoodInputs[0]] - MaskOffset;
7536         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7537             Mask[GoodInputs[1]] - MaskOffset;
7538         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7539         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7540       } else {
7541         // Otherwise pin the low inputs.
7542         for (int GoodInput : GoodInputs)
7543           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7544       }
7545
7546       int MoveMaskIdx =
7547           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7548           std::begin(MoveMask);
7549       assert(MoveMaskIdx >= MoveOffset && "Established above");
7550
7551       if (BadInputs.size() == 2) {
7552         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7553         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7554         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7555             Mask[BadInputs[0]] - MaskOffset;
7556         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7557             Mask[BadInputs[1]] - MaskOffset;
7558         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7559         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7560       } else {
7561         assert(BadInputs.size() == 1 && "All sizes handled");
7562         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7563         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7564       }
7565     }
7566
7567     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7568                                 MoveMask);
7569   };
7570   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7571                         /*MaskOffset*/ 0);
7572   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7573                         /*MaskOffset*/ 8);
7574
7575   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7576   // cross-half traffic in the final shuffle.
7577
7578   // Munge the mask to be a single-input mask after the unpack merges the
7579   // results.
7580   for (int &M : Mask)
7581     if (M != -1)
7582       M = 2 * (M % 4) + (M / 8);
7583
7584   return DAG.getVectorShuffle(
7585       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7586                                   DL, MVT::v8i16, V1, V2),
7587       DAG.getUNDEF(MVT::v8i16), Mask);
7588 }
7589
7590 /// \brief Generic lowering of 8-lane i16 shuffles.
7591 ///
7592 /// This handles both single-input shuffles and combined shuffle/blends with
7593 /// two inputs. The single input shuffles are immediately delegated to
7594 /// a dedicated lowering routine.
7595 ///
7596 /// The blends are lowered in one of three fundamental ways. If there are few
7597 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7598 /// of the input is significantly cheaper when lowered as an interleaving of
7599 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7600 /// halves of the inputs separately (making them have relatively few inputs)
7601 /// and then concatenate them.
7602 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7603                                        const X86Subtarget *Subtarget,
7604                                        SelectionDAG &DAG) {
7605   SDLoc DL(Op);
7606   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7607   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7608   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7609   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7610   ArrayRef<int> OrigMask = SVOp->getMask();
7611   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7612                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7613   MutableArrayRef<int> Mask(MaskStorage);
7614
7615   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7616
7617   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7618   auto isV2 = [](int M) { return M >= 8; };
7619
7620   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7621   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7622
7623   if (NumV2Inputs == 0)
7624     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7625
7626   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7627                             "to be V1-input shuffles.");
7628
7629   if (NumV1Inputs + NumV2Inputs <= 4)
7630     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7631
7632   // Check whether an interleaving lowering is likely to be more efficient.
7633   // This isn't perfect but it is a strong heuristic that tends to work well on
7634   // the kinds of shuffles that show up in practice.
7635   //
7636   // FIXME: Handle 1x, 2x, and 4x interleaving.
7637   if (shouldLowerAsInterleaving(Mask)) {
7638     // FIXME: Figure out whether we should pack these into the low or high
7639     // halves.
7640
7641     int EMask[8], OMask[8];
7642     for (int i = 0; i < 4; ++i) {
7643       EMask[i] = Mask[2*i];
7644       OMask[i] = Mask[2*i + 1];
7645       EMask[i + 4] = -1;
7646       OMask[i + 4] = -1;
7647     }
7648
7649     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7650     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7651
7652     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7653   }
7654
7655   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7656   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7657
7658   for (int i = 0; i < 4; ++i) {
7659     LoBlendMask[i] = Mask[i];
7660     HiBlendMask[i] = Mask[i + 4];
7661   }
7662
7663   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7664   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7665   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7666   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7667
7668   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7669                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7670 }
7671
7672 /// \brief Generic lowering of v16i8 shuffles.
7673 ///
7674 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7675 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7676 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7677 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7678 /// back together.
7679 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7680                                        const X86Subtarget *Subtarget,
7681                                        SelectionDAG &DAG) {
7682   SDLoc DL(Op);
7683   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7684   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7685   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7686   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7687   ArrayRef<int> OrigMask = SVOp->getMask();
7688   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7689   int MaskStorage[16] = {
7690       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7691       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7692       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7693       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7694   MutableArrayRef<int> Mask(MaskStorage);
7695   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7696   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7697
7698   // For single-input shuffles, there are some nicer lowering tricks we can use.
7699   if (isSingleInputShuffleMask(Mask)) {
7700     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7701     // Notably, this handles splat and partial-splat shuffles more efficiently.
7702     // However, it only makes sense if the pre-duplication shuffle simplifies
7703     // things significantly. Currently, this means we need to be able to
7704     // express the pre-duplication shuffle as an i16 shuffle.
7705     //
7706     // FIXME: We should check for other patterns which can be widened into an
7707     // i16 shuffle as well.
7708     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7709       for (int i = 0; i < 16; i += 2) {
7710         if (Mask[i] != Mask[i + 1])
7711           return false;
7712       }
7713       return true;
7714     };
7715     auto tryToWidenViaDuplication = [&]() -> SDValue {
7716       if (!canWidenViaDuplication(Mask))
7717         return SDValue();
7718       SmallVector<int, 4> LoInputs;
7719       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7720                    [](int M) { return M >= 0 && M < 8; });
7721       std::sort(LoInputs.begin(), LoInputs.end());
7722       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7723                      LoInputs.end());
7724       SmallVector<int, 4> HiInputs;
7725       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7726                    [](int M) { return M >= 8; });
7727       std::sort(HiInputs.begin(), HiInputs.end());
7728       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7729                      HiInputs.end());
7730
7731       bool TargetLo = LoInputs.size() >= HiInputs.size();
7732       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7733       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7734
7735       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7736       SmallDenseMap<int, int, 8> LaneMap;
7737       for (int I : InPlaceInputs) {
7738         PreDupI16Shuffle[I/2] = I/2;
7739         LaneMap[I] = I;
7740       }
7741       int j = TargetLo ? 0 : 4, je = j + 4;
7742       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7743         // Check if j is already a shuffle of this input. This happens when
7744         // there are two adjacent bytes after we move the low one.
7745         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7746           // If we haven't yet mapped the input, search for a slot into which
7747           // we can map it.
7748           while (j < je && PreDupI16Shuffle[j] != -1)
7749             ++j;
7750
7751           if (j == je)
7752             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7753             return SDValue();
7754
7755           // Map this input with the i16 shuffle.
7756           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7757         }
7758
7759         // Update the lane map based on the mapping we ended up with.
7760         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7761       }
7762       V1 = DAG.getNode(
7763           ISD::BITCAST, DL, MVT::v16i8,
7764           DAG.getVectorShuffle(MVT::v8i16, DL,
7765                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7766                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7767
7768       // Unpack the bytes to form the i16s that will be shuffled into place.
7769       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7770                        MVT::v16i8, V1, V1);
7771
7772       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7773       for (int i = 0; i < 16; i += 2) {
7774         if (Mask[i] != -1)
7775           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7776         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7777       }
7778       return DAG.getNode(
7779           ISD::BITCAST, DL, MVT::v16i8,
7780           DAG.getVectorShuffle(MVT::v8i16, DL,
7781                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7782                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7783     };
7784     if (SDValue V = tryToWidenViaDuplication())
7785       return V;
7786   }
7787
7788   // Check whether an interleaving lowering is likely to be more efficient.
7789   // This isn't perfect but it is a strong heuristic that tends to work well on
7790   // the kinds of shuffles that show up in practice.
7791   //
7792   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7793   if (shouldLowerAsInterleaving(Mask)) {
7794     // FIXME: Figure out whether we should pack these into the low or high
7795     // halves.
7796
7797     int EMask[16], OMask[16];
7798     for (int i = 0; i < 8; ++i) {
7799       EMask[i] = Mask[2*i];
7800       OMask[i] = Mask[2*i + 1];
7801       EMask[i + 8] = -1;
7802       OMask[i + 8] = -1;
7803     }
7804
7805     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7806     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7807
7808     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7809   }
7810
7811   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7812   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7813   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7814   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7815
7816   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7817                             MutableArrayRef<int> V1HalfBlendMask,
7818                             MutableArrayRef<int> V2HalfBlendMask) {
7819     for (int i = 0; i < 8; ++i)
7820       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7821         V1HalfBlendMask[i] = HalfMask[i];
7822         HalfMask[i] = i;
7823       } else if (HalfMask[i] >= 16) {
7824         V2HalfBlendMask[i] = HalfMask[i] - 16;
7825         HalfMask[i] = i + 8;
7826       }
7827   };
7828   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7829   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7830
7831   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7832
7833   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7834                              MutableArrayRef<int> HiBlendMask) {
7835     SDValue V1, V2;
7836     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7837     // them out and avoid using UNPCK{L,H} to extract the elements of V as
7838     // i16s.
7839     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7840                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
7841         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7842                      [](int M) { return M >= 0 && M % 2 == 1; })) {
7843       // Use a mask to drop the high bytes.
7844       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7845       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7846                        DAG.getConstant(0x00FF, MVT::v8i16));
7847
7848       // This will be a single vector shuffle instead of a blend so nuke V2.
7849       V2 = DAG.getUNDEF(MVT::v8i16);
7850
7851       // Squash the masks to point directly into V1.
7852       for (int &M : LoBlendMask)
7853         if (M >= 0)
7854           M /= 2;
7855       for (int &M : HiBlendMask)
7856         if (M >= 0)
7857           M /= 2;
7858     } else {
7859       // Otherwise just unpack the low half of V into V1 and the high half into
7860       // V2 so that we can blend them as i16s.
7861       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7862                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7863       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7864                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7865     }
7866
7867     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7868     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7869     return std::make_pair(BlendedLo, BlendedHi);
7870   };
7871   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7872   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7873   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7874
7875   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7876   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7877
7878   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7879 }
7880
7881 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7882 ///
7883 /// This routine breaks down the specific type of 128-bit shuffle and
7884 /// dispatches to the lowering routines accordingly.
7885 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7886                                         MVT VT, const X86Subtarget *Subtarget,
7887                                         SelectionDAG &DAG) {
7888   switch (VT.SimpleTy) {
7889   case MVT::v2i64:
7890     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7891   case MVT::v2f64:
7892     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7893   case MVT::v4i32:
7894     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7895   case MVT::v4f32:
7896     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7897   case MVT::v8i16:
7898     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7899   case MVT::v16i8:
7900     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7901
7902   default:
7903     llvm_unreachable("Unimplemented!");
7904   }
7905 }
7906
7907 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7908 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7909   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7910     if (Mask[i] + 1 != Mask[i+1])
7911       return false;
7912
7913   return true;
7914 }
7915
7916 /// \brief Top-level lowering for x86 vector shuffles.
7917 ///
7918 /// This handles decomposition, canonicalization, and lowering of all x86
7919 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7920 /// above in helper routines. The canonicalization attempts to widen shuffles
7921 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7922 /// s.t. only one of the two inputs needs to be tested, etc.
7923 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7924                                   SelectionDAG &DAG) {
7925   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7926   ArrayRef<int> Mask = SVOp->getMask();
7927   SDValue V1 = Op.getOperand(0);
7928   SDValue V2 = Op.getOperand(1);
7929   MVT VT = Op.getSimpleValueType();
7930   int NumElements = VT.getVectorNumElements();
7931   SDLoc dl(Op);
7932
7933   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7934
7935   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7936   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7937   if (V1IsUndef && V2IsUndef)
7938     return DAG.getUNDEF(VT);
7939
7940   // When we create a shuffle node we put the UNDEF node to second operand,
7941   // but in some cases the first operand may be transformed to UNDEF.
7942   // In this case we should just commute the node.
7943   if (V1IsUndef)
7944     return CommuteVectorShuffle(SVOp, DAG);
7945
7946   // Check for non-undef masks pointing at an undef vector and make the masks
7947   // undef as well. This makes it easier to match the shuffle based solely on
7948   // the mask.
7949   if (V2IsUndef)
7950     for (int M : Mask)
7951       if (M >= NumElements) {
7952         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7953         for (int &M : NewMask)
7954           if (M >= NumElements)
7955             M = -1;
7956         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7957       }
7958
7959   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7960   // lanes but wider integers. We cap this to not form integers larger than i64
7961   // but it might be interesting to form i128 integers to handle flipping the
7962   // low and high halves of AVX 256-bit vectors.
7963   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7964       areAdjacentMasksSequential(Mask)) {
7965     SmallVector<int, 8> NewMask;
7966     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7967       NewMask.push_back(Mask[i] / 2);
7968     MVT NewVT =
7969         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7970                          VT.getVectorNumElements() / 2);
7971     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7972     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7973     return DAG.getNode(ISD::BITCAST, dl, VT,
7974                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7975   }
7976
7977   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7978   for (int M : SVOp->getMask())
7979     if (M < 0)
7980       ++NumUndefElements;
7981     else if (M < NumElements)
7982       ++NumV1Elements;
7983     else
7984       ++NumV2Elements;
7985
7986   // Commute the shuffle as needed such that more elements come from V1 than
7987   // V2. This allows us to match the shuffle pattern strictly on how many
7988   // elements come from V1 without handling the symmetric cases.
7989   if (NumV2Elements > NumV1Elements)
7990     return CommuteVectorShuffle(SVOp, DAG);
7991
7992   // When the number of V1 and V2 elements are the same, try to minimize the
7993   // number of uses of V2 in the low half of the vector.
7994   if (NumV1Elements == NumV2Elements) {
7995     int LowV1Elements = 0, LowV2Elements = 0;
7996     for (int M : SVOp->getMask().slice(0, NumElements / 2))
7997       if (M >= NumElements)
7998         ++LowV2Elements;
7999       else if (M >= 0)
8000         ++LowV1Elements;
8001     if (LowV2Elements > LowV1Elements)
8002       return CommuteVectorShuffle(SVOp, DAG);
8003   }
8004
8005   // For each vector width, delegate to a specialized lowering routine.
8006   if (VT.getSizeInBits() == 128)
8007     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8008
8009   llvm_unreachable("Unimplemented!");
8010 }
8011
8012
8013 //===----------------------------------------------------------------------===//
8014 // Legacy vector shuffle lowering
8015 //
8016 // This code is the legacy code handling vector shuffles until the above
8017 // replaces its functionality and performance.
8018 //===----------------------------------------------------------------------===//
8019
8020 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8021                         bool hasInt256, unsigned *MaskOut = nullptr) {
8022   MVT EltVT = VT.getVectorElementType();
8023
8024   // There is no blend with immediate in AVX-512.
8025   if (VT.is512BitVector())
8026     return false;
8027
8028   if (!hasSSE41 || EltVT == MVT::i8)
8029     return false;
8030   if (!hasInt256 && VT == MVT::v16i16)
8031     return false;
8032
8033   unsigned MaskValue = 0;
8034   unsigned NumElems = VT.getVectorNumElements();
8035   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8036   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8037   unsigned NumElemsInLane = NumElems / NumLanes;
8038
8039   // Blend for v16i16 should be symetric for the both lanes.
8040   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8041
8042     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8043     int EltIdx = MaskVals[i];
8044
8045     if ((EltIdx < 0 || EltIdx == (int)i) &&
8046         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8047       continue;
8048
8049     if (((unsigned)EltIdx == (i + NumElems)) &&
8050         (SndLaneEltIdx < 0 ||
8051          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8052       MaskValue |= (1 << i);
8053     else
8054       return false;
8055   }
8056
8057   if (MaskOut)
8058     *MaskOut = MaskValue;
8059   return true;
8060 }
8061
8062 // Try to lower a shuffle node into a simple blend instruction.
8063 // This function assumes isBlendMask returns true for this
8064 // SuffleVectorSDNode
8065 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8066                                           unsigned MaskValue,
8067                                           const X86Subtarget *Subtarget,
8068                                           SelectionDAG &DAG) {
8069   MVT VT = SVOp->getSimpleValueType(0);
8070   MVT EltVT = VT.getVectorElementType();
8071   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8072                      Subtarget->hasInt256() && "Trying to lower a "
8073                                                "VECTOR_SHUFFLE to a Blend but "
8074                                                "with the wrong mask"));
8075   SDValue V1 = SVOp->getOperand(0);
8076   SDValue V2 = SVOp->getOperand(1);
8077   SDLoc dl(SVOp);
8078   unsigned NumElems = VT.getVectorNumElements();
8079
8080   // Convert i32 vectors to floating point if it is not AVX2.
8081   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8082   MVT BlendVT = VT;
8083   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8084     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8085                                NumElems);
8086     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8087     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8088   }
8089
8090   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8091                             DAG.getConstant(MaskValue, MVT::i32));
8092   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8093 }
8094
8095 /// In vector type \p VT, return true if the element at index \p InputIdx
8096 /// falls on a different 128-bit lane than \p OutputIdx.
8097 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8098                                      unsigned OutputIdx) {
8099   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8100   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8101 }
8102
8103 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8104 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8105 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8106 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8107 /// zero.
8108 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8109                          SelectionDAG &DAG) {
8110   MVT VT = V1.getSimpleValueType();
8111   assert(VT.is128BitVector() || VT.is256BitVector());
8112
8113   MVT EltVT = VT.getVectorElementType();
8114   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8115   unsigned NumElts = VT.getVectorNumElements();
8116
8117   SmallVector<SDValue, 32> PshufbMask;
8118   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8119     int InputIdx = MaskVals[OutputIdx];
8120     unsigned InputByteIdx;
8121
8122     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8123       InputByteIdx = 0x80;
8124     else {
8125       // Cross lane is not allowed.
8126       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8127         return SDValue();
8128       InputByteIdx = InputIdx * EltSizeInBytes;
8129       // Index is an byte offset within the 128-bit lane.
8130       InputByteIdx &= 0xf;
8131     }
8132
8133     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8134       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8135       if (InputByteIdx != 0x80)
8136         ++InputByteIdx;
8137     }
8138   }
8139
8140   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8141   if (ShufVT != VT)
8142     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8143   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8144                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8145 }
8146
8147 // v8i16 shuffles - Prefer shuffles in the following order:
8148 // 1. [all]   pshuflw, pshufhw, optional move
8149 // 2. [ssse3] 1 x pshufb
8150 // 3. [ssse3] 2 x pshufb + 1 x por
8151 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8152 static SDValue
8153 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8154                          SelectionDAG &DAG) {
8155   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8156   SDValue V1 = SVOp->getOperand(0);
8157   SDValue V2 = SVOp->getOperand(1);
8158   SDLoc dl(SVOp);
8159   SmallVector<int, 8> MaskVals;
8160
8161   // Determine if more than 1 of the words in each of the low and high quadwords
8162   // of the result come from the same quadword of one of the two inputs.  Undef
8163   // mask values count as coming from any quadword, for better codegen.
8164   //
8165   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8166   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8167   unsigned LoQuad[] = { 0, 0, 0, 0 };
8168   unsigned HiQuad[] = { 0, 0, 0, 0 };
8169   // Indices of quads used.
8170   std::bitset<4> InputQuads;
8171   for (unsigned i = 0; i < 8; ++i) {
8172     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8173     int EltIdx = SVOp->getMaskElt(i);
8174     MaskVals.push_back(EltIdx);
8175     if (EltIdx < 0) {
8176       ++Quad[0];
8177       ++Quad[1];
8178       ++Quad[2];
8179       ++Quad[3];
8180       continue;
8181     }
8182     ++Quad[EltIdx / 4];
8183     InputQuads.set(EltIdx / 4);
8184   }
8185
8186   int BestLoQuad = -1;
8187   unsigned MaxQuad = 1;
8188   for (unsigned i = 0; i < 4; ++i) {
8189     if (LoQuad[i] > MaxQuad) {
8190       BestLoQuad = i;
8191       MaxQuad = LoQuad[i];
8192     }
8193   }
8194
8195   int BestHiQuad = -1;
8196   MaxQuad = 1;
8197   for (unsigned i = 0; i < 4; ++i) {
8198     if (HiQuad[i] > MaxQuad) {
8199       BestHiQuad = i;
8200       MaxQuad = HiQuad[i];
8201     }
8202   }
8203
8204   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8205   // of the two input vectors, shuffle them into one input vector so only a
8206   // single pshufb instruction is necessary. If there are more than 2 input
8207   // quads, disable the next transformation since it does not help SSSE3.
8208   bool V1Used = InputQuads[0] || InputQuads[1];
8209   bool V2Used = InputQuads[2] || InputQuads[3];
8210   if (Subtarget->hasSSSE3()) {
8211     if (InputQuads.count() == 2 && V1Used && V2Used) {
8212       BestLoQuad = InputQuads[0] ? 0 : 1;
8213       BestHiQuad = InputQuads[2] ? 2 : 3;
8214     }
8215     if (InputQuads.count() > 2) {
8216       BestLoQuad = -1;
8217       BestHiQuad = -1;
8218     }
8219   }
8220
8221   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8222   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8223   // words from all 4 input quadwords.
8224   SDValue NewV;
8225   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8226     int MaskV[] = {
8227       BestLoQuad < 0 ? 0 : BestLoQuad,
8228       BestHiQuad < 0 ? 1 : BestHiQuad
8229     };
8230     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8231                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8232                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8233     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8234
8235     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8236     // source words for the shuffle, to aid later transformations.
8237     bool AllWordsInNewV = true;
8238     bool InOrder[2] = { true, true };
8239     for (unsigned i = 0; i != 8; ++i) {
8240       int idx = MaskVals[i];
8241       if (idx != (int)i)
8242         InOrder[i/4] = false;
8243       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8244         continue;
8245       AllWordsInNewV = false;
8246       break;
8247     }
8248
8249     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8250     if (AllWordsInNewV) {
8251       for (int i = 0; i != 8; ++i) {
8252         int idx = MaskVals[i];
8253         if (idx < 0)
8254           continue;
8255         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8256         if ((idx != i) && idx < 4)
8257           pshufhw = false;
8258         if ((idx != i) && idx > 3)
8259           pshuflw = false;
8260       }
8261       V1 = NewV;
8262       V2Used = false;
8263       BestLoQuad = 0;
8264       BestHiQuad = 1;
8265     }
8266
8267     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8268     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8269     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8270       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8271       unsigned TargetMask = 0;
8272       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8273                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8274       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8275       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8276                              getShufflePSHUFLWImmediate(SVOp);
8277       V1 = NewV.getOperand(0);
8278       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8279     }
8280   }
8281
8282   // Promote splats to a larger type which usually leads to more efficient code.
8283   // FIXME: Is this true if pshufb is available?
8284   if (SVOp->isSplat())
8285     return PromoteSplat(SVOp, DAG);
8286
8287   // If we have SSSE3, and all words of the result are from 1 input vector,
8288   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8289   // is present, fall back to case 4.
8290   if (Subtarget->hasSSSE3()) {
8291     SmallVector<SDValue,16> pshufbMask;
8292
8293     // If we have elements from both input vectors, set the high bit of the
8294     // shuffle mask element to zero out elements that come from V2 in the V1
8295     // mask, and elements that come from V1 in the V2 mask, so that the two
8296     // results can be OR'd together.
8297     bool TwoInputs = V1Used && V2Used;
8298     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8299     if (!TwoInputs)
8300       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8301
8302     // Calculate the shuffle mask for the second input, shuffle it, and
8303     // OR it with the first shuffled input.
8304     CommuteVectorShuffleMask(MaskVals, 8);
8305     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8306     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8307     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8308   }
8309
8310   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8311   // and update MaskVals with new element order.
8312   std::bitset<8> InOrder;
8313   if (BestLoQuad >= 0) {
8314     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8315     for (int i = 0; i != 4; ++i) {
8316       int idx = MaskVals[i];
8317       if (idx < 0) {
8318         InOrder.set(i);
8319       } else if ((idx / 4) == BestLoQuad) {
8320         MaskV[i] = idx & 3;
8321         InOrder.set(i);
8322       }
8323     }
8324     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8325                                 &MaskV[0]);
8326
8327     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8328       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8329       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8330                                   NewV.getOperand(0),
8331                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8332     }
8333   }
8334
8335   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8336   // and update MaskVals with the new element order.
8337   if (BestHiQuad >= 0) {
8338     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8339     for (unsigned i = 4; i != 8; ++i) {
8340       int idx = MaskVals[i];
8341       if (idx < 0) {
8342         InOrder.set(i);
8343       } else if ((idx / 4) == BestHiQuad) {
8344         MaskV[i] = (idx & 3) + 4;
8345         InOrder.set(i);
8346       }
8347     }
8348     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8349                                 &MaskV[0]);
8350
8351     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8352       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8353       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8354                                   NewV.getOperand(0),
8355                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8356     }
8357   }
8358
8359   // In case BestHi & BestLo were both -1, which means each quadword has a word
8360   // from each of the four input quadwords, calculate the InOrder bitvector now
8361   // before falling through to the insert/extract cleanup.
8362   if (BestLoQuad == -1 && BestHiQuad == -1) {
8363     NewV = V1;
8364     for (int i = 0; i != 8; ++i)
8365       if (MaskVals[i] < 0 || MaskVals[i] == i)
8366         InOrder.set(i);
8367   }
8368
8369   // The other elements are put in the right place using pextrw and pinsrw.
8370   for (unsigned i = 0; i != 8; ++i) {
8371     if (InOrder[i])
8372       continue;
8373     int EltIdx = MaskVals[i];
8374     if (EltIdx < 0)
8375       continue;
8376     SDValue ExtOp = (EltIdx < 8) ?
8377       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8378                   DAG.getIntPtrConstant(EltIdx)) :
8379       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8380                   DAG.getIntPtrConstant(EltIdx - 8));
8381     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8382                        DAG.getIntPtrConstant(i));
8383   }
8384   return NewV;
8385 }
8386
8387 /// \brief v16i16 shuffles
8388 ///
8389 /// FIXME: We only support generation of a single pshufb currently.  We can
8390 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8391 /// well (e.g 2 x pshufb + 1 x por).
8392 static SDValue
8393 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8394   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8395   SDValue V1 = SVOp->getOperand(0);
8396   SDValue V2 = SVOp->getOperand(1);
8397   SDLoc dl(SVOp);
8398
8399   if (V2.getOpcode() != ISD::UNDEF)
8400     return SDValue();
8401
8402   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8403   return getPSHUFB(MaskVals, V1, dl, DAG);
8404 }
8405
8406 // v16i8 shuffles - Prefer shuffles in the following order:
8407 // 1. [ssse3] 1 x pshufb
8408 // 2. [ssse3] 2 x pshufb + 1 x por
8409 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8410 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8411                                         const X86Subtarget* Subtarget,
8412                                         SelectionDAG &DAG) {
8413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8414   SDValue V1 = SVOp->getOperand(0);
8415   SDValue V2 = SVOp->getOperand(1);
8416   SDLoc dl(SVOp);
8417   ArrayRef<int> MaskVals = SVOp->getMask();
8418
8419   // Promote splats to a larger type which usually leads to more efficient code.
8420   // FIXME: Is this true if pshufb is available?
8421   if (SVOp->isSplat())
8422     return PromoteSplat(SVOp, DAG);
8423
8424   // If we have SSSE3, case 1 is generated when all result bytes come from
8425   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8426   // present, fall back to case 3.
8427
8428   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8429   if (Subtarget->hasSSSE3()) {
8430     SmallVector<SDValue,16> pshufbMask;
8431
8432     // If all result elements are from one input vector, then only translate
8433     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8434     //
8435     // Otherwise, we have elements from both input vectors, and must zero out
8436     // elements that come from V2 in the first mask, and V1 in the second mask
8437     // so that we can OR them together.
8438     for (unsigned i = 0; i != 16; ++i) {
8439       int EltIdx = MaskVals[i];
8440       if (EltIdx < 0 || EltIdx >= 16)
8441         EltIdx = 0x80;
8442       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8443     }
8444     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8445                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8446                                  MVT::v16i8, pshufbMask));
8447
8448     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8449     // the 2nd operand if it's undefined or zero.
8450     if (V2.getOpcode() == ISD::UNDEF ||
8451         ISD::isBuildVectorAllZeros(V2.getNode()))
8452       return V1;
8453
8454     // Calculate the shuffle mask for the second input, shuffle it, and
8455     // OR it with the first shuffled input.
8456     pshufbMask.clear();
8457     for (unsigned i = 0; i != 16; ++i) {
8458       int EltIdx = MaskVals[i];
8459       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8460       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8461     }
8462     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8463                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8464                                  MVT::v16i8, pshufbMask));
8465     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8466   }
8467
8468   // No SSSE3 - Calculate in place words and then fix all out of place words
8469   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8470   // the 16 different words that comprise the two doublequadword input vectors.
8471   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8472   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8473   SDValue NewV = V1;
8474   for (int i = 0; i != 8; ++i) {
8475     int Elt0 = MaskVals[i*2];
8476     int Elt1 = MaskVals[i*2+1];
8477
8478     // This word of the result is all undef, skip it.
8479     if (Elt0 < 0 && Elt1 < 0)
8480       continue;
8481
8482     // This word of the result is already in the correct place, skip it.
8483     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8484       continue;
8485
8486     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8487     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8488     SDValue InsElt;
8489
8490     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8491     // using a single extract together, load it and store it.
8492     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8493       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8494                            DAG.getIntPtrConstant(Elt1 / 2));
8495       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8496                         DAG.getIntPtrConstant(i));
8497       continue;
8498     }
8499
8500     // If Elt1 is defined, extract it from the appropriate source.  If the
8501     // source byte is not also odd, shift the extracted word left 8 bits
8502     // otherwise clear the bottom 8 bits if we need to do an or.
8503     if (Elt1 >= 0) {
8504       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8505                            DAG.getIntPtrConstant(Elt1 / 2));
8506       if ((Elt1 & 1) == 0)
8507         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8508                              DAG.getConstant(8,
8509                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8510       else if (Elt0 >= 0)
8511         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8512                              DAG.getConstant(0xFF00, MVT::i16));
8513     }
8514     // If Elt0 is defined, extract it from the appropriate source.  If the
8515     // source byte is not also even, shift the extracted word right 8 bits. If
8516     // Elt1 was also defined, OR the extracted values together before
8517     // inserting them in the result.
8518     if (Elt0 >= 0) {
8519       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8520                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8521       if ((Elt0 & 1) != 0)
8522         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8523                               DAG.getConstant(8,
8524                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8525       else if (Elt1 >= 0)
8526         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8527                              DAG.getConstant(0x00FF, MVT::i16));
8528       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8529                          : InsElt0;
8530     }
8531     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8532                        DAG.getIntPtrConstant(i));
8533   }
8534   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8535 }
8536
8537 // v32i8 shuffles - Translate to VPSHUFB if possible.
8538 static
8539 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8540                                  const X86Subtarget *Subtarget,
8541                                  SelectionDAG &DAG) {
8542   MVT VT = SVOp->getSimpleValueType(0);
8543   SDValue V1 = SVOp->getOperand(0);
8544   SDValue V2 = SVOp->getOperand(1);
8545   SDLoc dl(SVOp);
8546   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8547
8548   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8549   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8550   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8551
8552   // VPSHUFB may be generated if
8553   // (1) one of input vector is undefined or zeroinitializer.
8554   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8555   // And (2) the mask indexes don't cross the 128-bit lane.
8556   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8557       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8558     return SDValue();
8559
8560   if (V1IsAllZero && !V2IsAllZero) {
8561     CommuteVectorShuffleMask(MaskVals, 32);
8562     V1 = V2;
8563   }
8564   return getPSHUFB(MaskVals, V1, dl, DAG);
8565 }
8566
8567 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8568 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8569 /// done when every pair / quad of shuffle mask elements point to elements in
8570 /// the right sequence. e.g.
8571 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8572 static
8573 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8574                                  SelectionDAG &DAG) {
8575   MVT VT = SVOp->getSimpleValueType(0);
8576   SDLoc dl(SVOp);
8577   unsigned NumElems = VT.getVectorNumElements();
8578   MVT NewVT;
8579   unsigned Scale;
8580   switch (VT.SimpleTy) {
8581   default: llvm_unreachable("Unexpected!");
8582   case MVT::v2i64:
8583   case MVT::v2f64:
8584            return SDValue(SVOp, 0);
8585   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8586   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8587   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8588   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8589   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8590   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8591   }
8592
8593   SmallVector<int, 8> MaskVec;
8594   for (unsigned i = 0; i != NumElems; i += Scale) {
8595     int StartIdx = -1;
8596     for (unsigned j = 0; j != Scale; ++j) {
8597       int EltIdx = SVOp->getMaskElt(i+j);
8598       if (EltIdx < 0)
8599         continue;
8600       if (StartIdx < 0)
8601         StartIdx = (EltIdx / Scale);
8602       if (EltIdx != (int)(StartIdx*Scale + j))
8603         return SDValue();
8604     }
8605     MaskVec.push_back(StartIdx);
8606   }
8607
8608   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8609   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8610   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8611 }
8612
8613 /// getVZextMovL - Return a zero-extending vector move low node.
8614 ///
8615 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8616                             SDValue SrcOp, SelectionDAG &DAG,
8617                             const X86Subtarget *Subtarget, SDLoc dl) {
8618   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8619     LoadSDNode *LD = nullptr;
8620     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8621       LD = dyn_cast<LoadSDNode>(SrcOp);
8622     if (!LD) {
8623       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8624       // instead.
8625       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8626       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8627           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8628           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8629           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8630         // PR2108
8631         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8632         return DAG.getNode(ISD::BITCAST, dl, VT,
8633                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8634                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8635                                                    OpVT,
8636                                                    SrcOp.getOperand(0)
8637                                                           .getOperand(0))));
8638       }
8639     }
8640   }
8641
8642   return DAG.getNode(ISD::BITCAST, dl, VT,
8643                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8644                                  DAG.getNode(ISD::BITCAST, dl,
8645                                              OpVT, SrcOp)));
8646 }
8647
8648 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8649 /// which could not be matched by any known target speficic shuffle
8650 static SDValue
8651 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8652
8653   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8654   if (NewOp.getNode())
8655     return NewOp;
8656
8657   MVT VT = SVOp->getSimpleValueType(0);
8658
8659   unsigned NumElems = VT.getVectorNumElements();
8660   unsigned NumLaneElems = NumElems / 2;
8661
8662   SDLoc dl(SVOp);
8663   MVT EltVT = VT.getVectorElementType();
8664   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8665   SDValue Output[2];
8666
8667   SmallVector<int, 16> Mask;
8668   for (unsigned l = 0; l < 2; ++l) {
8669     // Build a shuffle mask for the output, discovering on the fly which
8670     // input vectors to use as shuffle operands (recorded in InputUsed).
8671     // If building a suitable shuffle vector proves too hard, then bail
8672     // out with UseBuildVector set.
8673     bool UseBuildVector = false;
8674     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8675     unsigned LaneStart = l * NumLaneElems;
8676     for (unsigned i = 0; i != NumLaneElems; ++i) {
8677       // The mask element.  This indexes into the input.
8678       int Idx = SVOp->getMaskElt(i+LaneStart);
8679       if (Idx < 0) {
8680         // the mask element does not index into any input vector.
8681         Mask.push_back(-1);
8682         continue;
8683       }
8684
8685       // The input vector this mask element indexes into.
8686       int Input = Idx / NumLaneElems;
8687
8688       // Turn the index into an offset from the start of the input vector.
8689       Idx -= Input * NumLaneElems;
8690
8691       // Find or create a shuffle vector operand to hold this input.
8692       unsigned OpNo;
8693       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8694         if (InputUsed[OpNo] == Input)
8695           // This input vector is already an operand.
8696           break;
8697         if (InputUsed[OpNo] < 0) {
8698           // Create a new operand for this input vector.
8699           InputUsed[OpNo] = Input;
8700           break;
8701         }
8702       }
8703
8704       if (OpNo >= array_lengthof(InputUsed)) {
8705         // More than two input vectors used!  Give up on trying to create a
8706         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8707         UseBuildVector = true;
8708         break;
8709       }
8710
8711       // Add the mask index for the new shuffle vector.
8712       Mask.push_back(Idx + OpNo * NumLaneElems);
8713     }
8714
8715     if (UseBuildVector) {
8716       SmallVector<SDValue, 16> SVOps;
8717       for (unsigned i = 0; i != NumLaneElems; ++i) {
8718         // The mask element.  This indexes into the input.
8719         int Idx = SVOp->getMaskElt(i+LaneStart);
8720         if (Idx < 0) {
8721           SVOps.push_back(DAG.getUNDEF(EltVT));
8722           continue;
8723         }
8724
8725         // The input vector this mask element indexes into.
8726         int Input = Idx / NumElems;
8727
8728         // Turn the index into an offset from the start of the input vector.
8729         Idx -= Input * NumElems;
8730
8731         // Extract the vector element by hand.
8732         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8733                                     SVOp->getOperand(Input),
8734                                     DAG.getIntPtrConstant(Idx)));
8735       }
8736
8737       // Construct the output using a BUILD_VECTOR.
8738       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8739     } else if (InputUsed[0] < 0) {
8740       // No input vectors were used! The result is undefined.
8741       Output[l] = DAG.getUNDEF(NVT);
8742     } else {
8743       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8744                                         (InputUsed[0] % 2) * NumLaneElems,
8745                                         DAG, dl);
8746       // If only one input was used, use an undefined vector for the other.
8747       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8748         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8749                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8750       // At least one input vector was used. Create a new shuffle vector.
8751       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8752     }
8753
8754     Mask.clear();
8755   }
8756
8757   // Concatenate the result back
8758   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8759 }
8760
8761 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8762 /// 4 elements, and match them with several different shuffle types.
8763 static SDValue
8764 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8765   SDValue V1 = SVOp->getOperand(0);
8766   SDValue V2 = SVOp->getOperand(1);
8767   SDLoc dl(SVOp);
8768   MVT VT = SVOp->getSimpleValueType(0);
8769
8770   assert(VT.is128BitVector() && "Unsupported vector size");
8771
8772   std::pair<int, int> Locs[4];
8773   int Mask1[] = { -1, -1, -1, -1 };
8774   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8775
8776   unsigned NumHi = 0;
8777   unsigned NumLo = 0;
8778   for (unsigned i = 0; i != 4; ++i) {
8779     int Idx = PermMask[i];
8780     if (Idx < 0) {
8781       Locs[i] = std::make_pair(-1, -1);
8782     } else {
8783       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8784       if (Idx < 4) {
8785         Locs[i] = std::make_pair(0, NumLo);
8786         Mask1[NumLo] = Idx;
8787         NumLo++;
8788       } else {
8789         Locs[i] = std::make_pair(1, NumHi);
8790         if (2+NumHi < 4)
8791           Mask1[2+NumHi] = Idx;
8792         NumHi++;
8793       }
8794     }
8795   }
8796
8797   if (NumLo <= 2 && NumHi <= 2) {
8798     // If no more than two elements come from either vector. This can be
8799     // implemented with two shuffles. First shuffle gather the elements.
8800     // The second shuffle, which takes the first shuffle as both of its
8801     // vector operands, put the elements into the right order.
8802     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8803
8804     int Mask2[] = { -1, -1, -1, -1 };
8805
8806     for (unsigned i = 0; i != 4; ++i)
8807       if (Locs[i].first != -1) {
8808         unsigned Idx = (i < 2) ? 0 : 4;
8809         Idx += Locs[i].first * 2 + Locs[i].second;
8810         Mask2[i] = Idx;
8811       }
8812
8813     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8814   }
8815
8816   if (NumLo == 3 || NumHi == 3) {
8817     // Otherwise, we must have three elements from one vector, call it X, and
8818     // one element from the other, call it Y.  First, use a shufps to build an
8819     // intermediate vector with the one element from Y and the element from X
8820     // that will be in the same half in the final destination (the indexes don't
8821     // matter). Then, use a shufps to build the final vector, taking the half
8822     // containing the element from Y from the intermediate, and the other half
8823     // from X.
8824     if (NumHi == 3) {
8825       // Normalize it so the 3 elements come from V1.
8826       CommuteVectorShuffleMask(PermMask, 4);
8827       std::swap(V1, V2);
8828     }
8829
8830     // Find the element from V2.
8831     unsigned HiIndex;
8832     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8833       int Val = PermMask[HiIndex];
8834       if (Val < 0)
8835         continue;
8836       if (Val >= 4)
8837         break;
8838     }
8839
8840     Mask1[0] = PermMask[HiIndex];
8841     Mask1[1] = -1;
8842     Mask1[2] = PermMask[HiIndex^1];
8843     Mask1[3] = -1;
8844     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8845
8846     if (HiIndex >= 2) {
8847       Mask1[0] = PermMask[0];
8848       Mask1[1] = PermMask[1];
8849       Mask1[2] = HiIndex & 1 ? 6 : 4;
8850       Mask1[3] = HiIndex & 1 ? 4 : 6;
8851       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8852     }
8853
8854     Mask1[0] = HiIndex & 1 ? 2 : 0;
8855     Mask1[1] = HiIndex & 1 ? 0 : 2;
8856     Mask1[2] = PermMask[2];
8857     Mask1[3] = PermMask[3];
8858     if (Mask1[2] >= 0)
8859       Mask1[2] += 4;
8860     if (Mask1[3] >= 0)
8861       Mask1[3] += 4;
8862     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8863   }
8864
8865   // Break it into (shuffle shuffle_hi, shuffle_lo).
8866   int LoMask[] = { -1, -1, -1, -1 };
8867   int HiMask[] = { -1, -1, -1, -1 };
8868
8869   int *MaskPtr = LoMask;
8870   unsigned MaskIdx = 0;
8871   unsigned LoIdx = 0;
8872   unsigned HiIdx = 2;
8873   for (unsigned i = 0; i != 4; ++i) {
8874     if (i == 2) {
8875       MaskPtr = HiMask;
8876       MaskIdx = 1;
8877       LoIdx = 0;
8878       HiIdx = 2;
8879     }
8880     int Idx = PermMask[i];
8881     if (Idx < 0) {
8882       Locs[i] = std::make_pair(-1, -1);
8883     } else if (Idx < 4) {
8884       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8885       MaskPtr[LoIdx] = Idx;
8886       LoIdx++;
8887     } else {
8888       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8889       MaskPtr[HiIdx] = Idx;
8890       HiIdx++;
8891     }
8892   }
8893
8894   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8895   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8896   int MaskOps[] = { -1, -1, -1, -1 };
8897   for (unsigned i = 0; i != 4; ++i)
8898     if (Locs[i].first != -1)
8899       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8900   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8901 }
8902
8903 static bool MayFoldVectorLoad(SDValue V) {
8904   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8905     V = V.getOperand(0);
8906
8907   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8908     V = V.getOperand(0);
8909   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8910       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8911     // BUILD_VECTOR (load), undef
8912     V = V.getOperand(0);
8913
8914   return MayFoldLoad(V);
8915 }
8916
8917 static
8918 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8919   MVT VT = Op.getSimpleValueType();
8920
8921   // Canonizalize to v2f64.
8922   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8923   return DAG.getNode(ISD::BITCAST, dl, VT,
8924                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8925                                           V1, DAG));
8926 }
8927
8928 static
8929 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8930                         bool HasSSE2) {
8931   SDValue V1 = Op.getOperand(0);
8932   SDValue V2 = Op.getOperand(1);
8933   MVT VT = Op.getSimpleValueType();
8934
8935   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8936
8937   if (HasSSE2 && VT == MVT::v2f64)
8938     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8939
8940   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8941   return DAG.getNode(ISD::BITCAST, dl, VT,
8942                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8943                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8944                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8945 }
8946
8947 static
8948 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8949   SDValue V1 = Op.getOperand(0);
8950   SDValue V2 = Op.getOperand(1);
8951   MVT VT = Op.getSimpleValueType();
8952
8953   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8954          "unsupported shuffle type");
8955
8956   if (V2.getOpcode() == ISD::UNDEF)
8957     V2 = V1;
8958
8959   // v4i32 or v4f32
8960   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8961 }
8962
8963 static
8964 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8965   SDValue V1 = Op.getOperand(0);
8966   SDValue V2 = Op.getOperand(1);
8967   MVT VT = Op.getSimpleValueType();
8968   unsigned NumElems = VT.getVectorNumElements();
8969
8970   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8971   // operand of these instructions is only memory, so check if there's a
8972   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8973   // same masks.
8974   bool CanFoldLoad = false;
8975
8976   // Trivial case, when V2 comes from a load.
8977   if (MayFoldVectorLoad(V2))
8978     CanFoldLoad = true;
8979
8980   // When V1 is a load, it can be folded later into a store in isel, example:
8981   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8982   //    turns into:
8983   //  (MOVLPSmr addr:$src1, VR128:$src2)
8984   // So, recognize this potential and also use MOVLPS or MOVLPD
8985   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8986     CanFoldLoad = true;
8987
8988   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8989   if (CanFoldLoad) {
8990     if (HasSSE2 && NumElems == 2)
8991       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8992
8993     if (NumElems == 4)
8994       // If we don't care about the second element, proceed to use movss.
8995       if (SVOp->getMaskElt(1) != -1)
8996         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8997   }
8998
8999   // movl and movlp will both match v2i64, but v2i64 is never matched by
9000   // movl earlier because we make it strict to avoid messing with the movlp load
9001   // folding logic (see the code above getMOVLP call). Match it here then,
9002   // this is horrible, but will stay like this until we move all shuffle
9003   // matching to x86 specific nodes. Note that for the 1st condition all
9004   // types are matched with movsd.
9005   if (HasSSE2) {
9006     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9007     // as to remove this logic from here, as much as possible
9008     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9009       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9010     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9011   }
9012
9013   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9014
9015   // Invert the operand order and use SHUFPS to match it.
9016   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9017                               getShuffleSHUFImmediate(SVOp), DAG);
9018 }
9019
9020 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9021                                          SelectionDAG &DAG) {
9022   SDLoc dl(Load);
9023   MVT VT = Load->getSimpleValueType(0);
9024   MVT EVT = VT.getVectorElementType();
9025   SDValue Addr = Load->getOperand(1);
9026   SDValue NewAddr = DAG.getNode(
9027       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9028       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9029
9030   SDValue NewLoad =
9031       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9032                   DAG.getMachineFunction().getMachineMemOperand(
9033                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9034   return NewLoad;
9035 }
9036
9037 // It is only safe to call this function if isINSERTPSMask is true for
9038 // this shufflevector mask.
9039 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9040                            SelectionDAG &DAG) {
9041   // Generate an insertps instruction when inserting an f32 from memory onto a
9042   // v4f32 or when copying a member from one v4f32 to another.
9043   // We also use it for transferring i32 from one register to another,
9044   // since it simply copies the same bits.
9045   // If we're transferring an i32 from memory to a specific element in a
9046   // register, we output a generic DAG that will match the PINSRD
9047   // instruction.
9048   MVT VT = SVOp->getSimpleValueType(0);
9049   MVT EVT = VT.getVectorElementType();
9050   SDValue V1 = SVOp->getOperand(0);
9051   SDValue V2 = SVOp->getOperand(1);
9052   auto Mask = SVOp->getMask();
9053   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9054          "unsupported vector type for insertps/pinsrd");
9055
9056   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9057   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9058   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9059
9060   SDValue From;
9061   SDValue To;
9062   unsigned DestIndex;
9063   if (FromV1 == 1) {
9064     From = V1;
9065     To = V2;
9066     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9067                 Mask.begin();
9068   } else {
9069     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9070            "More than one element from V1 and from V2, or no elements from one "
9071            "of the vectors. This case should not have returned true from "
9072            "isINSERTPSMask");
9073     From = V2;
9074     To = V1;
9075     DestIndex =
9076         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9077   }
9078
9079   unsigned SrcIndex = Mask[DestIndex] % 4;
9080   if (MayFoldLoad(From)) {
9081     // Trivial case, when From comes from a load and is only used by the
9082     // shuffle. Make it use insertps from the vector that we need from that
9083     // load.
9084     SDValue NewLoad =
9085         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9086     if (!NewLoad.getNode())
9087       return SDValue();
9088
9089     if (EVT == MVT::f32) {
9090       // Create this as a scalar to vector to match the instruction pattern.
9091       SDValue LoadScalarToVector =
9092           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9093       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9094       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9095                          InsertpsMask);
9096     } else { // EVT == MVT::i32
9097       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9098       // instruction, to match the PINSRD instruction, which loads an i32 to a
9099       // certain vector element.
9100       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9101                          DAG.getConstant(DestIndex, MVT::i32));
9102     }
9103   }
9104
9105   // Vector-element-to-vector
9106   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9107   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9108 }
9109
9110 // Reduce a vector shuffle to zext.
9111 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9112                                     SelectionDAG &DAG) {
9113   // PMOVZX is only available from SSE41.
9114   if (!Subtarget->hasSSE41())
9115     return SDValue();
9116
9117   MVT VT = Op.getSimpleValueType();
9118
9119   // Only AVX2 support 256-bit vector integer extending.
9120   if (!Subtarget->hasInt256() && VT.is256BitVector())
9121     return SDValue();
9122
9123   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9124   SDLoc DL(Op);
9125   SDValue V1 = Op.getOperand(0);
9126   SDValue V2 = Op.getOperand(1);
9127   unsigned NumElems = VT.getVectorNumElements();
9128
9129   // Extending is an unary operation and the element type of the source vector
9130   // won't be equal to or larger than i64.
9131   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9132       VT.getVectorElementType() == MVT::i64)
9133     return SDValue();
9134
9135   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9136   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9137   while ((1U << Shift) < NumElems) {
9138     if (SVOp->getMaskElt(1U << Shift) == 1)
9139       break;
9140     Shift += 1;
9141     // The maximal ratio is 8, i.e. from i8 to i64.
9142     if (Shift > 3)
9143       return SDValue();
9144   }
9145
9146   // Check the shuffle mask.
9147   unsigned Mask = (1U << Shift) - 1;
9148   for (unsigned i = 0; i != NumElems; ++i) {
9149     int EltIdx = SVOp->getMaskElt(i);
9150     if ((i & Mask) != 0 && EltIdx != -1)
9151       return SDValue();
9152     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9153       return SDValue();
9154   }
9155
9156   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9157   MVT NeVT = MVT::getIntegerVT(NBits);
9158   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9159
9160   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9161     return SDValue();
9162
9163   // Simplify the operand as it's prepared to be fed into shuffle.
9164   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9165   if (V1.getOpcode() == ISD::BITCAST &&
9166       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9167       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9168       V1.getOperand(0).getOperand(0)
9169         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9170     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9171     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9172     ConstantSDNode *CIdx =
9173       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9174     // If it's foldable, i.e. normal load with single use, we will let code
9175     // selection to fold it. Otherwise, we will short the conversion sequence.
9176     if (CIdx && CIdx->getZExtValue() == 0 &&
9177         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9178       MVT FullVT = V.getSimpleValueType();
9179       MVT V1VT = V1.getSimpleValueType();
9180       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9181         // The "ext_vec_elt" node is wider than the result node.
9182         // In this case we should extract subvector from V.
9183         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9184         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9185         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9186                                         FullVT.getVectorNumElements()/Ratio);
9187         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9188                         DAG.getIntPtrConstant(0));
9189       }
9190       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9191     }
9192   }
9193
9194   return DAG.getNode(ISD::BITCAST, DL, VT,
9195                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9196 }
9197
9198 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9199                                       SelectionDAG &DAG) {
9200   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9201   MVT VT = Op.getSimpleValueType();
9202   SDLoc dl(Op);
9203   SDValue V1 = Op.getOperand(0);
9204   SDValue V2 = Op.getOperand(1);
9205
9206   if (isZeroShuffle(SVOp))
9207     return getZeroVector(VT, Subtarget, DAG, dl);
9208
9209   // Handle splat operations
9210   if (SVOp->isSplat()) {
9211     // Use vbroadcast whenever the splat comes from a foldable load
9212     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9213     if (Broadcast.getNode())
9214       return Broadcast;
9215   }
9216
9217   // Check integer expanding shuffles.
9218   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9219   if (NewOp.getNode())
9220     return NewOp;
9221
9222   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9223   // do it!
9224   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9225       VT == MVT::v32i8) {
9226     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9227     if (NewOp.getNode())
9228       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9229   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9230     // FIXME: Figure out a cleaner way to do this.
9231     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9232       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9233       if (NewOp.getNode()) {
9234         MVT NewVT = NewOp.getSimpleValueType();
9235         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9236                                NewVT, true, false))
9237           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9238                               dl);
9239       }
9240     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9241       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9242       if (NewOp.getNode()) {
9243         MVT NewVT = NewOp.getSimpleValueType();
9244         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9245           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9246                               dl);
9247       }
9248     }
9249   }
9250   return SDValue();
9251 }
9252
9253 SDValue
9254 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9255   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9256   SDValue V1 = Op.getOperand(0);
9257   SDValue V2 = Op.getOperand(1);
9258   MVT VT = Op.getSimpleValueType();
9259   SDLoc dl(Op);
9260   unsigned NumElems = VT.getVectorNumElements();
9261   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9262   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9263   bool V1IsSplat = false;
9264   bool V2IsSplat = false;
9265   bool HasSSE2 = Subtarget->hasSSE2();
9266   bool HasFp256    = Subtarget->hasFp256();
9267   bool HasInt256   = Subtarget->hasInt256();
9268   MachineFunction &MF = DAG.getMachineFunction();
9269   bool OptForSize = MF.getFunction()->getAttributes().
9270     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9271
9272   // Check if we should use the experimental vector shuffle lowering. If so,
9273   // delegate completely to that code path.
9274   if (ExperimentalVectorShuffleLowering)
9275     return lowerVectorShuffle(Op, Subtarget, DAG);
9276
9277   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9278
9279   if (V1IsUndef && V2IsUndef)
9280     return DAG.getUNDEF(VT);
9281
9282   // When we create a shuffle node we put the UNDEF node to second operand,
9283   // but in some cases the first operand may be transformed to UNDEF.
9284   // In this case we should just commute the node.
9285   if (V1IsUndef)
9286     return CommuteVectorShuffle(SVOp, DAG);
9287
9288   // Vector shuffle lowering takes 3 steps:
9289   //
9290   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9291   //    narrowing and commutation of operands should be handled.
9292   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9293   //    shuffle nodes.
9294   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9295   //    so the shuffle can be broken into other shuffles and the legalizer can
9296   //    try the lowering again.
9297   //
9298   // The general idea is that no vector_shuffle operation should be left to
9299   // be matched during isel, all of them must be converted to a target specific
9300   // node here.
9301
9302   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9303   // narrowing and commutation of operands should be handled. The actual code
9304   // doesn't include all of those, work in progress...
9305   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9306   if (NewOp.getNode())
9307     return NewOp;
9308
9309   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9310
9311   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9312   // unpckh_undef). Only use pshufd if speed is more important than size.
9313   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9314     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9315   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9316     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9317
9318   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9319       V2IsUndef && MayFoldVectorLoad(V1))
9320     return getMOVDDup(Op, dl, V1, DAG);
9321
9322   if (isMOVHLPS_v_undef_Mask(M, VT))
9323     return getMOVHighToLow(Op, dl, DAG);
9324
9325   // Use to match splats
9326   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9327       (VT == MVT::v2f64 || VT == MVT::v2i64))
9328     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9329
9330   if (isPSHUFDMask(M, VT)) {
9331     // The actual implementation will match the mask in the if above and then
9332     // during isel it can match several different instructions, not only pshufd
9333     // as its name says, sad but true, emulate the behavior for now...
9334     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9335       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9336
9337     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9338
9339     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9340       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9341
9342     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9343       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9344                                   DAG);
9345
9346     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9347                                 TargetMask, DAG);
9348   }
9349
9350   if (isPALIGNRMask(M, VT, Subtarget))
9351     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9352                                 getShufflePALIGNRImmediate(SVOp),
9353                                 DAG);
9354
9355   // Check if this can be converted into a logical shift.
9356   bool isLeft = false;
9357   unsigned ShAmt = 0;
9358   SDValue ShVal;
9359   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9360   if (isShift && ShVal.hasOneUse()) {
9361     // If the shifted value has multiple uses, it may be cheaper to use
9362     // v_set0 + movlhps or movhlps, etc.
9363     MVT EltVT = VT.getVectorElementType();
9364     ShAmt *= EltVT.getSizeInBits();
9365     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9366   }
9367
9368   if (isMOVLMask(M, VT)) {
9369     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9370       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9371     if (!isMOVLPMask(M, VT)) {
9372       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9373         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9374
9375       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9376         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9377     }
9378   }
9379
9380   // FIXME: fold these into legal mask.
9381   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9382     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9383
9384   if (isMOVHLPSMask(M, VT))
9385     return getMOVHighToLow(Op, dl, DAG);
9386
9387   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9388     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9389
9390   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9391     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9392
9393   if (isMOVLPMask(M, VT))
9394     return getMOVLP(Op, dl, DAG, HasSSE2);
9395
9396   if (ShouldXformToMOVHLPS(M, VT) ||
9397       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9398     return CommuteVectorShuffle(SVOp, DAG);
9399
9400   if (isShift) {
9401     // No better options. Use a vshldq / vsrldq.
9402     MVT EltVT = VT.getVectorElementType();
9403     ShAmt *= EltVT.getSizeInBits();
9404     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9405   }
9406
9407   bool Commuted = false;
9408   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9409   // 1,1,1,1 -> v8i16 though.
9410   BitVector UndefElements;
9411   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9412     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9413       V1IsSplat = true;
9414   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9415     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9416       V2IsSplat = true;
9417
9418   // Canonicalize the splat or undef, if present, to be on the RHS.
9419   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9420     CommuteVectorShuffleMask(M, NumElems);
9421     std::swap(V1, V2);
9422     std::swap(V1IsSplat, V2IsSplat);
9423     Commuted = true;
9424   }
9425
9426   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9427     // Shuffling low element of v1 into undef, just return v1.
9428     if (V2IsUndef)
9429       return V1;
9430     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9431     // the instruction selector will not match, so get a canonical MOVL with
9432     // swapped operands to undo the commute.
9433     return getMOVL(DAG, dl, VT, V2, V1);
9434   }
9435
9436   if (isUNPCKLMask(M, VT, HasInt256))
9437     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9438
9439   if (isUNPCKHMask(M, VT, HasInt256))
9440     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9441
9442   if (V2IsSplat) {
9443     // Normalize mask so all entries that point to V2 points to its first
9444     // element then try to match unpck{h|l} again. If match, return a
9445     // new vector_shuffle with the corrected mask.p
9446     SmallVector<int, 8> NewMask(M.begin(), M.end());
9447     NormalizeMask(NewMask, NumElems);
9448     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9449       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9450     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9451       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9452   }
9453
9454   if (Commuted) {
9455     // Commute is back and try unpck* again.
9456     // FIXME: this seems wrong.
9457     CommuteVectorShuffleMask(M, NumElems);
9458     std::swap(V1, V2);
9459     std::swap(V1IsSplat, V2IsSplat);
9460
9461     if (isUNPCKLMask(M, VT, HasInt256))
9462       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9463
9464     if (isUNPCKHMask(M, VT, HasInt256))
9465       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9466   }
9467
9468   // Normalize the node to match x86 shuffle ops if needed
9469   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9470     return CommuteVectorShuffle(SVOp, DAG);
9471
9472   // The checks below are all present in isShuffleMaskLegal, but they are
9473   // inlined here right now to enable us to directly emit target specific
9474   // nodes, and remove one by one until they don't return Op anymore.
9475
9476   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9477       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9478     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9479       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9480   }
9481
9482   if (isPSHUFHWMask(M, VT, HasInt256))
9483     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9484                                 getShufflePSHUFHWImmediate(SVOp),
9485                                 DAG);
9486
9487   if (isPSHUFLWMask(M, VT, HasInt256))
9488     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9489                                 getShufflePSHUFLWImmediate(SVOp),
9490                                 DAG);
9491
9492   unsigned MaskValue;
9493   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9494                   &MaskValue))
9495     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9496
9497   if (isSHUFPMask(M, VT))
9498     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9499                                 getShuffleSHUFImmediate(SVOp), DAG);
9500
9501   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9502     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9503   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9504     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9505
9506   //===--------------------------------------------------------------------===//
9507   // Generate target specific nodes for 128 or 256-bit shuffles only
9508   // supported in the AVX instruction set.
9509   //
9510
9511   // Handle VMOVDDUPY permutations
9512   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9513     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9514
9515   // Handle VPERMILPS/D* permutations
9516   if (isVPERMILPMask(M, VT)) {
9517     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9518       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9519                                   getShuffleSHUFImmediate(SVOp), DAG);
9520     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9521                                 getShuffleSHUFImmediate(SVOp), DAG);
9522   }
9523
9524   unsigned Idx;
9525   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9526     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9527                               Idx*(NumElems/2), DAG, dl);
9528
9529   // Handle VPERM2F128/VPERM2I128 permutations
9530   if (isVPERM2X128Mask(M, VT, HasFp256))
9531     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9532                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9533
9534   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9535     return getINSERTPS(SVOp, dl, DAG);
9536
9537   unsigned Imm8;
9538   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9539     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9540
9541   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9542       VT.is512BitVector()) {
9543     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9544     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9545     SmallVector<SDValue, 16> permclMask;
9546     for (unsigned i = 0; i != NumElems; ++i) {
9547       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9548     }
9549
9550     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9551     if (V2IsUndef)
9552       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9553       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9554                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9555     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9556                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9557   }
9558
9559   //===--------------------------------------------------------------------===//
9560   // Since no target specific shuffle was selected for this generic one,
9561   // lower it into other known shuffles. FIXME: this isn't true yet, but
9562   // this is the plan.
9563   //
9564
9565   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9566   if (VT == MVT::v8i16) {
9567     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9568     if (NewOp.getNode())
9569       return NewOp;
9570   }
9571
9572   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9573     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9574     if (NewOp.getNode())
9575       return NewOp;
9576   }
9577
9578   if (VT == MVT::v16i8) {
9579     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9580     if (NewOp.getNode())
9581       return NewOp;
9582   }
9583
9584   if (VT == MVT::v32i8) {
9585     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9586     if (NewOp.getNode())
9587       return NewOp;
9588   }
9589
9590   // Handle all 128-bit wide vectors with 4 elements, and match them with
9591   // several different shuffle types.
9592   if (NumElems == 4 && VT.is128BitVector())
9593     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9594
9595   // Handle general 256-bit shuffles
9596   if (VT.is256BitVector())
9597     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9598
9599   return SDValue();
9600 }
9601
9602 // This function assumes its argument is a BUILD_VECTOR of constants or
9603 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9604 // true.
9605 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9606                                     unsigned &MaskValue) {
9607   MaskValue = 0;
9608   unsigned NumElems = BuildVector->getNumOperands();
9609   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9610   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9611   unsigned NumElemsInLane = NumElems / NumLanes;
9612
9613   // Blend for v16i16 should be symetric for the both lanes.
9614   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9615     SDValue EltCond = BuildVector->getOperand(i);
9616     SDValue SndLaneEltCond =
9617         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9618
9619     int Lane1Cond = -1, Lane2Cond = -1;
9620     if (isa<ConstantSDNode>(EltCond))
9621       Lane1Cond = !isZero(EltCond);
9622     if (isa<ConstantSDNode>(SndLaneEltCond))
9623       Lane2Cond = !isZero(SndLaneEltCond);
9624
9625     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9626       // Lane1Cond != 0, means we want the first argument.
9627       // Lane1Cond == 0, means we want the second argument.
9628       // The encoding of this argument is 0 for the first argument, 1
9629       // for the second. Therefore, invert the condition.
9630       MaskValue |= !Lane1Cond << i;
9631     else if (Lane1Cond < 0)
9632       MaskValue |= !Lane2Cond << i;
9633     else
9634       return false;
9635   }
9636   return true;
9637 }
9638
9639 // Try to lower a vselect node into a simple blend instruction.
9640 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9641                                    SelectionDAG &DAG) {
9642   SDValue Cond = Op.getOperand(0);
9643   SDValue LHS = Op.getOperand(1);
9644   SDValue RHS = Op.getOperand(2);
9645   SDLoc dl(Op);
9646   MVT VT = Op.getSimpleValueType();
9647   MVT EltVT = VT.getVectorElementType();
9648   unsigned NumElems = VT.getVectorNumElements();
9649
9650   // There is no blend with immediate in AVX-512.
9651   if (VT.is512BitVector())
9652     return SDValue();
9653
9654   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9655     return SDValue();
9656   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9657     return SDValue();
9658
9659   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9660     return SDValue();
9661
9662   // Check the mask for BLEND and build the value.
9663   unsigned MaskValue = 0;
9664   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9665     return SDValue();
9666
9667   // Convert i32 vectors to floating point if it is not AVX2.
9668   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9669   MVT BlendVT = VT;
9670   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9671     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9672                                NumElems);
9673     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9674     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9675   }
9676
9677   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9678                             DAG.getConstant(MaskValue, MVT::i32));
9679   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9680 }
9681
9682 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9683   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9684   if (BlendOp.getNode())
9685     return BlendOp;
9686
9687   // Some types for vselect were previously set to Expand, not Legal or
9688   // Custom. Return an empty SDValue so we fall-through to Expand, after
9689   // the Custom lowering phase.
9690   MVT VT = Op.getSimpleValueType();
9691   switch (VT.SimpleTy) {
9692   default:
9693     break;
9694   case MVT::v8i16:
9695   case MVT::v16i16:
9696     return SDValue();
9697   }
9698
9699   // We couldn't create a "Blend with immediate" node.
9700   // This node should still be legal, but we'll have to emit a blendv*
9701   // instruction.
9702   return Op;
9703 }
9704
9705 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9706   MVT VT = Op.getSimpleValueType();
9707   SDLoc dl(Op);
9708
9709   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9710     return SDValue();
9711
9712   if (VT.getSizeInBits() == 8) {
9713     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9714                                   Op.getOperand(0), Op.getOperand(1));
9715     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9716                                   DAG.getValueType(VT));
9717     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9718   }
9719
9720   if (VT.getSizeInBits() == 16) {
9721     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9722     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9723     if (Idx == 0)
9724       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9725                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9726                                      DAG.getNode(ISD::BITCAST, dl,
9727                                                  MVT::v4i32,
9728                                                  Op.getOperand(0)),
9729                                      Op.getOperand(1)));
9730     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9731                                   Op.getOperand(0), Op.getOperand(1));
9732     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9733                                   DAG.getValueType(VT));
9734     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9735   }
9736
9737   if (VT == MVT::f32) {
9738     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9739     // the result back to FR32 register. It's only worth matching if the
9740     // result has a single use which is a store or a bitcast to i32.  And in
9741     // the case of a store, it's not worth it if the index is a constant 0,
9742     // because a MOVSSmr can be used instead, which is smaller and faster.
9743     if (!Op.hasOneUse())
9744       return SDValue();
9745     SDNode *User = *Op.getNode()->use_begin();
9746     if ((User->getOpcode() != ISD::STORE ||
9747          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9748           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9749         (User->getOpcode() != ISD::BITCAST ||
9750          User->getValueType(0) != MVT::i32))
9751       return SDValue();
9752     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9753                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9754                                               Op.getOperand(0)),
9755                                               Op.getOperand(1));
9756     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9757   }
9758
9759   if (VT == MVT::i32 || VT == MVT::i64) {
9760     // ExtractPS/pextrq works with constant index.
9761     if (isa<ConstantSDNode>(Op.getOperand(1)))
9762       return Op;
9763   }
9764   return SDValue();
9765 }
9766
9767 /// Extract one bit from mask vector, like v16i1 or v8i1.
9768 /// AVX-512 feature.
9769 SDValue
9770 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9771   SDValue Vec = Op.getOperand(0);
9772   SDLoc dl(Vec);
9773   MVT VecVT = Vec.getSimpleValueType();
9774   SDValue Idx = Op.getOperand(1);
9775   MVT EltVT = Op.getSimpleValueType();
9776
9777   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9778
9779   // variable index can't be handled in mask registers,
9780   // extend vector to VR512
9781   if (!isa<ConstantSDNode>(Idx)) {
9782     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9783     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9784     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9785                               ExtVT.getVectorElementType(), Ext, Idx);
9786     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9787   }
9788
9789   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9790   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9791   unsigned MaxSift = rc->getSize()*8 - 1;
9792   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9793                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9794   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9795                     DAG.getConstant(MaxSift, MVT::i8));
9796   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9797                        DAG.getIntPtrConstant(0));
9798 }
9799
9800 SDValue
9801 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9802                                            SelectionDAG &DAG) const {
9803   SDLoc dl(Op);
9804   SDValue Vec = Op.getOperand(0);
9805   MVT VecVT = Vec.getSimpleValueType();
9806   SDValue Idx = Op.getOperand(1);
9807
9808   if (Op.getSimpleValueType() == MVT::i1)
9809     return ExtractBitFromMaskVector(Op, DAG);
9810
9811   if (!isa<ConstantSDNode>(Idx)) {
9812     if (VecVT.is512BitVector() ||
9813         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9814          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9815
9816       MVT MaskEltVT =
9817         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9818       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9819                                     MaskEltVT.getSizeInBits());
9820
9821       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9822       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9823                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9824                                 Idx, DAG.getConstant(0, getPointerTy()));
9825       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9826       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9827                         Perm, DAG.getConstant(0, getPointerTy()));
9828     }
9829     return SDValue();
9830   }
9831
9832   // If this is a 256-bit vector result, first extract the 128-bit vector and
9833   // then extract the element from the 128-bit vector.
9834   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9835
9836     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9837     // Get the 128-bit vector.
9838     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9839     MVT EltVT = VecVT.getVectorElementType();
9840
9841     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9842
9843     //if (IdxVal >= NumElems/2)
9844     //  IdxVal -= NumElems/2;
9845     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9846     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9847                        DAG.getConstant(IdxVal, MVT::i32));
9848   }
9849
9850   assert(VecVT.is128BitVector() && "Unexpected vector length");
9851
9852   if (Subtarget->hasSSE41()) {
9853     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9854     if (Res.getNode())
9855       return Res;
9856   }
9857
9858   MVT VT = Op.getSimpleValueType();
9859   // TODO: handle v16i8.
9860   if (VT.getSizeInBits() == 16) {
9861     SDValue Vec = Op.getOperand(0);
9862     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9863     if (Idx == 0)
9864       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9865                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9866                                      DAG.getNode(ISD::BITCAST, dl,
9867                                                  MVT::v4i32, Vec),
9868                                      Op.getOperand(1)));
9869     // Transform it so it match pextrw which produces a 32-bit result.
9870     MVT EltVT = MVT::i32;
9871     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9872                                   Op.getOperand(0), Op.getOperand(1));
9873     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9874                                   DAG.getValueType(VT));
9875     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9876   }
9877
9878   if (VT.getSizeInBits() == 32) {
9879     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9880     if (Idx == 0)
9881       return Op;
9882
9883     // SHUFPS the element to the lowest double word, then movss.
9884     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9885     MVT VVT = Op.getOperand(0).getSimpleValueType();
9886     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9887                                        DAG.getUNDEF(VVT), Mask);
9888     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9889                        DAG.getIntPtrConstant(0));
9890   }
9891
9892   if (VT.getSizeInBits() == 64) {
9893     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9894     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9895     //        to match extract_elt for f64.
9896     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9897     if (Idx == 0)
9898       return Op;
9899
9900     // UNPCKHPD the element to the lowest double word, then movsd.
9901     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9902     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9903     int Mask[2] = { 1, -1 };
9904     MVT VVT = Op.getOperand(0).getSimpleValueType();
9905     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9906                                        DAG.getUNDEF(VVT), Mask);
9907     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9908                        DAG.getIntPtrConstant(0));
9909   }
9910
9911   return SDValue();
9912 }
9913
9914 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9915   MVT VT = Op.getSimpleValueType();
9916   MVT EltVT = VT.getVectorElementType();
9917   SDLoc dl(Op);
9918
9919   SDValue N0 = Op.getOperand(0);
9920   SDValue N1 = Op.getOperand(1);
9921   SDValue N2 = Op.getOperand(2);
9922
9923   if (!VT.is128BitVector())
9924     return SDValue();
9925
9926   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9927       isa<ConstantSDNode>(N2)) {
9928     unsigned Opc;
9929     if (VT == MVT::v8i16)
9930       Opc = X86ISD::PINSRW;
9931     else if (VT == MVT::v16i8)
9932       Opc = X86ISD::PINSRB;
9933     else
9934       Opc = X86ISD::PINSRB;
9935
9936     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9937     // argument.
9938     if (N1.getValueType() != MVT::i32)
9939       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9940     if (N2.getValueType() != MVT::i32)
9941       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9942     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9943   }
9944
9945   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9946     // Bits [7:6] of the constant are the source select.  This will always be
9947     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9948     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9949     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9950     // Bits [5:4] of the constant are the destination select.  This is the
9951     //  value of the incoming immediate.
9952     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9953     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9954     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9955     // Create this as a scalar to vector..
9956     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9957     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9958   }
9959
9960   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9961     // PINSR* works with constant index.
9962     return Op;
9963   }
9964   return SDValue();
9965 }
9966
9967 /// Insert one bit to mask vector, like v16i1 or v8i1.
9968 /// AVX-512 feature.
9969 SDValue 
9970 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9971   SDLoc dl(Op);
9972   SDValue Vec = Op.getOperand(0);
9973   SDValue Elt = Op.getOperand(1);
9974   SDValue Idx = Op.getOperand(2);
9975   MVT VecVT = Vec.getSimpleValueType();
9976
9977   if (!isa<ConstantSDNode>(Idx)) {
9978     // Non constant index. Extend source and destination,
9979     // insert element and then truncate the result.
9980     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9981     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
9982     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
9983       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9984       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9985     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9986   }
9987
9988   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9989   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9990   if (Vec.getOpcode() == ISD::UNDEF)
9991     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9992                        DAG.getConstant(IdxVal, MVT::i8));
9993   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9994   unsigned MaxSift = rc->getSize()*8 - 1;
9995   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9996                     DAG.getConstant(MaxSift, MVT::i8));
9997   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9998                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9999   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10000 }
10001 SDValue
10002 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10003   MVT VT = Op.getSimpleValueType();
10004   MVT EltVT = VT.getVectorElementType();
10005   
10006   if (EltVT == MVT::i1)
10007     return InsertBitToMaskVector(Op, DAG);
10008
10009   SDLoc dl(Op);
10010   SDValue N0 = Op.getOperand(0);
10011   SDValue N1 = Op.getOperand(1);
10012   SDValue N2 = Op.getOperand(2);
10013
10014   // If this is a 256-bit vector result, first extract the 128-bit vector,
10015   // insert the element into the extracted half and then place it back.
10016   if (VT.is256BitVector() || VT.is512BitVector()) {
10017     if (!isa<ConstantSDNode>(N2))
10018       return SDValue();
10019
10020     // Get the desired 128-bit vector half.
10021     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10022     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10023
10024     // Insert the element into the desired half.
10025     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10026     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10027
10028     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10029                     DAG.getConstant(IdxIn128, MVT::i32));
10030
10031     // Insert the changed part back to the 256-bit vector
10032     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10033   }
10034
10035   if (Subtarget->hasSSE41())
10036     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10037
10038   if (EltVT == MVT::i8)
10039     return SDValue();
10040
10041   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10042     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10043     // as its second argument.
10044     if (N1.getValueType() != MVT::i32)
10045       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10046     if (N2.getValueType() != MVT::i32)
10047       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10048     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10049   }
10050   return SDValue();
10051 }
10052
10053 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10054   SDLoc dl(Op);
10055   MVT OpVT = Op.getSimpleValueType();
10056
10057   // If this is a 256-bit vector result, first insert into a 128-bit
10058   // vector and then insert into the 256-bit vector.
10059   if (!OpVT.is128BitVector()) {
10060     // Insert into a 128-bit vector.
10061     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10062     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10063                                  OpVT.getVectorNumElements() / SizeFactor);
10064
10065     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10066
10067     // Insert the 128-bit vector.
10068     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10069   }
10070
10071   if (OpVT == MVT::v1i64 &&
10072       Op.getOperand(0).getValueType() == MVT::i64)
10073     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10074
10075   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10076   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10077   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10078                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10079 }
10080
10081 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10082 // a simple subregister reference or explicit instructions to grab
10083 // upper bits of a vector.
10084 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10085                                       SelectionDAG &DAG) {
10086   SDLoc dl(Op);
10087   SDValue In =  Op.getOperand(0);
10088   SDValue Idx = Op.getOperand(1);
10089   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10090   MVT ResVT   = Op.getSimpleValueType();
10091   MVT InVT    = In.getSimpleValueType();
10092
10093   if (Subtarget->hasFp256()) {
10094     if (ResVT.is128BitVector() &&
10095         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10096         isa<ConstantSDNode>(Idx)) {
10097       return Extract128BitVector(In, IdxVal, DAG, dl);
10098     }
10099     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10100         isa<ConstantSDNode>(Idx)) {
10101       return Extract256BitVector(In, IdxVal, DAG, dl);
10102     }
10103   }
10104   return SDValue();
10105 }
10106
10107 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10108 // simple superregister reference or explicit instructions to insert
10109 // the upper bits of a vector.
10110 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10111                                      SelectionDAG &DAG) {
10112   if (Subtarget->hasFp256()) {
10113     SDLoc dl(Op.getNode());
10114     SDValue Vec = Op.getNode()->getOperand(0);
10115     SDValue SubVec = Op.getNode()->getOperand(1);
10116     SDValue Idx = Op.getNode()->getOperand(2);
10117
10118     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10119          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10120         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10121         isa<ConstantSDNode>(Idx)) {
10122       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10123       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10124     }
10125
10126     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10127         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10128         isa<ConstantSDNode>(Idx)) {
10129       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10130       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10131     }
10132   }
10133   return SDValue();
10134 }
10135
10136 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10137 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10138 // one of the above mentioned nodes. It has to be wrapped because otherwise
10139 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10140 // be used to form addressing mode. These wrapped nodes will be selected
10141 // into MOV32ri.
10142 SDValue
10143 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10144   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10145
10146   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10147   // global base reg.
10148   unsigned char OpFlag = 0;
10149   unsigned WrapperKind = X86ISD::Wrapper;
10150   CodeModel::Model M = DAG.getTarget().getCodeModel();
10151
10152   if (Subtarget->isPICStyleRIPRel() &&
10153       (M == CodeModel::Small || M == CodeModel::Kernel))
10154     WrapperKind = X86ISD::WrapperRIP;
10155   else if (Subtarget->isPICStyleGOT())
10156     OpFlag = X86II::MO_GOTOFF;
10157   else if (Subtarget->isPICStyleStubPIC())
10158     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10159
10160   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10161                                              CP->getAlignment(),
10162                                              CP->getOffset(), OpFlag);
10163   SDLoc DL(CP);
10164   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10165   // With PIC, the address is actually $g + Offset.
10166   if (OpFlag) {
10167     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10168                          DAG.getNode(X86ISD::GlobalBaseReg,
10169                                      SDLoc(), getPointerTy()),
10170                          Result);
10171   }
10172
10173   return Result;
10174 }
10175
10176 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10177   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10178
10179   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10180   // global base reg.
10181   unsigned char OpFlag = 0;
10182   unsigned WrapperKind = X86ISD::Wrapper;
10183   CodeModel::Model M = DAG.getTarget().getCodeModel();
10184
10185   if (Subtarget->isPICStyleRIPRel() &&
10186       (M == CodeModel::Small || M == CodeModel::Kernel))
10187     WrapperKind = X86ISD::WrapperRIP;
10188   else if (Subtarget->isPICStyleGOT())
10189     OpFlag = X86II::MO_GOTOFF;
10190   else if (Subtarget->isPICStyleStubPIC())
10191     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10192
10193   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10194                                           OpFlag);
10195   SDLoc DL(JT);
10196   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10197
10198   // With PIC, the address is actually $g + Offset.
10199   if (OpFlag)
10200     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10201                          DAG.getNode(X86ISD::GlobalBaseReg,
10202                                      SDLoc(), getPointerTy()),
10203                          Result);
10204
10205   return Result;
10206 }
10207
10208 SDValue
10209 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10210   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10211
10212   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10213   // global base reg.
10214   unsigned char OpFlag = 0;
10215   unsigned WrapperKind = X86ISD::Wrapper;
10216   CodeModel::Model M = DAG.getTarget().getCodeModel();
10217
10218   if (Subtarget->isPICStyleRIPRel() &&
10219       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10220     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10221       OpFlag = X86II::MO_GOTPCREL;
10222     WrapperKind = X86ISD::WrapperRIP;
10223   } else if (Subtarget->isPICStyleGOT()) {
10224     OpFlag = X86II::MO_GOT;
10225   } else if (Subtarget->isPICStyleStubPIC()) {
10226     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10227   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10228     OpFlag = X86II::MO_DARWIN_NONLAZY;
10229   }
10230
10231   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10232
10233   SDLoc DL(Op);
10234   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10235
10236   // With PIC, the address is actually $g + Offset.
10237   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10238       !Subtarget->is64Bit()) {
10239     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10240                          DAG.getNode(X86ISD::GlobalBaseReg,
10241                                      SDLoc(), getPointerTy()),
10242                          Result);
10243   }
10244
10245   // For symbols that require a load from a stub to get the address, emit the
10246   // load.
10247   if (isGlobalStubReference(OpFlag))
10248     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10249                          MachinePointerInfo::getGOT(), false, false, false, 0);
10250
10251   return Result;
10252 }
10253
10254 SDValue
10255 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10256   // Create the TargetBlockAddressAddress node.
10257   unsigned char OpFlags =
10258     Subtarget->ClassifyBlockAddressReference();
10259   CodeModel::Model M = DAG.getTarget().getCodeModel();
10260   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10261   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10262   SDLoc dl(Op);
10263   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10264                                              OpFlags);
10265
10266   if (Subtarget->isPICStyleRIPRel() &&
10267       (M == CodeModel::Small || M == CodeModel::Kernel))
10268     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10269   else
10270     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10271
10272   // With PIC, the address is actually $g + Offset.
10273   if (isGlobalRelativeToPICBase(OpFlags)) {
10274     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10275                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10276                          Result);
10277   }
10278
10279   return Result;
10280 }
10281
10282 SDValue
10283 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10284                                       int64_t Offset, SelectionDAG &DAG) const {
10285   // Create the TargetGlobalAddress node, folding in the constant
10286   // offset if it is legal.
10287   unsigned char OpFlags =
10288       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10289   CodeModel::Model M = DAG.getTarget().getCodeModel();
10290   SDValue Result;
10291   if (OpFlags == X86II::MO_NO_FLAG &&
10292       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10293     // A direct static reference to a global.
10294     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10295     Offset = 0;
10296   } else {
10297     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10298   }
10299
10300   if (Subtarget->isPICStyleRIPRel() &&
10301       (M == CodeModel::Small || M == CodeModel::Kernel))
10302     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10303   else
10304     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10305
10306   // With PIC, the address is actually $g + Offset.
10307   if (isGlobalRelativeToPICBase(OpFlags)) {
10308     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10309                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10310                          Result);
10311   }
10312
10313   // For globals that require a load from a stub to get the address, emit the
10314   // load.
10315   if (isGlobalStubReference(OpFlags))
10316     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10317                          MachinePointerInfo::getGOT(), false, false, false, 0);
10318
10319   // If there was a non-zero offset that we didn't fold, create an explicit
10320   // addition for it.
10321   if (Offset != 0)
10322     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10323                          DAG.getConstant(Offset, getPointerTy()));
10324
10325   return Result;
10326 }
10327
10328 SDValue
10329 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10330   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10331   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10332   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10333 }
10334
10335 static SDValue
10336 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10337            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10338            unsigned char OperandFlags, bool LocalDynamic = false) {
10339   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10340   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10341   SDLoc dl(GA);
10342   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10343                                            GA->getValueType(0),
10344                                            GA->getOffset(),
10345                                            OperandFlags);
10346
10347   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10348                                            : X86ISD::TLSADDR;
10349
10350   if (InFlag) {
10351     SDValue Ops[] = { Chain,  TGA, *InFlag };
10352     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10353   } else {
10354     SDValue Ops[]  = { Chain, TGA };
10355     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10356   }
10357
10358   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10359   MFI->setAdjustsStack(true);
10360
10361   SDValue Flag = Chain.getValue(1);
10362   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10363 }
10364
10365 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10366 static SDValue
10367 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10368                                 const EVT PtrVT) {
10369   SDValue InFlag;
10370   SDLoc dl(GA);  // ? function entry point might be better
10371   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10372                                    DAG.getNode(X86ISD::GlobalBaseReg,
10373                                                SDLoc(), PtrVT), InFlag);
10374   InFlag = Chain.getValue(1);
10375
10376   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10377 }
10378
10379 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10380 static SDValue
10381 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10382                                 const EVT PtrVT) {
10383   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10384                     X86::RAX, X86II::MO_TLSGD);
10385 }
10386
10387 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10388                                            SelectionDAG &DAG,
10389                                            const EVT PtrVT,
10390                                            bool is64Bit) {
10391   SDLoc dl(GA);
10392
10393   // Get the start address of the TLS block for this module.
10394   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10395       .getInfo<X86MachineFunctionInfo>();
10396   MFI->incNumLocalDynamicTLSAccesses();
10397
10398   SDValue Base;
10399   if (is64Bit) {
10400     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10401                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10402   } else {
10403     SDValue InFlag;
10404     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10405         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10406     InFlag = Chain.getValue(1);
10407     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10408                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10409   }
10410
10411   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10412   // of Base.
10413
10414   // Build x@dtpoff.
10415   unsigned char OperandFlags = X86II::MO_DTPOFF;
10416   unsigned WrapperKind = X86ISD::Wrapper;
10417   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10418                                            GA->getValueType(0),
10419                                            GA->getOffset(), OperandFlags);
10420   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10421
10422   // Add x@dtpoff with the base.
10423   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10424 }
10425
10426 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10427 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10428                                    const EVT PtrVT, TLSModel::Model model,
10429                                    bool is64Bit, bool isPIC) {
10430   SDLoc dl(GA);
10431
10432   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10433   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10434                                                          is64Bit ? 257 : 256));
10435
10436   SDValue ThreadPointer =
10437       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10438                   MachinePointerInfo(Ptr), false, false, false, 0);
10439
10440   unsigned char OperandFlags = 0;
10441   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10442   // initialexec.
10443   unsigned WrapperKind = X86ISD::Wrapper;
10444   if (model == TLSModel::LocalExec) {
10445     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10446   } else if (model == TLSModel::InitialExec) {
10447     if (is64Bit) {
10448       OperandFlags = X86II::MO_GOTTPOFF;
10449       WrapperKind = X86ISD::WrapperRIP;
10450     } else {
10451       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10452     }
10453   } else {
10454     llvm_unreachable("Unexpected model");
10455   }
10456
10457   // emit "addl x@ntpoff,%eax" (local exec)
10458   // or "addl x@indntpoff,%eax" (initial exec)
10459   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10460   SDValue TGA =
10461       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10462                                  GA->getOffset(), OperandFlags);
10463   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10464
10465   if (model == TLSModel::InitialExec) {
10466     if (isPIC && !is64Bit) {
10467       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10468                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10469                            Offset);
10470     }
10471
10472     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10473                          MachinePointerInfo::getGOT(), false, false, false, 0);
10474   }
10475
10476   // The address of the thread local variable is the add of the thread
10477   // pointer with the offset of the variable.
10478   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10479 }
10480
10481 SDValue
10482 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10483
10484   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10485   const GlobalValue *GV = GA->getGlobal();
10486
10487   if (Subtarget->isTargetELF()) {
10488     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10489
10490     switch (model) {
10491       case TLSModel::GeneralDynamic:
10492         if (Subtarget->is64Bit())
10493           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10494         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10495       case TLSModel::LocalDynamic:
10496         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10497                                            Subtarget->is64Bit());
10498       case TLSModel::InitialExec:
10499       case TLSModel::LocalExec:
10500         return LowerToTLSExecModel(
10501             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10502             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10503     }
10504     llvm_unreachable("Unknown TLS model.");
10505   }
10506
10507   if (Subtarget->isTargetDarwin()) {
10508     // Darwin only has one model of TLS.  Lower to that.
10509     unsigned char OpFlag = 0;
10510     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10511                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10512
10513     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10514     // global base reg.
10515     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10516                  !Subtarget->is64Bit();
10517     if (PIC32)
10518       OpFlag = X86II::MO_TLVP_PIC_BASE;
10519     else
10520       OpFlag = X86II::MO_TLVP;
10521     SDLoc DL(Op);
10522     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10523                                                 GA->getValueType(0),
10524                                                 GA->getOffset(), OpFlag);
10525     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10526
10527     // With PIC32, the address is actually $g + Offset.
10528     if (PIC32)
10529       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10530                            DAG.getNode(X86ISD::GlobalBaseReg,
10531                                        SDLoc(), getPointerTy()),
10532                            Offset);
10533
10534     // Lowering the machine isd will make sure everything is in the right
10535     // location.
10536     SDValue Chain = DAG.getEntryNode();
10537     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10538     SDValue Args[] = { Chain, Offset };
10539     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10540
10541     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10542     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10543     MFI->setAdjustsStack(true);
10544
10545     // And our return value (tls address) is in the standard call return value
10546     // location.
10547     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10548     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10549                               Chain.getValue(1));
10550   }
10551
10552   if (Subtarget->isTargetKnownWindowsMSVC() ||
10553       Subtarget->isTargetWindowsGNU()) {
10554     // Just use the implicit TLS architecture
10555     // Need to generate someting similar to:
10556     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10557     //                                  ; from TEB
10558     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10559     //   mov     rcx, qword [rdx+rcx*8]
10560     //   mov     eax, .tls$:tlsvar
10561     //   [rax+rcx] contains the address
10562     // Windows 64bit: gs:0x58
10563     // Windows 32bit: fs:__tls_array
10564
10565     SDLoc dl(GA);
10566     SDValue Chain = DAG.getEntryNode();
10567
10568     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10569     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10570     // use its literal value of 0x2C.
10571     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10572                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10573                                                              256)
10574                                         : Type::getInt32PtrTy(*DAG.getContext(),
10575                                                               257));
10576
10577     SDValue TlsArray =
10578         Subtarget->is64Bit()
10579             ? DAG.getIntPtrConstant(0x58)
10580             : (Subtarget->isTargetWindowsGNU()
10581                    ? DAG.getIntPtrConstant(0x2C)
10582                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10583
10584     SDValue ThreadPointer =
10585         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10586                     MachinePointerInfo(Ptr), false, false, false, 0);
10587
10588     // Load the _tls_index variable
10589     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10590     if (Subtarget->is64Bit())
10591       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10592                            IDX, MachinePointerInfo(), MVT::i32,
10593                            false, false, 0);
10594     else
10595       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10596                         false, false, false, 0);
10597
10598     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10599                                     getPointerTy());
10600     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10601
10602     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10603     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10604                       false, false, false, 0);
10605
10606     // Get the offset of start of .tls section
10607     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10608                                              GA->getValueType(0),
10609                                              GA->getOffset(), X86II::MO_SECREL);
10610     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10611
10612     // The address of the thread local variable is the add of the thread
10613     // pointer with the offset of the variable.
10614     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10615   }
10616
10617   llvm_unreachable("TLS not implemented for this target.");
10618 }
10619
10620 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10621 /// and take a 2 x i32 value to shift plus a shift amount.
10622 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10623   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10624   MVT VT = Op.getSimpleValueType();
10625   unsigned VTBits = VT.getSizeInBits();
10626   SDLoc dl(Op);
10627   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10628   SDValue ShOpLo = Op.getOperand(0);
10629   SDValue ShOpHi = Op.getOperand(1);
10630   SDValue ShAmt  = Op.getOperand(2);
10631   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10632   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10633   // during isel.
10634   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10635                                   DAG.getConstant(VTBits - 1, MVT::i8));
10636   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10637                                      DAG.getConstant(VTBits - 1, MVT::i8))
10638                        : DAG.getConstant(0, VT);
10639
10640   SDValue Tmp2, Tmp3;
10641   if (Op.getOpcode() == ISD::SHL_PARTS) {
10642     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10643     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10644   } else {
10645     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10646     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10647   }
10648
10649   // If the shift amount is larger or equal than the width of a part we can't
10650   // rely on the results of shld/shrd. Insert a test and select the appropriate
10651   // values for large shift amounts.
10652   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10653                                 DAG.getConstant(VTBits, MVT::i8));
10654   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10655                              AndNode, DAG.getConstant(0, MVT::i8));
10656
10657   SDValue Hi, Lo;
10658   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10659   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10660   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10661
10662   if (Op.getOpcode() == ISD::SHL_PARTS) {
10663     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10664     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10665   } else {
10666     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10667     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10668   }
10669
10670   SDValue Ops[2] = { Lo, Hi };
10671   return DAG.getMergeValues(Ops, dl);
10672 }
10673
10674 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10675                                            SelectionDAG &DAG) const {
10676   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10677
10678   if (SrcVT.isVector())
10679     return SDValue();
10680
10681   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10682          "Unknown SINT_TO_FP to lower!");
10683
10684   // These are really Legal; return the operand so the caller accepts it as
10685   // Legal.
10686   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10687     return Op;
10688   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10689       Subtarget->is64Bit()) {
10690     return Op;
10691   }
10692
10693   SDLoc dl(Op);
10694   unsigned Size = SrcVT.getSizeInBits()/8;
10695   MachineFunction &MF = DAG.getMachineFunction();
10696   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10697   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10698   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10699                                StackSlot,
10700                                MachinePointerInfo::getFixedStack(SSFI),
10701                                false, false, 0);
10702   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10703 }
10704
10705 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10706                                      SDValue StackSlot,
10707                                      SelectionDAG &DAG) const {
10708   // Build the FILD
10709   SDLoc DL(Op);
10710   SDVTList Tys;
10711   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10712   if (useSSE)
10713     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10714   else
10715     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10716
10717   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10718
10719   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10720   MachineMemOperand *MMO;
10721   if (FI) {
10722     int SSFI = FI->getIndex();
10723     MMO =
10724       DAG.getMachineFunction()
10725       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10726                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10727   } else {
10728     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10729     StackSlot = StackSlot.getOperand(1);
10730   }
10731   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10732   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10733                                            X86ISD::FILD, DL,
10734                                            Tys, Ops, SrcVT, MMO);
10735
10736   if (useSSE) {
10737     Chain = Result.getValue(1);
10738     SDValue InFlag = Result.getValue(2);
10739
10740     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10741     // shouldn't be necessary except that RFP cannot be live across
10742     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10743     MachineFunction &MF = DAG.getMachineFunction();
10744     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10745     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10746     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10747     Tys = DAG.getVTList(MVT::Other);
10748     SDValue Ops[] = {
10749       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10750     };
10751     MachineMemOperand *MMO =
10752       DAG.getMachineFunction()
10753       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10754                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10755
10756     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10757                                     Ops, Op.getValueType(), MMO);
10758     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10759                          MachinePointerInfo::getFixedStack(SSFI),
10760                          false, false, false, 0);
10761   }
10762
10763   return Result;
10764 }
10765
10766 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10767 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10768                                                SelectionDAG &DAG) const {
10769   // This algorithm is not obvious. Here it is what we're trying to output:
10770   /*
10771      movq       %rax,  %xmm0
10772      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10773      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10774      #ifdef __SSE3__
10775        haddpd   %xmm0, %xmm0
10776      #else
10777        pshufd   $0x4e, %xmm0, %xmm1
10778        addpd    %xmm1, %xmm0
10779      #endif
10780   */
10781
10782   SDLoc dl(Op);
10783   LLVMContext *Context = DAG.getContext();
10784
10785   // Build some magic constants.
10786   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10787   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10788   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10789
10790   SmallVector<Constant*,2> CV1;
10791   CV1.push_back(
10792     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10793                                       APInt(64, 0x4330000000000000ULL))));
10794   CV1.push_back(
10795     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10796                                       APInt(64, 0x4530000000000000ULL))));
10797   Constant *C1 = ConstantVector::get(CV1);
10798   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10799
10800   // Load the 64-bit value into an XMM register.
10801   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10802                             Op.getOperand(0));
10803   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10804                               MachinePointerInfo::getConstantPool(),
10805                               false, false, false, 16);
10806   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10807                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10808                               CLod0);
10809
10810   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10811                               MachinePointerInfo::getConstantPool(),
10812                               false, false, false, 16);
10813   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10814   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10815   SDValue Result;
10816
10817   if (Subtarget->hasSSE3()) {
10818     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10819     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10820   } else {
10821     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10822     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10823                                            S2F, 0x4E, DAG);
10824     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10825                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10826                          Sub);
10827   }
10828
10829   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10830                      DAG.getIntPtrConstant(0));
10831 }
10832
10833 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10834 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10835                                                SelectionDAG &DAG) const {
10836   SDLoc dl(Op);
10837   // FP constant to bias correct the final result.
10838   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10839                                    MVT::f64);
10840
10841   // Load the 32-bit value into an XMM register.
10842   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10843                              Op.getOperand(0));
10844
10845   // Zero out the upper parts of the register.
10846   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10847
10848   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10849                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10850                      DAG.getIntPtrConstant(0));
10851
10852   // Or the load with the bias.
10853   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10854                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10855                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10856                                                    MVT::v2f64, Load)),
10857                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10858                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10859                                                    MVT::v2f64, Bias)));
10860   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10861                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10862                    DAG.getIntPtrConstant(0));
10863
10864   // Subtract the bias.
10865   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10866
10867   // Handle final rounding.
10868   EVT DestVT = Op.getValueType();
10869
10870   if (DestVT.bitsLT(MVT::f64))
10871     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10872                        DAG.getIntPtrConstant(0));
10873   if (DestVT.bitsGT(MVT::f64))
10874     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10875
10876   // Handle final rounding.
10877   return Sub;
10878 }
10879
10880 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10881                                                SelectionDAG &DAG) const {
10882   SDValue N0 = Op.getOperand(0);
10883   MVT SVT = N0.getSimpleValueType();
10884   SDLoc dl(Op);
10885
10886   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10887           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10888          "Custom UINT_TO_FP is not supported!");
10889
10890   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10891   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10892                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10893 }
10894
10895 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10896                                            SelectionDAG &DAG) const {
10897   SDValue N0 = Op.getOperand(0);
10898   SDLoc dl(Op);
10899
10900   if (Op.getValueType().isVector())
10901     return lowerUINT_TO_FP_vec(Op, DAG);
10902
10903   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10904   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10905   // the optimization here.
10906   if (DAG.SignBitIsZero(N0))
10907     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10908
10909   MVT SrcVT = N0.getSimpleValueType();
10910   MVT DstVT = Op.getSimpleValueType();
10911   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10912     return LowerUINT_TO_FP_i64(Op, DAG);
10913   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10914     return LowerUINT_TO_FP_i32(Op, DAG);
10915   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10916     return SDValue();
10917
10918   // Make a 64-bit buffer, and use it to build an FILD.
10919   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10920   if (SrcVT == MVT::i32) {
10921     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10922     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10923                                      getPointerTy(), StackSlot, WordOff);
10924     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10925                                   StackSlot, MachinePointerInfo(),
10926                                   false, false, 0);
10927     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10928                                   OffsetSlot, MachinePointerInfo(),
10929                                   false, false, 0);
10930     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10931     return Fild;
10932   }
10933
10934   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10935   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10936                                StackSlot, MachinePointerInfo(),
10937                                false, false, 0);
10938   // For i64 source, we need to add the appropriate power of 2 if the input
10939   // was negative.  This is the same as the optimization in
10940   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10941   // we must be careful to do the computation in x87 extended precision, not
10942   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10943   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10944   MachineMemOperand *MMO =
10945     DAG.getMachineFunction()
10946     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10947                           MachineMemOperand::MOLoad, 8, 8);
10948
10949   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10950   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10951   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10952                                          MVT::i64, MMO);
10953
10954   APInt FF(32, 0x5F800000ULL);
10955
10956   // Check whether the sign bit is set.
10957   SDValue SignSet = DAG.getSetCC(dl,
10958                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10959                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10960                                  ISD::SETLT);
10961
10962   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10963   SDValue FudgePtr = DAG.getConstantPool(
10964                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10965                                          getPointerTy());
10966
10967   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10968   SDValue Zero = DAG.getIntPtrConstant(0);
10969   SDValue Four = DAG.getIntPtrConstant(4);
10970   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10971                                Zero, Four);
10972   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10973
10974   // Load the value out, extending it from f32 to f80.
10975   // FIXME: Avoid the extend by constructing the right constant pool?
10976   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10977                                  FudgePtr, MachinePointerInfo::getConstantPool(),
10978                                  MVT::f32, false, false, 4);
10979   // Extend everything to 80 bits to force it to be done on x87.
10980   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10981   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10982 }
10983
10984 std::pair<SDValue,SDValue>
10985 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10986                                     bool IsSigned, bool IsReplace) const {
10987   SDLoc DL(Op);
10988
10989   EVT DstTy = Op.getValueType();
10990
10991   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10992     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10993     DstTy = MVT::i64;
10994   }
10995
10996   assert(DstTy.getSimpleVT() <= MVT::i64 &&
10997          DstTy.getSimpleVT() >= MVT::i16 &&
10998          "Unknown FP_TO_INT to lower!");
10999
11000   // These are really Legal.
11001   if (DstTy == MVT::i32 &&
11002       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11003     return std::make_pair(SDValue(), SDValue());
11004   if (Subtarget->is64Bit() &&
11005       DstTy == MVT::i64 &&
11006       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11007     return std::make_pair(SDValue(), SDValue());
11008
11009   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11010   // stack slot, or into the FTOL runtime function.
11011   MachineFunction &MF = DAG.getMachineFunction();
11012   unsigned MemSize = DstTy.getSizeInBits()/8;
11013   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11014   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11015
11016   unsigned Opc;
11017   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11018     Opc = X86ISD::WIN_FTOL;
11019   else
11020     switch (DstTy.getSimpleVT().SimpleTy) {
11021     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11022     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11023     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11024     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11025     }
11026
11027   SDValue Chain = DAG.getEntryNode();
11028   SDValue Value = Op.getOperand(0);
11029   EVT TheVT = Op.getOperand(0).getValueType();
11030   // FIXME This causes a redundant load/store if the SSE-class value is already
11031   // in memory, such as if it is on the callstack.
11032   if (isScalarFPTypeInSSEReg(TheVT)) {
11033     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11034     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11035                          MachinePointerInfo::getFixedStack(SSFI),
11036                          false, false, 0);
11037     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11038     SDValue Ops[] = {
11039       Chain, StackSlot, DAG.getValueType(TheVT)
11040     };
11041
11042     MachineMemOperand *MMO =
11043       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11044                               MachineMemOperand::MOLoad, MemSize, MemSize);
11045     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11046     Chain = Value.getValue(1);
11047     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11048     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11049   }
11050
11051   MachineMemOperand *MMO =
11052     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11053                             MachineMemOperand::MOStore, MemSize, MemSize);
11054
11055   if (Opc != X86ISD::WIN_FTOL) {
11056     // Build the FP_TO_INT*_IN_MEM
11057     SDValue Ops[] = { Chain, Value, StackSlot };
11058     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11059                                            Ops, DstTy, MMO);
11060     return std::make_pair(FIST, StackSlot);
11061   } else {
11062     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11063       DAG.getVTList(MVT::Other, MVT::Glue),
11064       Chain, Value);
11065     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11066       MVT::i32, ftol.getValue(1));
11067     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11068       MVT::i32, eax.getValue(2));
11069     SDValue Ops[] = { eax, edx };
11070     SDValue pair = IsReplace
11071       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11072       : DAG.getMergeValues(Ops, DL);
11073     return std::make_pair(pair, SDValue());
11074   }
11075 }
11076
11077 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11078                               const X86Subtarget *Subtarget) {
11079   MVT VT = Op->getSimpleValueType(0);
11080   SDValue In = Op->getOperand(0);
11081   MVT InVT = In.getSimpleValueType();
11082   SDLoc dl(Op);
11083
11084   // Optimize vectors in AVX mode:
11085   //
11086   //   v8i16 -> v8i32
11087   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11088   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11089   //   Concat upper and lower parts.
11090   //
11091   //   v4i32 -> v4i64
11092   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11093   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11094   //   Concat upper and lower parts.
11095   //
11096
11097   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11098       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11099       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11100     return SDValue();
11101
11102   if (Subtarget->hasInt256())
11103     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11104
11105   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11106   SDValue Undef = DAG.getUNDEF(InVT);
11107   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11108   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11109   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11110
11111   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11112                              VT.getVectorNumElements()/2);
11113
11114   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11115   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11116
11117   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11118 }
11119
11120 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11121                                         SelectionDAG &DAG) {
11122   MVT VT = Op->getSimpleValueType(0);
11123   SDValue In = Op->getOperand(0);
11124   MVT InVT = In.getSimpleValueType();
11125   SDLoc DL(Op);
11126   unsigned int NumElts = VT.getVectorNumElements();
11127   if (NumElts != 8 && NumElts != 16)
11128     return SDValue();
11129
11130   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11131     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11132
11133   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11134   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11135   // Now we have only mask extension
11136   assert(InVT.getVectorElementType() == MVT::i1);
11137   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11138   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11139   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11140   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11141   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11142                            MachinePointerInfo::getConstantPool(),
11143                            false, false, false, Alignment);
11144
11145   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11146   if (VT.is512BitVector())
11147     return Brcst;
11148   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11149 }
11150
11151 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11152                                SelectionDAG &DAG) {
11153   if (Subtarget->hasFp256()) {
11154     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11155     if (Res.getNode())
11156       return Res;
11157   }
11158
11159   return SDValue();
11160 }
11161
11162 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11163                                 SelectionDAG &DAG) {
11164   SDLoc DL(Op);
11165   MVT VT = Op.getSimpleValueType();
11166   SDValue In = Op.getOperand(0);
11167   MVT SVT = In.getSimpleValueType();
11168
11169   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11170     return LowerZERO_EXTEND_AVX512(Op, DAG);
11171
11172   if (Subtarget->hasFp256()) {
11173     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11174     if (Res.getNode())
11175       return Res;
11176   }
11177
11178   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11179          VT.getVectorNumElements() != SVT.getVectorNumElements());
11180   return SDValue();
11181 }
11182
11183 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11184   SDLoc DL(Op);
11185   MVT VT = Op.getSimpleValueType();
11186   SDValue In = Op.getOperand(0);
11187   MVT InVT = In.getSimpleValueType();
11188
11189   if (VT == MVT::i1) {
11190     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11191            "Invalid scalar TRUNCATE operation");
11192     if (InVT == MVT::i32)
11193       return SDValue();
11194     if (InVT.getSizeInBits() == 64)
11195       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11196     else if (InVT.getSizeInBits() < 32)
11197       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11198     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11199   }
11200   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11201          "Invalid TRUNCATE operation");
11202
11203   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11204     if (VT.getVectorElementType().getSizeInBits() >=8)
11205       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11206
11207     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11208     unsigned NumElts = InVT.getVectorNumElements();
11209     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11210     if (InVT.getSizeInBits() < 512) {
11211       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11212       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11213       InVT = ExtVT;
11214     }
11215     
11216     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11217     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11218     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11219     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11220     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11221                            MachinePointerInfo::getConstantPool(),
11222                            false, false, false, Alignment);
11223     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11224     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11225     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11226   }
11227
11228   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11229     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11230     if (Subtarget->hasInt256()) {
11231       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11232       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11233       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11234                                 ShufMask);
11235       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11236                          DAG.getIntPtrConstant(0));
11237     }
11238
11239     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11240                                DAG.getIntPtrConstant(0));
11241     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11242                                DAG.getIntPtrConstant(2));
11243     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11244     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11245     static const int ShufMask[] = {0, 2, 4, 6};
11246     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11247   }
11248
11249   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11250     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11251     if (Subtarget->hasInt256()) {
11252       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11253
11254       SmallVector<SDValue,32> pshufbMask;
11255       for (unsigned i = 0; i < 2; ++i) {
11256         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11257         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11258         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11259         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11260         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11261         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11262         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11263         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11264         for (unsigned j = 0; j < 8; ++j)
11265           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11266       }
11267       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11268       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11269       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11270
11271       static const int ShufMask[] = {0,  2,  -1,  -1};
11272       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11273                                 &ShufMask[0]);
11274       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11275                        DAG.getIntPtrConstant(0));
11276       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11277     }
11278
11279     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11280                                DAG.getIntPtrConstant(0));
11281
11282     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11283                                DAG.getIntPtrConstant(4));
11284
11285     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11286     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11287
11288     // The PSHUFB mask:
11289     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11290                                    -1, -1, -1, -1, -1, -1, -1, -1};
11291
11292     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11293     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11294     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11295
11296     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11297     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11298
11299     // The MOVLHPS Mask:
11300     static const int ShufMask2[] = {0, 1, 4, 5};
11301     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11302     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11303   }
11304
11305   // Handle truncation of V256 to V128 using shuffles.
11306   if (!VT.is128BitVector() || !InVT.is256BitVector())
11307     return SDValue();
11308
11309   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11310
11311   unsigned NumElems = VT.getVectorNumElements();
11312   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11313
11314   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11315   // Prepare truncation shuffle mask
11316   for (unsigned i = 0; i != NumElems; ++i)
11317     MaskVec[i] = i * 2;
11318   SDValue V = DAG.getVectorShuffle(NVT, DL,
11319                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11320                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11321   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11322                      DAG.getIntPtrConstant(0));
11323 }
11324
11325 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11326                                            SelectionDAG &DAG) const {
11327   assert(!Op.getSimpleValueType().isVector());
11328
11329   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11330     /*IsSigned=*/ true, /*IsReplace=*/ false);
11331   SDValue FIST = Vals.first, StackSlot = Vals.second;
11332   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11333   if (!FIST.getNode()) return Op;
11334
11335   if (StackSlot.getNode())
11336     // Load the result.
11337     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11338                        FIST, StackSlot, MachinePointerInfo(),
11339                        false, false, false, 0);
11340
11341   // The node is the result.
11342   return FIST;
11343 }
11344
11345 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11346                                            SelectionDAG &DAG) const {
11347   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11348     /*IsSigned=*/ false, /*IsReplace=*/ false);
11349   SDValue FIST = Vals.first, StackSlot = Vals.second;
11350   assert(FIST.getNode() && "Unexpected failure");
11351
11352   if (StackSlot.getNode())
11353     // Load the result.
11354     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11355                        FIST, StackSlot, MachinePointerInfo(),
11356                        false, false, false, 0);
11357
11358   // The node is the result.
11359   return FIST;
11360 }
11361
11362 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11363   SDLoc DL(Op);
11364   MVT VT = Op.getSimpleValueType();
11365   SDValue In = Op.getOperand(0);
11366   MVT SVT = In.getSimpleValueType();
11367
11368   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11369
11370   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11371                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11372                                  In, DAG.getUNDEF(SVT)));
11373 }
11374
11375 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11376   LLVMContext *Context = DAG.getContext();
11377   SDLoc dl(Op);
11378   MVT VT = Op.getSimpleValueType();
11379   MVT EltVT = VT;
11380   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11381   if (VT.isVector()) {
11382     EltVT = VT.getVectorElementType();
11383     NumElts = VT.getVectorNumElements();
11384   }
11385   Constant *C;
11386   if (EltVT == MVT::f64)
11387     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11388                                           APInt(64, ~(1ULL << 63))));
11389   else
11390     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11391                                           APInt(32, ~(1U << 31))));
11392   C = ConstantVector::getSplat(NumElts, C);
11393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11394   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11395   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11396   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11397                              MachinePointerInfo::getConstantPool(),
11398                              false, false, false, Alignment);
11399   if (VT.isVector()) {
11400     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11401     return DAG.getNode(ISD::BITCAST, dl, VT,
11402                        DAG.getNode(ISD::AND, dl, ANDVT,
11403                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11404                                                Op.getOperand(0)),
11405                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11406   }
11407   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11408 }
11409
11410 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11411   LLVMContext *Context = DAG.getContext();
11412   SDLoc dl(Op);
11413   MVT VT = Op.getSimpleValueType();
11414   MVT EltVT = VT;
11415   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11416   if (VT.isVector()) {
11417     EltVT = VT.getVectorElementType();
11418     NumElts = VT.getVectorNumElements();
11419   }
11420   Constant *C;
11421   if (EltVT == MVT::f64)
11422     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11423                                           APInt(64, 1ULL << 63)));
11424   else
11425     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11426                                           APInt(32, 1U << 31)));
11427   C = ConstantVector::getSplat(NumElts, C);
11428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11429   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11430   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11431   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11432                              MachinePointerInfo::getConstantPool(),
11433                              false, false, false, Alignment);
11434   if (VT.isVector()) {
11435     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11436     return DAG.getNode(ISD::BITCAST, dl, VT,
11437                        DAG.getNode(ISD::XOR, dl, XORVT,
11438                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11439                                                Op.getOperand(0)),
11440                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11441   }
11442
11443   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11444 }
11445
11446 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11448   LLVMContext *Context = DAG.getContext();
11449   SDValue Op0 = Op.getOperand(0);
11450   SDValue Op1 = Op.getOperand(1);
11451   SDLoc dl(Op);
11452   MVT VT = Op.getSimpleValueType();
11453   MVT SrcVT = Op1.getSimpleValueType();
11454
11455   // If second operand is smaller, extend it first.
11456   if (SrcVT.bitsLT(VT)) {
11457     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11458     SrcVT = VT;
11459   }
11460   // And if it is bigger, shrink it first.
11461   if (SrcVT.bitsGT(VT)) {
11462     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11463     SrcVT = VT;
11464   }
11465
11466   // At this point the operands and the result should have the same
11467   // type, and that won't be f80 since that is not custom lowered.
11468
11469   // First get the sign bit of second operand.
11470   SmallVector<Constant*,4> CV;
11471   if (SrcVT == MVT::f64) {
11472     const fltSemantics &Sem = APFloat::IEEEdouble;
11473     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11474     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11475   } else {
11476     const fltSemantics &Sem = APFloat::IEEEsingle;
11477     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11478     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11479     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11480     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11481   }
11482   Constant *C = ConstantVector::get(CV);
11483   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11484   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11485                               MachinePointerInfo::getConstantPool(),
11486                               false, false, false, 16);
11487   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11488
11489   // Shift sign bit right or left if the two operands have different types.
11490   if (SrcVT.bitsGT(VT)) {
11491     // Op0 is MVT::f32, Op1 is MVT::f64.
11492     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11493     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11494                           DAG.getConstant(32, MVT::i32));
11495     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11496     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11497                           DAG.getIntPtrConstant(0));
11498   }
11499
11500   // Clear first operand sign bit.
11501   CV.clear();
11502   if (VT == MVT::f64) {
11503     const fltSemantics &Sem = APFloat::IEEEdouble;
11504     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11505                                                    APInt(64, ~(1ULL << 63)))));
11506     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11507   } else {
11508     const fltSemantics &Sem = APFloat::IEEEsingle;
11509     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11510                                                    APInt(32, ~(1U << 31)))));
11511     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11512     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11513     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11514   }
11515   C = ConstantVector::get(CV);
11516   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11517   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11518                               MachinePointerInfo::getConstantPool(),
11519                               false, false, false, 16);
11520   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11521
11522   // Or the value with the sign bit.
11523   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11524 }
11525
11526 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11527   SDValue N0 = Op.getOperand(0);
11528   SDLoc dl(Op);
11529   MVT VT = Op.getSimpleValueType();
11530
11531   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11532   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11533                                   DAG.getConstant(1, VT));
11534   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11535 }
11536
11537 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11538 //
11539 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11540                                       SelectionDAG &DAG) {
11541   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11542
11543   if (!Subtarget->hasSSE41())
11544     return SDValue();
11545
11546   if (!Op->hasOneUse())
11547     return SDValue();
11548
11549   SDNode *N = Op.getNode();
11550   SDLoc DL(N);
11551
11552   SmallVector<SDValue, 8> Opnds;
11553   DenseMap<SDValue, unsigned> VecInMap;
11554   SmallVector<SDValue, 8> VecIns;
11555   EVT VT = MVT::Other;
11556
11557   // Recognize a special case where a vector is casted into wide integer to
11558   // test all 0s.
11559   Opnds.push_back(N->getOperand(0));
11560   Opnds.push_back(N->getOperand(1));
11561
11562   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11563     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11564     // BFS traverse all OR'd operands.
11565     if (I->getOpcode() == ISD::OR) {
11566       Opnds.push_back(I->getOperand(0));
11567       Opnds.push_back(I->getOperand(1));
11568       // Re-evaluate the number of nodes to be traversed.
11569       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11570       continue;
11571     }
11572
11573     // Quit if a non-EXTRACT_VECTOR_ELT
11574     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11575       return SDValue();
11576
11577     // Quit if without a constant index.
11578     SDValue Idx = I->getOperand(1);
11579     if (!isa<ConstantSDNode>(Idx))
11580       return SDValue();
11581
11582     SDValue ExtractedFromVec = I->getOperand(0);
11583     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11584     if (M == VecInMap.end()) {
11585       VT = ExtractedFromVec.getValueType();
11586       // Quit if not 128/256-bit vector.
11587       if (!VT.is128BitVector() && !VT.is256BitVector())
11588         return SDValue();
11589       // Quit if not the same type.
11590       if (VecInMap.begin() != VecInMap.end() &&
11591           VT != VecInMap.begin()->first.getValueType())
11592         return SDValue();
11593       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11594       VecIns.push_back(ExtractedFromVec);
11595     }
11596     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11597   }
11598
11599   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11600          "Not extracted from 128-/256-bit vector.");
11601
11602   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11603
11604   for (DenseMap<SDValue, unsigned>::const_iterator
11605         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11606     // Quit if not all elements are used.
11607     if (I->second != FullMask)
11608       return SDValue();
11609   }
11610
11611   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11612
11613   // Cast all vectors into TestVT for PTEST.
11614   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11615     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11616
11617   // If more than one full vectors are evaluated, OR them first before PTEST.
11618   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11619     // Each iteration will OR 2 nodes and append the result until there is only
11620     // 1 node left, i.e. the final OR'd value of all vectors.
11621     SDValue LHS = VecIns[Slot];
11622     SDValue RHS = VecIns[Slot + 1];
11623     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11624   }
11625
11626   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11627                      VecIns.back(), VecIns.back());
11628 }
11629
11630 /// \brief return true if \c Op has a use that doesn't just read flags.
11631 static bool hasNonFlagsUse(SDValue Op) {
11632   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11633        ++UI) {
11634     SDNode *User = *UI;
11635     unsigned UOpNo = UI.getOperandNo();
11636     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11637       // Look pass truncate.
11638       UOpNo = User->use_begin().getOperandNo();
11639       User = *User->use_begin();
11640     }
11641
11642     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11643         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11644       return true;
11645   }
11646   return false;
11647 }
11648
11649 /// Emit nodes that will be selected as "test Op0,Op0", or something
11650 /// equivalent.
11651 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11652                                     SelectionDAG &DAG) const {
11653   if (Op.getValueType() == MVT::i1)
11654     // KORTEST instruction should be selected
11655     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11656                        DAG.getConstant(0, Op.getValueType()));
11657
11658   // CF and OF aren't always set the way we want. Determine which
11659   // of these we need.
11660   bool NeedCF = false;
11661   bool NeedOF = false;
11662   switch (X86CC) {
11663   default: break;
11664   case X86::COND_A: case X86::COND_AE:
11665   case X86::COND_B: case X86::COND_BE:
11666     NeedCF = true;
11667     break;
11668   case X86::COND_G: case X86::COND_GE:
11669   case X86::COND_L: case X86::COND_LE:
11670   case X86::COND_O: case X86::COND_NO: {
11671     // Check if we really need to set the
11672     // Overflow flag. If NoSignedWrap is present
11673     // that is not actually needed.
11674     switch (Op->getOpcode()) {
11675     case ISD::ADD:
11676     case ISD::SUB:
11677     case ISD::MUL:
11678     case ISD::SHL: {
11679       const BinaryWithFlagsSDNode *BinNode =
11680           cast<BinaryWithFlagsSDNode>(Op.getNode());
11681       if (BinNode->hasNoSignedWrap())
11682         break;
11683     }
11684     default:
11685       NeedOF = true;
11686       break;
11687     }
11688     break;
11689   }
11690   }
11691   // See if we can use the EFLAGS value from the operand instead of
11692   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11693   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11694   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11695     // Emit a CMP with 0, which is the TEST pattern.
11696     //if (Op.getValueType() == MVT::i1)
11697     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11698     //                     DAG.getConstant(0, MVT::i1));
11699     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11700                        DAG.getConstant(0, Op.getValueType()));
11701   }
11702   unsigned Opcode = 0;
11703   unsigned NumOperands = 0;
11704
11705   // Truncate operations may prevent the merge of the SETCC instruction
11706   // and the arithmetic instruction before it. Attempt to truncate the operands
11707   // of the arithmetic instruction and use a reduced bit-width instruction.
11708   bool NeedTruncation = false;
11709   SDValue ArithOp = Op;
11710   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11711     SDValue Arith = Op->getOperand(0);
11712     // Both the trunc and the arithmetic op need to have one user each.
11713     if (Arith->hasOneUse())
11714       switch (Arith.getOpcode()) {
11715         default: break;
11716         case ISD::ADD:
11717         case ISD::SUB:
11718         case ISD::AND:
11719         case ISD::OR:
11720         case ISD::XOR: {
11721           NeedTruncation = true;
11722           ArithOp = Arith;
11723         }
11724       }
11725   }
11726
11727   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11728   // which may be the result of a CAST.  We use the variable 'Op', which is the
11729   // non-casted variable when we check for possible users.
11730   switch (ArithOp.getOpcode()) {
11731   case ISD::ADD:
11732     // Due to an isel shortcoming, be conservative if this add is likely to be
11733     // selected as part of a load-modify-store instruction. When the root node
11734     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11735     // uses of other nodes in the match, such as the ADD in this case. This
11736     // leads to the ADD being left around and reselected, with the result being
11737     // two adds in the output.  Alas, even if none our users are stores, that
11738     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11739     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11740     // climbing the DAG back to the root, and it doesn't seem to be worth the
11741     // effort.
11742     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11743          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11744       if (UI->getOpcode() != ISD::CopyToReg &&
11745           UI->getOpcode() != ISD::SETCC &&
11746           UI->getOpcode() != ISD::STORE)
11747         goto default_case;
11748
11749     if (ConstantSDNode *C =
11750         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11751       // An add of one will be selected as an INC.
11752       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11753         Opcode = X86ISD::INC;
11754         NumOperands = 1;
11755         break;
11756       }
11757
11758       // An add of negative one (subtract of one) will be selected as a DEC.
11759       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11760         Opcode = X86ISD::DEC;
11761         NumOperands = 1;
11762         break;
11763       }
11764     }
11765
11766     // Otherwise use a regular EFLAGS-setting add.
11767     Opcode = X86ISD::ADD;
11768     NumOperands = 2;
11769     break;
11770   case ISD::SHL:
11771   case ISD::SRL:
11772     // If we have a constant logical shift that's only used in a comparison
11773     // against zero turn it into an equivalent AND. This allows turning it into
11774     // a TEST instruction later.
11775     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11776         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11777       EVT VT = Op.getValueType();
11778       unsigned BitWidth = VT.getSizeInBits();
11779       unsigned ShAmt = Op->getConstantOperandVal(1);
11780       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11781         break;
11782       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11783                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11784                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11785       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11786         break;
11787       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11788                                 DAG.getConstant(Mask, VT));
11789       DAG.ReplaceAllUsesWith(Op, New);
11790       Op = New;
11791     }
11792     break;
11793
11794   case ISD::AND:
11795     // If the primary and result isn't used, don't bother using X86ISD::AND,
11796     // because a TEST instruction will be better.
11797     if (!hasNonFlagsUse(Op))
11798       break;
11799     // FALL THROUGH
11800   case ISD::SUB:
11801   case ISD::OR:
11802   case ISD::XOR:
11803     // Due to the ISEL shortcoming noted above, be conservative if this op is
11804     // likely to be selected as part of a load-modify-store instruction.
11805     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11806            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11807       if (UI->getOpcode() == ISD::STORE)
11808         goto default_case;
11809
11810     // Otherwise use a regular EFLAGS-setting instruction.
11811     switch (ArithOp.getOpcode()) {
11812     default: llvm_unreachable("unexpected operator!");
11813     case ISD::SUB: Opcode = X86ISD::SUB; break;
11814     case ISD::XOR: Opcode = X86ISD::XOR; break;
11815     case ISD::AND: Opcode = X86ISD::AND; break;
11816     case ISD::OR: {
11817       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11818         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11819         if (EFLAGS.getNode())
11820           return EFLAGS;
11821       }
11822       Opcode = X86ISD::OR;
11823       break;
11824     }
11825     }
11826
11827     NumOperands = 2;
11828     break;
11829   case X86ISD::ADD:
11830   case X86ISD::SUB:
11831   case X86ISD::INC:
11832   case X86ISD::DEC:
11833   case X86ISD::OR:
11834   case X86ISD::XOR:
11835   case X86ISD::AND:
11836     return SDValue(Op.getNode(), 1);
11837   default:
11838   default_case:
11839     break;
11840   }
11841
11842   // If we found that truncation is beneficial, perform the truncation and
11843   // update 'Op'.
11844   if (NeedTruncation) {
11845     EVT VT = Op.getValueType();
11846     SDValue WideVal = Op->getOperand(0);
11847     EVT WideVT = WideVal.getValueType();
11848     unsigned ConvertedOp = 0;
11849     // Use a target machine opcode to prevent further DAGCombine
11850     // optimizations that may separate the arithmetic operations
11851     // from the setcc node.
11852     switch (WideVal.getOpcode()) {
11853       default: break;
11854       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11855       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11856       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11857       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11858       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11859     }
11860
11861     if (ConvertedOp) {
11862       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11863       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11864         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11865         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11866         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11867       }
11868     }
11869   }
11870
11871   if (Opcode == 0)
11872     // Emit a CMP with 0, which is the TEST pattern.
11873     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11874                        DAG.getConstant(0, Op.getValueType()));
11875
11876   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11877   SmallVector<SDValue, 4> Ops;
11878   for (unsigned i = 0; i != NumOperands; ++i)
11879     Ops.push_back(Op.getOperand(i));
11880
11881   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11882   DAG.ReplaceAllUsesWith(Op, New);
11883   return SDValue(New.getNode(), 1);
11884 }
11885
11886 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11887 /// equivalent.
11888 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11889                                    SDLoc dl, SelectionDAG &DAG) const {
11890   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11891     if (C->getAPIntValue() == 0)
11892       return EmitTest(Op0, X86CC, dl, DAG);
11893
11894      if (Op0.getValueType() == MVT::i1)
11895        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11896   }
11897  
11898   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11899        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11900     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11901     // This avoids subregister aliasing issues. Keep the smaller reference 
11902     // if we're optimizing for size, however, as that'll allow better folding 
11903     // of memory operations.
11904     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11905         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11906              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11907         !Subtarget->isAtom()) {
11908       unsigned ExtendOp =
11909           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11910       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11911       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11912     }
11913     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11914     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11915     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11916                               Op0, Op1);
11917     return SDValue(Sub.getNode(), 1);
11918   }
11919   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11920 }
11921
11922 /// Convert a comparison if required by the subtarget.
11923 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11924                                                  SelectionDAG &DAG) const {
11925   // If the subtarget does not support the FUCOMI instruction, floating-point
11926   // comparisons have to be converted.
11927   if (Subtarget->hasCMov() ||
11928       Cmp.getOpcode() != X86ISD::CMP ||
11929       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11930       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11931     return Cmp;
11932
11933   // The instruction selector will select an FUCOM instruction instead of
11934   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11935   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11936   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11937   SDLoc dl(Cmp);
11938   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11939   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11940   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11941                             DAG.getConstant(8, MVT::i8));
11942   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11943   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11944 }
11945
11946 static bool isAllOnes(SDValue V) {
11947   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11948   return C && C->isAllOnesValue();
11949 }
11950
11951 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11952 /// if it's possible.
11953 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11954                                      SDLoc dl, SelectionDAG &DAG) const {
11955   SDValue Op0 = And.getOperand(0);
11956   SDValue Op1 = And.getOperand(1);
11957   if (Op0.getOpcode() == ISD::TRUNCATE)
11958     Op0 = Op0.getOperand(0);
11959   if (Op1.getOpcode() == ISD::TRUNCATE)
11960     Op1 = Op1.getOperand(0);
11961
11962   SDValue LHS, RHS;
11963   if (Op1.getOpcode() == ISD::SHL)
11964     std::swap(Op0, Op1);
11965   if (Op0.getOpcode() == ISD::SHL) {
11966     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11967       if (And00C->getZExtValue() == 1) {
11968         // If we looked past a truncate, check that it's only truncating away
11969         // known zeros.
11970         unsigned BitWidth = Op0.getValueSizeInBits();
11971         unsigned AndBitWidth = And.getValueSizeInBits();
11972         if (BitWidth > AndBitWidth) {
11973           APInt Zeros, Ones;
11974           DAG.computeKnownBits(Op0, Zeros, Ones);
11975           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11976             return SDValue();
11977         }
11978         LHS = Op1;
11979         RHS = Op0.getOperand(1);
11980       }
11981   } else if (Op1.getOpcode() == ISD::Constant) {
11982     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11983     uint64_t AndRHSVal = AndRHS->getZExtValue();
11984     SDValue AndLHS = Op0;
11985
11986     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11987       LHS = AndLHS.getOperand(0);
11988       RHS = AndLHS.getOperand(1);
11989     }
11990
11991     // Use BT if the immediate can't be encoded in a TEST instruction.
11992     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11993       LHS = AndLHS;
11994       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11995     }
11996   }
11997
11998   if (LHS.getNode()) {
11999     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12000     // instruction.  Since the shift amount is in-range-or-undefined, we know
12001     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12002     // the encoding for the i16 version is larger than the i32 version.
12003     // Also promote i16 to i32 for performance / code size reason.
12004     if (LHS.getValueType() == MVT::i8 ||
12005         LHS.getValueType() == MVT::i16)
12006       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12007
12008     // If the operand types disagree, extend the shift amount to match.  Since
12009     // BT ignores high bits (like shifts) we can use anyextend.
12010     if (LHS.getValueType() != RHS.getValueType())
12011       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12012
12013     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12014     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12015     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12016                        DAG.getConstant(Cond, MVT::i8), BT);
12017   }
12018
12019   return SDValue();
12020 }
12021
12022 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12023 /// mask CMPs.
12024 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12025                               SDValue &Op1) {
12026   unsigned SSECC;
12027   bool Swap = false;
12028
12029   // SSE Condition code mapping:
12030   //  0 - EQ
12031   //  1 - LT
12032   //  2 - LE
12033   //  3 - UNORD
12034   //  4 - NEQ
12035   //  5 - NLT
12036   //  6 - NLE
12037   //  7 - ORD
12038   switch (SetCCOpcode) {
12039   default: llvm_unreachable("Unexpected SETCC condition");
12040   case ISD::SETOEQ:
12041   case ISD::SETEQ:  SSECC = 0; break;
12042   case ISD::SETOGT:
12043   case ISD::SETGT:  Swap = true; // Fallthrough
12044   case ISD::SETLT:
12045   case ISD::SETOLT: SSECC = 1; break;
12046   case ISD::SETOGE:
12047   case ISD::SETGE:  Swap = true; // Fallthrough
12048   case ISD::SETLE:
12049   case ISD::SETOLE: SSECC = 2; break;
12050   case ISD::SETUO:  SSECC = 3; break;
12051   case ISD::SETUNE:
12052   case ISD::SETNE:  SSECC = 4; break;
12053   case ISD::SETULE: Swap = true; // Fallthrough
12054   case ISD::SETUGE: SSECC = 5; break;
12055   case ISD::SETULT: Swap = true; // Fallthrough
12056   case ISD::SETUGT: SSECC = 6; break;
12057   case ISD::SETO:   SSECC = 7; break;
12058   case ISD::SETUEQ:
12059   case ISD::SETONE: SSECC = 8; break;
12060   }
12061   if (Swap)
12062     std::swap(Op0, Op1);
12063
12064   return SSECC;
12065 }
12066
12067 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12068 // ones, and then concatenate the result back.
12069 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12070   MVT VT = Op.getSimpleValueType();
12071
12072   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12073          "Unsupported value type for operation");
12074
12075   unsigned NumElems = VT.getVectorNumElements();
12076   SDLoc dl(Op);
12077   SDValue CC = Op.getOperand(2);
12078
12079   // Extract the LHS vectors
12080   SDValue LHS = Op.getOperand(0);
12081   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12082   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12083
12084   // Extract the RHS vectors
12085   SDValue RHS = Op.getOperand(1);
12086   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12087   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12088
12089   // Issue the operation on the smaller types and concatenate the result back
12090   MVT EltVT = VT.getVectorElementType();
12091   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12092   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12093                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12094                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12095 }
12096
12097 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12098                                      const X86Subtarget *Subtarget) {
12099   SDValue Op0 = Op.getOperand(0);
12100   SDValue Op1 = Op.getOperand(1);
12101   SDValue CC = Op.getOperand(2);
12102   MVT VT = Op.getSimpleValueType();
12103   SDLoc dl(Op);
12104
12105   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12106          Op.getValueType().getScalarType() == MVT::i1 &&
12107          "Cannot set masked compare for this operation");
12108
12109   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12110   unsigned  Opc = 0;
12111   bool Unsigned = false;
12112   bool Swap = false;
12113   unsigned SSECC;
12114   switch (SetCCOpcode) {
12115   default: llvm_unreachable("Unexpected SETCC condition");
12116   case ISD::SETNE:  SSECC = 4; break;
12117   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12118   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12119   case ISD::SETLT:  Swap = true; //fall-through
12120   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12121   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12122   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12123   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12124   case ISD::SETULE: Unsigned = true; //fall-through
12125   case ISD::SETLE:  SSECC = 2; break;
12126   }
12127
12128   if (Swap)
12129     std::swap(Op0, Op1);
12130   if (Opc)
12131     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12132   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12133   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12134                      DAG.getConstant(SSECC, MVT::i8));
12135 }
12136
12137 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12138 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12139 /// return an empty value.
12140 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12141 {
12142   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12143   if (!BV)
12144     return SDValue();
12145
12146   MVT VT = Op1.getSimpleValueType();
12147   MVT EVT = VT.getVectorElementType();
12148   unsigned n = VT.getVectorNumElements();
12149   SmallVector<SDValue, 8> ULTOp1;
12150
12151   for (unsigned i = 0; i < n; ++i) {
12152     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12153     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12154       return SDValue();
12155
12156     // Avoid underflow.
12157     APInt Val = Elt->getAPIntValue();
12158     if (Val == 0)
12159       return SDValue();
12160
12161     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12162   }
12163
12164   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12165 }
12166
12167 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12168                            SelectionDAG &DAG) {
12169   SDValue Op0 = Op.getOperand(0);
12170   SDValue Op1 = Op.getOperand(1);
12171   SDValue CC = Op.getOperand(2);
12172   MVT VT = Op.getSimpleValueType();
12173   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12174   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12175   SDLoc dl(Op);
12176
12177   if (isFP) {
12178 #ifndef NDEBUG
12179     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12180     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12181 #endif
12182
12183     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12184     unsigned Opc = X86ISD::CMPP;
12185     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12186       assert(VT.getVectorNumElements() <= 16);
12187       Opc = X86ISD::CMPM;
12188     }
12189     // In the two special cases we can't handle, emit two comparisons.
12190     if (SSECC == 8) {
12191       unsigned CC0, CC1;
12192       unsigned CombineOpc;
12193       if (SetCCOpcode == ISD::SETUEQ) {
12194         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12195       } else {
12196         assert(SetCCOpcode == ISD::SETONE);
12197         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12198       }
12199
12200       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12201                                  DAG.getConstant(CC0, MVT::i8));
12202       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12203                                  DAG.getConstant(CC1, MVT::i8));
12204       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12205     }
12206     // Handle all other FP comparisons here.
12207     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12208                        DAG.getConstant(SSECC, MVT::i8));
12209   }
12210
12211   // Break 256-bit integer vector compare into smaller ones.
12212   if (VT.is256BitVector() && !Subtarget->hasInt256())
12213     return Lower256IntVSETCC(Op, DAG);
12214
12215   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12216   EVT OpVT = Op1.getValueType();
12217   if (Subtarget->hasAVX512()) {
12218     if (Op1.getValueType().is512BitVector() ||
12219         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12220       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12221
12222     // In AVX-512 architecture setcc returns mask with i1 elements,
12223     // But there is no compare instruction for i8 and i16 elements.
12224     // We are not talking about 512-bit operands in this case, these
12225     // types are illegal.
12226     if (MaskResult &&
12227         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12228          OpVT.getVectorElementType().getSizeInBits() >= 8))
12229       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12230                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12231   }
12232
12233   // We are handling one of the integer comparisons here.  Since SSE only has
12234   // GT and EQ comparisons for integer, swapping operands and multiple
12235   // operations may be required for some comparisons.
12236   unsigned Opc;
12237   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12238   bool Subus = false;
12239
12240   switch (SetCCOpcode) {
12241   default: llvm_unreachable("Unexpected SETCC condition");
12242   case ISD::SETNE:  Invert = true;
12243   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12244   case ISD::SETLT:  Swap = true;
12245   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12246   case ISD::SETGE:  Swap = true;
12247   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12248                     Invert = true; break;
12249   case ISD::SETULT: Swap = true;
12250   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12251                     FlipSigns = true; break;
12252   case ISD::SETUGE: Swap = true;
12253   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12254                     FlipSigns = true; Invert = true; break;
12255   }
12256
12257   // Special case: Use min/max operations for SETULE/SETUGE
12258   MVT VET = VT.getVectorElementType();
12259   bool hasMinMax =
12260        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12261     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12262
12263   if (hasMinMax) {
12264     switch (SetCCOpcode) {
12265     default: break;
12266     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12267     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12268     }
12269
12270     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12271   }
12272
12273   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12274   if (!MinMax && hasSubus) {
12275     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12276     // Op0 u<= Op1:
12277     //   t = psubus Op0, Op1
12278     //   pcmpeq t, <0..0>
12279     switch (SetCCOpcode) {
12280     default: break;
12281     case ISD::SETULT: {
12282       // If the comparison is against a constant we can turn this into a
12283       // setule.  With psubus, setule does not require a swap.  This is
12284       // beneficial because the constant in the register is no longer
12285       // destructed as the destination so it can be hoisted out of a loop.
12286       // Only do this pre-AVX since vpcmp* is no longer destructive.
12287       if (Subtarget->hasAVX())
12288         break;
12289       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12290       if (ULEOp1.getNode()) {
12291         Op1 = ULEOp1;
12292         Subus = true; Invert = false; Swap = false;
12293       }
12294       break;
12295     }
12296     // Psubus is better than flip-sign because it requires no inversion.
12297     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12298     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12299     }
12300
12301     if (Subus) {
12302       Opc = X86ISD::SUBUS;
12303       FlipSigns = false;
12304     }
12305   }
12306
12307   if (Swap)
12308     std::swap(Op0, Op1);
12309
12310   // Check that the operation in question is available (most are plain SSE2,
12311   // but PCMPGTQ and PCMPEQQ have different requirements).
12312   if (VT == MVT::v2i64) {
12313     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12314       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12315
12316       // First cast everything to the right type.
12317       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12318       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12319
12320       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12321       // bits of the inputs before performing those operations. The lower
12322       // compare is always unsigned.
12323       SDValue SB;
12324       if (FlipSigns) {
12325         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12326       } else {
12327         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12328         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12329         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12330                          Sign, Zero, Sign, Zero);
12331       }
12332       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12333       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12334
12335       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12336       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12337       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12338
12339       // Create masks for only the low parts/high parts of the 64 bit integers.
12340       static const int MaskHi[] = { 1, 1, 3, 3 };
12341       static const int MaskLo[] = { 0, 0, 2, 2 };
12342       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12343       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12344       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12345
12346       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12347       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12348
12349       if (Invert)
12350         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12351
12352       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12353     }
12354
12355     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12356       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12357       // pcmpeqd + pshufd + pand.
12358       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12359
12360       // First cast everything to the right type.
12361       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12362       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12363
12364       // Do the compare.
12365       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12366
12367       // Make sure the lower and upper halves are both all-ones.
12368       static const int Mask[] = { 1, 0, 3, 2 };
12369       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12370       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12371
12372       if (Invert)
12373         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12374
12375       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12376     }
12377   }
12378
12379   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12380   // bits of the inputs before performing those operations.
12381   if (FlipSigns) {
12382     EVT EltVT = VT.getVectorElementType();
12383     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12384     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12385     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12386   }
12387
12388   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12389
12390   // If the logical-not of the result is required, perform that now.
12391   if (Invert)
12392     Result = DAG.getNOT(dl, Result, VT);
12393
12394   if (MinMax)
12395     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12396
12397   if (Subus)
12398     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12399                          getZeroVector(VT, Subtarget, DAG, dl));
12400
12401   return Result;
12402 }
12403
12404 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12405
12406   MVT VT = Op.getSimpleValueType();
12407
12408   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12409
12410   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12411          && "SetCC type must be 8-bit or 1-bit integer");
12412   SDValue Op0 = Op.getOperand(0);
12413   SDValue Op1 = Op.getOperand(1);
12414   SDLoc dl(Op);
12415   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12416
12417   // Optimize to BT if possible.
12418   // Lower (X & (1 << N)) == 0 to BT(X, N).
12419   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12420   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12421   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12422       Op1.getOpcode() == ISD::Constant &&
12423       cast<ConstantSDNode>(Op1)->isNullValue() &&
12424       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12425     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12426     if (NewSetCC.getNode())
12427       return NewSetCC;
12428   }
12429
12430   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12431   // these.
12432   if (Op1.getOpcode() == ISD::Constant &&
12433       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12434        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12435       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12436
12437     // If the input is a setcc, then reuse the input setcc or use a new one with
12438     // the inverted condition.
12439     if (Op0.getOpcode() == X86ISD::SETCC) {
12440       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12441       bool Invert = (CC == ISD::SETNE) ^
12442         cast<ConstantSDNode>(Op1)->isNullValue();
12443       if (!Invert)
12444         return Op0;
12445
12446       CCode = X86::GetOppositeBranchCondition(CCode);
12447       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12448                                   DAG.getConstant(CCode, MVT::i8),
12449                                   Op0.getOperand(1));
12450       if (VT == MVT::i1)
12451         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12452       return SetCC;
12453     }
12454   }
12455   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12456       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12457       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12458
12459     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12460     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12461   }
12462
12463   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12464   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12465   if (X86CC == X86::COND_INVALID)
12466     return SDValue();
12467
12468   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12469   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12470   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12471                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12472   if (VT == MVT::i1)
12473     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12474   return SetCC;
12475 }
12476
12477 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12478 static bool isX86LogicalCmp(SDValue Op) {
12479   unsigned Opc = Op.getNode()->getOpcode();
12480   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12481       Opc == X86ISD::SAHF)
12482     return true;
12483   if (Op.getResNo() == 1 &&
12484       (Opc == X86ISD::ADD ||
12485        Opc == X86ISD::SUB ||
12486        Opc == X86ISD::ADC ||
12487        Opc == X86ISD::SBB ||
12488        Opc == X86ISD::SMUL ||
12489        Opc == X86ISD::UMUL ||
12490        Opc == X86ISD::INC ||
12491        Opc == X86ISD::DEC ||
12492        Opc == X86ISD::OR ||
12493        Opc == X86ISD::XOR ||
12494        Opc == X86ISD::AND))
12495     return true;
12496
12497   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12498     return true;
12499
12500   return false;
12501 }
12502
12503 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12504   if (V.getOpcode() != ISD::TRUNCATE)
12505     return false;
12506
12507   SDValue VOp0 = V.getOperand(0);
12508   unsigned InBits = VOp0.getValueSizeInBits();
12509   unsigned Bits = V.getValueSizeInBits();
12510   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12511 }
12512
12513 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12514   bool addTest = true;
12515   SDValue Cond  = Op.getOperand(0);
12516   SDValue Op1 = Op.getOperand(1);
12517   SDValue Op2 = Op.getOperand(2);
12518   SDLoc DL(Op);
12519   EVT VT = Op1.getValueType();
12520   SDValue CC;
12521
12522   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12523   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12524   // sequence later on.
12525   if (Cond.getOpcode() == ISD::SETCC &&
12526       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12527        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12528       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12529     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12530     int SSECC = translateX86FSETCC(
12531         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12532
12533     if (SSECC != 8) {
12534       if (Subtarget->hasAVX512()) {
12535         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12536                                   DAG.getConstant(SSECC, MVT::i8));
12537         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12538       }
12539       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12540                                 DAG.getConstant(SSECC, MVT::i8));
12541       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12542       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12543       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12544     }
12545   }
12546
12547   if (Cond.getOpcode() == ISD::SETCC) {
12548     SDValue NewCond = LowerSETCC(Cond, DAG);
12549     if (NewCond.getNode())
12550       Cond = NewCond;
12551   }
12552
12553   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12554   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12555   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12556   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12557   if (Cond.getOpcode() == X86ISD::SETCC &&
12558       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12559       isZero(Cond.getOperand(1).getOperand(1))) {
12560     SDValue Cmp = Cond.getOperand(1);
12561
12562     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12563
12564     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12565         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12566       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12567
12568       SDValue CmpOp0 = Cmp.getOperand(0);
12569       // Apply further optimizations for special cases
12570       // (select (x != 0), -1, 0) -> neg & sbb
12571       // (select (x == 0), 0, -1) -> neg & sbb
12572       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12573         if (YC->isNullValue() &&
12574             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12575           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12576           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12577                                     DAG.getConstant(0, CmpOp0.getValueType()),
12578                                     CmpOp0);
12579           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12580                                     DAG.getConstant(X86::COND_B, MVT::i8),
12581                                     SDValue(Neg.getNode(), 1));
12582           return Res;
12583         }
12584
12585       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12586                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12587       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12588
12589       SDValue Res =   // Res = 0 or -1.
12590         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12591                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12592
12593       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12594         Res = DAG.getNOT(DL, Res, Res.getValueType());
12595
12596       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12597       if (!N2C || !N2C->isNullValue())
12598         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12599       return Res;
12600     }
12601   }
12602
12603   // Look past (and (setcc_carry (cmp ...)), 1).
12604   if (Cond.getOpcode() == ISD::AND &&
12605       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12606     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12607     if (C && C->getAPIntValue() == 1)
12608       Cond = Cond.getOperand(0);
12609   }
12610
12611   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12612   // setting operand in place of the X86ISD::SETCC.
12613   unsigned CondOpcode = Cond.getOpcode();
12614   if (CondOpcode == X86ISD::SETCC ||
12615       CondOpcode == X86ISD::SETCC_CARRY) {
12616     CC = Cond.getOperand(0);
12617
12618     SDValue Cmp = Cond.getOperand(1);
12619     unsigned Opc = Cmp.getOpcode();
12620     MVT VT = Op.getSimpleValueType();
12621
12622     bool IllegalFPCMov = false;
12623     if (VT.isFloatingPoint() && !VT.isVector() &&
12624         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12625       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12626
12627     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12628         Opc == X86ISD::BT) { // FIXME
12629       Cond = Cmp;
12630       addTest = false;
12631     }
12632   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12633              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12634              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12635               Cond.getOperand(0).getValueType() != MVT::i8)) {
12636     SDValue LHS = Cond.getOperand(0);
12637     SDValue RHS = Cond.getOperand(1);
12638     unsigned X86Opcode;
12639     unsigned X86Cond;
12640     SDVTList VTs;
12641     switch (CondOpcode) {
12642     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12643     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12644     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12645     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12646     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12647     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12648     default: llvm_unreachable("unexpected overflowing operator");
12649     }
12650     if (CondOpcode == ISD::UMULO)
12651       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12652                           MVT::i32);
12653     else
12654       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12655
12656     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12657
12658     if (CondOpcode == ISD::UMULO)
12659       Cond = X86Op.getValue(2);
12660     else
12661       Cond = X86Op.getValue(1);
12662
12663     CC = DAG.getConstant(X86Cond, MVT::i8);
12664     addTest = false;
12665   }
12666
12667   if (addTest) {
12668     // Look pass the truncate if the high bits are known zero.
12669     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12670         Cond = Cond.getOperand(0);
12671
12672     // We know the result of AND is compared against zero. Try to match
12673     // it to BT.
12674     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12675       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12676       if (NewSetCC.getNode()) {
12677         CC = NewSetCC.getOperand(0);
12678         Cond = NewSetCC.getOperand(1);
12679         addTest = false;
12680       }
12681     }
12682   }
12683
12684   if (addTest) {
12685     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12686     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12687   }
12688
12689   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12690   // a <  b ?  0 : -1 -> RES = setcc_carry
12691   // a >= b ? -1 :  0 -> RES = setcc_carry
12692   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12693   if (Cond.getOpcode() == X86ISD::SUB) {
12694     Cond = ConvertCmpIfNecessary(Cond, DAG);
12695     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12696
12697     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12698         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12699       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12700                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12701       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12702         return DAG.getNOT(DL, Res, Res.getValueType());
12703       return Res;
12704     }
12705   }
12706
12707   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12708   // widen the cmov and push the truncate through. This avoids introducing a new
12709   // branch during isel and doesn't add any extensions.
12710   if (Op.getValueType() == MVT::i8 &&
12711       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12712     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12713     if (T1.getValueType() == T2.getValueType() &&
12714         // Blacklist CopyFromReg to avoid partial register stalls.
12715         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12716       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12717       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12718       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12719     }
12720   }
12721
12722   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12723   // condition is true.
12724   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12725   SDValue Ops[] = { Op2, Op1, CC, Cond };
12726   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12727 }
12728
12729 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12730   MVT VT = Op->getSimpleValueType(0);
12731   SDValue In = Op->getOperand(0);
12732   MVT InVT = In.getSimpleValueType();
12733   SDLoc dl(Op);
12734
12735   unsigned int NumElts = VT.getVectorNumElements();
12736   if (NumElts != 8 && NumElts != 16)
12737     return SDValue();
12738
12739   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12740     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12741
12742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12743   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12744
12745   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12746   Constant *C = ConstantInt::get(*DAG.getContext(),
12747     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12748
12749   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12750   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12751   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12752                           MachinePointerInfo::getConstantPool(),
12753                           false, false, false, Alignment);
12754   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12755   if (VT.is512BitVector())
12756     return Brcst;
12757   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12758 }
12759
12760 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12761                                 SelectionDAG &DAG) {
12762   MVT VT = Op->getSimpleValueType(0);
12763   SDValue In = Op->getOperand(0);
12764   MVT InVT = In.getSimpleValueType();
12765   SDLoc dl(Op);
12766
12767   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12768     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12769
12770   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12771       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12772       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12773     return SDValue();
12774
12775   if (Subtarget->hasInt256())
12776     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12777
12778   // Optimize vectors in AVX mode
12779   // Sign extend  v8i16 to v8i32 and
12780   //              v4i32 to v4i64
12781   //
12782   // Divide input vector into two parts
12783   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12784   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12785   // concat the vectors to original VT
12786
12787   unsigned NumElems = InVT.getVectorNumElements();
12788   SDValue Undef = DAG.getUNDEF(InVT);
12789
12790   SmallVector<int,8> ShufMask1(NumElems, -1);
12791   for (unsigned i = 0; i != NumElems/2; ++i)
12792     ShufMask1[i] = i;
12793
12794   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12795
12796   SmallVector<int,8> ShufMask2(NumElems, -1);
12797   for (unsigned i = 0; i != NumElems/2; ++i)
12798     ShufMask2[i] = i + NumElems/2;
12799
12800   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12801
12802   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12803                                 VT.getVectorNumElements()/2);
12804
12805   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12806   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12807
12808   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12809 }
12810
12811 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12812 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12813 // from the AND / OR.
12814 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12815   Opc = Op.getOpcode();
12816   if (Opc != ISD::OR && Opc != ISD::AND)
12817     return false;
12818   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12819           Op.getOperand(0).hasOneUse() &&
12820           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12821           Op.getOperand(1).hasOneUse());
12822 }
12823
12824 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12825 // 1 and that the SETCC node has a single use.
12826 static bool isXor1OfSetCC(SDValue Op) {
12827   if (Op.getOpcode() != ISD::XOR)
12828     return false;
12829   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12830   if (N1C && N1C->getAPIntValue() == 1) {
12831     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12832       Op.getOperand(0).hasOneUse();
12833   }
12834   return false;
12835 }
12836
12837 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12838   bool addTest = true;
12839   SDValue Chain = Op.getOperand(0);
12840   SDValue Cond  = Op.getOperand(1);
12841   SDValue Dest  = Op.getOperand(2);
12842   SDLoc dl(Op);
12843   SDValue CC;
12844   bool Inverted = false;
12845
12846   if (Cond.getOpcode() == ISD::SETCC) {
12847     // Check for setcc([su]{add,sub,mul}o == 0).
12848     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12849         isa<ConstantSDNode>(Cond.getOperand(1)) &&
12850         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12851         Cond.getOperand(0).getResNo() == 1 &&
12852         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12853          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12854          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12855          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12856          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12857          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12858       Inverted = true;
12859       Cond = Cond.getOperand(0);
12860     } else {
12861       SDValue NewCond = LowerSETCC(Cond, DAG);
12862       if (NewCond.getNode())
12863         Cond = NewCond;
12864     }
12865   }
12866 #if 0
12867   // FIXME: LowerXALUO doesn't handle these!!
12868   else if (Cond.getOpcode() == X86ISD::ADD  ||
12869            Cond.getOpcode() == X86ISD::SUB  ||
12870            Cond.getOpcode() == X86ISD::SMUL ||
12871            Cond.getOpcode() == X86ISD::UMUL)
12872     Cond = LowerXALUO(Cond, DAG);
12873 #endif
12874
12875   // Look pass (and (setcc_carry (cmp ...)), 1).
12876   if (Cond.getOpcode() == ISD::AND &&
12877       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12878     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12879     if (C && C->getAPIntValue() == 1)
12880       Cond = Cond.getOperand(0);
12881   }
12882
12883   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12884   // setting operand in place of the X86ISD::SETCC.
12885   unsigned CondOpcode = Cond.getOpcode();
12886   if (CondOpcode == X86ISD::SETCC ||
12887       CondOpcode == X86ISD::SETCC_CARRY) {
12888     CC = Cond.getOperand(0);
12889
12890     SDValue Cmp = Cond.getOperand(1);
12891     unsigned Opc = Cmp.getOpcode();
12892     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12893     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12894       Cond = Cmp;
12895       addTest = false;
12896     } else {
12897       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12898       default: break;
12899       case X86::COND_O:
12900       case X86::COND_B:
12901         // These can only come from an arithmetic instruction with overflow,
12902         // e.g. SADDO, UADDO.
12903         Cond = Cond.getNode()->getOperand(1);
12904         addTest = false;
12905         break;
12906       }
12907     }
12908   }
12909   CondOpcode = Cond.getOpcode();
12910   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12911       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12912       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12913        Cond.getOperand(0).getValueType() != MVT::i8)) {
12914     SDValue LHS = Cond.getOperand(0);
12915     SDValue RHS = Cond.getOperand(1);
12916     unsigned X86Opcode;
12917     unsigned X86Cond;
12918     SDVTList VTs;
12919     // Keep this in sync with LowerXALUO, otherwise we might create redundant
12920     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12921     // X86ISD::INC).
12922     switch (CondOpcode) {
12923     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12924     case ISD::SADDO:
12925       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12926         if (C->isOne()) {
12927           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12928           break;
12929         }
12930       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12931     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12932     case ISD::SSUBO:
12933       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12934         if (C->isOne()) {
12935           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12936           break;
12937         }
12938       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12939     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12940     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12941     default: llvm_unreachable("unexpected overflowing operator");
12942     }
12943     if (Inverted)
12944       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12945     if (CondOpcode == ISD::UMULO)
12946       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12947                           MVT::i32);
12948     else
12949       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12950
12951     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12952
12953     if (CondOpcode == ISD::UMULO)
12954       Cond = X86Op.getValue(2);
12955     else
12956       Cond = X86Op.getValue(1);
12957
12958     CC = DAG.getConstant(X86Cond, MVT::i8);
12959     addTest = false;
12960   } else {
12961     unsigned CondOpc;
12962     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12963       SDValue Cmp = Cond.getOperand(0).getOperand(1);
12964       if (CondOpc == ISD::OR) {
12965         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12966         // two branches instead of an explicit OR instruction with a
12967         // separate test.
12968         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12969             isX86LogicalCmp(Cmp)) {
12970           CC = Cond.getOperand(0).getOperand(0);
12971           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12972                               Chain, Dest, CC, Cmp);
12973           CC = Cond.getOperand(1).getOperand(0);
12974           Cond = Cmp;
12975           addTest = false;
12976         }
12977       } else { // ISD::AND
12978         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12979         // two branches instead of an explicit AND instruction with a
12980         // separate test. However, we only do this if this block doesn't
12981         // have a fall-through edge, because this requires an explicit
12982         // jmp when the condition is false.
12983         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12984             isX86LogicalCmp(Cmp) &&
12985             Op.getNode()->hasOneUse()) {
12986           X86::CondCode CCode =
12987             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12988           CCode = X86::GetOppositeBranchCondition(CCode);
12989           CC = DAG.getConstant(CCode, MVT::i8);
12990           SDNode *User = *Op.getNode()->use_begin();
12991           // Look for an unconditional branch following this conditional branch.
12992           // We need this because we need to reverse the successors in order
12993           // to implement FCMP_OEQ.
12994           if (User->getOpcode() == ISD::BR) {
12995             SDValue FalseBB = User->getOperand(1);
12996             SDNode *NewBR =
12997               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12998             assert(NewBR == User);
12999             (void)NewBR;
13000             Dest = FalseBB;
13001
13002             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13003                                 Chain, Dest, CC, Cmp);
13004             X86::CondCode CCode =
13005               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13006             CCode = X86::GetOppositeBranchCondition(CCode);
13007             CC = DAG.getConstant(CCode, MVT::i8);
13008             Cond = Cmp;
13009             addTest = false;
13010           }
13011         }
13012       }
13013     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13014       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13015       // It should be transformed during dag combiner except when the condition
13016       // is set by a arithmetics with overflow node.
13017       X86::CondCode CCode =
13018         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13019       CCode = X86::GetOppositeBranchCondition(CCode);
13020       CC = DAG.getConstant(CCode, MVT::i8);
13021       Cond = Cond.getOperand(0).getOperand(1);
13022       addTest = false;
13023     } else if (Cond.getOpcode() == ISD::SETCC &&
13024                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13025       // For FCMP_OEQ, we can emit
13026       // two branches instead of an explicit AND instruction with a
13027       // separate test. However, we only do this if this block doesn't
13028       // have a fall-through edge, because this requires an explicit
13029       // jmp when the condition is false.
13030       if (Op.getNode()->hasOneUse()) {
13031         SDNode *User = *Op.getNode()->use_begin();
13032         // Look for an unconditional branch following this conditional branch.
13033         // We need this because we need to reverse the successors in order
13034         // to implement FCMP_OEQ.
13035         if (User->getOpcode() == ISD::BR) {
13036           SDValue FalseBB = User->getOperand(1);
13037           SDNode *NewBR =
13038             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13039           assert(NewBR == User);
13040           (void)NewBR;
13041           Dest = FalseBB;
13042
13043           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13044                                     Cond.getOperand(0), Cond.getOperand(1));
13045           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13046           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13047           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13048                               Chain, Dest, CC, Cmp);
13049           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13050           Cond = Cmp;
13051           addTest = false;
13052         }
13053       }
13054     } else if (Cond.getOpcode() == ISD::SETCC &&
13055                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13056       // For FCMP_UNE, we can emit
13057       // two branches instead of an explicit AND instruction with a
13058       // separate test. However, we only do this if this block doesn't
13059       // have a fall-through edge, because this requires an explicit
13060       // jmp when the condition is false.
13061       if (Op.getNode()->hasOneUse()) {
13062         SDNode *User = *Op.getNode()->use_begin();
13063         // Look for an unconditional branch following this conditional branch.
13064         // We need this because we need to reverse the successors in order
13065         // to implement FCMP_UNE.
13066         if (User->getOpcode() == ISD::BR) {
13067           SDValue FalseBB = User->getOperand(1);
13068           SDNode *NewBR =
13069             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13070           assert(NewBR == User);
13071           (void)NewBR;
13072
13073           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13074                                     Cond.getOperand(0), Cond.getOperand(1));
13075           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13076           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13077           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13078                               Chain, Dest, CC, Cmp);
13079           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13080           Cond = Cmp;
13081           addTest = false;
13082           Dest = FalseBB;
13083         }
13084       }
13085     }
13086   }
13087
13088   if (addTest) {
13089     // Look pass the truncate if the high bits are known zero.
13090     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13091         Cond = Cond.getOperand(0);
13092
13093     // We know the result of AND is compared against zero. Try to match
13094     // it to BT.
13095     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13096       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13097       if (NewSetCC.getNode()) {
13098         CC = NewSetCC.getOperand(0);
13099         Cond = NewSetCC.getOperand(1);
13100         addTest = false;
13101       }
13102     }
13103   }
13104
13105   if (addTest) {
13106     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13107     CC = DAG.getConstant(X86Cond, MVT::i8);
13108     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13109   }
13110   Cond = ConvertCmpIfNecessary(Cond, DAG);
13111   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13112                      Chain, Dest, CC, Cond);
13113 }
13114
13115 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13116 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13117 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13118 // that the guard pages used by the OS virtual memory manager are allocated in
13119 // correct sequence.
13120 SDValue
13121 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13122                                            SelectionDAG &DAG) const {
13123   MachineFunction &MF = DAG.getMachineFunction();
13124   bool SplitStack = MF.shouldSplitStack();
13125   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13126                SplitStack;
13127   SDLoc dl(Op);
13128
13129   if (!Lower) {
13130     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13131     SDNode* Node = Op.getNode();
13132
13133     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13134     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13135         " not tell us which reg is the stack pointer!");
13136     EVT VT = Node->getValueType(0);
13137     SDValue Tmp1 = SDValue(Node, 0);
13138     SDValue Tmp2 = SDValue(Node, 1);
13139     SDValue Tmp3 = Node->getOperand(2);
13140     SDValue Chain = Tmp1.getOperand(0);
13141
13142     // Chain the dynamic stack allocation so that it doesn't modify the stack
13143     // pointer when other instructions are using the stack.
13144     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13145         SDLoc(Node));
13146
13147     SDValue Size = Tmp2.getOperand(1);
13148     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13149     Chain = SP.getValue(1);
13150     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13151     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13152     unsigned StackAlign = TFI.getStackAlignment();
13153     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13154     if (Align > StackAlign)
13155       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13156           DAG.getConstant(-(uint64_t)Align, VT));
13157     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13158
13159     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13160         DAG.getIntPtrConstant(0, true), SDValue(),
13161         SDLoc(Node));
13162
13163     SDValue Ops[2] = { Tmp1, Tmp2 };
13164     return DAG.getMergeValues(Ops, dl);
13165   }
13166
13167   // Get the inputs.
13168   SDValue Chain = Op.getOperand(0);
13169   SDValue Size  = Op.getOperand(1);
13170   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13171   EVT VT = Op.getNode()->getValueType(0);
13172
13173   bool Is64Bit = Subtarget->is64Bit();
13174   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13175
13176   if (SplitStack) {
13177     MachineRegisterInfo &MRI = MF.getRegInfo();
13178
13179     if (Is64Bit) {
13180       // The 64 bit implementation of segmented stacks needs to clobber both r10
13181       // r11. This makes it impossible to use it along with nested parameters.
13182       const Function *F = MF.getFunction();
13183
13184       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13185            I != E; ++I)
13186         if (I->hasNestAttr())
13187           report_fatal_error("Cannot use segmented stacks with functions that "
13188                              "have nested arguments.");
13189     }
13190
13191     const TargetRegisterClass *AddrRegClass =
13192       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13193     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13194     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13195     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13196                                 DAG.getRegister(Vreg, SPTy));
13197     SDValue Ops1[2] = { Value, Chain };
13198     return DAG.getMergeValues(Ops1, dl);
13199   } else {
13200     SDValue Flag;
13201     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13202
13203     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13204     Flag = Chain.getValue(1);
13205     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13206
13207     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13208
13209     const X86RegisterInfo *RegInfo =
13210       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13211     unsigned SPReg = RegInfo->getStackRegister();
13212     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13213     Chain = SP.getValue(1);
13214
13215     if (Align) {
13216       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13217                        DAG.getConstant(-(uint64_t)Align, VT));
13218       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13219     }
13220
13221     SDValue Ops1[2] = { SP, Chain };
13222     return DAG.getMergeValues(Ops1, dl);
13223   }
13224 }
13225
13226 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13227   MachineFunction &MF = DAG.getMachineFunction();
13228   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13229
13230   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13231   SDLoc DL(Op);
13232
13233   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13234     // vastart just stores the address of the VarArgsFrameIndex slot into the
13235     // memory location argument.
13236     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13237                                    getPointerTy());
13238     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13239                         MachinePointerInfo(SV), false, false, 0);
13240   }
13241
13242   // __va_list_tag:
13243   //   gp_offset         (0 - 6 * 8)
13244   //   fp_offset         (48 - 48 + 8 * 16)
13245   //   overflow_arg_area (point to parameters coming in memory).
13246   //   reg_save_area
13247   SmallVector<SDValue, 8> MemOps;
13248   SDValue FIN = Op.getOperand(1);
13249   // Store gp_offset
13250   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13251                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13252                                                MVT::i32),
13253                                FIN, MachinePointerInfo(SV), false, false, 0);
13254   MemOps.push_back(Store);
13255
13256   // Store fp_offset
13257   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13258                     FIN, DAG.getIntPtrConstant(4));
13259   Store = DAG.getStore(Op.getOperand(0), DL,
13260                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13261                                        MVT::i32),
13262                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13263   MemOps.push_back(Store);
13264
13265   // Store ptr to overflow_arg_area
13266   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13267                     FIN, DAG.getIntPtrConstant(4));
13268   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13269                                     getPointerTy());
13270   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13271                        MachinePointerInfo(SV, 8),
13272                        false, false, 0);
13273   MemOps.push_back(Store);
13274
13275   // Store ptr to reg_save_area.
13276   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13277                     FIN, DAG.getIntPtrConstant(8));
13278   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13279                                     getPointerTy());
13280   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13281                        MachinePointerInfo(SV, 16), false, false, 0);
13282   MemOps.push_back(Store);
13283   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13284 }
13285
13286 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13287   assert(Subtarget->is64Bit() &&
13288          "LowerVAARG only handles 64-bit va_arg!");
13289   assert((Subtarget->isTargetLinux() ||
13290           Subtarget->isTargetDarwin()) &&
13291           "Unhandled target in LowerVAARG");
13292   assert(Op.getNode()->getNumOperands() == 4);
13293   SDValue Chain = Op.getOperand(0);
13294   SDValue SrcPtr = Op.getOperand(1);
13295   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13296   unsigned Align = Op.getConstantOperandVal(3);
13297   SDLoc dl(Op);
13298
13299   EVT ArgVT = Op.getNode()->getValueType(0);
13300   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13301   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13302   uint8_t ArgMode;
13303
13304   // Decide which area this value should be read from.
13305   // TODO: Implement the AMD64 ABI in its entirety. This simple
13306   // selection mechanism works only for the basic types.
13307   if (ArgVT == MVT::f80) {
13308     llvm_unreachable("va_arg for f80 not yet implemented");
13309   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13310     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13311   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13312     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13313   } else {
13314     llvm_unreachable("Unhandled argument type in LowerVAARG");
13315   }
13316
13317   if (ArgMode == 2) {
13318     // Sanity Check: Make sure using fp_offset makes sense.
13319     assert(!DAG.getTarget().Options.UseSoftFloat &&
13320            !(DAG.getMachineFunction()
13321                 .getFunction()->getAttributes()
13322                 .hasAttribute(AttributeSet::FunctionIndex,
13323                               Attribute::NoImplicitFloat)) &&
13324            Subtarget->hasSSE1());
13325   }
13326
13327   // Insert VAARG_64 node into the DAG
13328   // VAARG_64 returns two values: Variable Argument Address, Chain
13329   SmallVector<SDValue, 11> InstOps;
13330   InstOps.push_back(Chain);
13331   InstOps.push_back(SrcPtr);
13332   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13333   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13334   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13335   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13336   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13337                                           VTs, InstOps, MVT::i64,
13338                                           MachinePointerInfo(SV),
13339                                           /*Align=*/0,
13340                                           /*Volatile=*/false,
13341                                           /*ReadMem=*/true,
13342                                           /*WriteMem=*/true);
13343   Chain = VAARG.getValue(1);
13344
13345   // Load the next argument and return it
13346   return DAG.getLoad(ArgVT, dl,
13347                      Chain,
13348                      VAARG,
13349                      MachinePointerInfo(),
13350                      false, false, false, 0);
13351 }
13352
13353 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13354                            SelectionDAG &DAG) {
13355   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13356   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13357   SDValue Chain = Op.getOperand(0);
13358   SDValue DstPtr = Op.getOperand(1);
13359   SDValue SrcPtr = Op.getOperand(2);
13360   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13361   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13362   SDLoc DL(Op);
13363
13364   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13365                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13366                        false,
13367                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13368 }
13369
13370 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13371 // amount is a constant. Takes immediate version of shift as input.
13372 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13373                                           SDValue SrcOp, uint64_t ShiftAmt,
13374                                           SelectionDAG &DAG) {
13375   MVT ElementType = VT.getVectorElementType();
13376
13377   // Fold this packed shift into its first operand if ShiftAmt is 0.
13378   if (ShiftAmt == 0)
13379     return SrcOp;
13380
13381   // Check for ShiftAmt >= element width
13382   if (ShiftAmt >= ElementType.getSizeInBits()) {
13383     if (Opc == X86ISD::VSRAI)
13384       ShiftAmt = ElementType.getSizeInBits() - 1;
13385     else
13386       return DAG.getConstant(0, VT);
13387   }
13388
13389   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13390          && "Unknown target vector shift-by-constant node");
13391
13392   // Fold this packed vector shift into a build vector if SrcOp is a
13393   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13394   if (VT == SrcOp.getSimpleValueType() &&
13395       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13396     SmallVector<SDValue, 8> Elts;
13397     unsigned NumElts = SrcOp->getNumOperands();
13398     ConstantSDNode *ND;
13399
13400     switch(Opc) {
13401     default: llvm_unreachable(nullptr);
13402     case X86ISD::VSHLI:
13403       for (unsigned i=0; i!=NumElts; ++i) {
13404         SDValue CurrentOp = SrcOp->getOperand(i);
13405         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13406           Elts.push_back(CurrentOp);
13407           continue;
13408         }
13409         ND = cast<ConstantSDNode>(CurrentOp);
13410         const APInt &C = ND->getAPIntValue();
13411         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13412       }
13413       break;
13414     case X86ISD::VSRLI:
13415       for (unsigned i=0; i!=NumElts; ++i) {
13416         SDValue CurrentOp = SrcOp->getOperand(i);
13417         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13418           Elts.push_back(CurrentOp);
13419           continue;
13420         }
13421         ND = cast<ConstantSDNode>(CurrentOp);
13422         const APInt &C = ND->getAPIntValue();
13423         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13424       }
13425       break;
13426     case X86ISD::VSRAI:
13427       for (unsigned i=0; i!=NumElts; ++i) {
13428         SDValue CurrentOp = SrcOp->getOperand(i);
13429         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13430           Elts.push_back(CurrentOp);
13431           continue;
13432         }
13433         ND = cast<ConstantSDNode>(CurrentOp);
13434         const APInt &C = ND->getAPIntValue();
13435         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13436       }
13437       break;
13438     }
13439
13440     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13441   }
13442
13443   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13444 }
13445
13446 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13447 // may or may not be a constant. Takes immediate version of shift as input.
13448 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13449                                    SDValue SrcOp, SDValue ShAmt,
13450                                    SelectionDAG &DAG) {
13451   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13452
13453   // Catch shift-by-constant.
13454   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13455     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13456                                       CShAmt->getZExtValue(), DAG);
13457
13458   // Change opcode to non-immediate version
13459   switch (Opc) {
13460     default: llvm_unreachable("Unknown target vector shift node");
13461     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13462     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13463     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13464   }
13465
13466   // Need to build a vector containing shift amount
13467   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13468   SDValue ShOps[4];
13469   ShOps[0] = ShAmt;
13470   ShOps[1] = DAG.getConstant(0, MVT::i32);
13471   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13472   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13473
13474   // The return type has to be a 128-bit type with the same element
13475   // type as the input type.
13476   MVT EltVT = VT.getVectorElementType();
13477   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13478
13479   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13480   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13481 }
13482
13483 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13484   SDLoc dl(Op);
13485   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13486   switch (IntNo) {
13487   default: return SDValue();    // Don't custom lower most intrinsics.
13488   // Comparison intrinsics.
13489   case Intrinsic::x86_sse_comieq_ss:
13490   case Intrinsic::x86_sse_comilt_ss:
13491   case Intrinsic::x86_sse_comile_ss:
13492   case Intrinsic::x86_sse_comigt_ss:
13493   case Intrinsic::x86_sse_comige_ss:
13494   case Intrinsic::x86_sse_comineq_ss:
13495   case Intrinsic::x86_sse_ucomieq_ss:
13496   case Intrinsic::x86_sse_ucomilt_ss:
13497   case Intrinsic::x86_sse_ucomile_ss:
13498   case Intrinsic::x86_sse_ucomigt_ss:
13499   case Intrinsic::x86_sse_ucomige_ss:
13500   case Intrinsic::x86_sse_ucomineq_ss:
13501   case Intrinsic::x86_sse2_comieq_sd:
13502   case Intrinsic::x86_sse2_comilt_sd:
13503   case Intrinsic::x86_sse2_comile_sd:
13504   case Intrinsic::x86_sse2_comigt_sd:
13505   case Intrinsic::x86_sse2_comige_sd:
13506   case Intrinsic::x86_sse2_comineq_sd:
13507   case Intrinsic::x86_sse2_ucomieq_sd:
13508   case Intrinsic::x86_sse2_ucomilt_sd:
13509   case Intrinsic::x86_sse2_ucomile_sd:
13510   case Intrinsic::x86_sse2_ucomigt_sd:
13511   case Intrinsic::x86_sse2_ucomige_sd:
13512   case Intrinsic::x86_sse2_ucomineq_sd: {
13513     unsigned Opc;
13514     ISD::CondCode CC;
13515     switch (IntNo) {
13516     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13517     case Intrinsic::x86_sse_comieq_ss:
13518     case Intrinsic::x86_sse2_comieq_sd:
13519       Opc = X86ISD::COMI;
13520       CC = ISD::SETEQ;
13521       break;
13522     case Intrinsic::x86_sse_comilt_ss:
13523     case Intrinsic::x86_sse2_comilt_sd:
13524       Opc = X86ISD::COMI;
13525       CC = ISD::SETLT;
13526       break;
13527     case Intrinsic::x86_sse_comile_ss:
13528     case Intrinsic::x86_sse2_comile_sd:
13529       Opc = X86ISD::COMI;
13530       CC = ISD::SETLE;
13531       break;
13532     case Intrinsic::x86_sse_comigt_ss:
13533     case Intrinsic::x86_sse2_comigt_sd:
13534       Opc = X86ISD::COMI;
13535       CC = ISD::SETGT;
13536       break;
13537     case Intrinsic::x86_sse_comige_ss:
13538     case Intrinsic::x86_sse2_comige_sd:
13539       Opc = X86ISD::COMI;
13540       CC = ISD::SETGE;
13541       break;
13542     case Intrinsic::x86_sse_comineq_ss:
13543     case Intrinsic::x86_sse2_comineq_sd:
13544       Opc = X86ISD::COMI;
13545       CC = ISD::SETNE;
13546       break;
13547     case Intrinsic::x86_sse_ucomieq_ss:
13548     case Intrinsic::x86_sse2_ucomieq_sd:
13549       Opc = X86ISD::UCOMI;
13550       CC = ISD::SETEQ;
13551       break;
13552     case Intrinsic::x86_sse_ucomilt_ss:
13553     case Intrinsic::x86_sse2_ucomilt_sd:
13554       Opc = X86ISD::UCOMI;
13555       CC = ISD::SETLT;
13556       break;
13557     case Intrinsic::x86_sse_ucomile_ss:
13558     case Intrinsic::x86_sse2_ucomile_sd:
13559       Opc = X86ISD::UCOMI;
13560       CC = ISD::SETLE;
13561       break;
13562     case Intrinsic::x86_sse_ucomigt_ss:
13563     case Intrinsic::x86_sse2_ucomigt_sd:
13564       Opc = X86ISD::UCOMI;
13565       CC = ISD::SETGT;
13566       break;
13567     case Intrinsic::x86_sse_ucomige_ss:
13568     case Intrinsic::x86_sse2_ucomige_sd:
13569       Opc = X86ISD::UCOMI;
13570       CC = ISD::SETGE;
13571       break;
13572     case Intrinsic::x86_sse_ucomineq_ss:
13573     case Intrinsic::x86_sse2_ucomineq_sd:
13574       Opc = X86ISD::UCOMI;
13575       CC = ISD::SETNE;
13576       break;
13577     }
13578
13579     SDValue LHS = Op.getOperand(1);
13580     SDValue RHS = Op.getOperand(2);
13581     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13582     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13583     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13584     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13585                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13586     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13587   }
13588
13589   // Arithmetic intrinsics.
13590   case Intrinsic::x86_sse2_pmulu_dq:
13591   case Intrinsic::x86_avx2_pmulu_dq:
13592     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13593                        Op.getOperand(1), Op.getOperand(2));
13594
13595   case Intrinsic::x86_sse41_pmuldq:
13596   case Intrinsic::x86_avx2_pmul_dq:
13597     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13598                        Op.getOperand(1), Op.getOperand(2));
13599
13600   case Intrinsic::x86_sse2_pmulhu_w:
13601   case Intrinsic::x86_avx2_pmulhu_w:
13602     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13603                        Op.getOperand(1), Op.getOperand(2));
13604
13605   case Intrinsic::x86_sse2_pmulh_w:
13606   case Intrinsic::x86_avx2_pmulh_w:
13607     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13608                        Op.getOperand(1), Op.getOperand(2));
13609
13610   // SSE2/AVX2 sub with unsigned saturation intrinsics
13611   case Intrinsic::x86_sse2_psubus_b:
13612   case Intrinsic::x86_sse2_psubus_w:
13613   case Intrinsic::x86_avx2_psubus_b:
13614   case Intrinsic::x86_avx2_psubus_w:
13615     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13616                        Op.getOperand(1), Op.getOperand(2));
13617
13618   // SSE3/AVX horizontal add/sub intrinsics
13619   case Intrinsic::x86_sse3_hadd_ps:
13620   case Intrinsic::x86_sse3_hadd_pd:
13621   case Intrinsic::x86_avx_hadd_ps_256:
13622   case Intrinsic::x86_avx_hadd_pd_256:
13623   case Intrinsic::x86_sse3_hsub_ps:
13624   case Intrinsic::x86_sse3_hsub_pd:
13625   case Intrinsic::x86_avx_hsub_ps_256:
13626   case Intrinsic::x86_avx_hsub_pd_256:
13627   case Intrinsic::x86_ssse3_phadd_w_128:
13628   case Intrinsic::x86_ssse3_phadd_d_128:
13629   case Intrinsic::x86_avx2_phadd_w:
13630   case Intrinsic::x86_avx2_phadd_d:
13631   case Intrinsic::x86_ssse3_phsub_w_128:
13632   case Intrinsic::x86_ssse3_phsub_d_128:
13633   case Intrinsic::x86_avx2_phsub_w:
13634   case Intrinsic::x86_avx2_phsub_d: {
13635     unsigned Opcode;
13636     switch (IntNo) {
13637     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13638     case Intrinsic::x86_sse3_hadd_ps:
13639     case Intrinsic::x86_sse3_hadd_pd:
13640     case Intrinsic::x86_avx_hadd_ps_256:
13641     case Intrinsic::x86_avx_hadd_pd_256:
13642       Opcode = X86ISD::FHADD;
13643       break;
13644     case Intrinsic::x86_sse3_hsub_ps:
13645     case Intrinsic::x86_sse3_hsub_pd:
13646     case Intrinsic::x86_avx_hsub_ps_256:
13647     case Intrinsic::x86_avx_hsub_pd_256:
13648       Opcode = X86ISD::FHSUB;
13649       break;
13650     case Intrinsic::x86_ssse3_phadd_w_128:
13651     case Intrinsic::x86_ssse3_phadd_d_128:
13652     case Intrinsic::x86_avx2_phadd_w:
13653     case Intrinsic::x86_avx2_phadd_d:
13654       Opcode = X86ISD::HADD;
13655       break;
13656     case Intrinsic::x86_ssse3_phsub_w_128:
13657     case Intrinsic::x86_ssse3_phsub_d_128:
13658     case Intrinsic::x86_avx2_phsub_w:
13659     case Intrinsic::x86_avx2_phsub_d:
13660       Opcode = X86ISD::HSUB;
13661       break;
13662     }
13663     return DAG.getNode(Opcode, dl, Op.getValueType(),
13664                        Op.getOperand(1), Op.getOperand(2));
13665   }
13666
13667   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13668   case Intrinsic::x86_sse2_pmaxu_b:
13669   case Intrinsic::x86_sse41_pmaxuw:
13670   case Intrinsic::x86_sse41_pmaxud:
13671   case Intrinsic::x86_avx2_pmaxu_b:
13672   case Intrinsic::x86_avx2_pmaxu_w:
13673   case Intrinsic::x86_avx2_pmaxu_d:
13674   case Intrinsic::x86_sse2_pminu_b:
13675   case Intrinsic::x86_sse41_pminuw:
13676   case Intrinsic::x86_sse41_pminud:
13677   case Intrinsic::x86_avx2_pminu_b:
13678   case Intrinsic::x86_avx2_pminu_w:
13679   case Intrinsic::x86_avx2_pminu_d:
13680   case Intrinsic::x86_sse41_pmaxsb:
13681   case Intrinsic::x86_sse2_pmaxs_w:
13682   case Intrinsic::x86_sse41_pmaxsd:
13683   case Intrinsic::x86_avx2_pmaxs_b:
13684   case Intrinsic::x86_avx2_pmaxs_w:
13685   case Intrinsic::x86_avx2_pmaxs_d:
13686   case Intrinsic::x86_sse41_pminsb:
13687   case Intrinsic::x86_sse2_pmins_w:
13688   case Intrinsic::x86_sse41_pminsd:
13689   case Intrinsic::x86_avx2_pmins_b:
13690   case Intrinsic::x86_avx2_pmins_w:
13691   case Intrinsic::x86_avx2_pmins_d: {
13692     unsigned Opcode;
13693     switch (IntNo) {
13694     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13695     case Intrinsic::x86_sse2_pmaxu_b:
13696     case Intrinsic::x86_sse41_pmaxuw:
13697     case Intrinsic::x86_sse41_pmaxud:
13698     case Intrinsic::x86_avx2_pmaxu_b:
13699     case Intrinsic::x86_avx2_pmaxu_w:
13700     case Intrinsic::x86_avx2_pmaxu_d:
13701       Opcode = X86ISD::UMAX;
13702       break;
13703     case Intrinsic::x86_sse2_pminu_b:
13704     case Intrinsic::x86_sse41_pminuw:
13705     case Intrinsic::x86_sse41_pminud:
13706     case Intrinsic::x86_avx2_pminu_b:
13707     case Intrinsic::x86_avx2_pminu_w:
13708     case Intrinsic::x86_avx2_pminu_d:
13709       Opcode = X86ISD::UMIN;
13710       break;
13711     case Intrinsic::x86_sse41_pmaxsb:
13712     case Intrinsic::x86_sse2_pmaxs_w:
13713     case Intrinsic::x86_sse41_pmaxsd:
13714     case Intrinsic::x86_avx2_pmaxs_b:
13715     case Intrinsic::x86_avx2_pmaxs_w:
13716     case Intrinsic::x86_avx2_pmaxs_d:
13717       Opcode = X86ISD::SMAX;
13718       break;
13719     case Intrinsic::x86_sse41_pminsb:
13720     case Intrinsic::x86_sse2_pmins_w:
13721     case Intrinsic::x86_sse41_pminsd:
13722     case Intrinsic::x86_avx2_pmins_b:
13723     case Intrinsic::x86_avx2_pmins_w:
13724     case Intrinsic::x86_avx2_pmins_d:
13725       Opcode = X86ISD::SMIN;
13726       break;
13727     }
13728     return DAG.getNode(Opcode, dl, Op.getValueType(),
13729                        Op.getOperand(1), Op.getOperand(2));
13730   }
13731
13732   // SSE/SSE2/AVX floating point max/min intrinsics.
13733   case Intrinsic::x86_sse_max_ps:
13734   case Intrinsic::x86_sse2_max_pd:
13735   case Intrinsic::x86_avx_max_ps_256:
13736   case Intrinsic::x86_avx_max_pd_256:
13737   case Intrinsic::x86_sse_min_ps:
13738   case Intrinsic::x86_sse2_min_pd:
13739   case Intrinsic::x86_avx_min_ps_256:
13740   case Intrinsic::x86_avx_min_pd_256: {
13741     unsigned Opcode;
13742     switch (IntNo) {
13743     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13744     case Intrinsic::x86_sse_max_ps:
13745     case Intrinsic::x86_sse2_max_pd:
13746     case Intrinsic::x86_avx_max_ps_256:
13747     case Intrinsic::x86_avx_max_pd_256:
13748       Opcode = X86ISD::FMAX;
13749       break;
13750     case Intrinsic::x86_sse_min_ps:
13751     case Intrinsic::x86_sse2_min_pd:
13752     case Intrinsic::x86_avx_min_ps_256:
13753     case Intrinsic::x86_avx_min_pd_256:
13754       Opcode = X86ISD::FMIN;
13755       break;
13756     }
13757     return DAG.getNode(Opcode, dl, Op.getValueType(),
13758                        Op.getOperand(1), Op.getOperand(2));
13759   }
13760
13761   // AVX2 variable shift intrinsics
13762   case Intrinsic::x86_avx2_psllv_d:
13763   case Intrinsic::x86_avx2_psllv_q:
13764   case Intrinsic::x86_avx2_psllv_d_256:
13765   case Intrinsic::x86_avx2_psllv_q_256:
13766   case Intrinsic::x86_avx2_psrlv_d:
13767   case Intrinsic::x86_avx2_psrlv_q:
13768   case Intrinsic::x86_avx2_psrlv_d_256:
13769   case Intrinsic::x86_avx2_psrlv_q_256:
13770   case Intrinsic::x86_avx2_psrav_d:
13771   case Intrinsic::x86_avx2_psrav_d_256: {
13772     unsigned Opcode;
13773     switch (IntNo) {
13774     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13775     case Intrinsic::x86_avx2_psllv_d:
13776     case Intrinsic::x86_avx2_psllv_q:
13777     case Intrinsic::x86_avx2_psllv_d_256:
13778     case Intrinsic::x86_avx2_psllv_q_256:
13779       Opcode = ISD::SHL;
13780       break;
13781     case Intrinsic::x86_avx2_psrlv_d:
13782     case Intrinsic::x86_avx2_psrlv_q:
13783     case Intrinsic::x86_avx2_psrlv_d_256:
13784     case Intrinsic::x86_avx2_psrlv_q_256:
13785       Opcode = ISD::SRL;
13786       break;
13787     case Intrinsic::x86_avx2_psrav_d:
13788     case Intrinsic::x86_avx2_psrav_d_256:
13789       Opcode = ISD::SRA;
13790       break;
13791     }
13792     return DAG.getNode(Opcode, dl, Op.getValueType(),
13793                        Op.getOperand(1), Op.getOperand(2));
13794   }
13795
13796   case Intrinsic::x86_sse2_packssdw_128:
13797   case Intrinsic::x86_sse2_packsswb_128:
13798   case Intrinsic::x86_avx2_packssdw:
13799   case Intrinsic::x86_avx2_packsswb:
13800     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13801                        Op.getOperand(1), Op.getOperand(2));
13802
13803   case Intrinsic::x86_sse2_packuswb_128:
13804   case Intrinsic::x86_sse41_packusdw:
13805   case Intrinsic::x86_avx2_packuswb:
13806   case Intrinsic::x86_avx2_packusdw:
13807     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13808                        Op.getOperand(1), Op.getOperand(2));
13809
13810   case Intrinsic::x86_ssse3_pshuf_b_128:
13811   case Intrinsic::x86_avx2_pshuf_b:
13812     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13813                        Op.getOperand(1), Op.getOperand(2));
13814
13815   case Intrinsic::x86_sse2_pshuf_d:
13816     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13817                        Op.getOperand(1), Op.getOperand(2));
13818
13819   case Intrinsic::x86_sse2_pshufl_w:
13820     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13821                        Op.getOperand(1), Op.getOperand(2));
13822
13823   case Intrinsic::x86_sse2_pshufh_w:
13824     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13825                        Op.getOperand(1), Op.getOperand(2));
13826
13827   case Intrinsic::x86_ssse3_psign_b_128:
13828   case Intrinsic::x86_ssse3_psign_w_128:
13829   case Intrinsic::x86_ssse3_psign_d_128:
13830   case Intrinsic::x86_avx2_psign_b:
13831   case Intrinsic::x86_avx2_psign_w:
13832   case Intrinsic::x86_avx2_psign_d:
13833     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13834                        Op.getOperand(1), Op.getOperand(2));
13835
13836   case Intrinsic::x86_sse41_insertps:
13837     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13838                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13839
13840   case Intrinsic::x86_avx_vperm2f128_ps_256:
13841   case Intrinsic::x86_avx_vperm2f128_pd_256:
13842   case Intrinsic::x86_avx_vperm2f128_si_256:
13843   case Intrinsic::x86_avx2_vperm2i128:
13844     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13845                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13846
13847   case Intrinsic::x86_avx2_permd:
13848   case Intrinsic::x86_avx2_permps:
13849     // Operands intentionally swapped. Mask is last operand to intrinsic,
13850     // but second operand for node/instruction.
13851     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13852                        Op.getOperand(2), Op.getOperand(1));
13853
13854   case Intrinsic::x86_sse_sqrt_ps:
13855   case Intrinsic::x86_sse2_sqrt_pd:
13856   case Intrinsic::x86_avx_sqrt_ps_256:
13857   case Intrinsic::x86_avx_sqrt_pd_256:
13858     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13859
13860   // ptest and testp intrinsics. The intrinsic these come from are designed to
13861   // return an integer value, not just an instruction so lower it to the ptest
13862   // or testp pattern and a setcc for the result.
13863   case Intrinsic::x86_sse41_ptestz:
13864   case Intrinsic::x86_sse41_ptestc:
13865   case Intrinsic::x86_sse41_ptestnzc:
13866   case Intrinsic::x86_avx_ptestz_256:
13867   case Intrinsic::x86_avx_ptestc_256:
13868   case Intrinsic::x86_avx_ptestnzc_256:
13869   case Intrinsic::x86_avx_vtestz_ps:
13870   case Intrinsic::x86_avx_vtestc_ps:
13871   case Intrinsic::x86_avx_vtestnzc_ps:
13872   case Intrinsic::x86_avx_vtestz_pd:
13873   case Intrinsic::x86_avx_vtestc_pd:
13874   case Intrinsic::x86_avx_vtestnzc_pd:
13875   case Intrinsic::x86_avx_vtestz_ps_256:
13876   case Intrinsic::x86_avx_vtestc_ps_256:
13877   case Intrinsic::x86_avx_vtestnzc_ps_256:
13878   case Intrinsic::x86_avx_vtestz_pd_256:
13879   case Intrinsic::x86_avx_vtestc_pd_256:
13880   case Intrinsic::x86_avx_vtestnzc_pd_256: {
13881     bool IsTestPacked = false;
13882     unsigned X86CC;
13883     switch (IntNo) {
13884     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13885     case Intrinsic::x86_avx_vtestz_ps:
13886     case Intrinsic::x86_avx_vtestz_pd:
13887     case Intrinsic::x86_avx_vtestz_ps_256:
13888     case Intrinsic::x86_avx_vtestz_pd_256:
13889       IsTestPacked = true; // Fallthrough
13890     case Intrinsic::x86_sse41_ptestz:
13891     case Intrinsic::x86_avx_ptestz_256:
13892       // ZF = 1
13893       X86CC = X86::COND_E;
13894       break;
13895     case Intrinsic::x86_avx_vtestc_ps:
13896     case Intrinsic::x86_avx_vtestc_pd:
13897     case Intrinsic::x86_avx_vtestc_ps_256:
13898     case Intrinsic::x86_avx_vtestc_pd_256:
13899       IsTestPacked = true; // Fallthrough
13900     case Intrinsic::x86_sse41_ptestc:
13901     case Intrinsic::x86_avx_ptestc_256:
13902       // CF = 1
13903       X86CC = X86::COND_B;
13904       break;
13905     case Intrinsic::x86_avx_vtestnzc_ps:
13906     case Intrinsic::x86_avx_vtestnzc_pd:
13907     case Intrinsic::x86_avx_vtestnzc_ps_256:
13908     case Intrinsic::x86_avx_vtestnzc_pd_256:
13909       IsTestPacked = true; // Fallthrough
13910     case Intrinsic::x86_sse41_ptestnzc:
13911     case Intrinsic::x86_avx_ptestnzc_256:
13912       // ZF and CF = 0
13913       X86CC = X86::COND_A;
13914       break;
13915     }
13916
13917     SDValue LHS = Op.getOperand(1);
13918     SDValue RHS = Op.getOperand(2);
13919     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13920     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13921     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13922     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13923     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13924   }
13925   case Intrinsic::x86_avx512_kortestz_w:
13926   case Intrinsic::x86_avx512_kortestc_w: {
13927     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13928     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13929     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13930     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13931     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13932     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13933     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13934   }
13935
13936   // SSE/AVX shift intrinsics
13937   case Intrinsic::x86_sse2_psll_w:
13938   case Intrinsic::x86_sse2_psll_d:
13939   case Intrinsic::x86_sse2_psll_q:
13940   case Intrinsic::x86_avx2_psll_w:
13941   case Intrinsic::x86_avx2_psll_d:
13942   case Intrinsic::x86_avx2_psll_q:
13943   case Intrinsic::x86_sse2_psrl_w:
13944   case Intrinsic::x86_sse2_psrl_d:
13945   case Intrinsic::x86_sse2_psrl_q:
13946   case Intrinsic::x86_avx2_psrl_w:
13947   case Intrinsic::x86_avx2_psrl_d:
13948   case Intrinsic::x86_avx2_psrl_q:
13949   case Intrinsic::x86_sse2_psra_w:
13950   case Intrinsic::x86_sse2_psra_d:
13951   case Intrinsic::x86_avx2_psra_w:
13952   case Intrinsic::x86_avx2_psra_d: {
13953     unsigned Opcode;
13954     switch (IntNo) {
13955     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13956     case Intrinsic::x86_sse2_psll_w:
13957     case Intrinsic::x86_sse2_psll_d:
13958     case Intrinsic::x86_sse2_psll_q:
13959     case Intrinsic::x86_avx2_psll_w:
13960     case Intrinsic::x86_avx2_psll_d:
13961     case Intrinsic::x86_avx2_psll_q:
13962       Opcode = X86ISD::VSHL;
13963       break;
13964     case Intrinsic::x86_sse2_psrl_w:
13965     case Intrinsic::x86_sse2_psrl_d:
13966     case Intrinsic::x86_sse2_psrl_q:
13967     case Intrinsic::x86_avx2_psrl_w:
13968     case Intrinsic::x86_avx2_psrl_d:
13969     case Intrinsic::x86_avx2_psrl_q:
13970       Opcode = X86ISD::VSRL;
13971       break;
13972     case Intrinsic::x86_sse2_psra_w:
13973     case Intrinsic::x86_sse2_psra_d:
13974     case Intrinsic::x86_avx2_psra_w:
13975     case Intrinsic::x86_avx2_psra_d:
13976       Opcode = X86ISD::VSRA;
13977       break;
13978     }
13979     return DAG.getNode(Opcode, dl, Op.getValueType(),
13980                        Op.getOperand(1), Op.getOperand(2));
13981   }
13982
13983   // SSE/AVX immediate shift intrinsics
13984   case Intrinsic::x86_sse2_pslli_w:
13985   case Intrinsic::x86_sse2_pslli_d:
13986   case Intrinsic::x86_sse2_pslli_q:
13987   case Intrinsic::x86_avx2_pslli_w:
13988   case Intrinsic::x86_avx2_pslli_d:
13989   case Intrinsic::x86_avx2_pslli_q:
13990   case Intrinsic::x86_sse2_psrli_w:
13991   case Intrinsic::x86_sse2_psrli_d:
13992   case Intrinsic::x86_sse2_psrli_q:
13993   case Intrinsic::x86_avx2_psrli_w:
13994   case Intrinsic::x86_avx2_psrli_d:
13995   case Intrinsic::x86_avx2_psrli_q:
13996   case Intrinsic::x86_sse2_psrai_w:
13997   case Intrinsic::x86_sse2_psrai_d:
13998   case Intrinsic::x86_avx2_psrai_w:
13999   case Intrinsic::x86_avx2_psrai_d: {
14000     unsigned Opcode;
14001     switch (IntNo) {
14002     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14003     case Intrinsic::x86_sse2_pslli_w:
14004     case Intrinsic::x86_sse2_pslli_d:
14005     case Intrinsic::x86_sse2_pslli_q:
14006     case Intrinsic::x86_avx2_pslli_w:
14007     case Intrinsic::x86_avx2_pslli_d:
14008     case Intrinsic::x86_avx2_pslli_q:
14009       Opcode = X86ISD::VSHLI;
14010       break;
14011     case Intrinsic::x86_sse2_psrli_w:
14012     case Intrinsic::x86_sse2_psrli_d:
14013     case Intrinsic::x86_sse2_psrli_q:
14014     case Intrinsic::x86_avx2_psrli_w:
14015     case Intrinsic::x86_avx2_psrli_d:
14016     case Intrinsic::x86_avx2_psrli_q:
14017       Opcode = X86ISD::VSRLI;
14018       break;
14019     case Intrinsic::x86_sse2_psrai_w:
14020     case Intrinsic::x86_sse2_psrai_d:
14021     case Intrinsic::x86_avx2_psrai_w:
14022     case Intrinsic::x86_avx2_psrai_d:
14023       Opcode = X86ISD::VSRAI;
14024       break;
14025     }
14026     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14027                                Op.getOperand(1), Op.getOperand(2), DAG);
14028   }
14029
14030   case Intrinsic::x86_sse42_pcmpistria128:
14031   case Intrinsic::x86_sse42_pcmpestria128:
14032   case Intrinsic::x86_sse42_pcmpistric128:
14033   case Intrinsic::x86_sse42_pcmpestric128:
14034   case Intrinsic::x86_sse42_pcmpistrio128:
14035   case Intrinsic::x86_sse42_pcmpestrio128:
14036   case Intrinsic::x86_sse42_pcmpistris128:
14037   case Intrinsic::x86_sse42_pcmpestris128:
14038   case Intrinsic::x86_sse42_pcmpistriz128:
14039   case Intrinsic::x86_sse42_pcmpestriz128: {
14040     unsigned Opcode;
14041     unsigned X86CC;
14042     switch (IntNo) {
14043     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14044     case Intrinsic::x86_sse42_pcmpistria128:
14045       Opcode = X86ISD::PCMPISTRI;
14046       X86CC = X86::COND_A;
14047       break;
14048     case Intrinsic::x86_sse42_pcmpestria128:
14049       Opcode = X86ISD::PCMPESTRI;
14050       X86CC = X86::COND_A;
14051       break;
14052     case Intrinsic::x86_sse42_pcmpistric128:
14053       Opcode = X86ISD::PCMPISTRI;
14054       X86CC = X86::COND_B;
14055       break;
14056     case Intrinsic::x86_sse42_pcmpestric128:
14057       Opcode = X86ISD::PCMPESTRI;
14058       X86CC = X86::COND_B;
14059       break;
14060     case Intrinsic::x86_sse42_pcmpistrio128:
14061       Opcode = X86ISD::PCMPISTRI;
14062       X86CC = X86::COND_O;
14063       break;
14064     case Intrinsic::x86_sse42_pcmpestrio128:
14065       Opcode = X86ISD::PCMPESTRI;
14066       X86CC = X86::COND_O;
14067       break;
14068     case Intrinsic::x86_sse42_pcmpistris128:
14069       Opcode = X86ISD::PCMPISTRI;
14070       X86CC = X86::COND_S;
14071       break;
14072     case Intrinsic::x86_sse42_pcmpestris128:
14073       Opcode = X86ISD::PCMPESTRI;
14074       X86CC = X86::COND_S;
14075       break;
14076     case Intrinsic::x86_sse42_pcmpistriz128:
14077       Opcode = X86ISD::PCMPISTRI;
14078       X86CC = X86::COND_E;
14079       break;
14080     case Intrinsic::x86_sse42_pcmpestriz128:
14081       Opcode = X86ISD::PCMPESTRI;
14082       X86CC = X86::COND_E;
14083       break;
14084     }
14085     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14086     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14087     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14088     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14089                                 DAG.getConstant(X86CC, MVT::i8),
14090                                 SDValue(PCMP.getNode(), 1));
14091     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14092   }
14093
14094   case Intrinsic::x86_sse42_pcmpistri128:
14095   case Intrinsic::x86_sse42_pcmpestri128: {
14096     unsigned Opcode;
14097     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14098       Opcode = X86ISD::PCMPISTRI;
14099     else
14100       Opcode = X86ISD::PCMPESTRI;
14101
14102     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14103     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14104     return DAG.getNode(Opcode, dl, VTs, NewOps);
14105   }
14106   case Intrinsic::x86_fma_vfmadd_ps:
14107   case Intrinsic::x86_fma_vfmadd_pd:
14108   case Intrinsic::x86_fma_vfmsub_ps:
14109   case Intrinsic::x86_fma_vfmsub_pd:
14110   case Intrinsic::x86_fma_vfnmadd_ps:
14111   case Intrinsic::x86_fma_vfnmadd_pd:
14112   case Intrinsic::x86_fma_vfnmsub_ps:
14113   case Intrinsic::x86_fma_vfnmsub_pd:
14114   case Intrinsic::x86_fma_vfmaddsub_ps:
14115   case Intrinsic::x86_fma_vfmaddsub_pd:
14116   case Intrinsic::x86_fma_vfmsubadd_ps:
14117   case Intrinsic::x86_fma_vfmsubadd_pd:
14118   case Intrinsic::x86_fma_vfmadd_ps_256:
14119   case Intrinsic::x86_fma_vfmadd_pd_256:
14120   case Intrinsic::x86_fma_vfmsub_ps_256:
14121   case Intrinsic::x86_fma_vfmsub_pd_256:
14122   case Intrinsic::x86_fma_vfnmadd_ps_256:
14123   case Intrinsic::x86_fma_vfnmadd_pd_256:
14124   case Intrinsic::x86_fma_vfnmsub_ps_256:
14125   case Intrinsic::x86_fma_vfnmsub_pd_256:
14126   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14127   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14128   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14129   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14130   case Intrinsic::x86_fma_vfmadd_ps_512:
14131   case Intrinsic::x86_fma_vfmadd_pd_512:
14132   case Intrinsic::x86_fma_vfmsub_ps_512:
14133   case Intrinsic::x86_fma_vfmsub_pd_512:
14134   case Intrinsic::x86_fma_vfnmadd_ps_512:
14135   case Intrinsic::x86_fma_vfnmadd_pd_512:
14136   case Intrinsic::x86_fma_vfnmsub_ps_512:
14137   case Intrinsic::x86_fma_vfnmsub_pd_512:
14138   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14139   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14140   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14141   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14142     unsigned Opc;
14143     switch (IntNo) {
14144     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14145     case Intrinsic::x86_fma_vfmadd_ps:
14146     case Intrinsic::x86_fma_vfmadd_pd:
14147     case Intrinsic::x86_fma_vfmadd_ps_256:
14148     case Intrinsic::x86_fma_vfmadd_pd_256:
14149     case Intrinsic::x86_fma_vfmadd_ps_512:
14150     case Intrinsic::x86_fma_vfmadd_pd_512:
14151       Opc = X86ISD::FMADD;
14152       break;
14153     case Intrinsic::x86_fma_vfmsub_ps:
14154     case Intrinsic::x86_fma_vfmsub_pd:
14155     case Intrinsic::x86_fma_vfmsub_ps_256:
14156     case Intrinsic::x86_fma_vfmsub_pd_256:
14157     case Intrinsic::x86_fma_vfmsub_ps_512:
14158     case Intrinsic::x86_fma_vfmsub_pd_512:
14159       Opc = X86ISD::FMSUB;
14160       break;
14161     case Intrinsic::x86_fma_vfnmadd_ps:
14162     case Intrinsic::x86_fma_vfnmadd_pd:
14163     case Intrinsic::x86_fma_vfnmadd_ps_256:
14164     case Intrinsic::x86_fma_vfnmadd_pd_256:
14165     case Intrinsic::x86_fma_vfnmadd_ps_512:
14166     case Intrinsic::x86_fma_vfnmadd_pd_512:
14167       Opc = X86ISD::FNMADD;
14168       break;
14169     case Intrinsic::x86_fma_vfnmsub_ps:
14170     case Intrinsic::x86_fma_vfnmsub_pd:
14171     case Intrinsic::x86_fma_vfnmsub_ps_256:
14172     case Intrinsic::x86_fma_vfnmsub_pd_256:
14173     case Intrinsic::x86_fma_vfnmsub_ps_512:
14174     case Intrinsic::x86_fma_vfnmsub_pd_512:
14175       Opc = X86ISD::FNMSUB;
14176       break;
14177     case Intrinsic::x86_fma_vfmaddsub_ps:
14178     case Intrinsic::x86_fma_vfmaddsub_pd:
14179     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14180     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14181     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14182     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14183       Opc = X86ISD::FMADDSUB;
14184       break;
14185     case Intrinsic::x86_fma_vfmsubadd_ps:
14186     case Intrinsic::x86_fma_vfmsubadd_pd:
14187     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14188     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14189     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14190     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14191       Opc = X86ISD::FMSUBADD;
14192       break;
14193     }
14194
14195     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14196                        Op.getOperand(2), Op.getOperand(3));
14197   }
14198   }
14199 }
14200
14201 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14202                               SDValue Src, SDValue Mask, SDValue Base,
14203                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14204                               const X86Subtarget * Subtarget) {
14205   SDLoc dl(Op);
14206   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14207   assert(C && "Invalid scale type");
14208   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14209   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14210                              Index.getSimpleValueType().getVectorNumElements());
14211   SDValue MaskInReg;
14212   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14213   if (MaskC)
14214     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14215   else
14216     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14217   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14218   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14219   SDValue Segment = DAG.getRegister(0, MVT::i32);
14220   if (Src.getOpcode() == ISD::UNDEF)
14221     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14222   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14223   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14224   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14225   return DAG.getMergeValues(RetOps, dl);
14226 }
14227
14228 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14229                                SDValue Src, SDValue Mask, SDValue Base,
14230                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14231   SDLoc dl(Op);
14232   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14233   assert(C && "Invalid scale type");
14234   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14235   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14236   SDValue Segment = DAG.getRegister(0, MVT::i32);
14237   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14238                              Index.getSimpleValueType().getVectorNumElements());
14239   SDValue MaskInReg;
14240   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14241   if (MaskC)
14242     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14243   else
14244     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14245   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14246   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14247   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14248   return SDValue(Res, 1);
14249 }
14250
14251 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14252                                SDValue Mask, SDValue Base, SDValue Index,
14253                                SDValue ScaleOp, SDValue Chain) {
14254   SDLoc dl(Op);
14255   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14256   assert(C && "Invalid scale type");
14257   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14258   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14259   SDValue Segment = DAG.getRegister(0, MVT::i32);
14260   EVT MaskVT =
14261     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14262   SDValue MaskInReg;
14263   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14264   if (MaskC)
14265     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14266   else
14267     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14268   //SDVTList VTs = DAG.getVTList(MVT::Other);
14269   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14270   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14271   return SDValue(Res, 0);
14272 }
14273
14274 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14275 // read performance monitor counters (x86_rdpmc).
14276 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14277                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14278                               SmallVectorImpl<SDValue> &Results) {
14279   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14280   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14281   SDValue LO, HI;
14282
14283   // The ECX register is used to select the index of the performance counter
14284   // to read.
14285   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14286                                    N->getOperand(2));
14287   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14288
14289   // Reads the content of a 64-bit performance counter and returns it in the
14290   // registers EDX:EAX.
14291   if (Subtarget->is64Bit()) {
14292     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14293     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14294                             LO.getValue(2));
14295   } else {
14296     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14297     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14298                             LO.getValue(2));
14299   }
14300   Chain = HI.getValue(1);
14301
14302   if (Subtarget->is64Bit()) {
14303     // The EAX register is loaded with the low-order 32 bits. The EDX register
14304     // is loaded with the supported high-order bits of the counter.
14305     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14306                               DAG.getConstant(32, MVT::i8));
14307     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14308     Results.push_back(Chain);
14309     return;
14310   }
14311
14312   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14313   SDValue Ops[] = { LO, HI };
14314   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14315   Results.push_back(Pair);
14316   Results.push_back(Chain);
14317 }
14318
14319 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14320 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14321 // also used to custom lower READCYCLECOUNTER nodes.
14322 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14323                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14324                               SmallVectorImpl<SDValue> &Results) {
14325   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14326   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14327   SDValue LO, HI;
14328
14329   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14330   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14331   // and the EAX register is loaded with the low-order 32 bits.
14332   if (Subtarget->is64Bit()) {
14333     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14334     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14335                             LO.getValue(2));
14336   } else {
14337     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14338     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14339                             LO.getValue(2));
14340   }
14341   SDValue Chain = HI.getValue(1);
14342
14343   if (Opcode == X86ISD::RDTSCP_DAG) {
14344     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14345
14346     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14347     // the ECX register. Add 'ecx' explicitly to the chain.
14348     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14349                                      HI.getValue(2));
14350     // Explicitly store the content of ECX at the location passed in input
14351     // to the 'rdtscp' intrinsic.
14352     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14353                          MachinePointerInfo(), false, false, 0);
14354   }
14355
14356   if (Subtarget->is64Bit()) {
14357     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14358     // the EAX register is loaded with the low-order 32 bits.
14359     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14360                               DAG.getConstant(32, MVT::i8));
14361     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14362     Results.push_back(Chain);
14363     return;
14364   }
14365
14366   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14367   SDValue Ops[] = { LO, HI };
14368   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14369   Results.push_back(Pair);
14370   Results.push_back(Chain);
14371 }
14372
14373 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14374                                      SelectionDAG &DAG) {
14375   SmallVector<SDValue, 2> Results;
14376   SDLoc DL(Op);
14377   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14378                           Results);
14379   return DAG.getMergeValues(Results, DL);
14380 }
14381
14382 enum IntrinsicType {
14383   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14384 };
14385
14386 struct IntrinsicData {
14387   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14388     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14389   IntrinsicType Type;
14390   unsigned      Opc0;
14391   unsigned      Opc1;
14392 };
14393
14394 std::map < unsigned, IntrinsicData> IntrMap;
14395 static void InitIntinsicsMap() {
14396   static bool Initialized = false;
14397   if (Initialized) 
14398     return;
14399   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14400                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14401   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14402                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14403   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14404                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14405   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14406                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14407   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14408                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14409   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14410                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14411   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14412                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14413   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14414                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14415   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14416                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14417
14418   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14419                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14420   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14421                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14422   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14423                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14424   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14425                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14426   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14427                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14428   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14429                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14430   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14431                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14432   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14433                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14434    
14435   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14436                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14437                                                         X86::VGATHERPF1QPSm)));
14438   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14439                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14440                                                         X86::VGATHERPF1QPDm)));
14441   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14442                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14443                                                         X86::VGATHERPF1DPDm)));
14444   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14445                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14446                                                         X86::VGATHERPF1DPSm)));
14447   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14448                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14449                                                         X86::VSCATTERPF1QPSm)));
14450   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14451                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14452                                                         X86::VSCATTERPF1QPDm)));
14453   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14454                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14455                                                         X86::VSCATTERPF1DPDm)));
14456   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14457                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14458                                                         X86::VSCATTERPF1DPSm)));
14459   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14460                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14461   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14462                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14463   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14464                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14465   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14466                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14467   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14468                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14469   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14470                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14471   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14472                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14473   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14474                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14475   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14476                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14477   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14478                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14479   Initialized = true;
14480 }
14481
14482 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14483                                       SelectionDAG &DAG) {
14484   InitIntinsicsMap();
14485   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14486   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14487   if (itr == IntrMap.end())
14488     return SDValue();
14489
14490   SDLoc dl(Op);
14491   IntrinsicData Intr = itr->second;
14492   switch(Intr.Type) {
14493   case RDSEED:
14494   case RDRAND: {
14495     // Emit the node with the right value type.
14496     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14497     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14498
14499     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14500     // Otherwise return the value from Rand, which is always 0, casted to i32.
14501     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14502                       DAG.getConstant(1, Op->getValueType(1)),
14503                       DAG.getConstant(X86::COND_B, MVT::i32),
14504                       SDValue(Result.getNode(), 1) };
14505     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14506                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14507                                   Ops);
14508
14509     // Return { result, isValid, chain }.
14510     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14511                        SDValue(Result.getNode(), 2));
14512   }
14513   case GATHER: {
14514   //gather(v1, mask, index, base, scale);
14515     SDValue Chain = Op.getOperand(0);
14516     SDValue Src   = Op.getOperand(2);
14517     SDValue Base  = Op.getOperand(3);
14518     SDValue Index = Op.getOperand(4);
14519     SDValue Mask  = Op.getOperand(5);
14520     SDValue Scale = Op.getOperand(6);
14521     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14522                           Subtarget);
14523   }
14524   case SCATTER: {
14525   //scatter(base, mask, index, v1, scale);
14526     SDValue Chain = Op.getOperand(0);
14527     SDValue Base  = Op.getOperand(2);
14528     SDValue Mask  = Op.getOperand(3);
14529     SDValue Index = Op.getOperand(4);
14530     SDValue Src   = Op.getOperand(5);
14531     SDValue Scale = Op.getOperand(6);
14532     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14533   }
14534   case PREFETCH: {
14535     SDValue Hint = Op.getOperand(6);
14536     unsigned HintVal;
14537     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14538         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14539       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14540     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14541     SDValue Chain = Op.getOperand(0);
14542     SDValue Mask  = Op.getOperand(2);
14543     SDValue Index = Op.getOperand(3);
14544     SDValue Base  = Op.getOperand(4);
14545     SDValue Scale = Op.getOperand(5);
14546     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14547   }
14548   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14549   case RDTSC: {
14550     SmallVector<SDValue, 2> Results;
14551     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14552     return DAG.getMergeValues(Results, dl);
14553   }
14554   // Read Performance Monitoring Counters.
14555   case RDPMC: {
14556     SmallVector<SDValue, 2> Results;
14557     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14558     return DAG.getMergeValues(Results, dl);
14559   }
14560   // XTEST intrinsics.
14561   case XTEST: {
14562     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14563     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14564     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14565                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14566                                 InTrans);
14567     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14568     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14569                        Ret, SDValue(InTrans.getNode(), 1));
14570   }
14571   }
14572   llvm_unreachable("Unknown Intrinsic Type");
14573 }
14574
14575 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14576                                            SelectionDAG &DAG) const {
14577   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14578   MFI->setReturnAddressIsTaken(true);
14579
14580   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14581     return SDValue();
14582
14583   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14584   SDLoc dl(Op);
14585   EVT PtrVT = getPointerTy();
14586
14587   if (Depth > 0) {
14588     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14589     const X86RegisterInfo *RegInfo =
14590       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14591     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14592     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14593                        DAG.getNode(ISD::ADD, dl, PtrVT,
14594                                    FrameAddr, Offset),
14595                        MachinePointerInfo(), false, false, false, 0);
14596   }
14597
14598   // Just load the return address.
14599   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14600   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14601                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14602 }
14603
14604 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14605   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14606   MFI->setFrameAddressIsTaken(true);
14607
14608   EVT VT = Op.getValueType();
14609   SDLoc dl(Op);  // FIXME probably not meaningful
14610   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14611   const X86RegisterInfo *RegInfo =
14612     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14613   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14614   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14615           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14616          "Invalid Frame Register!");
14617   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14618   while (Depth--)
14619     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14620                             MachinePointerInfo(),
14621                             false, false, false, 0);
14622   return FrameAddr;
14623 }
14624
14625 // FIXME? Maybe this could be a TableGen attribute on some registers and
14626 // this table could be generated automatically from RegInfo.
14627 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14628                                               EVT VT) const {
14629   unsigned Reg = StringSwitch<unsigned>(RegName)
14630                        .Case("esp", X86::ESP)
14631                        .Case("rsp", X86::RSP)
14632                        .Default(0);
14633   if (Reg)
14634     return Reg;
14635   report_fatal_error("Invalid register name global variable");
14636 }
14637
14638 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14639                                                      SelectionDAG &DAG) const {
14640   const X86RegisterInfo *RegInfo =
14641     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14642   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14643 }
14644
14645 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14646   SDValue Chain     = Op.getOperand(0);
14647   SDValue Offset    = Op.getOperand(1);
14648   SDValue Handler   = Op.getOperand(2);
14649   SDLoc dl      (Op);
14650
14651   EVT PtrVT = getPointerTy();
14652   const X86RegisterInfo *RegInfo =
14653     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14654   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14655   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14656           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14657          "Invalid Frame Register!");
14658   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14659   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14660
14661   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14662                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14663   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14664   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14665                        false, false, 0);
14666   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14667
14668   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14669                      DAG.getRegister(StoreAddrReg, PtrVT));
14670 }
14671
14672 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14673                                                SelectionDAG &DAG) const {
14674   SDLoc DL(Op);
14675   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14676                      DAG.getVTList(MVT::i32, MVT::Other),
14677                      Op.getOperand(0), Op.getOperand(1));
14678 }
14679
14680 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14681                                                 SelectionDAG &DAG) const {
14682   SDLoc DL(Op);
14683   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14684                      Op.getOperand(0), Op.getOperand(1));
14685 }
14686
14687 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14688   return Op.getOperand(0);
14689 }
14690
14691 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14692                                                 SelectionDAG &DAG) const {
14693   SDValue Root = Op.getOperand(0);
14694   SDValue Trmp = Op.getOperand(1); // trampoline
14695   SDValue FPtr = Op.getOperand(2); // nested function
14696   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14697   SDLoc dl (Op);
14698
14699   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14700   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14701
14702   if (Subtarget->is64Bit()) {
14703     SDValue OutChains[6];
14704
14705     // Large code-model.
14706     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14707     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14708
14709     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14710     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14711
14712     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14713
14714     // Load the pointer to the nested function into R11.
14715     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14716     SDValue Addr = Trmp;
14717     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14718                                 Addr, MachinePointerInfo(TrmpAddr),
14719                                 false, false, 0);
14720
14721     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14722                        DAG.getConstant(2, MVT::i64));
14723     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14724                                 MachinePointerInfo(TrmpAddr, 2),
14725                                 false, false, 2);
14726
14727     // Load the 'nest' parameter value into R10.
14728     // R10 is specified in X86CallingConv.td
14729     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14730     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14731                        DAG.getConstant(10, MVT::i64));
14732     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14733                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14734                                 false, false, 0);
14735
14736     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14737                        DAG.getConstant(12, MVT::i64));
14738     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14739                                 MachinePointerInfo(TrmpAddr, 12),
14740                                 false, false, 2);
14741
14742     // Jump to the nested function.
14743     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14744     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14745                        DAG.getConstant(20, MVT::i64));
14746     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14747                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14748                                 false, false, 0);
14749
14750     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14751     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14752                        DAG.getConstant(22, MVT::i64));
14753     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14754                                 MachinePointerInfo(TrmpAddr, 22),
14755                                 false, false, 0);
14756
14757     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14758   } else {
14759     const Function *Func =
14760       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14761     CallingConv::ID CC = Func->getCallingConv();
14762     unsigned NestReg;
14763
14764     switch (CC) {
14765     default:
14766       llvm_unreachable("Unsupported calling convention");
14767     case CallingConv::C:
14768     case CallingConv::X86_StdCall: {
14769       // Pass 'nest' parameter in ECX.
14770       // Must be kept in sync with X86CallingConv.td
14771       NestReg = X86::ECX;
14772
14773       // Check that ECX wasn't needed by an 'inreg' parameter.
14774       FunctionType *FTy = Func->getFunctionType();
14775       const AttributeSet &Attrs = Func->getAttributes();
14776
14777       if (!Attrs.isEmpty() && !Func->isVarArg()) {
14778         unsigned InRegCount = 0;
14779         unsigned Idx = 1;
14780
14781         for (FunctionType::param_iterator I = FTy->param_begin(),
14782              E = FTy->param_end(); I != E; ++I, ++Idx)
14783           if (Attrs.hasAttribute(Idx, Attribute::InReg))
14784             // FIXME: should only count parameters that are lowered to integers.
14785             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14786
14787         if (InRegCount > 2) {
14788           report_fatal_error("Nest register in use - reduce number of inreg"
14789                              " parameters!");
14790         }
14791       }
14792       break;
14793     }
14794     case CallingConv::X86_FastCall:
14795     case CallingConv::X86_ThisCall:
14796     case CallingConv::Fast:
14797       // Pass 'nest' parameter in EAX.
14798       // Must be kept in sync with X86CallingConv.td
14799       NestReg = X86::EAX;
14800       break;
14801     }
14802
14803     SDValue OutChains[4];
14804     SDValue Addr, Disp;
14805
14806     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14807                        DAG.getConstant(10, MVT::i32));
14808     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14809
14810     // This is storing the opcode for MOV32ri.
14811     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14812     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14813     OutChains[0] = DAG.getStore(Root, dl,
14814                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14815                                 Trmp, MachinePointerInfo(TrmpAddr),
14816                                 false, false, 0);
14817
14818     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14819                        DAG.getConstant(1, MVT::i32));
14820     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14821                                 MachinePointerInfo(TrmpAddr, 1),
14822                                 false, false, 1);
14823
14824     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14825     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14826                        DAG.getConstant(5, MVT::i32));
14827     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14828                                 MachinePointerInfo(TrmpAddr, 5),
14829                                 false, false, 1);
14830
14831     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14832                        DAG.getConstant(6, MVT::i32));
14833     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14834                                 MachinePointerInfo(TrmpAddr, 6),
14835                                 false, false, 1);
14836
14837     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14838   }
14839 }
14840
14841 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14842                                             SelectionDAG &DAG) const {
14843   /*
14844    The rounding mode is in bits 11:10 of FPSR, and has the following
14845    settings:
14846      00 Round to nearest
14847      01 Round to -inf
14848      10 Round to +inf
14849      11 Round to 0
14850
14851   FLT_ROUNDS, on the other hand, expects the following:
14852     -1 Undefined
14853      0 Round to 0
14854      1 Round to nearest
14855      2 Round to +inf
14856      3 Round to -inf
14857
14858   To perform the conversion, we do:
14859     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14860   */
14861
14862   MachineFunction &MF = DAG.getMachineFunction();
14863   const TargetMachine &TM = MF.getTarget();
14864   const TargetFrameLowering &TFI = *TM.getFrameLowering();
14865   unsigned StackAlignment = TFI.getStackAlignment();
14866   MVT VT = Op.getSimpleValueType();
14867   SDLoc DL(Op);
14868
14869   // Save FP Control Word to stack slot
14870   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14871   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14872
14873   MachineMemOperand *MMO =
14874    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14875                            MachineMemOperand::MOStore, 2, 2);
14876
14877   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14878   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14879                                           DAG.getVTList(MVT::Other),
14880                                           Ops, MVT::i16, MMO);
14881
14882   // Load FP Control Word from stack slot
14883   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14884                             MachinePointerInfo(), false, false, false, 0);
14885
14886   // Transform as necessary
14887   SDValue CWD1 =
14888     DAG.getNode(ISD::SRL, DL, MVT::i16,
14889                 DAG.getNode(ISD::AND, DL, MVT::i16,
14890                             CWD, DAG.getConstant(0x800, MVT::i16)),
14891                 DAG.getConstant(11, MVT::i8));
14892   SDValue CWD2 =
14893     DAG.getNode(ISD::SRL, DL, MVT::i16,
14894                 DAG.getNode(ISD::AND, DL, MVT::i16,
14895                             CWD, DAG.getConstant(0x400, MVT::i16)),
14896                 DAG.getConstant(9, MVT::i8));
14897
14898   SDValue RetVal =
14899     DAG.getNode(ISD::AND, DL, MVT::i16,
14900                 DAG.getNode(ISD::ADD, DL, MVT::i16,
14901                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14902                             DAG.getConstant(1, MVT::i16)),
14903                 DAG.getConstant(3, MVT::i16));
14904
14905   return DAG.getNode((VT.getSizeInBits() < 16 ?
14906                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14907 }
14908
14909 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14910   MVT VT = Op.getSimpleValueType();
14911   EVT OpVT = VT;
14912   unsigned NumBits = VT.getSizeInBits();
14913   SDLoc dl(Op);
14914
14915   Op = Op.getOperand(0);
14916   if (VT == MVT::i8) {
14917     // Zero extend to i32 since there is not an i8 bsr.
14918     OpVT = MVT::i32;
14919     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14920   }
14921
14922   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14923   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14924   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14925
14926   // If src is zero (i.e. bsr sets ZF), returns NumBits.
14927   SDValue Ops[] = {
14928     Op,
14929     DAG.getConstant(NumBits+NumBits-1, OpVT),
14930     DAG.getConstant(X86::COND_E, MVT::i8),
14931     Op.getValue(1)
14932   };
14933   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14934
14935   // Finally xor with NumBits-1.
14936   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14937
14938   if (VT == MVT::i8)
14939     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14940   return Op;
14941 }
14942
14943 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14944   MVT VT = Op.getSimpleValueType();
14945   EVT OpVT = VT;
14946   unsigned NumBits = VT.getSizeInBits();
14947   SDLoc dl(Op);
14948
14949   Op = Op.getOperand(0);
14950   if (VT == MVT::i8) {
14951     // Zero extend to i32 since there is not an i8 bsr.
14952     OpVT = MVT::i32;
14953     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14954   }
14955
14956   // Issue a bsr (scan bits in reverse).
14957   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14958   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14959
14960   // And xor with NumBits-1.
14961   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14962
14963   if (VT == MVT::i8)
14964     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14965   return Op;
14966 }
14967
14968 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14969   MVT VT = Op.getSimpleValueType();
14970   unsigned NumBits = VT.getSizeInBits();
14971   SDLoc dl(Op);
14972   Op = Op.getOperand(0);
14973
14974   // Issue a bsf (scan bits forward) which also sets EFLAGS.
14975   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14976   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14977
14978   // If src is zero (i.e. bsf sets ZF), returns NumBits.
14979   SDValue Ops[] = {
14980     Op,
14981     DAG.getConstant(NumBits, VT),
14982     DAG.getConstant(X86::COND_E, MVT::i8),
14983     Op.getValue(1)
14984   };
14985   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14986 }
14987
14988 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14989 // ones, and then concatenate the result back.
14990 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14991   MVT VT = Op.getSimpleValueType();
14992
14993   assert(VT.is256BitVector() && VT.isInteger() &&
14994          "Unsupported value type for operation");
14995
14996   unsigned NumElems = VT.getVectorNumElements();
14997   SDLoc dl(Op);
14998
14999   // Extract the LHS vectors
15000   SDValue LHS = Op.getOperand(0);
15001   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15002   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15003
15004   // Extract the RHS vectors
15005   SDValue RHS = Op.getOperand(1);
15006   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15007   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15008
15009   MVT EltVT = VT.getVectorElementType();
15010   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15011
15012   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15013                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15014                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15015 }
15016
15017 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15018   assert(Op.getSimpleValueType().is256BitVector() &&
15019          Op.getSimpleValueType().isInteger() &&
15020          "Only handle AVX 256-bit vector integer operation");
15021   return Lower256IntArith(Op, DAG);
15022 }
15023
15024 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15025   assert(Op.getSimpleValueType().is256BitVector() &&
15026          Op.getSimpleValueType().isInteger() &&
15027          "Only handle AVX 256-bit vector integer operation");
15028   return Lower256IntArith(Op, DAG);
15029 }
15030
15031 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15032                         SelectionDAG &DAG) {
15033   SDLoc dl(Op);
15034   MVT VT = Op.getSimpleValueType();
15035
15036   // Decompose 256-bit ops into smaller 128-bit ops.
15037   if (VT.is256BitVector() && !Subtarget->hasInt256())
15038     return Lower256IntArith(Op, DAG);
15039
15040   SDValue A = Op.getOperand(0);
15041   SDValue B = Op.getOperand(1);
15042
15043   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15044   if (VT == MVT::v4i32) {
15045     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15046            "Should not custom lower when pmuldq is available!");
15047
15048     // Extract the odd parts.
15049     static const int UnpackMask[] = { 1, -1, 3, -1 };
15050     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15051     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15052
15053     // Multiply the even parts.
15054     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15055     // Now multiply odd parts.
15056     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15057
15058     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15059     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15060
15061     // Merge the two vectors back together with a shuffle. This expands into 2
15062     // shuffles.
15063     static const int ShufMask[] = { 0, 4, 2, 6 };
15064     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15065   }
15066
15067   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15068          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15069
15070   //  Ahi = psrlqi(a, 32);
15071   //  Bhi = psrlqi(b, 32);
15072   //
15073   //  AloBlo = pmuludq(a, b);
15074   //  AloBhi = pmuludq(a, Bhi);
15075   //  AhiBlo = pmuludq(Ahi, b);
15076
15077   //  AloBhi = psllqi(AloBhi, 32);
15078   //  AhiBlo = psllqi(AhiBlo, 32);
15079   //  return AloBlo + AloBhi + AhiBlo;
15080
15081   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15082   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15083
15084   // Bit cast to 32-bit vectors for MULUDQ
15085   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15086                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15087   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15088   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15089   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15090   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15091
15092   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15093   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15094   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15095
15096   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15097   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15098
15099   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15100   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15101 }
15102
15103 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15104   assert(Subtarget->isTargetWin64() && "Unexpected target");
15105   EVT VT = Op.getValueType();
15106   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15107          "Unexpected return type for lowering");
15108
15109   RTLIB::Libcall LC;
15110   bool isSigned;
15111   switch (Op->getOpcode()) {
15112   default: llvm_unreachable("Unexpected request for libcall!");
15113   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15114   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15115   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15116   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15117   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15118   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15119   }
15120
15121   SDLoc dl(Op);
15122   SDValue InChain = DAG.getEntryNode();
15123
15124   TargetLowering::ArgListTy Args;
15125   TargetLowering::ArgListEntry Entry;
15126   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15127     EVT ArgVT = Op->getOperand(i).getValueType();
15128     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15129            "Unexpected argument type for lowering");
15130     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15131     Entry.Node = StackPtr;
15132     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15133                            false, false, 16);
15134     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15135     Entry.Ty = PointerType::get(ArgTy,0);
15136     Entry.isSExt = false;
15137     Entry.isZExt = false;
15138     Args.push_back(Entry);
15139   }
15140
15141   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15142                                          getPointerTy());
15143
15144   TargetLowering::CallLoweringInfo CLI(DAG);
15145   CLI.setDebugLoc(dl).setChain(InChain)
15146     .setCallee(getLibcallCallingConv(LC),
15147                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15148                Callee, std::move(Args), 0)
15149     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15150
15151   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15152   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15153 }
15154
15155 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15156                              SelectionDAG &DAG) {
15157   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15158   EVT VT = Op0.getValueType();
15159   SDLoc dl(Op);
15160
15161   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15162          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15163
15164   // PMULxD operations multiply each even value (starting at 0) of LHS with
15165   // the related value of RHS and produce a widen result.
15166   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15167   // => <2 x i64> <ae|cg>
15168   //
15169   // In other word, to have all the results, we need to perform two PMULxD:
15170   // 1. one with the even values.
15171   // 2. one with the odd values.
15172   // To achieve #2, with need to place the odd values at an even position.
15173   //
15174   // Place the odd value at an even position (basically, shift all values 1
15175   // step to the left):
15176   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15177   // <a|b|c|d> => <b|undef|d|undef>
15178   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15179   // <e|f|g|h> => <f|undef|h|undef>
15180   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15181
15182   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15183   // ints.
15184   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15185   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15186   unsigned Opcode =
15187       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15188   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15189   // => <2 x i64> <ae|cg>
15190   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15191                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15192   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15193   // => <2 x i64> <bf|dh>
15194   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15195                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15196
15197   // Shuffle it back into the right order.
15198   // The internal representation is big endian.
15199   // In other words, a i64 bitcasted to 2 x i32 has its high part at index 0
15200   // and its low part at index 1.
15201   // Moreover, we have: Mul1 = <ae|cg> ; Mul2 = <bf|dh>
15202   // Vector index                0 1   ;          2 3
15203   // We want      <ae|bf|cg|dh>
15204   // Vector index   0  2  1  3
15205   // Since each element is seen as 2 x i32, we get:
15206   // high_mask[i] = 2 x vector_index[i]
15207   // low_mask[i] = 2 x vector_index[i] + 1
15208   // where vector_index = {0, Size/2, 1, Size/2 + 1, ...,
15209   //                       Size/2 - 1, Size/2 + Size/2 - 1}
15210   // where Size is the number of element of the final vector.
15211   SDValue Highs, Lows;
15212   if (VT == MVT::v8i32) {
15213     const int HighMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15214     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15215     const int LowMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15216     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15217   } else {
15218     const int HighMask[] = {0, 4, 2, 6};
15219     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15220     const int LowMask[] = {1, 5, 3, 7};
15221     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15222   }
15223
15224   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15225   // unsigned multiply.
15226   if (IsSigned && !Subtarget->hasSSE41()) {
15227     SDValue ShAmt =
15228         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15229     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15230                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15231     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15232                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15233
15234     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15235     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15236   }
15237
15238   // The low part of a MUL_LOHI is supposed to be the first value and the
15239   // high part the second value.
15240   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Lows, Highs);
15241 }
15242
15243 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15244                                          const X86Subtarget *Subtarget) {
15245   MVT VT = Op.getSimpleValueType();
15246   SDLoc dl(Op);
15247   SDValue R = Op.getOperand(0);
15248   SDValue Amt = Op.getOperand(1);
15249
15250   // Optimize shl/srl/sra with constant shift amount.
15251   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15252     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15253       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15254
15255       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15256           (Subtarget->hasInt256() &&
15257            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15258           (Subtarget->hasAVX512() &&
15259            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15260         if (Op.getOpcode() == ISD::SHL)
15261           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15262                                             DAG);
15263         if (Op.getOpcode() == ISD::SRL)
15264           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15265                                             DAG);
15266         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15267           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15268                                             DAG);
15269       }
15270
15271       if (VT == MVT::v16i8) {
15272         if (Op.getOpcode() == ISD::SHL) {
15273           // Make a large shift.
15274           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15275                                                    MVT::v8i16, R, ShiftAmt,
15276                                                    DAG);
15277           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15278           // Zero out the rightmost bits.
15279           SmallVector<SDValue, 16> V(16,
15280                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15281                                                      MVT::i8));
15282           return DAG.getNode(ISD::AND, dl, VT, SHL,
15283                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15284         }
15285         if (Op.getOpcode() == ISD::SRL) {
15286           // Make a large shift.
15287           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15288                                                    MVT::v8i16, R, ShiftAmt,
15289                                                    DAG);
15290           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15291           // Zero out the leftmost bits.
15292           SmallVector<SDValue, 16> V(16,
15293                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15294                                                      MVT::i8));
15295           return DAG.getNode(ISD::AND, dl, VT, SRL,
15296                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15297         }
15298         if (Op.getOpcode() == ISD::SRA) {
15299           if (ShiftAmt == 7) {
15300             // R s>> 7  ===  R s< 0
15301             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15302             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15303           }
15304
15305           // R s>> a === ((R u>> a) ^ m) - m
15306           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15307           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15308                                                          MVT::i8));
15309           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15310           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15311           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15312           return Res;
15313         }
15314         llvm_unreachable("Unknown shift opcode.");
15315       }
15316
15317       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15318         if (Op.getOpcode() == ISD::SHL) {
15319           // Make a large shift.
15320           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15321                                                    MVT::v16i16, R, ShiftAmt,
15322                                                    DAG);
15323           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15324           // Zero out the rightmost bits.
15325           SmallVector<SDValue, 32> V(32,
15326                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15327                                                      MVT::i8));
15328           return DAG.getNode(ISD::AND, dl, VT, SHL,
15329                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15330         }
15331         if (Op.getOpcode() == ISD::SRL) {
15332           // Make a large shift.
15333           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15334                                                    MVT::v16i16, R, ShiftAmt,
15335                                                    DAG);
15336           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15337           // Zero out the leftmost bits.
15338           SmallVector<SDValue, 32> V(32,
15339                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15340                                                      MVT::i8));
15341           return DAG.getNode(ISD::AND, dl, VT, SRL,
15342                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15343         }
15344         if (Op.getOpcode() == ISD::SRA) {
15345           if (ShiftAmt == 7) {
15346             // R s>> 7  ===  R s< 0
15347             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15348             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15349           }
15350
15351           // R s>> a === ((R u>> a) ^ m) - m
15352           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15353           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15354                                                          MVT::i8));
15355           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15356           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15357           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15358           return Res;
15359         }
15360         llvm_unreachable("Unknown shift opcode.");
15361       }
15362     }
15363   }
15364
15365   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15366   if (!Subtarget->is64Bit() &&
15367       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15368       Amt.getOpcode() == ISD::BITCAST &&
15369       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15370     Amt = Amt.getOperand(0);
15371     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15372                      VT.getVectorNumElements();
15373     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15374     uint64_t ShiftAmt = 0;
15375     for (unsigned i = 0; i != Ratio; ++i) {
15376       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15377       if (!C)
15378         return SDValue();
15379       // 6 == Log2(64)
15380       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15381     }
15382     // Check remaining shift amounts.
15383     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15384       uint64_t ShAmt = 0;
15385       for (unsigned j = 0; j != Ratio; ++j) {
15386         ConstantSDNode *C =
15387           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15388         if (!C)
15389           return SDValue();
15390         // 6 == Log2(64)
15391         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15392       }
15393       if (ShAmt != ShiftAmt)
15394         return SDValue();
15395     }
15396     switch (Op.getOpcode()) {
15397     default:
15398       llvm_unreachable("Unknown shift opcode!");
15399     case ISD::SHL:
15400       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15401                                         DAG);
15402     case ISD::SRL:
15403       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15404                                         DAG);
15405     case ISD::SRA:
15406       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15407                                         DAG);
15408     }
15409   }
15410
15411   return SDValue();
15412 }
15413
15414 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15415                                         const X86Subtarget* Subtarget) {
15416   MVT VT = Op.getSimpleValueType();
15417   SDLoc dl(Op);
15418   SDValue R = Op.getOperand(0);
15419   SDValue Amt = Op.getOperand(1);
15420
15421   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15422       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15423       (Subtarget->hasInt256() &&
15424        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15425         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15426        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15427     SDValue BaseShAmt;
15428     EVT EltVT = VT.getVectorElementType();
15429
15430     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15431       unsigned NumElts = VT.getVectorNumElements();
15432       unsigned i, j;
15433       for (i = 0; i != NumElts; ++i) {
15434         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15435           continue;
15436         break;
15437       }
15438       for (j = i; j != NumElts; ++j) {
15439         SDValue Arg = Amt.getOperand(j);
15440         if (Arg.getOpcode() == ISD::UNDEF) continue;
15441         if (Arg != Amt.getOperand(i))
15442           break;
15443       }
15444       if (i != NumElts && j == NumElts)
15445         BaseShAmt = Amt.getOperand(i);
15446     } else {
15447       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15448         Amt = Amt.getOperand(0);
15449       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15450                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15451         SDValue InVec = Amt.getOperand(0);
15452         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15453           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15454           unsigned i = 0;
15455           for (; i != NumElts; ++i) {
15456             SDValue Arg = InVec.getOperand(i);
15457             if (Arg.getOpcode() == ISD::UNDEF) continue;
15458             BaseShAmt = Arg;
15459             break;
15460           }
15461         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15462            if (ConstantSDNode *C =
15463                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15464              unsigned SplatIdx =
15465                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15466              if (C->getZExtValue() == SplatIdx)
15467                BaseShAmt = InVec.getOperand(1);
15468            }
15469         }
15470         if (!BaseShAmt.getNode())
15471           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15472                                   DAG.getIntPtrConstant(0));
15473       }
15474     }
15475
15476     if (BaseShAmt.getNode()) {
15477       if (EltVT.bitsGT(MVT::i32))
15478         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15479       else if (EltVT.bitsLT(MVT::i32))
15480         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15481
15482       switch (Op.getOpcode()) {
15483       default:
15484         llvm_unreachable("Unknown shift opcode!");
15485       case ISD::SHL:
15486         switch (VT.SimpleTy) {
15487         default: return SDValue();
15488         case MVT::v2i64:
15489         case MVT::v4i32:
15490         case MVT::v8i16:
15491         case MVT::v4i64:
15492         case MVT::v8i32:
15493         case MVT::v16i16:
15494         case MVT::v16i32:
15495         case MVT::v8i64:
15496           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15497         }
15498       case ISD::SRA:
15499         switch (VT.SimpleTy) {
15500         default: return SDValue();
15501         case MVT::v4i32:
15502         case MVT::v8i16:
15503         case MVT::v8i32:
15504         case MVT::v16i16:
15505         case MVT::v16i32:
15506         case MVT::v8i64:
15507           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15508         }
15509       case ISD::SRL:
15510         switch (VT.SimpleTy) {
15511         default: return SDValue();
15512         case MVT::v2i64:
15513         case MVT::v4i32:
15514         case MVT::v8i16:
15515         case MVT::v4i64:
15516         case MVT::v8i32:
15517         case MVT::v16i16:
15518         case MVT::v16i32:
15519         case MVT::v8i64:
15520           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15521         }
15522       }
15523     }
15524   }
15525
15526   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15527   if (!Subtarget->is64Bit() &&
15528       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15529       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15530       Amt.getOpcode() == ISD::BITCAST &&
15531       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15532     Amt = Amt.getOperand(0);
15533     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15534                      VT.getVectorNumElements();
15535     std::vector<SDValue> Vals(Ratio);
15536     for (unsigned i = 0; i != Ratio; ++i)
15537       Vals[i] = Amt.getOperand(i);
15538     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15539       for (unsigned j = 0; j != Ratio; ++j)
15540         if (Vals[j] != Amt.getOperand(i + j))
15541           return SDValue();
15542     }
15543     switch (Op.getOpcode()) {
15544     default:
15545       llvm_unreachable("Unknown shift opcode!");
15546     case ISD::SHL:
15547       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15548     case ISD::SRL:
15549       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15550     case ISD::SRA:
15551       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15552     }
15553   }
15554
15555   return SDValue();
15556 }
15557
15558 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15559                           SelectionDAG &DAG) {
15560   MVT VT = Op.getSimpleValueType();
15561   SDLoc dl(Op);
15562   SDValue R = Op.getOperand(0);
15563   SDValue Amt = Op.getOperand(1);
15564   SDValue V;
15565
15566   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15567   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15568
15569   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15570   if (V.getNode())
15571     return V;
15572
15573   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15574   if (V.getNode())
15575       return V;
15576
15577   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15578     return Op;
15579   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15580   if (Subtarget->hasInt256()) {
15581     if (Op.getOpcode() == ISD::SRL &&
15582         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15583          VT == MVT::v4i64 || VT == MVT::v8i32))
15584       return Op;
15585     if (Op.getOpcode() == ISD::SHL &&
15586         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15587          VT == MVT::v4i64 || VT == MVT::v8i32))
15588       return Op;
15589     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15590       return Op;
15591   }
15592
15593   // If possible, lower this packed shift into a vector multiply instead of
15594   // expanding it into a sequence of scalar shifts.
15595   // Do this only if the vector shift count is a constant build_vector.
15596   if (Op.getOpcode() == ISD::SHL && 
15597       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15598        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15599       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15600     SmallVector<SDValue, 8> Elts;
15601     EVT SVT = VT.getScalarType();
15602     unsigned SVTBits = SVT.getSizeInBits();
15603     const APInt &One = APInt(SVTBits, 1);
15604     unsigned NumElems = VT.getVectorNumElements();
15605
15606     for (unsigned i=0; i !=NumElems; ++i) {
15607       SDValue Op = Amt->getOperand(i);
15608       if (Op->getOpcode() == ISD::UNDEF) {
15609         Elts.push_back(Op);
15610         continue;
15611       }
15612
15613       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15614       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15615       uint64_t ShAmt = C.getZExtValue();
15616       if (ShAmt >= SVTBits) {
15617         Elts.push_back(DAG.getUNDEF(SVT));
15618         continue;
15619       }
15620       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15621     }
15622     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15623     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15624   }
15625
15626   // Lower SHL with variable shift amount.
15627   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15628     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15629
15630     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15631     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15632     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15633     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15634   }
15635
15636   // If possible, lower this shift as a sequence of two shifts by
15637   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15638   // Example:
15639   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15640   //
15641   // Could be rewritten as:
15642   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15643   //
15644   // The advantage is that the two shifts from the example would be
15645   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15646   // the vector shift into four scalar shifts plus four pairs of vector
15647   // insert/extract.
15648   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15649       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15650     unsigned TargetOpcode = X86ISD::MOVSS;
15651     bool CanBeSimplified;
15652     // The splat value for the first packed shift (the 'X' from the example).
15653     SDValue Amt1 = Amt->getOperand(0);
15654     // The splat value for the second packed shift (the 'Y' from the example).
15655     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15656                                         Amt->getOperand(2);
15657
15658     // See if it is possible to replace this node with a sequence of
15659     // two shifts followed by a MOVSS/MOVSD
15660     if (VT == MVT::v4i32) {
15661       // Check if it is legal to use a MOVSS.
15662       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15663                         Amt2 == Amt->getOperand(3);
15664       if (!CanBeSimplified) {
15665         // Otherwise, check if we can still simplify this node using a MOVSD.
15666         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15667                           Amt->getOperand(2) == Amt->getOperand(3);
15668         TargetOpcode = X86ISD::MOVSD;
15669         Amt2 = Amt->getOperand(2);
15670       }
15671     } else {
15672       // Do similar checks for the case where the machine value type
15673       // is MVT::v8i16.
15674       CanBeSimplified = Amt1 == Amt->getOperand(1);
15675       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15676         CanBeSimplified = Amt2 == Amt->getOperand(i);
15677
15678       if (!CanBeSimplified) {
15679         TargetOpcode = X86ISD::MOVSD;
15680         CanBeSimplified = true;
15681         Amt2 = Amt->getOperand(4);
15682         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15683           CanBeSimplified = Amt1 == Amt->getOperand(i);
15684         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15685           CanBeSimplified = Amt2 == Amt->getOperand(j);
15686       }
15687     }
15688     
15689     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15690         isa<ConstantSDNode>(Amt2)) {
15691       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15692       EVT CastVT = MVT::v4i32;
15693       SDValue Splat1 = 
15694         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15695       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15696       SDValue Splat2 = 
15697         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15698       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15699       if (TargetOpcode == X86ISD::MOVSD)
15700         CastVT = MVT::v2i64;
15701       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15702       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15703       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15704                                             BitCast1, DAG);
15705       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15706     }
15707   }
15708
15709   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15710     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15711
15712     // a = a << 5;
15713     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15714     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15715
15716     // Turn 'a' into a mask suitable for VSELECT
15717     SDValue VSelM = DAG.getConstant(0x80, VT);
15718     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15719     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15720
15721     SDValue CM1 = DAG.getConstant(0x0f, VT);
15722     SDValue CM2 = DAG.getConstant(0x3f, VT);
15723
15724     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15725     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15726     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15727     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15728     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15729
15730     // a += a
15731     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15732     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15733     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15734
15735     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15736     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15737     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15738     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15739     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15740
15741     // a += a
15742     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15743     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15744     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15745
15746     // return VSELECT(r, r+r, a);
15747     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15748                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15749     return R;
15750   }
15751
15752   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15753   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15754   // solution better.
15755   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15756     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15757     unsigned ExtOpc =
15758         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15759     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15760     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15761     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15762                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15763     }
15764
15765   // Decompose 256-bit shifts into smaller 128-bit shifts.
15766   if (VT.is256BitVector()) {
15767     unsigned NumElems = VT.getVectorNumElements();
15768     MVT EltVT = VT.getVectorElementType();
15769     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15770
15771     // Extract the two vectors
15772     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15773     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15774
15775     // Recreate the shift amount vectors
15776     SDValue Amt1, Amt2;
15777     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15778       // Constant shift amount
15779       SmallVector<SDValue, 4> Amt1Csts;
15780       SmallVector<SDValue, 4> Amt2Csts;
15781       for (unsigned i = 0; i != NumElems/2; ++i)
15782         Amt1Csts.push_back(Amt->getOperand(i));
15783       for (unsigned i = NumElems/2; i != NumElems; ++i)
15784         Amt2Csts.push_back(Amt->getOperand(i));
15785
15786       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15787       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15788     } else {
15789       // Variable shift amount
15790       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15791       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15792     }
15793
15794     // Issue new vector shifts for the smaller types
15795     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15796     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15797
15798     // Concatenate the result back
15799     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15800   }
15801
15802   return SDValue();
15803 }
15804
15805 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15806   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15807   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15808   // looks for this combo and may remove the "setcc" instruction if the "setcc"
15809   // has only one use.
15810   SDNode *N = Op.getNode();
15811   SDValue LHS = N->getOperand(0);
15812   SDValue RHS = N->getOperand(1);
15813   unsigned BaseOp = 0;
15814   unsigned Cond = 0;
15815   SDLoc DL(Op);
15816   switch (Op.getOpcode()) {
15817   default: llvm_unreachable("Unknown ovf instruction!");
15818   case ISD::SADDO:
15819     // A subtract of one will be selected as a INC. Note that INC doesn't
15820     // set CF, so we can't do this for UADDO.
15821     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15822       if (C->isOne()) {
15823         BaseOp = X86ISD::INC;
15824         Cond = X86::COND_O;
15825         break;
15826       }
15827     BaseOp = X86ISD::ADD;
15828     Cond = X86::COND_O;
15829     break;
15830   case ISD::UADDO:
15831     BaseOp = X86ISD::ADD;
15832     Cond = X86::COND_B;
15833     break;
15834   case ISD::SSUBO:
15835     // A subtract of one will be selected as a DEC. Note that DEC doesn't
15836     // set CF, so we can't do this for USUBO.
15837     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15838       if (C->isOne()) {
15839         BaseOp = X86ISD::DEC;
15840         Cond = X86::COND_O;
15841         break;
15842       }
15843     BaseOp = X86ISD::SUB;
15844     Cond = X86::COND_O;
15845     break;
15846   case ISD::USUBO:
15847     BaseOp = X86ISD::SUB;
15848     Cond = X86::COND_B;
15849     break;
15850   case ISD::SMULO:
15851     BaseOp = X86ISD::SMUL;
15852     Cond = X86::COND_O;
15853     break;
15854   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15855     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15856                                  MVT::i32);
15857     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15858
15859     SDValue SetCC =
15860       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15861                   DAG.getConstant(X86::COND_O, MVT::i32),
15862                   SDValue(Sum.getNode(), 2));
15863
15864     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15865   }
15866   }
15867
15868   // Also sets EFLAGS.
15869   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15870   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15871
15872   SDValue SetCC =
15873     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15874                 DAG.getConstant(Cond, MVT::i32),
15875                 SDValue(Sum.getNode(), 1));
15876
15877   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15878 }
15879
15880 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15881                                                   SelectionDAG &DAG) const {
15882   SDLoc dl(Op);
15883   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15884   MVT VT = Op.getSimpleValueType();
15885
15886   if (!Subtarget->hasSSE2() || !VT.isVector())
15887     return SDValue();
15888
15889   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15890                       ExtraVT.getScalarType().getSizeInBits();
15891
15892   switch (VT.SimpleTy) {
15893     default: return SDValue();
15894     case MVT::v8i32:
15895     case MVT::v16i16:
15896       if (!Subtarget->hasFp256())
15897         return SDValue();
15898       if (!Subtarget->hasInt256()) {
15899         // needs to be split
15900         unsigned NumElems = VT.getVectorNumElements();
15901
15902         // Extract the LHS vectors
15903         SDValue LHS = Op.getOperand(0);
15904         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15905         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15906
15907         MVT EltVT = VT.getVectorElementType();
15908         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15909
15910         EVT ExtraEltVT = ExtraVT.getVectorElementType();
15911         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15912         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15913                                    ExtraNumElems/2);
15914         SDValue Extra = DAG.getValueType(ExtraVT);
15915
15916         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15917         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15918
15919         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15920       }
15921       // fall through
15922     case MVT::v4i32:
15923     case MVT::v8i16: {
15924       SDValue Op0 = Op.getOperand(0);
15925       SDValue Op00 = Op0.getOperand(0);
15926       SDValue Tmp1;
15927       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15928       if (Op0.getOpcode() == ISD::BITCAST &&
15929           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15930         // (sext (vzext x)) -> (vsext x)
15931         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15932         if (Tmp1.getNode()) {
15933           EVT ExtraEltVT = ExtraVT.getVectorElementType();
15934           // This folding is only valid when the in-reg type is a vector of i8,
15935           // i16, or i32.
15936           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15937               ExtraEltVT == MVT::i32) {
15938             SDValue Tmp1Op0 = Tmp1.getOperand(0);
15939             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15940                    "This optimization is invalid without a VZEXT.");
15941             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15942           }
15943           Op0 = Tmp1;
15944         }
15945       }
15946
15947       // If the above didn't work, then just use Shift-Left + Shift-Right.
15948       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15949                                         DAG);
15950       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15951                                         DAG);
15952     }
15953   }
15954 }
15955
15956 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15957                                  SelectionDAG &DAG) {
15958   SDLoc dl(Op);
15959   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15960     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15961   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15962     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15963
15964   // The only fence that needs an instruction is a sequentially-consistent
15965   // cross-thread fence.
15966   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15967     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15968     // no-sse2). There isn't any reason to disable it if the target processor
15969     // supports it.
15970     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15971       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15972
15973     SDValue Chain = Op.getOperand(0);
15974     SDValue Zero = DAG.getConstant(0, MVT::i32);
15975     SDValue Ops[] = {
15976       DAG.getRegister(X86::ESP, MVT::i32), // Base
15977       DAG.getTargetConstant(1, MVT::i8),   // Scale
15978       DAG.getRegister(0, MVT::i32),        // Index
15979       DAG.getTargetConstant(0, MVT::i32),  // Disp
15980       DAG.getRegister(0, MVT::i32),        // Segment.
15981       Zero,
15982       Chain
15983     };
15984     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15985     return SDValue(Res, 0);
15986   }
15987
15988   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15989   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15990 }
15991
15992 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15993                              SelectionDAG &DAG) {
15994   MVT T = Op.getSimpleValueType();
15995   SDLoc DL(Op);
15996   unsigned Reg = 0;
15997   unsigned size = 0;
15998   switch(T.SimpleTy) {
15999   default: llvm_unreachable("Invalid value type!");
16000   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16001   case MVT::i16: Reg = X86::AX;  size = 2; break;
16002   case MVT::i32: Reg = X86::EAX; size = 4; break;
16003   case MVT::i64:
16004     assert(Subtarget->is64Bit() && "Node not type legal!");
16005     Reg = X86::RAX; size = 8;
16006     break;
16007   }
16008   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16009                                   Op.getOperand(2), SDValue());
16010   SDValue Ops[] = { cpIn.getValue(0),
16011                     Op.getOperand(1),
16012                     Op.getOperand(3),
16013                     DAG.getTargetConstant(size, MVT::i8),
16014                     cpIn.getValue(1) };
16015   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16016   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16017   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16018                                            Ops, T, MMO);
16019
16020   SDValue cpOut =
16021     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16022   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16023                                       MVT::i32, cpOut.getValue(2));
16024   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16025                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16026
16027   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16028   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16029   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16030   return SDValue();
16031 }
16032
16033 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16034                             SelectionDAG &DAG) {
16035   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16036   MVT DstVT = Op.getSimpleValueType();
16037
16038   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16039     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16040     if (DstVT != MVT::f64)
16041       // This conversion needs to be expanded.
16042       return SDValue();
16043
16044     SDValue InVec = Op->getOperand(0);
16045     SDLoc dl(Op);
16046     unsigned NumElts = SrcVT.getVectorNumElements();
16047     EVT SVT = SrcVT.getVectorElementType();
16048
16049     // Widen the vector in input in the case of MVT::v2i32.
16050     // Example: from MVT::v2i32 to MVT::v4i32.
16051     SmallVector<SDValue, 16> Elts;
16052     for (unsigned i = 0, e = NumElts; i != e; ++i)
16053       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16054                                  DAG.getIntPtrConstant(i)));
16055
16056     // Explicitly mark the extra elements as Undef.
16057     SDValue Undef = DAG.getUNDEF(SVT);
16058     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16059       Elts.push_back(Undef);
16060
16061     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16062     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16063     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16064     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16065                        DAG.getIntPtrConstant(0));
16066   }
16067
16068   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16069          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16070   assert((DstVT == MVT::i64 ||
16071           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16072          "Unexpected custom BITCAST");
16073   // i64 <=> MMX conversions are Legal.
16074   if (SrcVT==MVT::i64 && DstVT.isVector())
16075     return Op;
16076   if (DstVT==MVT::i64 && SrcVT.isVector())
16077     return Op;
16078   // MMX <=> MMX conversions are Legal.
16079   if (SrcVT.isVector() && DstVT.isVector())
16080     return Op;
16081   // All other conversions need to be expanded.
16082   return SDValue();
16083 }
16084
16085 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16086   SDNode *Node = Op.getNode();
16087   SDLoc dl(Node);
16088   EVT T = Node->getValueType(0);
16089   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16090                               DAG.getConstant(0, T), Node->getOperand(2));
16091   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16092                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16093                        Node->getOperand(0),
16094                        Node->getOperand(1), negOp,
16095                        cast<AtomicSDNode>(Node)->getMemOperand(),
16096                        cast<AtomicSDNode>(Node)->getOrdering(),
16097                        cast<AtomicSDNode>(Node)->getSynchScope());
16098 }
16099
16100 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16101   SDNode *Node = Op.getNode();
16102   SDLoc dl(Node);
16103   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16104
16105   // Convert seq_cst store -> xchg
16106   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16107   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16108   //        (The only way to get a 16-byte store is cmpxchg16b)
16109   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16110   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16111       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16112     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16113                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16114                                  Node->getOperand(0),
16115                                  Node->getOperand(1), Node->getOperand(2),
16116                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16117                                  cast<AtomicSDNode>(Node)->getOrdering(),
16118                                  cast<AtomicSDNode>(Node)->getSynchScope());
16119     return Swap.getValue(1);
16120   }
16121   // Other atomic stores have a simple pattern.
16122   return Op;
16123 }
16124
16125 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16126   EVT VT = Op.getNode()->getSimpleValueType(0);
16127
16128   // Let legalize expand this if it isn't a legal type yet.
16129   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16130     return SDValue();
16131
16132   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16133
16134   unsigned Opc;
16135   bool ExtraOp = false;
16136   switch (Op.getOpcode()) {
16137   default: llvm_unreachable("Invalid code");
16138   case ISD::ADDC: Opc = X86ISD::ADD; break;
16139   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16140   case ISD::SUBC: Opc = X86ISD::SUB; break;
16141   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16142   }
16143
16144   if (!ExtraOp)
16145     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16146                        Op.getOperand(1));
16147   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16148                      Op.getOperand(1), Op.getOperand(2));
16149 }
16150
16151 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16152                             SelectionDAG &DAG) {
16153   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16154
16155   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16156   // which returns the values as { float, float } (in XMM0) or
16157   // { double, double } (which is returned in XMM0, XMM1).
16158   SDLoc dl(Op);
16159   SDValue Arg = Op.getOperand(0);
16160   EVT ArgVT = Arg.getValueType();
16161   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16162
16163   TargetLowering::ArgListTy Args;
16164   TargetLowering::ArgListEntry Entry;
16165
16166   Entry.Node = Arg;
16167   Entry.Ty = ArgTy;
16168   Entry.isSExt = false;
16169   Entry.isZExt = false;
16170   Args.push_back(Entry);
16171
16172   bool isF64 = ArgVT == MVT::f64;
16173   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16174   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16175   // the results are returned via SRet in memory.
16176   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16178   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16179
16180   Type *RetTy = isF64
16181     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16182     : (Type*)VectorType::get(ArgTy, 4);
16183
16184   TargetLowering::CallLoweringInfo CLI(DAG);
16185   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16186     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16187
16188   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16189
16190   if (isF64)
16191     // Returned in xmm0 and xmm1.
16192     return CallResult.first;
16193
16194   // Returned in bits 0:31 and 32:64 xmm0.
16195   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16196                                CallResult.first, DAG.getIntPtrConstant(0));
16197   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16198                                CallResult.first, DAG.getIntPtrConstant(1));
16199   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16200   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16201 }
16202
16203 /// LowerOperation - Provide custom lowering hooks for some operations.
16204 ///
16205 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16206   switch (Op.getOpcode()) {
16207   default: llvm_unreachable("Should not custom lower this!");
16208   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16209   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16210   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16211     return LowerCMP_SWAP(Op, Subtarget, DAG);
16212   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16213   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16214   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16215   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16216   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16217   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16218   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16219   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16220   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16221   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16222   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16223   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16224   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16225   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16226   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16227   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16228   case ISD::SHL_PARTS:
16229   case ISD::SRA_PARTS:
16230   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16231   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16232   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16233   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16234   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16235   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16236   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16237   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16238   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16239   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16240   case ISD::FABS:               return LowerFABS(Op, DAG);
16241   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16242   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16243   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16244   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16245   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16246   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16247   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16248   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16249   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16250   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16251   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16252   case ISD::INTRINSIC_VOID:
16253   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16254   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16255   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16256   case ISD::FRAME_TO_ARGS_OFFSET:
16257                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16258   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16259   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16260   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16261   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16262   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16263   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16264   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16265   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16266   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16267   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16268   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16269   case ISD::UMUL_LOHI:
16270   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16271   case ISD::SRA:
16272   case ISD::SRL:
16273   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16274   case ISD::SADDO:
16275   case ISD::UADDO:
16276   case ISD::SSUBO:
16277   case ISD::USUBO:
16278   case ISD::SMULO:
16279   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16280   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16281   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16282   case ISD::ADDC:
16283   case ISD::ADDE:
16284   case ISD::SUBC:
16285   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16286   case ISD::ADD:                return LowerADD(Op, DAG);
16287   case ISD::SUB:                return LowerSUB(Op, DAG);
16288   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16289   }
16290 }
16291
16292 static void ReplaceATOMIC_LOAD(SDNode *Node,
16293                                SmallVectorImpl<SDValue> &Results,
16294                                SelectionDAG &DAG) {
16295   SDLoc dl(Node);
16296   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16297
16298   // Convert wide load -> cmpxchg8b/cmpxchg16b
16299   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16300   //        (The only way to get a 16-byte load is cmpxchg16b)
16301   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16302   SDValue Zero = DAG.getConstant(0, VT);
16303   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16304   SDValue Swap =
16305       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16306                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16307                            cast<AtomicSDNode>(Node)->getMemOperand(),
16308                            cast<AtomicSDNode>(Node)->getOrdering(),
16309                            cast<AtomicSDNode>(Node)->getOrdering(),
16310                            cast<AtomicSDNode>(Node)->getSynchScope());
16311   Results.push_back(Swap.getValue(0));
16312   Results.push_back(Swap.getValue(2));
16313 }
16314
16315 /// ReplaceNodeResults - Replace a node with an illegal result type
16316 /// with a new node built out of custom code.
16317 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16318                                            SmallVectorImpl<SDValue>&Results,
16319                                            SelectionDAG &DAG) const {
16320   SDLoc dl(N);
16321   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16322   switch (N->getOpcode()) {
16323   default:
16324     llvm_unreachable("Do not know how to custom type legalize this operation!");
16325   case ISD::SIGN_EXTEND_INREG:
16326   case ISD::ADDC:
16327   case ISD::ADDE:
16328   case ISD::SUBC:
16329   case ISD::SUBE:
16330     // We don't want to expand or promote these.
16331     return;
16332   case ISD::SDIV:
16333   case ISD::UDIV:
16334   case ISD::SREM:
16335   case ISD::UREM:
16336   case ISD::SDIVREM:
16337   case ISD::UDIVREM: {
16338     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16339     Results.push_back(V);
16340     return;
16341   }
16342   case ISD::FP_TO_SINT:
16343   case ISD::FP_TO_UINT: {
16344     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16345
16346     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16347       return;
16348
16349     std::pair<SDValue,SDValue> Vals =
16350         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16351     SDValue FIST = Vals.first, StackSlot = Vals.second;
16352     if (FIST.getNode()) {
16353       EVT VT = N->getValueType(0);
16354       // Return a load from the stack slot.
16355       if (StackSlot.getNode())
16356         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16357                                       MachinePointerInfo(),
16358                                       false, false, false, 0));
16359       else
16360         Results.push_back(FIST);
16361     }
16362     return;
16363   }
16364   case ISD::UINT_TO_FP: {
16365     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16366     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16367         N->getValueType(0) != MVT::v2f32)
16368       return;
16369     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16370                                  N->getOperand(0));
16371     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16372                                      MVT::f64);
16373     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16374     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16375                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16376     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16377     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16378     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16379     return;
16380   }
16381   case ISD::FP_ROUND: {
16382     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16383         return;
16384     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16385     Results.push_back(V);
16386     return;
16387   }
16388   case ISD::INTRINSIC_W_CHAIN: {
16389     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16390     switch (IntNo) {
16391     default : llvm_unreachable("Do not know how to custom type "
16392                                "legalize this intrinsic operation!");
16393     case Intrinsic::x86_rdtsc:
16394       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16395                                      Results);
16396     case Intrinsic::x86_rdtscp:
16397       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16398                                      Results);
16399     case Intrinsic::x86_rdpmc:
16400       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16401     }
16402   }
16403   case ISD::READCYCLECOUNTER: {
16404     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16405                                    Results);
16406   }
16407   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16408     EVT T = N->getValueType(0);
16409     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16410     bool Regs64bit = T == MVT::i128;
16411     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16412     SDValue cpInL, cpInH;
16413     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16414                         DAG.getConstant(0, HalfT));
16415     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16416                         DAG.getConstant(1, HalfT));
16417     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16418                              Regs64bit ? X86::RAX : X86::EAX,
16419                              cpInL, SDValue());
16420     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16421                              Regs64bit ? X86::RDX : X86::EDX,
16422                              cpInH, cpInL.getValue(1));
16423     SDValue swapInL, swapInH;
16424     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16425                           DAG.getConstant(0, HalfT));
16426     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16427                           DAG.getConstant(1, HalfT));
16428     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16429                                Regs64bit ? X86::RBX : X86::EBX,
16430                                swapInL, cpInH.getValue(1));
16431     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16432                                Regs64bit ? X86::RCX : X86::ECX,
16433                                swapInH, swapInL.getValue(1));
16434     SDValue Ops[] = { swapInH.getValue(0),
16435                       N->getOperand(1),
16436                       swapInH.getValue(1) };
16437     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16438     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16439     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16440                                   X86ISD::LCMPXCHG8_DAG;
16441     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16442     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16443                                         Regs64bit ? X86::RAX : X86::EAX,
16444                                         HalfT, Result.getValue(1));
16445     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16446                                         Regs64bit ? X86::RDX : X86::EDX,
16447                                         HalfT, cpOutL.getValue(2));
16448     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16449
16450     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16451                                         MVT::i32, cpOutH.getValue(2));
16452     SDValue Success =
16453         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16454                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16455     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16456
16457     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16458     Results.push_back(Success);
16459     Results.push_back(EFLAGS.getValue(1));
16460     return;
16461   }
16462   case ISD::ATOMIC_SWAP:
16463   case ISD::ATOMIC_LOAD_ADD:
16464   case ISD::ATOMIC_LOAD_SUB:
16465   case ISD::ATOMIC_LOAD_AND:
16466   case ISD::ATOMIC_LOAD_OR:
16467   case ISD::ATOMIC_LOAD_XOR:
16468   case ISD::ATOMIC_LOAD_NAND:
16469   case ISD::ATOMIC_LOAD_MIN:
16470   case ISD::ATOMIC_LOAD_MAX:
16471   case ISD::ATOMIC_LOAD_UMIN:
16472   case ISD::ATOMIC_LOAD_UMAX:
16473     // Delegate to generic TypeLegalization. Situations we can really handle
16474     // should have already been dealt with by X86AtomicExpand.cpp.
16475     break;
16476   case ISD::ATOMIC_LOAD: {
16477     ReplaceATOMIC_LOAD(N, Results, DAG);
16478     return;
16479   }
16480   case ISD::BITCAST: {
16481     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16482     EVT DstVT = N->getValueType(0);
16483     EVT SrcVT = N->getOperand(0)->getValueType(0);
16484
16485     if (SrcVT != MVT::f64 ||
16486         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16487       return;
16488
16489     unsigned NumElts = DstVT.getVectorNumElements();
16490     EVT SVT = DstVT.getVectorElementType();
16491     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16492     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16493                                    MVT::v2f64, N->getOperand(0));
16494     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16495
16496     if (ExperimentalVectorWideningLegalization) {
16497       // If we are legalizing vectors by widening, we already have the desired
16498       // legal vector type, just return it.
16499       Results.push_back(ToVecInt);
16500       return;
16501     }
16502
16503     SmallVector<SDValue, 8> Elts;
16504     for (unsigned i = 0, e = NumElts; i != e; ++i)
16505       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16506                                    ToVecInt, DAG.getIntPtrConstant(i)));
16507
16508     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16509   }
16510   }
16511 }
16512
16513 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16514   switch (Opcode) {
16515   default: return nullptr;
16516   case X86ISD::BSF:                return "X86ISD::BSF";
16517   case X86ISD::BSR:                return "X86ISD::BSR";
16518   case X86ISD::SHLD:               return "X86ISD::SHLD";
16519   case X86ISD::SHRD:               return "X86ISD::SHRD";
16520   case X86ISD::FAND:               return "X86ISD::FAND";
16521   case X86ISD::FANDN:              return "X86ISD::FANDN";
16522   case X86ISD::FOR:                return "X86ISD::FOR";
16523   case X86ISD::FXOR:               return "X86ISD::FXOR";
16524   case X86ISD::FSRL:               return "X86ISD::FSRL";
16525   case X86ISD::FILD:               return "X86ISD::FILD";
16526   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16527   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16528   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16529   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16530   case X86ISD::FLD:                return "X86ISD::FLD";
16531   case X86ISD::FST:                return "X86ISD::FST";
16532   case X86ISD::CALL:               return "X86ISD::CALL";
16533   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16534   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16535   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16536   case X86ISD::BT:                 return "X86ISD::BT";
16537   case X86ISD::CMP:                return "X86ISD::CMP";
16538   case X86ISD::COMI:               return "X86ISD::COMI";
16539   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16540   case X86ISD::CMPM:               return "X86ISD::CMPM";
16541   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16542   case X86ISD::SETCC:              return "X86ISD::SETCC";
16543   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16544   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16545   case X86ISD::CMOV:               return "X86ISD::CMOV";
16546   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16547   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16548   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16549   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16550   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16551   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16552   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16553   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16554   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16555   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16556   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16557   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16558   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16559   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16560   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16561   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16562   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16563   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16564   case X86ISD::HADD:               return "X86ISD::HADD";
16565   case X86ISD::HSUB:               return "X86ISD::HSUB";
16566   case X86ISD::FHADD:              return "X86ISD::FHADD";
16567   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16568   case X86ISD::UMAX:               return "X86ISD::UMAX";
16569   case X86ISD::UMIN:               return "X86ISD::UMIN";
16570   case X86ISD::SMAX:               return "X86ISD::SMAX";
16571   case X86ISD::SMIN:               return "X86ISD::SMIN";
16572   case X86ISD::FMAX:               return "X86ISD::FMAX";
16573   case X86ISD::FMIN:               return "X86ISD::FMIN";
16574   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16575   case X86ISD::FMINC:              return "X86ISD::FMINC";
16576   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16577   case X86ISD::FRCP:               return "X86ISD::FRCP";
16578   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16579   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16580   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16581   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16582   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16583   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16584   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16585   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16586   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16587   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16588   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16589   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16590   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16591   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16592   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16593   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16594   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16595   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16596   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16597   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16598   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16599   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16600   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16601   case X86ISD::VSHL:               return "X86ISD::VSHL";
16602   case X86ISD::VSRL:               return "X86ISD::VSRL";
16603   case X86ISD::VSRA:               return "X86ISD::VSRA";
16604   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16605   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16606   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16607   case X86ISD::CMPP:               return "X86ISD::CMPP";
16608   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16609   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16610   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16611   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16612   case X86ISD::ADD:                return "X86ISD::ADD";
16613   case X86ISD::SUB:                return "X86ISD::SUB";
16614   case X86ISD::ADC:                return "X86ISD::ADC";
16615   case X86ISD::SBB:                return "X86ISD::SBB";
16616   case X86ISD::SMUL:               return "X86ISD::SMUL";
16617   case X86ISD::UMUL:               return "X86ISD::UMUL";
16618   case X86ISD::INC:                return "X86ISD::INC";
16619   case X86ISD::DEC:                return "X86ISD::DEC";
16620   case X86ISD::OR:                 return "X86ISD::OR";
16621   case X86ISD::XOR:                return "X86ISD::XOR";
16622   case X86ISD::AND:                return "X86ISD::AND";
16623   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16624   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16625   case X86ISD::PTEST:              return "X86ISD::PTEST";
16626   case X86ISD::TESTP:              return "X86ISD::TESTP";
16627   case X86ISD::TESTM:              return "X86ISD::TESTM";
16628   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16629   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16630   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16631   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16632   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16633   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16634   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16635   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16636   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16637   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16638   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16639   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16640   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16641   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16642   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16643   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16644   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16645   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16646   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16647   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16648   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16649   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16650   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16651   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16652   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16653   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16654   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16655   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16656   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16657   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16658   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16659   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16660   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16661   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16662   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16663   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16664   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16665   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16666   case X86ISD::SAHF:               return "X86ISD::SAHF";
16667   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16668   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16669   case X86ISD::FMADD:              return "X86ISD::FMADD";
16670   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16671   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16672   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16673   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16674   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16675   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16676   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16677   case X86ISD::XTEST:              return "X86ISD::XTEST";
16678   }
16679 }
16680
16681 // isLegalAddressingMode - Return true if the addressing mode represented
16682 // by AM is legal for this target, for a load/store of the specified type.
16683 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16684                                               Type *Ty) const {
16685   // X86 supports extremely general addressing modes.
16686   CodeModel::Model M = getTargetMachine().getCodeModel();
16687   Reloc::Model R = getTargetMachine().getRelocationModel();
16688
16689   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16690   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16691     return false;
16692
16693   if (AM.BaseGV) {
16694     unsigned GVFlags =
16695       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16696
16697     // If a reference to this global requires an extra load, we can't fold it.
16698     if (isGlobalStubReference(GVFlags))
16699       return false;
16700
16701     // If BaseGV requires a register for the PIC base, we cannot also have a
16702     // BaseReg specified.
16703     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16704       return false;
16705
16706     // If lower 4G is not available, then we must use rip-relative addressing.
16707     if ((M != CodeModel::Small || R != Reloc::Static) &&
16708         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16709       return false;
16710   }
16711
16712   switch (AM.Scale) {
16713   case 0:
16714   case 1:
16715   case 2:
16716   case 4:
16717   case 8:
16718     // These scales always work.
16719     break;
16720   case 3:
16721   case 5:
16722   case 9:
16723     // These scales are formed with basereg+scalereg.  Only accept if there is
16724     // no basereg yet.
16725     if (AM.HasBaseReg)
16726       return false;
16727     break;
16728   default:  // Other stuff never works.
16729     return false;
16730   }
16731
16732   return true;
16733 }
16734
16735 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16736   unsigned Bits = Ty->getScalarSizeInBits();
16737
16738   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16739   // particularly cheaper than those without.
16740   if (Bits == 8)
16741     return false;
16742
16743   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16744   // variable shifts just as cheap as scalar ones.
16745   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16746     return false;
16747
16748   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16749   // fully general vector.
16750   return true;
16751 }
16752
16753 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16754   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16755     return false;
16756   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16757   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16758   return NumBits1 > NumBits2;
16759 }
16760
16761 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16762   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16763     return false;
16764
16765   if (!isTypeLegal(EVT::getEVT(Ty1)))
16766     return false;
16767
16768   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16769
16770   // Assuming the caller doesn't have a zeroext or signext return parameter,
16771   // truncation all the way down to i1 is valid.
16772   return true;
16773 }
16774
16775 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16776   return isInt<32>(Imm);
16777 }
16778
16779 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16780   // Can also use sub to handle negated immediates.
16781   return isInt<32>(Imm);
16782 }
16783
16784 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16785   if (!VT1.isInteger() || !VT2.isInteger())
16786     return false;
16787   unsigned NumBits1 = VT1.getSizeInBits();
16788   unsigned NumBits2 = VT2.getSizeInBits();
16789   return NumBits1 > NumBits2;
16790 }
16791
16792 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16793   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16794   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16795 }
16796
16797 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16798   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16799   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16800 }
16801
16802 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16803   EVT VT1 = Val.getValueType();
16804   if (isZExtFree(VT1, VT2))
16805     return true;
16806
16807   if (Val.getOpcode() != ISD::LOAD)
16808     return false;
16809
16810   if (!VT1.isSimple() || !VT1.isInteger() ||
16811       !VT2.isSimple() || !VT2.isInteger())
16812     return false;
16813
16814   switch (VT1.getSimpleVT().SimpleTy) {
16815   default: break;
16816   case MVT::i8:
16817   case MVT::i16:
16818   case MVT::i32:
16819     // X86 has 8, 16, and 32-bit zero-extending loads.
16820     return true;
16821   }
16822
16823   return false;
16824 }
16825
16826 bool
16827 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16828   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16829     return false;
16830
16831   VT = VT.getScalarType();
16832
16833   if (!VT.isSimple())
16834     return false;
16835
16836   switch (VT.getSimpleVT().SimpleTy) {
16837   case MVT::f32:
16838   case MVT::f64:
16839     return true;
16840   default:
16841     break;
16842   }
16843
16844   return false;
16845 }
16846
16847 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16848   // i16 instructions are longer (0x66 prefix) and potentially slower.
16849   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16850 }
16851
16852 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16853 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16854 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16855 /// are assumed to be legal.
16856 bool
16857 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16858                                       EVT VT) const {
16859   if (!VT.isSimple())
16860     return false;
16861
16862   MVT SVT = VT.getSimpleVT();
16863
16864   // Very little shuffling can be done for 64-bit vectors right now.
16865   if (VT.getSizeInBits() == 64)
16866     return false;
16867
16868   // If this is a single-input shuffle with no 128 bit lane crossings we can
16869   // lower it into pshufb.
16870   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16871       (SVT.is256BitVector() && Subtarget->hasInt256())) {
16872     bool isLegal = true;
16873     for (unsigned I = 0, E = M.size(); I != E; ++I) {
16874       if (M[I] >= (int)SVT.getVectorNumElements() ||
16875           ShuffleCrosses128bitLane(SVT, I, M[I])) {
16876         isLegal = false;
16877         break;
16878       }
16879     }
16880     if (isLegal)
16881       return true;
16882   }
16883
16884   // FIXME: blends, shifts.
16885   return (SVT.getVectorNumElements() == 2 ||
16886           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16887           isMOVLMask(M, SVT) ||
16888           isMOVHLPSMask(M, SVT) ||
16889           isSHUFPMask(M, SVT) ||
16890           isPSHUFDMask(M, SVT) ||
16891           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16892           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16893           isPALIGNRMask(M, SVT, Subtarget) ||
16894           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16895           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16896           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16897           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16898           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16899 }
16900
16901 bool
16902 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16903                                           EVT VT) const {
16904   if (!VT.isSimple())
16905     return false;
16906
16907   MVT SVT = VT.getSimpleVT();
16908   unsigned NumElts = SVT.getVectorNumElements();
16909   // FIXME: This collection of masks seems suspect.
16910   if (NumElts == 2)
16911     return true;
16912   if (NumElts == 4 && SVT.is128BitVector()) {
16913     return (isMOVLMask(Mask, SVT)  ||
16914             isCommutedMOVLMask(Mask, SVT, true) ||
16915             isSHUFPMask(Mask, SVT) ||
16916             isSHUFPMask(Mask, SVT, /* Commuted */ true));
16917   }
16918   return false;
16919 }
16920
16921 //===----------------------------------------------------------------------===//
16922 //                           X86 Scheduler Hooks
16923 //===----------------------------------------------------------------------===//
16924
16925 /// Utility function to emit xbegin specifying the start of an RTM region.
16926 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16927                                      const TargetInstrInfo *TII) {
16928   DebugLoc DL = MI->getDebugLoc();
16929
16930   const BasicBlock *BB = MBB->getBasicBlock();
16931   MachineFunction::iterator I = MBB;
16932   ++I;
16933
16934   // For the v = xbegin(), we generate
16935   //
16936   // thisMBB:
16937   //  xbegin sinkMBB
16938   //
16939   // mainMBB:
16940   //  eax = -1
16941   //
16942   // sinkMBB:
16943   //  v = eax
16944
16945   MachineBasicBlock *thisMBB = MBB;
16946   MachineFunction *MF = MBB->getParent();
16947   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16948   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16949   MF->insert(I, mainMBB);
16950   MF->insert(I, sinkMBB);
16951
16952   // Transfer the remainder of BB and its successor edges to sinkMBB.
16953   sinkMBB->splice(sinkMBB->begin(), MBB,
16954                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16955   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16956
16957   // thisMBB:
16958   //  xbegin sinkMBB
16959   //  # fallthrough to mainMBB
16960   //  # abortion to sinkMBB
16961   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16962   thisMBB->addSuccessor(mainMBB);
16963   thisMBB->addSuccessor(sinkMBB);
16964
16965   // mainMBB:
16966   //  EAX = -1
16967   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16968   mainMBB->addSuccessor(sinkMBB);
16969
16970   // sinkMBB:
16971   // EAX is live into the sinkMBB
16972   sinkMBB->addLiveIn(X86::EAX);
16973   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16974           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16975     .addReg(X86::EAX);
16976
16977   MI->eraseFromParent();
16978   return sinkMBB;
16979 }
16980
16981 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16982 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16983 // in the .td file.
16984 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16985                                        const TargetInstrInfo *TII) {
16986   unsigned Opc;
16987   switch (MI->getOpcode()) {
16988   default: llvm_unreachable("illegal opcode!");
16989   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16990   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16991   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16992   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16993   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16994   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16995   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16996   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16997   }
16998
16999   DebugLoc dl = MI->getDebugLoc();
17000   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17001
17002   unsigned NumArgs = MI->getNumOperands();
17003   for (unsigned i = 1; i < NumArgs; ++i) {
17004     MachineOperand &Op = MI->getOperand(i);
17005     if (!(Op.isReg() && Op.isImplicit()))
17006       MIB.addOperand(Op);
17007   }
17008   if (MI->hasOneMemOperand())
17009     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17010
17011   BuildMI(*BB, MI, dl,
17012     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17013     .addReg(X86::XMM0);
17014
17015   MI->eraseFromParent();
17016   return BB;
17017 }
17018
17019 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17020 // defs in an instruction pattern
17021 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17022                                        const TargetInstrInfo *TII) {
17023   unsigned Opc;
17024   switch (MI->getOpcode()) {
17025   default: llvm_unreachable("illegal opcode!");
17026   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17027   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17028   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17029   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17030   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17031   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17032   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17033   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17034   }
17035
17036   DebugLoc dl = MI->getDebugLoc();
17037   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17038
17039   unsigned NumArgs = MI->getNumOperands(); // remove the results
17040   for (unsigned i = 1; i < NumArgs; ++i) {
17041     MachineOperand &Op = MI->getOperand(i);
17042     if (!(Op.isReg() && Op.isImplicit()))
17043       MIB.addOperand(Op);
17044   }
17045   if (MI->hasOneMemOperand())
17046     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17047
17048   BuildMI(*BB, MI, dl,
17049     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17050     .addReg(X86::ECX);
17051
17052   MI->eraseFromParent();
17053   return BB;
17054 }
17055
17056 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17057                                        const TargetInstrInfo *TII,
17058                                        const X86Subtarget* Subtarget) {
17059   DebugLoc dl = MI->getDebugLoc();
17060
17061   // Address into RAX/EAX, other two args into ECX, EDX.
17062   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17063   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17064   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17065   for (int i = 0; i < X86::AddrNumOperands; ++i)
17066     MIB.addOperand(MI->getOperand(i));
17067
17068   unsigned ValOps = X86::AddrNumOperands;
17069   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17070     .addReg(MI->getOperand(ValOps).getReg());
17071   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17072     .addReg(MI->getOperand(ValOps+1).getReg());
17073
17074   // The instruction doesn't actually take any operands though.
17075   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17076
17077   MI->eraseFromParent(); // The pseudo is gone now.
17078   return BB;
17079 }
17080
17081 MachineBasicBlock *
17082 X86TargetLowering::EmitVAARG64WithCustomInserter(
17083                    MachineInstr *MI,
17084                    MachineBasicBlock *MBB) const {
17085   // Emit va_arg instruction on X86-64.
17086
17087   // Operands to this pseudo-instruction:
17088   // 0  ) Output        : destination address (reg)
17089   // 1-5) Input         : va_list address (addr, i64mem)
17090   // 6  ) ArgSize       : Size (in bytes) of vararg type
17091   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17092   // 8  ) Align         : Alignment of type
17093   // 9  ) EFLAGS (implicit-def)
17094
17095   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17096   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17097
17098   unsigned DestReg = MI->getOperand(0).getReg();
17099   MachineOperand &Base = MI->getOperand(1);
17100   MachineOperand &Scale = MI->getOperand(2);
17101   MachineOperand &Index = MI->getOperand(3);
17102   MachineOperand &Disp = MI->getOperand(4);
17103   MachineOperand &Segment = MI->getOperand(5);
17104   unsigned ArgSize = MI->getOperand(6).getImm();
17105   unsigned ArgMode = MI->getOperand(7).getImm();
17106   unsigned Align = MI->getOperand(8).getImm();
17107
17108   // Memory Reference
17109   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17110   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17111   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17112
17113   // Machine Information
17114   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17115   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17116   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17117   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17118   DebugLoc DL = MI->getDebugLoc();
17119
17120   // struct va_list {
17121   //   i32   gp_offset
17122   //   i32   fp_offset
17123   //   i64   overflow_area (address)
17124   //   i64   reg_save_area (address)
17125   // }
17126   // sizeof(va_list) = 24
17127   // alignment(va_list) = 8
17128
17129   unsigned TotalNumIntRegs = 6;
17130   unsigned TotalNumXMMRegs = 8;
17131   bool UseGPOffset = (ArgMode == 1);
17132   bool UseFPOffset = (ArgMode == 2);
17133   unsigned MaxOffset = TotalNumIntRegs * 8 +
17134                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17135
17136   /* Align ArgSize to a multiple of 8 */
17137   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17138   bool NeedsAlign = (Align > 8);
17139
17140   MachineBasicBlock *thisMBB = MBB;
17141   MachineBasicBlock *overflowMBB;
17142   MachineBasicBlock *offsetMBB;
17143   MachineBasicBlock *endMBB;
17144
17145   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17146   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17147   unsigned OffsetReg = 0;
17148
17149   if (!UseGPOffset && !UseFPOffset) {
17150     // If we only pull from the overflow region, we don't create a branch.
17151     // We don't need to alter control flow.
17152     OffsetDestReg = 0; // unused
17153     OverflowDestReg = DestReg;
17154
17155     offsetMBB = nullptr;
17156     overflowMBB = thisMBB;
17157     endMBB = thisMBB;
17158   } else {
17159     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17160     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17161     // If not, pull from overflow_area. (branch to overflowMBB)
17162     //
17163     //       thisMBB
17164     //         |     .
17165     //         |        .
17166     //     offsetMBB   overflowMBB
17167     //         |        .
17168     //         |     .
17169     //        endMBB
17170
17171     // Registers for the PHI in endMBB
17172     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17173     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17174
17175     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17176     MachineFunction *MF = MBB->getParent();
17177     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17178     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17179     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17180
17181     MachineFunction::iterator MBBIter = MBB;
17182     ++MBBIter;
17183
17184     // Insert the new basic blocks
17185     MF->insert(MBBIter, offsetMBB);
17186     MF->insert(MBBIter, overflowMBB);
17187     MF->insert(MBBIter, endMBB);
17188
17189     // Transfer the remainder of MBB and its successor edges to endMBB.
17190     endMBB->splice(endMBB->begin(), thisMBB,
17191                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17192     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17193
17194     // Make offsetMBB and overflowMBB successors of thisMBB
17195     thisMBB->addSuccessor(offsetMBB);
17196     thisMBB->addSuccessor(overflowMBB);
17197
17198     // endMBB is a successor of both offsetMBB and overflowMBB
17199     offsetMBB->addSuccessor(endMBB);
17200     overflowMBB->addSuccessor(endMBB);
17201
17202     // Load the offset value into a register
17203     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17204     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17205       .addOperand(Base)
17206       .addOperand(Scale)
17207       .addOperand(Index)
17208       .addDisp(Disp, UseFPOffset ? 4 : 0)
17209       .addOperand(Segment)
17210       .setMemRefs(MMOBegin, MMOEnd);
17211
17212     // Check if there is enough room left to pull this argument.
17213     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17214       .addReg(OffsetReg)
17215       .addImm(MaxOffset + 8 - ArgSizeA8);
17216
17217     // Branch to "overflowMBB" if offset >= max
17218     // Fall through to "offsetMBB" otherwise
17219     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17220       .addMBB(overflowMBB);
17221   }
17222
17223   // In offsetMBB, emit code to use the reg_save_area.
17224   if (offsetMBB) {
17225     assert(OffsetReg != 0);
17226
17227     // Read the reg_save_area address.
17228     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17229     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17230       .addOperand(Base)
17231       .addOperand(Scale)
17232       .addOperand(Index)
17233       .addDisp(Disp, 16)
17234       .addOperand(Segment)
17235       .setMemRefs(MMOBegin, MMOEnd);
17236
17237     // Zero-extend the offset
17238     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17239       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17240         .addImm(0)
17241         .addReg(OffsetReg)
17242         .addImm(X86::sub_32bit);
17243
17244     // Add the offset to the reg_save_area to get the final address.
17245     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17246       .addReg(OffsetReg64)
17247       .addReg(RegSaveReg);
17248
17249     // Compute the offset for the next argument
17250     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17251     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17252       .addReg(OffsetReg)
17253       .addImm(UseFPOffset ? 16 : 8);
17254
17255     // Store it back into the va_list.
17256     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17257       .addOperand(Base)
17258       .addOperand(Scale)
17259       .addOperand(Index)
17260       .addDisp(Disp, UseFPOffset ? 4 : 0)
17261       .addOperand(Segment)
17262       .addReg(NextOffsetReg)
17263       .setMemRefs(MMOBegin, MMOEnd);
17264
17265     // Jump to endMBB
17266     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17267       .addMBB(endMBB);
17268   }
17269
17270   //
17271   // Emit code to use overflow area
17272   //
17273
17274   // Load the overflow_area address into a register.
17275   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17276   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17277     .addOperand(Base)
17278     .addOperand(Scale)
17279     .addOperand(Index)
17280     .addDisp(Disp, 8)
17281     .addOperand(Segment)
17282     .setMemRefs(MMOBegin, MMOEnd);
17283
17284   // If we need to align it, do so. Otherwise, just copy the address
17285   // to OverflowDestReg.
17286   if (NeedsAlign) {
17287     // Align the overflow address
17288     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17289     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17290
17291     // aligned_addr = (addr + (align-1)) & ~(align-1)
17292     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17293       .addReg(OverflowAddrReg)
17294       .addImm(Align-1);
17295
17296     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17297       .addReg(TmpReg)
17298       .addImm(~(uint64_t)(Align-1));
17299   } else {
17300     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17301       .addReg(OverflowAddrReg);
17302   }
17303
17304   // Compute the next overflow address after this argument.
17305   // (the overflow address should be kept 8-byte aligned)
17306   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17307   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17308     .addReg(OverflowDestReg)
17309     .addImm(ArgSizeA8);
17310
17311   // Store the new overflow address.
17312   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17313     .addOperand(Base)
17314     .addOperand(Scale)
17315     .addOperand(Index)
17316     .addDisp(Disp, 8)
17317     .addOperand(Segment)
17318     .addReg(NextAddrReg)
17319     .setMemRefs(MMOBegin, MMOEnd);
17320
17321   // If we branched, emit the PHI to the front of endMBB.
17322   if (offsetMBB) {
17323     BuildMI(*endMBB, endMBB->begin(), DL,
17324             TII->get(X86::PHI), DestReg)
17325       .addReg(OffsetDestReg).addMBB(offsetMBB)
17326       .addReg(OverflowDestReg).addMBB(overflowMBB);
17327   }
17328
17329   // Erase the pseudo instruction
17330   MI->eraseFromParent();
17331
17332   return endMBB;
17333 }
17334
17335 MachineBasicBlock *
17336 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17337                                                  MachineInstr *MI,
17338                                                  MachineBasicBlock *MBB) const {
17339   // Emit code to save XMM registers to the stack. The ABI says that the
17340   // number of registers to save is given in %al, so it's theoretically
17341   // possible to do an indirect jump trick to avoid saving all of them,
17342   // however this code takes a simpler approach and just executes all
17343   // of the stores if %al is non-zero. It's less code, and it's probably
17344   // easier on the hardware branch predictor, and stores aren't all that
17345   // expensive anyway.
17346
17347   // Create the new basic blocks. One block contains all the XMM stores,
17348   // and one block is the final destination regardless of whether any
17349   // stores were performed.
17350   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17351   MachineFunction *F = MBB->getParent();
17352   MachineFunction::iterator MBBIter = MBB;
17353   ++MBBIter;
17354   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17355   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17356   F->insert(MBBIter, XMMSaveMBB);
17357   F->insert(MBBIter, EndMBB);
17358
17359   // Transfer the remainder of MBB and its successor edges to EndMBB.
17360   EndMBB->splice(EndMBB->begin(), MBB,
17361                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17362   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17363
17364   // The original block will now fall through to the XMM save block.
17365   MBB->addSuccessor(XMMSaveMBB);
17366   // The XMMSaveMBB will fall through to the end block.
17367   XMMSaveMBB->addSuccessor(EndMBB);
17368
17369   // Now add the instructions.
17370   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17371   DebugLoc DL = MI->getDebugLoc();
17372
17373   unsigned CountReg = MI->getOperand(0).getReg();
17374   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17375   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17376
17377   if (!Subtarget->isTargetWin64()) {
17378     // If %al is 0, branch around the XMM save block.
17379     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17380     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17381     MBB->addSuccessor(EndMBB);
17382   }
17383
17384   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17385   // that was just emitted, but clearly shouldn't be "saved".
17386   assert((MI->getNumOperands() <= 3 ||
17387           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17388           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17389          && "Expected last argument to be EFLAGS");
17390   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17391   // In the XMM save block, save all the XMM argument registers.
17392   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17393     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17394     MachineMemOperand *MMO =
17395       F->getMachineMemOperand(
17396           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17397         MachineMemOperand::MOStore,
17398         /*Size=*/16, /*Align=*/16);
17399     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17400       .addFrameIndex(RegSaveFrameIndex)
17401       .addImm(/*Scale=*/1)
17402       .addReg(/*IndexReg=*/0)
17403       .addImm(/*Disp=*/Offset)
17404       .addReg(/*Segment=*/0)
17405       .addReg(MI->getOperand(i).getReg())
17406       .addMemOperand(MMO);
17407   }
17408
17409   MI->eraseFromParent();   // The pseudo instruction is gone now.
17410
17411   return EndMBB;
17412 }
17413
17414 // The EFLAGS operand of SelectItr might be missing a kill marker
17415 // because there were multiple uses of EFLAGS, and ISel didn't know
17416 // which to mark. Figure out whether SelectItr should have had a
17417 // kill marker, and set it if it should. Returns the correct kill
17418 // marker value.
17419 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17420                                      MachineBasicBlock* BB,
17421                                      const TargetRegisterInfo* TRI) {
17422   // Scan forward through BB for a use/def of EFLAGS.
17423   MachineBasicBlock::iterator miI(std::next(SelectItr));
17424   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17425     const MachineInstr& mi = *miI;
17426     if (mi.readsRegister(X86::EFLAGS))
17427       return false;
17428     if (mi.definesRegister(X86::EFLAGS))
17429       break; // Should have kill-flag - update below.
17430   }
17431
17432   // If we hit the end of the block, check whether EFLAGS is live into a
17433   // successor.
17434   if (miI == BB->end()) {
17435     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17436                                           sEnd = BB->succ_end();
17437          sItr != sEnd; ++sItr) {
17438       MachineBasicBlock* succ = *sItr;
17439       if (succ->isLiveIn(X86::EFLAGS))
17440         return false;
17441     }
17442   }
17443
17444   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17445   // out. SelectMI should have a kill flag on EFLAGS.
17446   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17447   return true;
17448 }
17449
17450 MachineBasicBlock *
17451 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17452                                      MachineBasicBlock *BB) const {
17453   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17454   DebugLoc DL = MI->getDebugLoc();
17455
17456   // To "insert" a SELECT_CC instruction, we actually have to insert the
17457   // diamond control-flow pattern.  The incoming instruction knows the
17458   // destination vreg to set, the condition code register to branch on, the
17459   // true/false values to select between, and a branch opcode to use.
17460   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17461   MachineFunction::iterator It = BB;
17462   ++It;
17463
17464   //  thisMBB:
17465   //  ...
17466   //   TrueVal = ...
17467   //   cmpTY ccX, r1, r2
17468   //   bCC copy1MBB
17469   //   fallthrough --> copy0MBB
17470   MachineBasicBlock *thisMBB = BB;
17471   MachineFunction *F = BB->getParent();
17472   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17473   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17474   F->insert(It, copy0MBB);
17475   F->insert(It, sinkMBB);
17476
17477   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17478   // live into the sink and copy blocks.
17479   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17480   if (!MI->killsRegister(X86::EFLAGS) &&
17481       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17482     copy0MBB->addLiveIn(X86::EFLAGS);
17483     sinkMBB->addLiveIn(X86::EFLAGS);
17484   }
17485
17486   // Transfer the remainder of BB and its successor edges to sinkMBB.
17487   sinkMBB->splice(sinkMBB->begin(), BB,
17488                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17489   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17490
17491   // Add the true and fallthrough blocks as its successors.
17492   BB->addSuccessor(copy0MBB);
17493   BB->addSuccessor(sinkMBB);
17494
17495   // Create the conditional branch instruction.
17496   unsigned Opc =
17497     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17498   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17499
17500   //  copy0MBB:
17501   //   %FalseValue = ...
17502   //   # fallthrough to sinkMBB
17503   copy0MBB->addSuccessor(sinkMBB);
17504
17505   //  sinkMBB:
17506   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17507   //  ...
17508   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17509           TII->get(X86::PHI), MI->getOperand(0).getReg())
17510     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17511     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17512
17513   MI->eraseFromParent();   // The pseudo instruction is gone now.
17514   return sinkMBB;
17515 }
17516
17517 MachineBasicBlock *
17518 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17519                                         bool Is64Bit) const {
17520   MachineFunction *MF = BB->getParent();
17521   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17522   DebugLoc DL = MI->getDebugLoc();
17523   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17524
17525   assert(MF->shouldSplitStack());
17526
17527   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17528   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17529
17530   // BB:
17531   //  ... [Till the alloca]
17532   // If stacklet is not large enough, jump to mallocMBB
17533   //
17534   // bumpMBB:
17535   //  Allocate by subtracting from RSP
17536   //  Jump to continueMBB
17537   //
17538   // mallocMBB:
17539   //  Allocate by call to runtime
17540   //
17541   // continueMBB:
17542   //  ...
17543   //  [rest of original BB]
17544   //
17545
17546   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17547   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17548   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17549
17550   MachineRegisterInfo &MRI = MF->getRegInfo();
17551   const TargetRegisterClass *AddrRegClass =
17552     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17553
17554   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17555     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17556     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17557     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17558     sizeVReg = MI->getOperand(1).getReg(),
17559     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17560
17561   MachineFunction::iterator MBBIter = BB;
17562   ++MBBIter;
17563
17564   MF->insert(MBBIter, bumpMBB);
17565   MF->insert(MBBIter, mallocMBB);
17566   MF->insert(MBBIter, continueMBB);
17567
17568   continueMBB->splice(continueMBB->begin(), BB,
17569                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17570   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17571
17572   // Add code to the main basic block to check if the stack limit has been hit,
17573   // and if so, jump to mallocMBB otherwise to bumpMBB.
17574   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17575   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17576     .addReg(tmpSPVReg).addReg(sizeVReg);
17577   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17578     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17579     .addReg(SPLimitVReg);
17580   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17581
17582   // bumpMBB simply decreases the stack pointer, since we know the current
17583   // stacklet has enough space.
17584   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17585     .addReg(SPLimitVReg);
17586   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17587     .addReg(SPLimitVReg);
17588   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17589
17590   // Calls into a routine in libgcc to allocate more space from the heap.
17591   const uint32_t *RegMask =
17592     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17593   if (Is64Bit) {
17594     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17595       .addReg(sizeVReg);
17596     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17597       .addExternalSymbol("__morestack_allocate_stack_space")
17598       .addRegMask(RegMask)
17599       .addReg(X86::RDI, RegState::Implicit)
17600       .addReg(X86::RAX, RegState::ImplicitDefine);
17601   } else {
17602     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17603       .addImm(12);
17604     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17605     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17606       .addExternalSymbol("__morestack_allocate_stack_space")
17607       .addRegMask(RegMask)
17608       .addReg(X86::EAX, RegState::ImplicitDefine);
17609   }
17610
17611   if (!Is64Bit)
17612     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17613       .addImm(16);
17614
17615   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17616     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17617   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17618
17619   // Set up the CFG correctly.
17620   BB->addSuccessor(bumpMBB);
17621   BB->addSuccessor(mallocMBB);
17622   mallocMBB->addSuccessor(continueMBB);
17623   bumpMBB->addSuccessor(continueMBB);
17624
17625   // Take care of the PHI nodes.
17626   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17627           MI->getOperand(0).getReg())
17628     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17629     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17630
17631   // Delete the original pseudo instruction.
17632   MI->eraseFromParent();
17633
17634   // And we're done.
17635   return continueMBB;
17636 }
17637
17638 MachineBasicBlock *
17639 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17640                                         MachineBasicBlock *BB) const {
17641   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17642   DebugLoc DL = MI->getDebugLoc();
17643
17644   assert(!Subtarget->isTargetMacho());
17645
17646   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17647   // non-trivial part is impdef of ESP.
17648
17649   if (Subtarget->isTargetWin64()) {
17650     if (Subtarget->isTargetCygMing()) {
17651       // ___chkstk(Mingw64):
17652       // Clobbers R10, R11, RAX and EFLAGS.
17653       // Updates RSP.
17654       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17655         .addExternalSymbol("___chkstk")
17656         .addReg(X86::RAX, RegState::Implicit)
17657         .addReg(X86::RSP, RegState::Implicit)
17658         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17659         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17660         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17661     } else {
17662       // __chkstk(MSVCRT): does not update stack pointer.
17663       // Clobbers R10, R11 and EFLAGS.
17664       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17665         .addExternalSymbol("__chkstk")
17666         .addReg(X86::RAX, RegState::Implicit)
17667         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17668       // RAX has the offset to be subtracted from RSP.
17669       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17670         .addReg(X86::RSP)
17671         .addReg(X86::RAX);
17672     }
17673   } else {
17674     const char *StackProbeSymbol =
17675       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17676
17677     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17678       .addExternalSymbol(StackProbeSymbol)
17679       .addReg(X86::EAX, RegState::Implicit)
17680       .addReg(X86::ESP, RegState::Implicit)
17681       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17682       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17683       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17684   }
17685
17686   MI->eraseFromParent();   // The pseudo instruction is gone now.
17687   return BB;
17688 }
17689
17690 MachineBasicBlock *
17691 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17692                                       MachineBasicBlock *BB) const {
17693   // This is pretty easy.  We're taking the value that we received from
17694   // our load from the relocation, sticking it in either RDI (x86-64)
17695   // or EAX and doing an indirect call.  The return value will then
17696   // be in the normal return register.
17697   MachineFunction *F = BB->getParent();
17698   const X86InstrInfo *TII
17699     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17700   DebugLoc DL = MI->getDebugLoc();
17701
17702   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17703   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17704
17705   // Get a register mask for the lowered call.
17706   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17707   // proper register mask.
17708   const uint32_t *RegMask =
17709     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17710   if (Subtarget->is64Bit()) {
17711     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17712                                       TII->get(X86::MOV64rm), X86::RDI)
17713     .addReg(X86::RIP)
17714     .addImm(0).addReg(0)
17715     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17716                       MI->getOperand(3).getTargetFlags())
17717     .addReg(0);
17718     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17719     addDirectMem(MIB, X86::RDI);
17720     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17721   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17722     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17723                                       TII->get(X86::MOV32rm), X86::EAX)
17724     .addReg(0)
17725     .addImm(0).addReg(0)
17726     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17727                       MI->getOperand(3).getTargetFlags())
17728     .addReg(0);
17729     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17730     addDirectMem(MIB, X86::EAX);
17731     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17732   } else {
17733     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17734                                       TII->get(X86::MOV32rm), X86::EAX)
17735     .addReg(TII->getGlobalBaseReg(F))
17736     .addImm(0).addReg(0)
17737     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17738                       MI->getOperand(3).getTargetFlags())
17739     .addReg(0);
17740     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17741     addDirectMem(MIB, X86::EAX);
17742     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17743   }
17744
17745   MI->eraseFromParent(); // The pseudo instruction is gone now.
17746   return BB;
17747 }
17748
17749 MachineBasicBlock *
17750 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17751                                     MachineBasicBlock *MBB) const {
17752   DebugLoc DL = MI->getDebugLoc();
17753   MachineFunction *MF = MBB->getParent();
17754   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17755   MachineRegisterInfo &MRI = MF->getRegInfo();
17756
17757   const BasicBlock *BB = MBB->getBasicBlock();
17758   MachineFunction::iterator I = MBB;
17759   ++I;
17760
17761   // Memory Reference
17762   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17763   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17764
17765   unsigned DstReg;
17766   unsigned MemOpndSlot = 0;
17767
17768   unsigned CurOp = 0;
17769
17770   DstReg = MI->getOperand(CurOp++).getReg();
17771   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17772   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17773   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17774   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17775
17776   MemOpndSlot = CurOp;
17777
17778   MVT PVT = getPointerTy();
17779   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17780          "Invalid Pointer Size!");
17781
17782   // For v = setjmp(buf), we generate
17783   //
17784   // thisMBB:
17785   //  buf[LabelOffset] = restoreMBB
17786   //  SjLjSetup restoreMBB
17787   //
17788   // mainMBB:
17789   //  v_main = 0
17790   //
17791   // sinkMBB:
17792   //  v = phi(main, restore)
17793   //
17794   // restoreMBB:
17795   //  v_restore = 1
17796
17797   MachineBasicBlock *thisMBB = MBB;
17798   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17799   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17800   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17801   MF->insert(I, mainMBB);
17802   MF->insert(I, sinkMBB);
17803   MF->push_back(restoreMBB);
17804
17805   MachineInstrBuilder MIB;
17806
17807   // Transfer the remainder of BB and its successor edges to sinkMBB.
17808   sinkMBB->splice(sinkMBB->begin(), MBB,
17809                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17810   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17811
17812   // thisMBB:
17813   unsigned PtrStoreOpc = 0;
17814   unsigned LabelReg = 0;
17815   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17816   Reloc::Model RM = MF->getTarget().getRelocationModel();
17817   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17818                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17819
17820   // Prepare IP either in reg or imm.
17821   if (!UseImmLabel) {
17822     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17823     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17824     LabelReg = MRI.createVirtualRegister(PtrRC);
17825     if (Subtarget->is64Bit()) {
17826       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17827               .addReg(X86::RIP)
17828               .addImm(0)
17829               .addReg(0)
17830               .addMBB(restoreMBB)
17831               .addReg(0);
17832     } else {
17833       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17834       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17835               .addReg(XII->getGlobalBaseReg(MF))
17836               .addImm(0)
17837               .addReg(0)
17838               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17839               .addReg(0);
17840     }
17841   } else
17842     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17843   // Store IP
17844   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17845   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17846     if (i == X86::AddrDisp)
17847       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17848     else
17849       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17850   }
17851   if (!UseImmLabel)
17852     MIB.addReg(LabelReg);
17853   else
17854     MIB.addMBB(restoreMBB);
17855   MIB.setMemRefs(MMOBegin, MMOEnd);
17856   // Setup
17857   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17858           .addMBB(restoreMBB);
17859
17860   const X86RegisterInfo *RegInfo =
17861     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17862   MIB.addRegMask(RegInfo->getNoPreservedMask());
17863   thisMBB->addSuccessor(mainMBB);
17864   thisMBB->addSuccessor(restoreMBB);
17865
17866   // mainMBB:
17867   //  EAX = 0
17868   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17869   mainMBB->addSuccessor(sinkMBB);
17870
17871   // sinkMBB:
17872   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17873           TII->get(X86::PHI), DstReg)
17874     .addReg(mainDstReg).addMBB(mainMBB)
17875     .addReg(restoreDstReg).addMBB(restoreMBB);
17876
17877   // restoreMBB:
17878   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17879   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17880   restoreMBB->addSuccessor(sinkMBB);
17881
17882   MI->eraseFromParent();
17883   return sinkMBB;
17884 }
17885
17886 MachineBasicBlock *
17887 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17888                                      MachineBasicBlock *MBB) const {
17889   DebugLoc DL = MI->getDebugLoc();
17890   MachineFunction *MF = MBB->getParent();
17891   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17892   MachineRegisterInfo &MRI = MF->getRegInfo();
17893
17894   // Memory Reference
17895   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17896   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17897
17898   MVT PVT = getPointerTy();
17899   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17900          "Invalid Pointer Size!");
17901
17902   const TargetRegisterClass *RC =
17903     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17904   unsigned Tmp = MRI.createVirtualRegister(RC);
17905   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17906   const X86RegisterInfo *RegInfo =
17907     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17908   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17909   unsigned SP = RegInfo->getStackRegister();
17910
17911   MachineInstrBuilder MIB;
17912
17913   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17914   const int64_t SPOffset = 2 * PVT.getStoreSize();
17915
17916   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17917   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17918
17919   // Reload FP
17920   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17921   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17922     MIB.addOperand(MI->getOperand(i));
17923   MIB.setMemRefs(MMOBegin, MMOEnd);
17924   // Reload IP
17925   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17926   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17927     if (i == X86::AddrDisp)
17928       MIB.addDisp(MI->getOperand(i), LabelOffset);
17929     else
17930       MIB.addOperand(MI->getOperand(i));
17931   }
17932   MIB.setMemRefs(MMOBegin, MMOEnd);
17933   // Reload SP
17934   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17935   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17936     if (i == X86::AddrDisp)
17937       MIB.addDisp(MI->getOperand(i), SPOffset);
17938     else
17939       MIB.addOperand(MI->getOperand(i));
17940   }
17941   MIB.setMemRefs(MMOBegin, MMOEnd);
17942   // Jump
17943   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17944
17945   MI->eraseFromParent();
17946   return MBB;
17947 }
17948
17949 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17950 // accumulator loops. Writing back to the accumulator allows the coalescer
17951 // to remove extra copies in the loop.   
17952 MachineBasicBlock *
17953 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17954                                  MachineBasicBlock *MBB) const {
17955   MachineOperand &AddendOp = MI->getOperand(3);
17956
17957   // Bail out early if the addend isn't a register - we can't switch these.
17958   if (!AddendOp.isReg())
17959     return MBB;
17960
17961   MachineFunction &MF = *MBB->getParent();
17962   MachineRegisterInfo &MRI = MF.getRegInfo();
17963
17964   // Check whether the addend is defined by a PHI:
17965   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17966   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17967   if (!AddendDef.isPHI())
17968     return MBB;
17969
17970   // Look for the following pattern:
17971   // loop:
17972   //   %addend = phi [%entry, 0], [%loop, %result]
17973   //   ...
17974   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17975
17976   // Replace with:
17977   //   loop:
17978   //   %addend = phi [%entry, 0], [%loop, %result]
17979   //   ...
17980   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17981
17982   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17983     assert(AddendDef.getOperand(i).isReg());
17984     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17985     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17986     if (&PHISrcInst == MI) {
17987       // Found a matching instruction.
17988       unsigned NewFMAOpc = 0;
17989       switch (MI->getOpcode()) {
17990         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17991         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17992         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17993         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17994         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17995         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17996         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17997         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17998         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17999         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18000         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18001         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18002         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18003         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18004         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18005         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18006         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18007         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18008         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18009         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18010         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18011         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18012         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18013         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18014         default: llvm_unreachable("Unrecognized FMA variant.");
18015       }
18016
18017       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18018       MachineInstrBuilder MIB =
18019         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18020         .addOperand(MI->getOperand(0))
18021         .addOperand(MI->getOperand(3))
18022         .addOperand(MI->getOperand(2))
18023         .addOperand(MI->getOperand(1));
18024       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18025       MI->eraseFromParent();
18026     }
18027   }
18028
18029   return MBB;
18030 }
18031
18032 MachineBasicBlock *
18033 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18034                                                MachineBasicBlock *BB) const {
18035   switch (MI->getOpcode()) {
18036   default: llvm_unreachable("Unexpected instr type to insert");
18037   case X86::TAILJMPd64:
18038   case X86::TAILJMPr64:
18039   case X86::TAILJMPm64:
18040     llvm_unreachable("TAILJMP64 would not be touched here.");
18041   case X86::TCRETURNdi64:
18042   case X86::TCRETURNri64:
18043   case X86::TCRETURNmi64:
18044     return BB;
18045   case X86::WIN_ALLOCA:
18046     return EmitLoweredWinAlloca(MI, BB);
18047   case X86::SEG_ALLOCA_32:
18048     return EmitLoweredSegAlloca(MI, BB, false);
18049   case X86::SEG_ALLOCA_64:
18050     return EmitLoweredSegAlloca(MI, BB, true);
18051   case X86::TLSCall_32:
18052   case X86::TLSCall_64:
18053     return EmitLoweredTLSCall(MI, BB);
18054   case X86::CMOV_GR8:
18055   case X86::CMOV_FR32:
18056   case X86::CMOV_FR64:
18057   case X86::CMOV_V4F32:
18058   case X86::CMOV_V2F64:
18059   case X86::CMOV_V2I64:
18060   case X86::CMOV_V8F32:
18061   case X86::CMOV_V4F64:
18062   case X86::CMOV_V4I64:
18063   case X86::CMOV_V16F32:
18064   case X86::CMOV_V8F64:
18065   case X86::CMOV_V8I64:
18066   case X86::CMOV_GR16:
18067   case X86::CMOV_GR32:
18068   case X86::CMOV_RFP32:
18069   case X86::CMOV_RFP64:
18070   case X86::CMOV_RFP80:
18071     return EmitLoweredSelect(MI, BB);
18072
18073   case X86::FP32_TO_INT16_IN_MEM:
18074   case X86::FP32_TO_INT32_IN_MEM:
18075   case X86::FP32_TO_INT64_IN_MEM:
18076   case X86::FP64_TO_INT16_IN_MEM:
18077   case X86::FP64_TO_INT32_IN_MEM:
18078   case X86::FP64_TO_INT64_IN_MEM:
18079   case X86::FP80_TO_INT16_IN_MEM:
18080   case X86::FP80_TO_INT32_IN_MEM:
18081   case X86::FP80_TO_INT64_IN_MEM: {
18082     MachineFunction *F = BB->getParent();
18083     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18084     DebugLoc DL = MI->getDebugLoc();
18085
18086     // Change the floating point control register to use "round towards zero"
18087     // mode when truncating to an integer value.
18088     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18089     addFrameReference(BuildMI(*BB, MI, DL,
18090                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18091
18092     // Load the old value of the high byte of the control word...
18093     unsigned OldCW =
18094       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18095     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18096                       CWFrameIdx);
18097
18098     // Set the high part to be round to zero...
18099     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18100       .addImm(0xC7F);
18101
18102     // Reload the modified control word now...
18103     addFrameReference(BuildMI(*BB, MI, DL,
18104                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18105
18106     // Restore the memory image of control word to original value
18107     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18108       .addReg(OldCW);
18109
18110     // Get the X86 opcode to use.
18111     unsigned Opc;
18112     switch (MI->getOpcode()) {
18113     default: llvm_unreachable("illegal opcode!");
18114     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18115     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18116     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18117     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18118     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18119     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18120     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18121     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18122     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18123     }
18124
18125     X86AddressMode AM;
18126     MachineOperand &Op = MI->getOperand(0);
18127     if (Op.isReg()) {
18128       AM.BaseType = X86AddressMode::RegBase;
18129       AM.Base.Reg = Op.getReg();
18130     } else {
18131       AM.BaseType = X86AddressMode::FrameIndexBase;
18132       AM.Base.FrameIndex = Op.getIndex();
18133     }
18134     Op = MI->getOperand(1);
18135     if (Op.isImm())
18136       AM.Scale = Op.getImm();
18137     Op = MI->getOperand(2);
18138     if (Op.isImm())
18139       AM.IndexReg = Op.getImm();
18140     Op = MI->getOperand(3);
18141     if (Op.isGlobal()) {
18142       AM.GV = Op.getGlobal();
18143     } else {
18144       AM.Disp = Op.getImm();
18145     }
18146     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18147                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18148
18149     // Reload the original control word now.
18150     addFrameReference(BuildMI(*BB, MI, DL,
18151                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18152
18153     MI->eraseFromParent();   // The pseudo instruction is gone now.
18154     return BB;
18155   }
18156     // String/text processing lowering.
18157   case X86::PCMPISTRM128REG:
18158   case X86::VPCMPISTRM128REG:
18159   case X86::PCMPISTRM128MEM:
18160   case X86::VPCMPISTRM128MEM:
18161   case X86::PCMPESTRM128REG:
18162   case X86::VPCMPESTRM128REG:
18163   case X86::PCMPESTRM128MEM:
18164   case X86::VPCMPESTRM128MEM:
18165     assert(Subtarget->hasSSE42() &&
18166            "Target must have SSE4.2 or AVX features enabled");
18167     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18168
18169   // String/text processing lowering.
18170   case X86::PCMPISTRIREG:
18171   case X86::VPCMPISTRIREG:
18172   case X86::PCMPISTRIMEM:
18173   case X86::VPCMPISTRIMEM:
18174   case X86::PCMPESTRIREG:
18175   case X86::VPCMPESTRIREG:
18176   case X86::PCMPESTRIMEM:
18177   case X86::VPCMPESTRIMEM:
18178     assert(Subtarget->hasSSE42() &&
18179            "Target must have SSE4.2 or AVX features enabled");
18180     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18181
18182   // Thread synchronization.
18183   case X86::MONITOR:
18184     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18185
18186   // xbegin
18187   case X86::XBEGIN:
18188     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18189
18190   case X86::VASTART_SAVE_XMM_REGS:
18191     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18192
18193   case X86::VAARG_64:
18194     return EmitVAARG64WithCustomInserter(MI, BB);
18195
18196   case X86::EH_SjLj_SetJmp32:
18197   case X86::EH_SjLj_SetJmp64:
18198     return emitEHSjLjSetJmp(MI, BB);
18199
18200   case X86::EH_SjLj_LongJmp32:
18201   case X86::EH_SjLj_LongJmp64:
18202     return emitEHSjLjLongJmp(MI, BB);
18203
18204   case TargetOpcode::STACKMAP:
18205   case TargetOpcode::PATCHPOINT:
18206     return emitPatchPoint(MI, BB);
18207
18208   case X86::VFMADDPDr213r:
18209   case X86::VFMADDPSr213r:
18210   case X86::VFMADDSDr213r:
18211   case X86::VFMADDSSr213r:
18212   case X86::VFMSUBPDr213r:
18213   case X86::VFMSUBPSr213r:
18214   case X86::VFMSUBSDr213r:
18215   case X86::VFMSUBSSr213r:
18216   case X86::VFNMADDPDr213r:
18217   case X86::VFNMADDPSr213r:
18218   case X86::VFNMADDSDr213r:
18219   case X86::VFNMADDSSr213r:
18220   case X86::VFNMSUBPDr213r:
18221   case X86::VFNMSUBPSr213r:
18222   case X86::VFNMSUBSDr213r:
18223   case X86::VFNMSUBSSr213r:
18224   case X86::VFMADDPDr213rY:
18225   case X86::VFMADDPSr213rY:
18226   case X86::VFMSUBPDr213rY:
18227   case X86::VFMSUBPSr213rY:
18228   case X86::VFNMADDPDr213rY:
18229   case X86::VFNMADDPSr213rY:
18230   case X86::VFNMSUBPDr213rY:
18231   case X86::VFNMSUBPSr213rY:
18232     return emitFMA3Instr(MI, BB);
18233   }
18234 }
18235
18236 //===----------------------------------------------------------------------===//
18237 //                           X86 Optimization Hooks
18238 //===----------------------------------------------------------------------===//
18239
18240 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18241                                                       APInt &KnownZero,
18242                                                       APInt &KnownOne,
18243                                                       const SelectionDAG &DAG,
18244                                                       unsigned Depth) const {
18245   unsigned BitWidth = KnownZero.getBitWidth();
18246   unsigned Opc = Op.getOpcode();
18247   assert((Opc >= ISD::BUILTIN_OP_END ||
18248           Opc == ISD::INTRINSIC_WO_CHAIN ||
18249           Opc == ISD::INTRINSIC_W_CHAIN ||
18250           Opc == ISD::INTRINSIC_VOID) &&
18251          "Should use MaskedValueIsZero if you don't know whether Op"
18252          " is a target node!");
18253
18254   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18255   switch (Opc) {
18256   default: break;
18257   case X86ISD::ADD:
18258   case X86ISD::SUB:
18259   case X86ISD::ADC:
18260   case X86ISD::SBB:
18261   case X86ISD::SMUL:
18262   case X86ISD::UMUL:
18263   case X86ISD::INC:
18264   case X86ISD::DEC:
18265   case X86ISD::OR:
18266   case X86ISD::XOR:
18267   case X86ISD::AND:
18268     // These nodes' second result is a boolean.
18269     if (Op.getResNo() == 0)
18270       break;
18271     // Fallthrough
18272   case X86ISD::SETCC:
18273     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18274     break;
18275   case ISD::INTRINSIC_WO_CHAIN: {
18276     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18277     unsigned NumLoBits = 0;
18278     switch (IntId) {
18279     default: break;
18280     case Intrinsic::x86_sse_movmsk_ps:
18281     case Intrinsic::x86_avx_movmsk_ps_256:
18282     case Intrinsic::x86_sse2_movmsk_pd:
18283     case Intrinsic::x86_avx_movmsk_pd_256:
18284     case Intrinsic::x86_mmx_pmovmskb:
18285     case Intrinsic::x86_sse2_pmovmskb_128:
18286     case Intrinsic::x86_avx2_pmovmskb: {
18287       // High bits of movmskp{s|d}, pmovmskb are known zero.
18288       switch (IntId) {
18289         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18290         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18291         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18292         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18293         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18294         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18295         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18296         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18297       }
18298       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18299       break;
18300     }
18301     }
18302     break;
18303   }
18304   }
18305 }
18306
18307 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18308   SDValue Op,
18309   const SelectionDAG &,
18310   unsigned Depth) const {
18311   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18312   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18313     return Op.getValueType().getScalarType().getSizeInBits();
18314
18315   // Fallback case.
18316   return 1;
18317 }
18318
18319 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18320 /// node is a GlobalAddress + offset.
18321 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18322                                        const GlobalValue* &GA,
18323                                        int64_t &Offset) const {
18324   if (N->getOpcode() == X86ISD::Wrapper) {
18325     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18326       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18327       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18328       return true;
18329     }
18330   }
18331   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18332 }
18333
18334 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18335 /// same as extracting the high 128-bit part of 256-bit vector and then
18336 /// inserting the result into the low part of a new 256-bit vector
18337 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18338   EVT VT = SVOp->getValueType(0);
18339   unsigned NumElems = VT.getVectorNumElements();
18340
18341   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18342   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18343     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18344         SVOp->getMaskElt(j) >= 0)
18345       return false;
18346
18347   return true;
18348 }
18349
18350 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18351 /// same as extracting the low 128-bit part of 256-bit vector and then
18352 /// inserting the result into the high part of a new 256-bit vector
18353 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18354   EVT VT = SVOp->getValueType(0);
18355   unsigned NumElems = VT.getVectorNumElements();
18356
18357   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18358   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18359     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18360         SVOp->getMaskElt(j) >= 0)
18361       return false;
18362
18363   return true;
18364 }
18365
18366 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18367 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18368                                         TargetLowering::DAGCombinerInfo &DCI,
18369                                         const X86Subtarget* Subtarget) {
18370   SDLoc dl(N);
18371   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18372   SDValue V1 = SVOp->getOperand(0);
18373   SDValue V2 = SVOp->getOperand(1);
18374   EVT VT = SVOp->getValueType(0);
18375   unsigned NumElems = VT.getVectorNumElements();
18376
18377   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18378       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18379     //
18380     //                   0,0,0,...
18381     //                      |
18382     //    V      UNDEF    BUILD_VECTOR    UNDEF
18383     //     \      /           \           /
18384     //  CONCAT_VECTOR         CONCAT_VECTOR
18385     //         \                  /
18386     //          \                /
18387     //          RESULT: V + zero extended
18388     //
18389     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18390         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18391         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18392       return SDValue();
18393
18394     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18395       return SDValue();
18396
18397     // To match the shuffle mask, the first half of the mask should
18398     // be exactly the first vector, and all the rest a splat with the
18399     // first element of the second one.
18400     for (unsigned i = 0; i != NumElems/2; ++i)
18401       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18402           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18403         return SDValue();
18404
18405     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18406     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18407       if (Ld->hasNUsesOfValue(1, 0)) {
18408         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18409         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18410         SDValue ResNode =
18411           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18412                                   Ld->getMemoryVT(),
18413                                   Ld->getPointerInfo(),
18414                                   Ld->getAlignment(),
18415                                   false/*isVolatile*/, true/*ReadMem*/,
18416                                   false/*WriteMem*/);
18417
18418         // Make sure the newly-created LOAD is in the same position as Ld in
18419         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18420         // and update uses of Ld's output chain to use the TokenFactor.
18421         if (Ld->hasAnyUseOfValue(1)) {
18422           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18423                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18424           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18425           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18426                                  SDValue(ResNode.getNode(), 1));
18427         }
18428
18429         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18430       }
18431     }
18432
18433     // Emit a zeroed vector and insert the desired subvector on its
18434     // first half.
18435     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18436     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18437     return DCI.CombineTo(N, InsV);
18438   }
18439
18440   //===--------------------------------------------------------------------===//
18441   // Combine some shuffles into subvector extracts and inserts:
18442   //
18443
18444   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18445   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18446     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18447     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18448     return DCI.CombineTo(N, InsV);
18449   }
18450
18451   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18452   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18453     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18454     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18455     return DCI.CombineTo(N, InsV);
18456   }
18457
18458   return SDValue();
18459 }
18460
18461 /// \brief Get the PSHUF-style mask from PSHUF node.
18462 ///
18463 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18464 /// PSHUF-style masks that can be reused with such instructions.
18465 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18466   SmallVector<int, 4> Mask;
18467   bool IsUnary;
18468   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18469   (void)HaveMask;
18470   assert(HaveMask);
18471
18472   switch (N.getOpcode()) {
18473   case X86ISD::PSHUFD:
18474     return Mask;
18475   case X86ISD::PSHUFLW:
18476     Mask.resize(4);
18477     return Mask;
18478   case X86ISD::PSHUFHW:
18479     Mask.erase(Mask.begin(), Mask.begin() + 4);
18480     for (int &M : Mask)
18481       M -= 4;
18482     return Mask;
18483   default:
18484     llvm_unreachable("No valid shuffle instruction found!");
18485   }
18486 }
18487
18488 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18489 ///
18490 /// We walk up the chain and look for a combinable shuffle, skipping over
18491 /// shuffles that we could hoist this shuffle's transformation past without
18492 /// altering anything.
18493 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18494                                          SelectionDAG &DAG,
18495                                          TargetLowering::DAGCombinerInfo &DCI) {
18496   assert(N.getOpcode() == X86ISD::PSHUFD &&
18497          "Called with something other than an x86 128-bit half shuffle!");
18498   SDLoc DL(N);
18499
18500   // Walk up a single-use chain looking for a combinable shuffle.
18501   SDValue V = N.getOperand(0);
18502   for (; V.hasOneUse(); V = V.getOperand(0)) {
18503     switch (V.getOpcode()) {
18504     default:
18505       return false; // Nothing combined!
18506
18507     case ISD::BITCAST:
18508       // Skip bitcasts as we always know the type for the target specific
18509       // instructions.
18510       continue;
18511
18512     case X86ISD::PSHUFD:
18513       // Found another dword shuffle.
18514       break;
18515
18516     case X86ISD::PSHUFLW:
18517       // Check that the low words (being shuffled) are the identity in the
18518       // dword shuffle, and the high words are self-contained.
18519       if (Mask[0] != 0 || Mask[1] != 1 ||
18520           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18521         return false;
18522
18523       continue;
18524
18525     case X86ISD::PSHUFHW:
18526       // Check that the high words (being shuffled) are the identity in the
18527       // dword shuffle, and the low words are self-contained.
18528       if (Mask[2] != 2 || Mask[3] != 3 ||
18529           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18530         return false;
18531
18532       continue;
18533
18534     case X86ISD::UNPCKL:
18535     case X86ISD::UNPCKH:
18536       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
18537       // shuffle into a preceding word shuffle.
18538       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
18539         return false;
18540
18541       // Search for a half-shuffle which we can combine with.
18542       unsigned CombineOp =
18543           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18544       if (V.getOperand(0) != V.getOperand(1) ||
18545           !V->isOnlyUserOf(V.getOperand(0).getNode()))
18546         return false;
18547       V = V.getOperand(0);
18548       do {
18549         switch (V.getOpcode()) {
18550         default:
18551           return false; // Nothing to combine.
18552
18553         case X86ISD::PSHUFLW:
18554         case X86ISD::PSHUFHW:
18555           if (V.getOpcode() == CombineOp)
18556             break;
18557
18558           // Fallthrough!
18559         case ISD::BITCAST:
18560           V = V.getOperand(0);
18561           continue;
18562         }
18563         break;
18564       } while (V.hasOneUse());
18565       break;
18566     }
18567     // Break out of the loop if we break out of the switch.
18568     break;
18569   }
18570
18571   if (!V.hasOneUse())
18572     // We fell out of the loop without finding a viable combining instruction.
18573     return false;
18574
18575   // Record the old value to use in RAUW-ing.
18576   SDValue Old = V;
18577
18578   // Merge this node's mask and our incoming mask.
18579   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18580   for (int &M : Mask)
18581     M = VMask[M];
18582   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
18583                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18584
18585   // It is possible that one of the combinable shuffles was completely absorbed
18586   // by the other, just replace it and revisit all users in that case.
18587   if (Old.getNode() == V.getNode()) {
18588     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18589     return true;
18590   }
18591
18592   // Replace N with its operand as we're going to combine that shuffle away.
18593   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18594
18595   // Replace the combinable shuffle with the combined one, updating all users
18596   // so that we re-evaluate the chain here.
18597   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18598   return true;
18599 }
18600
18601 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18602 ///
18603 /// We walk up the chain, skipping shuffles of the other half and looking
18604 /// through shuffles which switch halves trying to find a shuffle of the same
18605 /// pair of dwords.
18606 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18607                                         SelectionDAG &DAG,
18608                                         TargetLowering::DAGCombinerInfo &DCI) {
18609   assert(
18610       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18611       "Called with something other than an x86 128-bit half shuffle!");
18612   SDLoc DL(N);
18613   unsigned CombineOpcode = N.getOpcode();
18614
18615   // Walk up a single-use chain looking for a combinable shuffle.
18616   SDValue V = N.getOperand(0);
18617   for (; V.hasOneUse(); V = V.getOperand(0)) {
18618     switch (V.getOpcode()) {
18619     default:
18620       return false; // Nothing combined!
18621
18622     case ISD::BITCAST:
18623       // Skip bitcasts as we always know the type for the target specific
18624       // instructions.
18625       continue;
18626
18627     case X86ISD::PSHUFLW:
18628     case X86ISD::PSHUFHW:
18629       if (V.getOpcode() == CombineOpcode)
18630         break;
18631
18632       // Other-half shuffles are no-ops.
18633       continue;
18634
18635     case X86ISD::PSHUFD: {
18636       // We can only handle pshufd if the half we are combining either stays in
18637       // its half, or switches to the other half. Bail if one of these isn't
18638       // true.
18639       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18640       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18641       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18642             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18643         return false;
18644
18645       // Map the mask through the pshufd and keep walking up the chain.
18646       for (int i = 0; i < 4; ++i)
18647         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18648
18649       // Switch halves if the pshufd does.
18650       CombineOpcode =
18651           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18652       continue;
18653     }
18654     }
18655     // Break out of the loop if we break out of the switch.
18656     break;
18657   }
18658
18659   if (!V.hasOneUse())
18660     // We fell out of the loop without finding a viable combining instruction.
18661     return false;
18662
18663   // Record the old value to use in RAUW-ing.
18664   SDValue Old = V;
18665
18666   // Merge this node's mask and our incoming mask (adjusted to account for all
18667   // the pshufd instructions encountered).
18668   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18669   for (int &M : Mask)
18670     M = VMask[M];
18671   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18672                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18673
18674   // Replace N with its operand as we're going to combine that shuffle away.
18675   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18676
18677   // Replace the combinable shuffle with the combined one, updating all users
18678   // so that we re-evaluate the chain here.
18679   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18680   return true;
18681 }
18682
18683 /// \brief Try to combine x86 target specific shuffles.
18684 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18685                                            TargetLowering::DAGCombinerInfo &DCI,
18686                                            const X86Subtarget *Subtarget) {
18687   SDLoc DL(N);
18688   MVT VT = N.getSimpleValueType();
18689   SmallVector<int, 4> Mask;
18690
18691   switch (N.getOpcode()) {
18692   case X86ISD::PSHUFD:
18693   case X86ISD::PSHUFLW:
18694   case X86ISD::PSHUFHW:
18695     Mask = getPSHUFShuffleMask(N);
18696     assert(Mask.size() == 4);
18697     break;
18698   default:
18699     return SDValue();
18700   }
18701
18702   // Nuke no-op shuffles that show up after combining.
18703   if (isNoopShuffleMask(Mask))
18704     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18705
18706   // Look for simplifications involving one or two shuffle instructions.
18707   SDValue V = N.getOperand(0);
18708   switch (N.getOpcode()) {
18709   default:
18710     break;
18711   case X86ISD::PSHUFLW:
18712   case X86ISD::PSHUFHW:
18713     assert(VT == MVT::v8i16);
18714     (void)VT;
18715
18716     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18717       return SDValue(); // We combined away this shuffle, so we're done.
18718
18719     // See if this reduces to a PSHUFD which is no more expensive and can
18720     // combine with more operations.
18721     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18722         areAdjacentMasksSequential(Mask)) {
18723       int DMask[] = {-1, -1, -1, -1};
18724       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18725       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18726       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18727       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18728       DCI.AddToWorklist(V.getNode());
18729       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18730                       getV4X86ShuffleImm8ForMask(DMask, DAG));
18731       DCI.AddToWorklist(V.getNode());
18732       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18733     }
18734
18735     // Look for shuffle patterns which can be implemented as a single unpack.
18736     // FIXME: This doesn't handle the location of the PSHUFD generically, and
18737     // only works when we have a PSHUFD followed by two half-shuffles.
18738     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
18739         (V.getOpcode() == X86ISD::PSHUFLW ||
18740          V.getOpcode() == X86ISD::PSHUFHW) &&
18741         V.getOpcode() != N.getOpcode() &&
18742         V.hasOneUse()) {
18743       SDValue D = V.getOperand(0);
18744       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
18745         D = D.getOperand(0);
18746       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
18747         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18748         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
18749         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18750         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18751         int WordMask[8];
18752         for (int i = 0; i < 4; ++i) {
18753           WordMask[i + NOffset] = Mask[i] + NOffset;
18754           WordMask[i + VOffset] = VMask[i] + VOffset;
18755         }
18756         // Map the word mask through the DWord mask.
18757         int MappedMask[8];
18758         for (int i = 0; i < 8; ++i)
18759           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
18760         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
18761         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
18762         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
18763                        std::begin(UnpackLoMask)) ||
18764             std::equal(std::begin(MappedMask), std::end(MappedMask),
18765                        std::begin(UnpackHiMask))) {
18766           // We can replace all three shuffles with an unpack.
18767           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
18768           DCI.AddToWorklist(V.getNode());
18769           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
18770                                                 : X86ISD::UNPCKH,
18771                              DL, MVT::v8i16, V, V);
18772         }
18773       }
18774     }
18775
18776     break;
18777
18778   case X86ISD::PSHUFD:
18779     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18780       return SDValue(); // We combined away this shuffle.
18781
18782     break;
18783   }
18784
18785   return SDValue();
18786 }
18787
18788 /// PerformShuffleCombine - Performs several different shuffle combines.
18789 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18790                                      TargetLowering::DAGCombinerInfo &DCI,
18791                                      const X86Subtarget *Subtarget) {
18792   SDLoc dl(N);
18793   SDValue N0 = N->getOperand(0);
18794   SDValue N1 = N->getOperand(1);
18795   EVT VT = N->getValueType(0);
18796
18797   // Canonicalize shuffles that perform 'addsub' on packed float vectors
18798   // according to the rule:
18799   //  (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18800   //  (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18801   //
18802   // Where 'Mask' is:
18803   //  <0,5,2,7>             -- for v4f32 and v4f64 shuffles;
18804   //  <0,3>                 -- for v2f64 shuffles;
18805   //  <0,9,2,11,4,13,6,15>  -- for v8f32 shuffles.
18806   //
18807   // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18808   // during ISel stage.
18809   if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18810       ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18811        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18812       N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18813       // Operands to the FADD and FSUB must be the same.
18814       ((N0->getOperand(0) == N1->getOperand(0) &&
18815         N0->getOperand(1) == N1->getOperand(1)) ||
18816        // FADD is commutable. See if by commuting the operands of the FADD
18817        // we would still be able to match the operands of the FSUB dag node.
18818        (N0->getOperand(1) == N1->getOperand(0) &&
18819         N0->getOperand(0) == N1->getOperand(1))) &&
18820       N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18821       N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18822     
18823     ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18824     unsigned NumElts = VT.getVectorNumElements();
18825     ArrayRef<int> Mask = SV->getMask();
18826     bool CanFold = true;
18827
18828     for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18829       CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18830
18831     if (CanFold) {
18832       SDValue Op0 = N1->getOperand(0);
18833       SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18834       SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18835       SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18836       return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18837     }
18838   }
18839
18840   // Don't create instructions with illegal types after legalize types has run.
18841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18842   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18843     return SDValue();
18844
18845   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18846   if (Subtarget->hasFp256() && VT.is256BitVector() &&
18847       N->getOpcode() == ISD::VECTOR_SHUFFLE)
18848     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18849
18850   // During Type Legalization, when promoting illegal vector types,
18851   // the backend might introduce new shuffle dag nodes and bitcasts.
18852   //
18853   // This code performs the following transformation:
18854   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18855   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18856   //
18857   // We do this only if both the bitcast and the BINOP dag nodes have
18858   // one use. Also, perform this transformation only if the new binary
18859   // operation is legal. This is to avoid introducing dag nodes that
18860   // potentially need to be further expanded (or custom lowered) into a
18861   // less optimal sequence of dag nodes.
18862   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18863       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18864       N0.getOpcode() == ISD::BITCAST) {
18865     SDValue BC0 = N0.getOperand(0);
18866     EVT SVT = BC0.getValueType();
18867     unsigned Opcode = BC0.getOpcode();
18868     unsigned NumElts = VT.getVectorNumElements();
18869     
18870     if (BC0.hasOneUse() && SVT.isVector() &&
18871         SVT.getVectorNumElements() * 2 == NumElts &&
18872         TLI.isOperationLegal(Opcode, VT)) {
18873       bool CanFold = false;
18874       switch (Opcode) {
18875       default : break;
18876       case ISD::ADD :
18877       case ISD::FADD :
18878       case ISD::SUB :
18879       case ISD::FSUB :
18880       case ISD::MUL :
18881       case ISD::FMUL :
18882         CanFold = true;
18883       }
18884
18885       unsigned SVTNumElts = SVT.getVectorNumElements();
18886       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18887       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18888         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18889       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18890         CanFold = SVOp->getMaskElt(i) < 0;
18891
18892       if (CanFold) {
18893         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18894         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18895         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18896         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18897       }
18898     }
18899   }
18900
18901   // Only handle 128 wide vector from here on.
18902   if (!VT.is128BitVector())
18903     return SDValue();
18904
18905   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18906   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18907   // consecutive, non-overlapping, and in the right order.
18908   SmallVector<SDValue, 16> Elts;
18909   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18910     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18911
18912   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18913   if (LD.getNode())
18914     return LD;
18915
18916   if (isTargetShuffle(N->getOpcode())) {
18917     SDValue Shuffle =
18918         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18919     if (Shuffle.getNode())
18920       return Shuffle;
18921   }
18922
18923   return SDValue();
18924 }
18925
18926 /// PerformTruncateCombine - Converts truncate operation to
18927 /// a sequence of vector shuffle operations.
18928 /// It is possible when we truncate 256-bit vector to 128-bit vector
18929 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18930                                       TargetLowering::DAGCombinerInfo &DCI,
18931                                       const X86Subtarget *Subtarget)  {
18932   return SDValue();
18933 }
18934
18935 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18936 /// specific shuffle of a load can be folded into a single element load.
18937 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18938 /// shuffles have been customed lowered so we need to handle those here.
18939 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18940                                          TargetLowering::DAGCombinerInfo &DCI) {
18941   if (DCI.isBeforeLegalizeOps())
18942     return SDValue();
18943
18944   SDValue InVec = N->getOperand(0);
18945   SDValue EltNo = N->getOperand(1);
18946
18947   if (!isa<ConstantSDNode>(EltNo))
18948     return SDValue();
18949
18950   EVT VT = InVec.getValueType();
18951
18952   bool HasShuffleIntoBitcast = false;
18953   if (InVec.getOpcode() == ISD::BITCAST) {
18954     // Don't duplicate a load with other uses.
18955     if (!InVec.hasOneUse())
18956       return SDValue();
18957     EVT BCVT = InVec.getOperand(0).getValueType();
18958     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18959       return SDValue();
18960     InVec = InVec.getOperand(0);
18961     HasShuffleIntoBitcast = true;
18962   }
18963
18964   if (!isTargetShuffle(InVec.getOpcode()))
18965     return SDValue();
18966
18967   // Don't duplicate a load with other uses.
18968   if (!InVec.hasOneUse())
18969     return SDValue();
18970
18971   SmallVector<int, 16> ShuffleMask;
18972   bool UnaryShuffle;
18973   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18974                             UnaryShuffle))
18975     return SDValue();
18976
18977   // Select the input vector, guarding against out of range extract vector.
18978   unsigned NumElems = VT.getVectorNumElements();
18979   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18980   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18981   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18982                                          : InVec.getOperand(1);
18983
18984   // If inputs to shuffle are the same for both ops, then allow 2 uses
18985   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18986
18987   if (LdNode.getOpcode() == ISD::BITCAST) {
18988     // Don't duplicate a load with other uses.
18989     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18990       return SDValue();
18991
18992     AllowedUses = 1; // only allow 1 load use if we have a bitcast
18993     LdNode = LdNode.getOperand(0);
18994   }
18995
18996   if (!ISD::isNormalLoad(LdNode.getNode()))
18997     return SDValue();
18998
18999   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19000
19001   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19002     return SDValue();
19003
19004   if (HasShuffleIntoBitcast) {
19005     // If there's a bitcast before the shuffle, check if the load type and
19006     // alignment is valid.
19007     unsigned Align = LN0->getAlignment();
19008     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19009     unsigned NewAlign = TLI.getDataLayout()->
19010       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19011
19012     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19013       return SDValue();
19014   }
19015
19016   // All checks match so transform back to vector_shuffle so that DAG combiner
19017   // can finish the job
19018   SDLoc dl(N);
19019
19020   // Create shuffle node taking into account the case that its a unary shuffle
19021   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19022   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19023                                  InVec.getOperand(0), Shuffle,
19024                                  &ShuffleMask[0]);
19025   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19026   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19027                      EltNo);
19028 }
19029
19030 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19031 /// generation and convert it from being a bunch of shuffles and extracts
19032 /// to a simple store and scalar loads to extract the elements.
19033 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19034                                          TargetLowering::DAGCombinerInfo &DCI) {
19035   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19036   if (NewOp.getNode())
19037     return NewOp;
19038
19039   SDValue InputVector = N->getOperand(0);
19040
19041   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19042   // from mmx to v2i32 has a single usage.
19043   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19044       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19045       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19046     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19047                        N->getValueType(0),
19048                        InputVector.getNode()->getOperand(0));
19049
19050   // Only operate on vectors of 4 elements, where the alternative shuffling
19051   // gets to be more expensive.
19052   if (InputVector.getValueType() != MVT::v4i32)
19053     return SDValue();
19054
19055   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19056   // single use which is a sign-extend or zero-extend, and all elements are
19057   // used.
19058   SmallVector<SDNode *, 4> Uses;
19059   unsigned ExtractedElements = 0;
19060   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19061        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19062     if (UI.getUse().getResNo() != InputVector.getResNo())
19063       return SDValue();
19064
19065     SDNode *Extract = *UI;
19066     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19067       return SDValue();
19068
19069     if (Extract->getValueType(0) != MVT::i32)
19070       return SDValue();
19071     if (!Extract->hasOneUse())
19072       return SDValue();
19073     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19074         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19075       return SDValue();
19076     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19077       return SDValue();
19078
19079     // Record which element was extracted.
19080     ExtractedElements |=
19081       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19082
19083     Uses.push_back(Extract);
19084   }
19085
19086   // If not all the elements were used, this may not be worthwhile.
19087   if (ExtractedElements != 15)
19088     return SDValue();
19089
19090   // Ok, we've now decided to do the transformation.
19091   SDLoc dl(InputVector);
19092
19093   // Store the value to a temporary stack slot.
19094   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19095   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19096                             MachinePointerInfo(), false, false, 0);
19097
19098   // Replace each use (extract) with a load of the appropriate element.
19099   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19100        UE = Uses.end(); UI != UE; ++UI) {
19101     SDNode *Extract = *UI;
19102
19103     // cOMpute the element's address.
19104     SDValue Idx = Extract->getOperand(1);
19105     unsigned EltSize =
19106         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19107     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19108     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19109     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19110
19111     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19112                                      StackPtr, OffsetVal);
19113
19114     // Load the scalar.
19115     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19116                                      ScalarAddr, MachinePointerInfo(),
19117                                      false, false, false, 0);
19118
19119     // Replace the exact with the load.
19120     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19121   }
19122
19123   // The replacement was made in place; don't return anything.
19124   return SDValue();
19125 }
19126
19127 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19128 static std::pair<unsigned, bool>
19129 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19130                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19131   if (!VT.isVector())
19132     return std::make_pair(0, false);
19133
19134   bool NeedSplit = false;
19135   switch (VT.getSimpleVT().SimpleTy) {
19136   default: return std::make_pair(0, false);
19137   case MVT::v32i8:
19138   case MVT::v16i16:
19139   case MVT::v8i32:
19140     if (!Subtarget->hasAVX2())
19141       NeedSplit = true;
19142     if (!Subtarget->hasAVX())
19143       return std::make_pair(0, false);
19144     break;
19145   case MVT::v16i8:
19146   case MVT::v8i16:
19147   case MVT::v4i32:
19148     if (!Subtarget->hasSSE2())
19149       return std::make_pair(0, false);
19150   }
19151
19152   // SSE2 has only a small subset of the operations.
19153   bool hasUnsigned = Subtarget->hasSSE41() ||
19154                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19155   bool hasSigned = Subtarget->hasSSE41() ||
19156                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19157
19158   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19159
19160   unsigned Opc = 0;
19161   // Check for x CC y ? x : y.
19162   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19163       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19164     switch (CC) {
19165     default: break;
19166     case ISD::SETULT:
19167     case ISD::SETULE:
19168       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19169     case ISD::SETUGT:
19170     case ISD::SETUGE:
19171       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19172     case ISD::SETLT:
19173     case ISD::SETLE:
19174       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19175     case ISD::SETGT:
19176     case ISD::SETGE:
19177       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19178     }
19179   // Check for x CC y ? y : x -- a min/max with reversed arms.
19180   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19181              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19182     switch (CC) {
19183     default: break;
19184     case ISD::SETULT:
19185     case ISD::SETULE:
19186       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19187     case ISD::SETUGT:
19188     case ISD::SETUGE:
19189       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19190     case ISD::SETLT:
19191     case ISD::SETLE:
19192       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19193     case ISD::SETGT:
19194     case ISD::SETGE:
19195       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19196     }
19197   }
19198
19199   return std::make_pair(Opc, NeedSplit);
19200 }
19201
19202 static SDValue
19203 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19204                                       const X86Subtarget *Subtarget) {
19205   SDLoc dl(N);
19206   SDValue Cond = N->getOperand(0);
19207   SDValue LHS = N->getOperand(1);
19208   SDValue RHS = N->getOperand(2);
19209
19210   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19211     SDValue CondSrc = Cond->getOperand(0);
19212     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19213       Cond = CondSrc->getOperand(0);
19214   }
19215
19216   MVT VT = N->getSimpleValueType(0);
19217   MVT EltVT = VT.getVectorElementType();
19218   unsigned NumElems = VT.getVectorNumElements();
19219   // There is no blend with immediate in AVX-512.
19220   if (VT.is512BitVector())
19221     return SDValue();
19222
19223   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19224     return SDValue();
19225   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19226     return SDValue();
19227
19228   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19229     return SDValue();
19230
19231   unsigned MaskValue = 0;
19232   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19233     return SDValue();
19234
19235   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19236   for (unsigned i = 0; i < NumElems; ++i) {
19237     // Be sure we emit undef where we can.
19238     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19239       ShuffleMask[i] = -1;
19240     else
19241       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19242   }
19243
19244   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19245 }
19246
19247 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19248 /// nodes.
19249 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19250                                     TargetLowering::DAGCombinerInfo &DCI,
19251                                     const X86Subtarget *Subtarget) {
19252   SDLoc DL(N);
19253   SDValue Cond = N->getOperand(0);
19254   // Get the LHS/RHS of the select.
19255   SDValue LHS = N->getOperand(1);
19256   SDValue RHS = N->getOperand(2);
19257   EVT VT = LHS.getValueType();
19258   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19259
19260   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19261   // instructions match the semantics of the common C idiom x<y?x:y but not
19262   // x<=y?x:y, because of how they handle negative zero (which can be
19263   // ignored in unsafe-math mode).
19264   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19265       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19266       (Subtarget->hasSSE2() ||
19267        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19268     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19269
19270     unsigned Opcode = 0;
19271     // Check for x CC y ? x : y.
19272     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19273         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19274       switch (CC) {
19275       default: break;
19276       case ISD::SETULT:
19277         // Converting this to a min would handle NaNs incorrectly, and swapping
19278         // the operands would cause it to handle comparisons between positive
19279         // and negative zero incorrectly.
19280         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19281           if (!DAG.getTarget().Options.UnsafeFPMath &&
19282               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19283             break;
19284           std::swap(LHS, RHS);
19285         }
19286         Opcode = X86ISD::FMIN;
19287         break;
19288       case ISD::SETOLE:
19289         // Converting this to a min would handle comparisons between positive
19290         // and negative zero incorrectly.
19291         if (!DAG.getTarget().Options.UnsafeFPMath &&
19292             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19293           break;
19294         Opcode = X86ISD::FMIN;
19295         break;
19296       case ISD::SETULE:
19297         // Converting this to a min would handle both negative zeros and NaNs
19298         // incorrectly, but we can swap the operands to fix both.
19299         std::swap(LHS, RHS);
19300       case ISD::SETOLT:
19301       case ISD::SETLT:
19302       case ISD::SETLE:
19303         Opcode = X86ISD::FMIN;
19304         break;
19305
19306       case ISD::SETOGE:
19307         // Converting this to a max would handle comparisons between positive
19308         // and negative zero incorrectly.
19309         if (!DAG.getTarget().Options.UnsafeFPMath &&
19310             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19311           break;
19312         Opcode = X86ISD::FMAX;
19313         break;
19314       case ISD::SETUGT:
19315         // Converting this to a max would handle NaNs incorrectly, and swapping
19316         // the operands would cause it to handle comparisons between positive
19317         // and negative zero incorrectly.
19318         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19319           if (!DAG.getTarget().Options.UnsafeFPMath &&
19320               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19321             break;
19322           std::swap(LHS, RHS);
19323         }
19324         Opcode = X86ISD::FMAX;
19325         break;
19326       case ISD::SETUGE:
19327         // Converting this to a max would handle both negative zeros and NaNs
19328         // incorrectly, but we can swap the operands to fix both.
19329         std::swap(LHS, RHS);
19330       case ISD::SETOGT:
19331       case ISD::SETGT:
19332       case ISD::SETGE:
19333         Opcode = X86ISD::FMAX;
19334         break;
19335       }
19336     // Check for x CC y ? y : x -- a min/max with reversed arms.
19337     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19338                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19339       switch (CC) {
19340       default: break;
19341       case ISD::SETOGE:
19342         // Converting this to a min would handle comparisons between positive
19343         // and negative zero incorrectly, and swapping the operands would
19344         // cause it to handle NaNs incorrectly.
19345         if (!DAG.getTarget().Options.UnsafeFPMath &&
19346             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19347           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19348             break;
19349           std::swap(LHS, RHS);
19350         }
19351         Opcode = X86ISD::FMIN;
19352         break;
19353       case ISD::SETUGT:
19354         // Converting this to a min would handle NaNs incorrectly.
19355         if (!DAG.getTarget().Options.UnsafeFPMath &&
19356             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19357           break;
19358         Opcode = X86ISD::FMIN;
19359         break;
19360       case ISD::SETUGE:
19361         // Converting this to a min would handle both negative zeros and NaNs
19362         // incorrectly, but we can swap the operands to fix both.
19363         std::swap(LHS, RHS);
19364       case ISD::SETOGT:
19365       case ISD::SETGT:
19366       case ISD::SETGE:
19367         Opcode = X86ISD::FMIN;
19368         break;
19369
19370       case ISD::SETULT:
19371         // Converting this to a max would handle NaNs incorrectly.
19372         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19373           break;
19374         Opcode = X86ISD::FMAX;
19375         break;
19376       case ISD::SETOLE:
19377         // Converting this to a max would handle comparisons between positive
19378         // and negative zero incorrectly, and swapping the operands would
19379         // cause it to handle NaNs incorrectly.
19380         if (!DAG.getTarget().Options.UnsafeFPMath &&
19381             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19382           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19383             break;
19384           std::swap(LHS, RHS);
19385         }
19386         Opcode = X86ISD::FMAX;
19387         break;
19388       case ISD::SETULE:
19389         // Converting this to a max would handle both negative zeros and NaNs
19390         // incorrectly, but we can swap the operands to fix both.
19391         std::swap(LHS, RHS);
19392       case ISD::SETOLT:
19393       case ISD::SETLT:
19394       case ISD::SETLE:
19395         Opcode = X86ISD::FMAX;
19396         break;
19397       }
19398     }
19399
19400     if (Opcode)
19401       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19402   }
19403
19404   EVT CondVT = Cond.getValueType();
19405   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19406       CondVT.getVectorElementType() == MVT::i1) {
19407     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19408     // lowering on AVX-512. In this case we convert it to
19409     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19410     // The same situation for all 128 and 256-bit vectors of i8 and i16
19411     EVT OpVT = LHS.getValueType();
19412     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19413         (OpVT.getVectorElementType() == MVT::i8 ||
19414          OpVT.getVectorElementType() == MVT::i16)) {
19415       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19416       DCI.AddToWorklist(Cond.getNode());
19417       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19418     }
19419   }
19420   // If this is a select between two integer constants, try to do some
19421   // optimizations.
19422   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19423     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19424       // Don't do this for crazy integer types.
19425       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19426         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19427         // so that TrueC (the true value) is larger than FalseC.
19428         bool NeedsCondInvert = false;
19429
19430         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19431             // Efficiently invertible.
19432             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19433              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19434               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19435           NeedsCondInvert = true;
19436           std::swap(TrueC, FalseC);
19437         }
19438
19439         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19440         if (FalseC->getAPIntValue() == 0 &&
19441             TrueC->getAPIntValue().isPowerOf2()) {
19442           if (NeedsCondInvert) // Invert the condition if needed.
19443             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19444                                DAG.getConstant(1, Cond.getValueType()));
19445
19446           // Zero extend the condition if needed.
19447           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19448
19449           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19450           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19451                              DAG.getConstant(ShAmt, MVT::i8));
19452         }
19453
19454         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19455         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19456           if (NeedsCondInvert) // Invert the condition if needed.
19457             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19458                                DAG.getConstant(1, Cond.getValueType()));
19459
19460           // Zero extend the condition if needed.
19461           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19462                              FalseC->getValueType(0), Cond);
19463           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19464                              SDValue(FalseC, 0));
19465         }
19466
19467         // Optimize cases that will turn into an LEA instruction.  This requires
19468         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19469         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19470           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19471           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19472
19473           bool isFastMultiplier = false;
19474           if (Diff < 10) {
19475             switch ((unsigned char)Diff) {
19476               default: break;
19477               case 1:  // result = add base, cond
19478               case 2:  // result = lea base(    , cond*2)
19479               case 3:  // result = lea base(cond, cond*2)
19480               case 4:  // result = lea base(    , cond*4)
19481               case 5:  // result = lea base(cond, cond*4)
19482               case 8:  // result = lea base(    , cond*8)
19483               case 9:  // result = lea base(cond, cond*8)
19484                 isFastMultiplier = true;
19485                 break;
19486             }
19487           }
19488
19489           if (isFastMultiplier) {
19490             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19491             if (NeedsCondInvert) // Invert the condition if needed.
19492               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19493                                  DAG.getConstant(1, Cond.getValueType()));
19494
19495             // Zero extend the condition if needed.
19496             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19497                                Cond);
19498             // Scale the condition by the difference.
19499             if (Diff != 1)
19500               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19501                                  DAG.getConstant(Diff, Cond.getValueType()));
19502
19503             // Add the base if non-zero.
19504             if (FalseC->getAPIntValue() != 0)
19505               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19506                                  SDValue(FalseC, 0));
19507             return Cond;
19508           }
19509         }
19510       }
19511   }
19512
19513   // Canonicalize max and min:
19514   // (x > y) ? x : y -> (x >= y) ? x : y
19515   // (x < y) ? x : y -> (x <= y) ? x : y
19516   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19517   // the need for an extra compare
19518   // against zero. e.g.
19519   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19520   // subl   %esi, %edi
19521   // testl  %edi, %edi
19522   // movl   $0, %eax
19523   // cmovgl %edi, %eax
19524   // =>
19525   // xorl   %eax, %eax
19526   // subl   %esi, $edi
19527   // cmovsl %eax, %edi
19528   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19529       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19530       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19531     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19532     switch (CC) {
19533     default: break;
19534     case ISD::SETLT:
19535     case ISD::SETGT: {
19536       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19537       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19538                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
19539       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19540     }
19541     }
19542   }
19543
19544   // Early exit check
19545   if (!TLI.isTypeLegal(VT))
19546     return SDValue();
19547
19548   // Match VSELECTs into subs with unsigned saturation.
19549   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19550       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19551       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19552        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19553     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19554
19555     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19556     // left side invert the predicate to simplify logic below.
19557     SDValue Other;
19558     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19559       Other = RHS;
19560       CC = ISD::getSetCCInverse(CC, true);
19561     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19562       Other = LHS;
19563     }
19564
19565     if (Other.getNode() && Other->getNumOperands() == 2 &&
19566         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19567       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19568       SDValue CondRHS = Cond->getOperand(1);
19569
19570       // Look for a general sub with unsigned saturation first.
19571       // x >= y ? x-y : 0 --> subus x, y
19572       // x >  y ? x-y : 0 --> subus x, y
19573       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19574           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19575         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19576
19577       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19578         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19579           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19580             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19581               // If the RHS is a constant we have to reverse the const
19582               // canonicalization.
19583               // x > C-1 ? x+-C : 0 --> subus x, C
19584               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19585                   CondRHSConst->getAPIntValue() ==
19586                       (-OpRHSConst->getAPIntValue() - 1))
19587                 return DAG.getNode(
19588                     X86ISD::SUBUS, DL, VT, OpLHS,
19589                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19590
19591           // Another special case: If C was a sign bit, the sub has been
19592           // canonicalized into a xor.
19593           // FIXME: Would it be better to use computeKnownBits to determine
19594           //        whether it's safe to decanonicalize the xor?
19595           // x s< 0 ? x^C : 0 --> subus x, C
19596           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19597               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19598               OpRHSConst->getAPIntValue().isSignBit())
19599             // Note that we have to rebuild the RHS constant here to ensure we
19600             // don't rely on particular values of undef lanes.
19601             return DAG.getNode(
19602                 X86ISD::SUBUS, DL, VT, OpLHS,
19603                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19604         }
19605     }
19606   }
19607
19608   // Try to match a min/max vector operation.
19609   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19610     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19611     unsigned Opc = ret.first;
19612     bool NeedSplit = ret.second;
19613
19614     if (Opc && NeedSplit) {
19615       unsigned NumElems = VT.getVectorNumElements();
19616       // Extract the LHS vectors
19617       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19618       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19619
19620       // Extract the RHS vectors
19621       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19622       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19623
19624       // Create min/max for each subvector
19625       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19626       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19627
19628       // Merge the result
19629       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19630     } else if (Opc)
19631       return DAG.getNode(Opc, DL, VT, LHS, RHS);
19632   }
19633
19634   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19635   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19636       // Check if SETCC has already been promoted
19637       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19638       // Check that condition value type matches vselect operand type
19639       CondVT == VT) { 
19640
19641     assert(Cond.getValueType().isVector() &&
19642            "vector select expects a vector selector!");
19643
19644     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19645     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19646
19647     if (!TValIsAllOnes && !FValIsAllZeros) {
19648       // Try invert the condition if true value is not all 1s and false value
19649       // is not all 0s.
19650       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19651       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19652
19653       if (TValIsAllZeros || FValIsAllOnes) {
19654         SDValue CC = Cond.getOperand(2);
19655         ISD::CondCode NewCC =
19656           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19657                                Cond.getOperand(0).getValueType().isInteger());
19658         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19659         std::swap(LHS, RHS);
19660         TValIsAllOnes = FValIsAllOnes;
19661         FValIsAllZeros = TValIsAllZeros;
19662       }
19663     }
19664
19665     if (TValIsAllOnes || FValIsAllZeros) {
19666       SDValue Ret;
19667
19668       if (TValIsAllOnes && FValIsAllZeros)
19669         Ret = Cond;
19670       else if (TValIsAllOnes)
19671         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19672                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19673       else if (FValIsAllZeros)
19674         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19675                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19676
19677       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19678     }
19679   }
19680
19681   // Try to fold this VSELECT into a MOVSS/MOVSD
19682   if (N->getOpcode() == ISD::VSELECT &&
19683       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19684     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19685         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19686       bool CanFold = false;
19687       unsigned NumElems = Cond.getNumOperands();
19688       SDValue A = LHS;
19689       SDValue B = RHS;
19690       
19691       if (isZero(Cond.getOperand(0))) {
19692         CanFold = true;
19693
19694         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19695         // fold (vselect <0,-1> -> (movsd A, B)
19696         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19697           CanFold = isAllOnes(Cond.getOperand(i));
19698       } else if (isAllOnes(Cond.getOperand(0))) {
19699         CanFold = true;
19700         std::swap(A, B);
19701
19702         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19703         // fold (vselect <-1,0> -> (movsd B, A)
19704         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19705           CanFold = isZero(Cond.getOperand(i));
19706       }
19707
19708       if (CanFold) {
19709         if (VT == MVT::v4i32 || VT == MVT::v4f32)
19710           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19711         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19712       }
19713
19714       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19715         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19716         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19717         //                             (v2i64 (bitcast B)))))
19718         //
19719         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19720         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19721         //                             (v2f64 (bitcast B)))))
19722         //
19723         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19724         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19725         //                             (v2i64 (bitcast A)))))
19726         //
19727         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19728         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19729         //                             (v2f64 (bitcast A)))))
19730
19731         CanFold = (isZero(Cond.getOperand(0)) &&
19732                    isZero(Cond.getOperand(1)) &&
19733                    isAllOnes(Cond.getOperand(2)) &&
19734                    isAllOnes(Cond.getOperand(3)));
19735
19736         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19737             isAllOnes(Cond.getOperand(1)) &&
19738             isZero(Cond.getOperand(2)) &&
19739             isZero(Cond.getOperand(3))) {
19740           CanFold = true;
19741           std::swap(LHS, RHS);
19742         }
19743
19744         if (CanFold) {
19745           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19746           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19747           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19748           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19749                                                 NewB, DAG);
19750           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19751         }
19752       }
19753     }
19754   }
19755
19756   // If we know that this node is legal then we know that it is going to be
19757   // matched by one of the SSE/AVX BLEND instructions. These instructions only
19758   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19759   // to simplify previous instructions.
19760   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19761       !DCI.isBeforeLegalize() &&
19762       // We explicitly check against v8i16 and v16i16 because, although
19763       // they're marked as Custom, they might only be legal when Cond is a
19764       // build_vector of constants. This will be taken care in a later
19765       // condition.
19766       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19767        VT != MVT::v8i16)) {
19768     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19769
19770     // Don't optimize vector selects that map to mask-registers.
19771     if (BitWidth == 1)
19772       return SDValue();
19773
19774     // Check all uses of that condition operand to check whether it will be
19775     // consumed by non-BLEND instructions, which may depend on all bits are set
19776     // properly.
19777     for (SDNode::use_iterator I = Cond->use_begin(),
19778                               E = Cond->use_end(); I != E; ++I)
19779       if (I->getOpcode() != ISD::VSELECT)
19780         // TODO: Add other opcodes eventually lowered into BLEND.
19781         return SDValue();
19782
19783     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19784     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19785
19786     APInt KnownZero, KnownOne;
19787     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19788                                           DCI.isBeforeLegalizeOps());
19789     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19790         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19791       DCI.CommitTargetLoweringOpt(TLO);
19792   }
19793
19794   // We should generate an X86ISD::BLENDI from a vselect if its argument
19795   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19796   // constants. This specific pattern gets generated when we split a
19797   // selector for a 512 bit vector in a machine without AVX512 (but with
19798   // 256-bit vectors), during legalization:
19799   //
19800   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19801   //
19802   // Iff we find this pattern and the build_vectors are built from
19803   // constants, we translate the vselect into a shuffle_vector that we
19804   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19805   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19806     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19807     if (Shuffle.getNode())
19808       return Shuffle;
19809   }
19810
19811   return SDValue();
19812 }
19813
19814 // Check whether a boolean test is testing a boolean value generated by
19815 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19816 // code.
19817 //
19818 // Simplify the following patterns:
19819 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19820 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19821 // to (Op EFLAGS Cond)
19822 //
19823 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19824 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19825 // to (Op EFLAGS !Cond)
19826 //
19827 // where Op could be BRCOND or CMOV.
19828 //
19829 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19830   // Quit if not CMP and SUB with its value result used.
19831   if (Cmp.getOpcode() != X86ISD::CMP &&
19832       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19833       return SDValue();
19834
19835   // Quit if not used as a boolean value.
19836   if (CC != X86::COND_E && CC != X86::COND_NE)
19837     return SDValue();
19838
19839   // Check CMP operands. One of them should be 0 or 1 and the other should be
19840   // an SetCC or extended from it.
19841   SDValue Op1 = Cmp.getOperand(0);
19842   SDValue Op2 = Cmp.getOperand(1);
19843
19844   SDValue SetCC;
19845   const ConstantSDNode* C = nullptr;
19846   bool needOppositeCond = (CC == X86::COND_E);
19847   bool checkAgainstTrue = false; // Is it a comparison against 1?
19848
19849   if ((C = dyn_cast<ConstantSDNode>(Op1)))
19850     SetCC = Op2;
19851   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19852     SetCC = Op1;
19853   else // Quit if all operands are not constants.
19854     return SDValue();
19855
19856   if (C->getZExtValue() == 1) {
19857     needOppositeCond = !needOppositeCond;
19858     checkAgainstTrue = true;
19859   } else if (C->getZExtValue() != 0)
19860     // Quit if the constant is neither 0 or 1.
19861     return SDValue();
19862
19863   bool truncatedToBoolWithAnd = false;
19864   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19865   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19866          SetCC.getOpcode() == ISD::TRUNCATE ||
19867          SetCC.getOpcode() == ISD::AND) {
19868     if (SetCC.getOpcode() == ISD::AND) {
19869       int OpIdx = -1;
19870       ConstantSDNode *CS;
19871       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19872           CS->getZExtValue() == 1)
19873         OpIdx = 1;
19874       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19875           CS->getZExtValue() == 1)
19876         OpIdx = 0;
19877       if (OpIdx == -1)
19878         break;
19879       SetCC = SetCC.getOperand(OpIdx);
19880       truncatedToBoolWithAnd = true;
19881     } else
19882       SetCC = SetCC.getOperand(0);
19883   }
19884
19885   switch (SetCC.getOpcode()) {
19886   case X86ISD::SETCC_CARRY:
19887     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19888     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19889     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19890     // truncated to i1 using 'and'.
19891     if (checkAgainstTrue && !truncatedToBoolWithAnd)
19892       break;
19893     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19894            "Invalid use of SETCC_CARRY!");
19895     // FALL THROUGH
19896   case X86ISD::SETCC:
19897     // Set the condition code or opposite one if necessary.
19898     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19899     if (needOppositeCond)
19900       CC = X86::GetOppositeBranchCondition(CC);
19901     return SetCC.getOperand(1);
19902   case X86ISD::CMOV: {
19903     // Check whether false/true value has canonical one, i.e. 0 or 1.
19904     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19905     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19906     // Quit if true value is not a constant.
19907     if (!TVal)
19908       return SDValue();
19909     // Quit if false value is not a constant.
19910     if (!FVal) {
19911       SDValue Op = SetCC.getOperand(0);
19912       // Skip 'zext' or 'trunc' node.
19913       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19914           Op.getOpcode() == ISD::TRUNCATE)
19915         Op = Op.getOperand(0);
19916       // A special case for rdrand/rdseed, where 0 is set if false cond is
19917       // found.
19918       if ((Op.getOpcode() != X86ISD::RDRAND &&
19919            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19920         return SDValue();
19921     }
19922     // Quit if false value is not the constant 0 or 1.
19923     bool FValIsFalse = true;
19924     if (FVal && FVal->getZExtValue() != 0) {
19925       if (FVal->getZExtValue() != 1)
19926         return SDValue();
19927       // If FVal is 1, opposite cond is needed.
19928       needOppositeCond = !needOppositeCond;
19929       FValIsFalse = false;
19930     }
19931     // Quit if TVal is not the constant opposite of FVal.
19932     if (FValIsFalse && TVal->getZExtValue() != 1)
19933       return SDValue();
19934     if (!FValIsFalse && TVal->getZExtValue() != 0)
19935       return SDValue();
19936     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19937     if (needOppositeCond)
19938       CC = X86::GetOppositeBranchCondition(CC);
19939     return SetCC.getOperand(3);
19940   }
19941   }
19942
19943   return SDValue();
19944 }
19945
19946 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19947 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19948                                   TargetLowering::DAGCombinerInfo &DCI,
19949                                   const X86Subtarget *Subtarget) {
19950   SDLoc DL(N);
19951
19952   // If the flag operand isn't dead, don't touch this CMOV.
19953   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19954     return SDValue();
19955
19956   SDValue FalseOp = N->getOperand(0);
19957   SDValue TrueOp = N->getOperand(1);
19958   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19959   SDValue Cond = N->getOperand(3);
19960
19961   if (CC == X86::COND_E || CC == X86::COND_NE) {
19962     switch (Cond.getOpcode()) {
19963     default: break;
19964     case X86ISD::BSR:
19965     case X86ISD::BSF:
19966       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19967       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19968         return (CC == X86::COND_E) ? FalseOp : TrueOp;
19969     }
19970   }
19971
19972   SDValue Flags;
19973
19974   Flags = checkBoolTestSetCCCombine(Cond, CC);
19975   if (Flags.getNode() &&
19976       // Extra check as FCMOV only supports a subset of X86 cond.
19977       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19978     SDValue Ops[] = { FalseOp, TrueOp,
19979                       DAG.getConstant(CC, MVT::i8), Flags };
19980     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19981   }
19982
19983   // If this is a select between two integer constants, try to do some
19984   // optimizations.  Note that the operands are ordered the opposite of SELECT
19985   // operands.
19986   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19987     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19988       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19989       // larger than FalseC (the false value).
19990       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19991         CC = X86::GetOppositeBranchCondition(CC);
19992         std::swap(TrueC, FalseC);
19993         std::swap(TrueOp, FalseOp);
19994       }
19995
19996       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
19997       // This is efficient for any integer data type (including i8/i16) and
19998       // shift amount.
19999       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20000         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20001                            DAG.getConstant(CC, MVT::i8), Cond);
20002
20003         // Zero extend the condition if needed.
20004         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20005
20006         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20007         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20008                            DAG.getConstant(ShAmt, MVT::i8));
20009         if (N->getNumValues() == 2)  // Dead flag value?
20010           return DCI.CombineTo(N, Cond, SDValue());
20011         return Cond;
20012       }
20013
20014       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20015       // for any integer data type, including i8/i16.
20016       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20017         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20018                            DAG.getConstant(CC, MVT::i8), Cond);
20019
20020         // Zero extend the condition if needed.
20021         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20022                            FalseC->getValueType(0), Cond);
20023         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20024                            SDValue(FalseC, 0));
20025
20026         if (N->getNumValues() == 2)  // Dead flag value?
20027           return DCI.CombineTo(N, Cond, SDValue());
20028         return Cond;
20029       }
20030
20031       // Optimize cases that will turn into an LEA instruction.  This requires
20032       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20033       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20034         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20035         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20036
20037         bool isFastMultiplier = false;
20038         if (Diff < 10) {
20039           switch ((unsigned char)Diff) {
20040           default: break;
20041           case 1:  // result = add base, cond
20042           case 2:  // result = lea base(    , cond*2)
20043           case 3:  // result = lea base(cond, cond*2)
20044           case 4:  // result = lea base(    , cond*4)
20045           case 5:  // result = lea base(cond, cond*4)
20046           case 8:  // result = lea base(    , cond*8)
20047           case 9:  // result = lea base(cond, cond*8)
20048             isFastMultiplier = true;
20049             break;
20050           }
20051         }
20052
20053         if (isFastMultiplier) {
20054           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20055           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20056                              DAG.getConstant(CC, MVT::i8), Cond);
20057           // Zero extend the condition if needed.
20058           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20059                              Cond);
20060           // Scale the condition by the difference.
20061           if (Diff != 1)
20062             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20063                                DAG.getConstant(Diff, Cond.getValueType()));
20064
20065           // Add the base if non-zero.
20066           if (FalseC->getAPIntValue() != 0)
20067             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20068                                SDValue(FalseC, 0));
20069           if (N->getNumValues() == 2)  // Dead flag value?
20070             return DCI.CombineTo(N, Cond, SDValue());
20071           return Cond;
20072         }
20073       }
20074     }
20075   }
20076
20077   // Handle these cases:
20078   //   (select (x != c), e, c) -> select (x != c), e, x),
20079   //   (select (x == c), c, e) -> select (x == c), x, e)
20080   // where the c is an integer constant, and the "select" is the combination
20081   // of CMOV and CMP.
20082   //
20083   // The rationale for this change is that the conditional-move from a constant
20084   // needs two instructions, however, conditional-move from a register needs
20085   // only one instruction.
20086   //
20087   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20088   //  some instruction-combining opportunities. This opt needs to be
20089   //  postponed as late as possible.
20090   //
20091   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20092     // the DCI.xxxx conditions are provided to postpone the optimization as
20093     // late as possible.
20094
20095     ConstantSDNode *CmpAgainst = nullptr;
20096     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20097         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20098         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20099
20100       if (CC == X86::COND_NE &&
20101           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20102         CC = X86::GetOppositeBranchCondition(CC);
20103         std::swap(TrueOp, FalseOp);
20104       }
20105
20106       if (CC == X86::COND_E &&
20107           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20108         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20109                           DAG.getConstant(CC, MVT::i8), Cond };
20110         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20111       }
20112     }
20113   }
20114
20115   return SDValue();
20116 }
20117
20118 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20119                                                 const X86Subtarget *Subtarget) {
20120   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20121   switch (IntNo) {
20122   default: return SDValue();
20123   // SSE/AVX/AVX2 blend intrinsics.
20124   case Intrinsic::x86_avx2_pblendvb:
20125   case Intrinsic::x86_avx2_pblendw:
20126   case Intrinsic::x86_avx2_pblendd_128:
20127   case Intrinsic::x86_avx2_pblendd_256:
20128     // Don't try to simplify this intrinsic if we don't have AVX2.
20129     if (!Subtarget->hasAVX2())
20130       return SDValue();
20131     // FALL-THROUGH
20132   case Intrinsic::x86_avx_blend_pd_256:
20133   case Intrinsic::x86_avx_blend_ps_256:
20134   case Intrinsic::x86_avx_blendv_pd_256:
20135   case Intrinsic::x86_avx_blendv_ps_256:
20136     // Don't try to simplify this intrinsic if we don't have AVX.
20137     if (!Subtarget->hasAVX())
20138       return SDValue();
20139     // FALL-THROUGH
20140   case Intrinsic::x86_sse41_pblendw:
20141   case Intrinsic::x86_sse41_blendpd:
20142   case Intrinsic::x86_sse41_blendps:
20143   case Intrinsic::x86_sse41_blendvps:
20144   case Intrinsic::x86_sse41_blendvpd:
20145   case Intrinsic::x86_sse41_pblendvb: {
20146     SDValue Op0 = N->getOperand(1);
20147     SDValue Op1 = N->getOperand(2);
20148     SDValue Mask = N->getOperand(3);
20149
20150     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20151     if (!Subtarget->hasSSE41())
20152       return SDValue();
20153
20154     // fold (blend A, A, Mask) -> A
20155     if (Op0 == Op1)
20156       return Op0;
20157     // fold (blend A, B, allZeros) -> A
20158     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20159       return Op0;
20160     // fold (blend A, B, allOnes) -> B
20161     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20162       return Op1;
20163     
20164     // Simplify the case where the mask is a constant i32 value.
20165     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20166       if (C->isNullValue())
20167         return Op0;
20168       if (C->isAllOnesValue())
20169         return Op1;
20170     }
20171
20172     return SDValue();
20173   }
20174
20175   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20176   case Intrinsic::x86_sse2_psrai_w:
20177   case Intrinsic::x86_sse2_psrai_d:
20178   case Intrinsic::x86_avx2_psrai_w:
20179   case Intrinsic::x86_avx2_psrai_d:
20180   case Intrinsic::x86_sse2_psra_w:
20181   case Intrinsic::x86_sse2_psra_d:
20182   case Intrinsic::x86_avx2_psra_w:
20183   case Intrinsic::x86_avx2_psra_d: {
20184     SDValue Op0 = N->getOperand(1);
20185     SDValue Op1 = N->getOperand(2);
20186     EVT VT = Op0.getValueType();
20187     assert(VT.isVector() && "Expected a vector type!");
20188
20189     if (isa<BuildVectorSDNode>(Op1))
20190       Op1 = Op1.getOperand(0);
20191
20192     if (!isa<ConstantSDNode>(Op1))
20193       return SDValue();
20194
20195     EVT SVT = VT.getVectorElementType();
20196     unsigned SVTBits = SVT.getSizeInBits();
20197
20198     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20199     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20200     uint64_t ShAmt = C.getZExtValue();
20201
20202     // Don't try to convert this shift into a ISD::SRA if the shift
20203     // count is bigger than or equal to the element size.
20204     if (ShAmt >= SVTBits)
20205       return SDValue();
20206
20207     // Trivial case: if the shift count is zero, then fold this
20208     // into the first operand.
20209     if (ShAmt == 0)
20210       return Op0;
20211
20212     // Replace this packed shift intrinsic with a target independent
20213     // shift dag node.
20214     SDValue Splat = DAG.getConstant(C, VT);
20215     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20216   }
20217   }
20218 }
20219
20220 /// PerformMulCombine - Optimize a single multiply with constant into two
20221 /// in order to implement it with two cheaper instructions, e.g.
20222 /// LEA + SHL, LEA + LEA.
20223 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20224                                  TargetLowering::DAGCombinerInfo &DCI) {
20225   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20226     return SDValue();
20227
20228   EVT VT = N->getValueType(0);
20229   if (VT != MVT::i64)
20230     return SDValue();
20231
20232   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20233   if (!C)
20234     return SDValue();
20235   uint64_t MulAmt = C->getZExtValue();
20236   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20237     return SDValue();
20238
20239   uint64_t MulAmt1 = 0;
20240   uint64_t MulAmt2 = 0;
20241   if ((MulAmt % 9) == 0) {
20242     MulAmt1 = 9;
20243     MulAmt2 = MulAmt / 9;
20244   } else if ((MulAmt % 5) == 0) {
20245     MulAmt1 = 5;
20246     MulAmt2 = MulAmt / 5;
20247   } else if ((MulAmt % 3) == 0) {
20248     MulAmt1 = 3;
20249     MulAmt2 = MulAmt / 3;
20250   }
20251   if (MulAmt2 &&
20252       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20253     SDLoc DL(N);
20254
20255     if (isPowerOf2_64(MulAmt2) &&
20256         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20257       // If second multiplifer is pow2, issue it first. We want the multiply by
20258       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20259       // is an add.
20260       std::swap(MulAmt1, MulAmt2);
20261
20262     SDValue NewMul;
20263     if (isPowerOf2_64(MulAmt1))
20264       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20265                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20266     else
20267       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20268                            DAG.getConstant(MulAmt1, VT));
20269
20270     if (isPowerOf2_64(MulAmt2))
20271       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20272                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20273     else
20274       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20275                            DAG.getConstant(MulAmt2, VT));
20276
20277     // Do not add new nodes to DAG combiner worklist.
20278     DCI.CombineTo(N, NewMul, false);
20279   }
20280   return SDValue();
20281 }
20282
20283 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20284   SDValue N0 = N->getOperand(0);
20285   SDValue N1 = N->getOperand(1);
20286   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20287   EVT VT = N0.getValueType();
20288
20289   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20290   // since the result of setcc_c is all zero's or all ones.
20291   if (VT.isInteger() && !VT.isVector() &&
20292       N1C && N0.getOpcode() == ISD::AND &&
20293       N0.getOperand(1).getOpcode() == ISD::Constant) {
20294     SDValue N00 = N0.getOperand(0);
20295     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20296         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20297           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20298          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20299       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20300       APInt ShAmt = N1C->getAPIntValue();
20301       Mask = Mask.shl(ShAmt);
20302       if (Mask != 0)
20303         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20304                            N00, DAG.getConstant(Mask, VT));
20305     }
20306   }
20307
20308   // Hardware support for vector shifts is sparse which makes us scalarize the
20309   // vector operations in many cases. Also, on sandybridge ADD is faster than
20310   // shl.
20311   // (shl V, 1) -> add V,V
20312   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20313     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20314       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20315       // We shift all of the values by one. In many cases we do not have
20316       // hardware support for this operation. This is better expressed as an ADD
20317       // of two values.
20318       if (N1SplatC->getZExtValue() == 1)
20319         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20320     }
20321
20322   return SDValue();
20323 }
20324
20325 /// \brief Returns a vector of 0s if the node in input is a vector logical
20326 /// shift by a constant amount which is known to be bigger than or equal
20327 /// to the vector element size in bits.
20328 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20329                                       const X86Subtarget *Subtarget) {
20330   EVT VT = N->getValueType(0);
20331
20332   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20333       (!Subtarget->hasInt256() ||
20334        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20335     return SDValue();
20336
20337   SDValue Amt = N->getOperand(1);
20338   SDLoc DL(N);
20339   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20340     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20341       APInt ShiftAmt = AmtSplat->getAPIntValue();
20342       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20343
20344       // SSE2/AVX2 logical shifts always return a vector of 0s
20345       // if the shift amount is bigger than or equal to
20346       // the element size. The constant shift amount will be
20347       // encoded as a 8-bit immediate.
20348       if (ShiftAmt.trunc(8).uge(MaxAmount))
20349         return getZeroVector(VT, Subtarget, DAG, DL);
20350     }
20351
20352   return SDValue();
20353 }
20354
20355 /// PerformShiftCombine - Combine shifts.
20356 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20357                                    TargetLowering::DAGCombinerInfo &DCI,
20358                                    const X86Subtarget *Subtarget) {
20359   if (N->getOpcode() == ISD::SHL) {
20360     SDValue V = PerformSHLCombine(N, DAG);
20361     if (V.getNode()) return V;
20362   }
20363
20364   if (N->getOpcode() != ISD::SRA) {
20365     // Try to fold this logical shift into a zero vector.
20366     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20367     if (V.getNode()) return V;
20368   }
20369
20370   return SDValue();
20371 }
20372
20373 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20374 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20375 // and friends.  Likewise for OR -> CMPNEQSS.
20376 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20377                             TargetLowering::DAGCombinerInfo &DCI,
20378                             const X86Subtarget *Subtarget) {
20379   unsigned opcode;
20380
20381   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20382   // we're requiring SSE2 for both.
20383   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20384     SDValue N0 = N->getOperand(0);
20385     SDValue N1 = N->getOperand(1);
20386     SDValue CMP0 = N0->getOperand(1);
20387     SDValue CMP1 = N1->getOperand(1);
20388     SDLoc DL(N);
20389
20390     // The SETCCs should both refer to the same CMP.
20391     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20392       return SDValue();
20393
20394     SDValue CMP00 = CMP0->getOperand(0);
20395     SDValue CMP01 = CMP0->getOperand(1);
20396     EVT     VT    = CMP00.getValueType();
20397
20398     if (VT == MVT::f32 || VT == MVT::f64) {
20399       bool ExpectingFlags = false;
20400       // Check for any users that want flags:
20401       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20402            !ExpectingFlags && UI != UE; ++UI)
20403         switch (UI->getOpcode()) {
20404         default:
20405         case ISD::BR_CC:
20406         case ISD::BRCOND:
20407         case ISD::SELECT:
20408           ExpectingFlags = true;
20409           break;
20410         case ISD::CopyToReg:
20411         case ISD::SIGN_EXTEND:
20412         case ISD::ZERO_EXTEND:
20413         case ISD::ANY_EXTEND:
20414           break;
20415         }
20416
20417       if (!ExpectingFlags) {
20418         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20419         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20420
20421         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20422           X86::CondCode tmp = cc0;
20423           cc0 = cc1;
20424           cc1 = tmp;
20425         }
20426
20427         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20428             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20429           // FIXME: need symbolic constants for these magic numbers.
20430           // See X86ATTInstPrinter.cpp:printSSECC().
20431           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20432           if (Subtarget->hasAVX512()) {
20433             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20434                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20435             if (N->getValueType(0) != MVT::i1)
20436               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20437                                  FSetCC);
20438             return FSetCC;
20439           }
20440           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20441                                               CMP00.getValueType(), CMP00, CMP01,
20442                                               DAG.getConstant(x86cc, MVT::i8));
20443
20444           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20445           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20446
20447           if (is64BitFP && !Subtarget->is64Bit()) {
20448             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20449             // 64-bit integer, since that's not a legal type. Since
20450             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20451             // bits, but can do this little dance to extract the lowest 32 bits
20452             // and work with those going forward.
20453             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20454                                            OnesOrZeroesF);
20455             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20456                                            Vector64);
20457             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20458                                         Vector32, DAG.getIntPtrConstant(0));
20459             IntVT = MVT::i32;
20460           }
20461
20462           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20463           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20464                                       DAG.getConstant(1, IntVT));
20465           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20466           return OneBitOfTruth;
20467         }
20468       }
20469     }
20470   }
20471   return SDValue();
20472 }
20473
20474 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20475 /// so it can be folded inside ANDNP.
20476 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20477   EVT VT = N->getValueType(0);
20478
20479   // Match direct AllOnes for 128 and 256-bit vectors
20480   if (ISD::isBuildVectorAllOnes(N))
20481     return true;
20482
20483   // Look through a bit convert.
20484   if (N->getOpcode() == ISD::BITCAST)
20485     N = N->getOperand(0).getNode();
20486
20487   // Sometimes the operand may come from a insert_subvector building a 256-bit
20488   // allones vector
20489   if (VT.is256BitVector() &&
20490       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20491     SDValue V1 = N->getOperand(0);
20492     SDValue V2 = N->getOperand(1);
20493
20494     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20495         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20496         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20497         ISD::isBuildVectorAllOnes(V2.getNode()))
20498       return true;
20499   }
20500
20501   return false;
20502 }
20503
20504 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20505 // register. In most cases we actually compare or select YMM-sized registers
20506 // and mixing the two types creates horrible code. This method optimizes
20507 // some of the transition sequences.
20508 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20509                                  TargetLowering::DAGCombinerInfo &DCI,
20510                                  const X86Subtarget *Subtarget) {
20511   EVT VT = N->getValueType(0);
20512   if (!VT.is256BitVector())
20513     return SDValue();
20514
20515   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20516           N->getOpcode() == ISD::ZERO_EXTEND ||
20517           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20518
20519   SDValue Narrow = N->getOperand(0);
20520   EVT NarrowVT = Narrow->getValueType(0);
20521   if (!NarrowVT.is128BitVector())
20522     return SDValue();
20523
20524   if (Narrow->getOpcode() != ISD::XOR &&
20525       Narrow->getOpcode() != ISD::AND &&
20526       Narrow->getOpcode() != ISD::OR)
20527     return SDValue();
20528
20529   SDValue N0  = Narrow->getOperand(0);
20530   SDValue N1  = Narrow->getOperand(1);
20531   SDLoc DL(Narrow);
20532
20533   // The Left side has to be a trunc.
20534   if (N0.getOpcode() != ISD::TRUNCATE)
20535     return SDValue();
20536
20537   // The type of the truncated inputs.
20538   EVT WideVT = N0->getOperand(0)->getValueType(0);
20539   if (WideVT != VT)
20540     return SDValue();
20541
20542   // The right side has to be a 'trunc' or a constant vector.
20543   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20544   ConstantSDNode *RHSConstSplat = nullptr;
20545   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20546     RHSConstSplat = RHSBV->getConstantSplatNode();
20547   if (!RHSTrunc && !RHSConstSplat)
20548     return SDValue();
20549
20550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20551
20552   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20553     return SDValue();
20554
20555   // Set N0 and N1 to hold the inputs to the new wide operation.
20556   N0 = N0->getOperand(0);
20557   if (RHSConstSplat) {
20558     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20559                      SDValue(RHSConstSplat, 0));
20560     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20561     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20562   } else if (RHSTrunc) {
20563     N1 = N1->getOperand(0);
20564   }
20565
20566   // Generate the wide operation.
20567   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20568   unsigned Opcode = N->getOpcode();
20569   switch (Opcode) {
20570   case ISD::ANY_EXTEND:
20571     return Op;
20572   case ISD::ZERO_EXTEND: {
20573     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20574     APInt Mask = APInt::getAllOnesValue(InBits);
20575     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20576     return DAG.getNode(ISD::AND, DL, VT,
20577                        Op, DAG.getConstant(Mask, VT));
20578   }
20579   case ISD::SIGN_EXTEND:
20580     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20581                        Op, DAG.getValueType(NarrowVT));
20582   default:
20583     llvm_unreachable("Unexpected opcode");
20584   }
20585 }
20586
20587 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20588                                  TargetLowering::DAGCombinerInfo &DCI,
20589                                  const X86Subtarget *Subtarget) {
20590   EVT VT = N->getValueType(0);
20591   if (DCI.isBeforeLegalizeOps())
20592     return SDValue();
20593
20594   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20595   if (R.getNode())
20596     return R;
20597
20598   // Create BEXTR instructions
20599   // BEXTR is ((X >> imm) & (2**size-1))
20600   if (VT == MVT::i32 || VT == MVT::i64) {
20601     SDValue N0 = N->getOperand(0);
20602     SDValue N1 = N->getOperand(1);
20603     SDLoc DL(N);
20604
20605     // Check for BEXTR.
20606     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20607         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20608       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20609       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20610       if (MaskNode && ShiftNode) {
20611         uint64_t Mask = MaskNode->getZExtValue();
20612         uint64_t Shift = ShiftNode->getZExtValue();
20613         if (isMask_64(Mask)) {
20614           uint64_t MaskSize = CountPopulation_64(Mask);
20615           if (Shift + MaskSize <= VT.getSizeInBits())
20616             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20617                                DAG.getConstant(Shift | (MaskSize << 8), VT));
20618         }
20619       }
20620     } // BEXTR
20621
20622     return SDValue();
20623   }
20624
20625   // Want to form ANDNP nodes:
20626   // 1) In the hopes of then easily combining them with OR and AND nodes
20627   //    to form PBLEND/PSIGN.
20628   // 2) To match ANDN packed intrinsics
20629   if (VT != MVT::v2i64 && VT != MVT::v4i64)
20630     return SDValue();
20631
20632   SDValue N0 = N->getOperand(0);
20633   SDValue N1 = N->getOperand(1);
20634   SDLoc DL(N);
20635
20636   // Check LHS for vnot
20637   if (N0.getOpcode() == ISD::XOR &&
20638       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20639       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20640     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20641
20642   // Check RHS for vnot
20643   if (N1.getOpcode() == ISD::XOR &&
20644       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20645       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20646     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20647
20648   return SDValue();
20649 }
20650
20651 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20652                                 TargetLowering::DAGCombinerInfo &DCI,
20653                                 const X86Subtarget *Subtarget) {
20654   if (DCI.isBeforeLegalizeOps())
20655     return SDValue();
20656
20657   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20658   if (R.getNode())
20659     return R;
20660
20661   SDValue N0 = N->getOperand(0);
20662   SDValue N1 = N->getOperand(1);
20663   EVT VT = N->getValueType(0);
20664
20665   // look for psign/blend
20666   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20667     if (!Subtarget->hasSSSE3() ||
20668         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20669       return SDValue();
20670
20671     // Canonicalize pandn to RHS
20672     if (N0.getOpcode() == X86ISD::ANDNP)
20673       std::swap(N0, N1);
20674     // or (and (m, y), (pandn m, x))
20675     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20676       SDValue Mask = N1.getOperand(0);
20677       SDValue X    = N1.getOperand(1);
20678       SDValue Y;
20679       if (N0.getOperand(0) == Mask)
20680         Y = N0.getOperand(1);
20681       if (N0.getOperand(1) == Mask)
20682         Y = N0.getOperand(0);
20683
20684       // Check to see if the mask appeared in both the AND and ANDNP and
20685       if (!Y.getNode())
20686         return SDValue();
20687
20688       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20689       // Look through mask bitcast.
20690       if (Mask.getOpcode() == ISD::BITCAST)
20691         Mask = Mask.getOperand(0);
20692       if (X.getOpcode() == ISD::BITCAST)
20693         X = X.getOperand(0);
20694       if (Y.getOpcode() == ISD::BITCAST)
20695         Y = Y.getOperand(0);
20696
20697       EVT MaskVT = Mask.getValueType();
20698
20699       // Validate that the Mask operand is a vector sra node.
20700       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20701       // there is no psrai.b
20702       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20703       unsigned SraAmt = ~0;
20704       if (Mask.getOpcode() == ISD::SRA) {
20705         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20706           if (auto *AmtConst = AmtBV->getConstantSplatNode())
20707             SraAmt = AmtConst->getZExtValue();
20708       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20709         SDValue SraC = Mask.getOperand(1);
20710         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
20711       }
20712       if ((SraAmt + 1) != EltBits)
20713         return SDValue();
20714
20715       SDLoc DL(N);
20716
20717       // Now we know we at least have a plendvb with the mask val.  See if
20718       // we can form a psignb/w/d.
20719       // psign = x.type == y.type == mask.type && y = sub(0, x);
20720       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20721           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20722           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20723         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20724                "Unsupported VT for PSIGN");
20725         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20726         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20727       }
20728       // PBLENDVB only available on SSE 4.1
20729       if (!Subtarget->hasSSE41())
20730         return SDValue();
20731
20732       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20733
20734       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20735       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20736       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20737       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20738       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20739     }
20740   }
20741
20742   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20743     return SDValue();
20744
20745   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20746   MachineFunction &MF = DAG.getMachineFunction();
20747   bool OptForSize = MF.getFunction()->getAttributes().
20748     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20749
20750   // SHLD/SHRD instructions have lower register pressure, but on some
20751   // platforms they have higher latency than the equivalent
20752   // series of shifts/or that would otherwise be generated.
20753   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20754   // have higher latencies and we are not optimizing for size.
20755   if (!OptForSize && Subtarget->isSHLDSlow())
20756     return SDValue();
20757
20758   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20759     std::swap(N0, N1);
20760   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20761     return SDValue();
20762   if (!N0.hasOneUse() || !N1.hasOneUse())
20763     return SDValue();
20764
20765   SDValue ShAmt0 = N0.getOperand(1);
20766   if (ShAmt0.getValueType() != MVT::i8)
20767     return SDValue();
20768   SDValue ShAmt1 = N1.getOperand(1);
20769   if (ShAmt1.getValueType() != MVT::i8)
20770     return SDValue();
20771   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20772     ShAmt0 = ShAmt0.getOperand(0);
20773   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20774     ShAmt1 = ShAmt1.getOperand(0);
20775
20776   SDLoc DL(N);
20777   unsigned Opc = X86ISD::SHLD;
20778   SDValue Op0 = N0.getOperand(0);
20779   SDValue Op1 = N1.getOperand(0);
20780   if (ShAmt0.getOpcode() == ISD::SUB) {
20781     Opc = X86ISD::SHRD;
20782     std::swap(Op0, Op1);
20783     std::swap(ShAmt0, ShAmt1);
20784   }
20785
20786   unsigned Bits = VT.getSizeInBits();
20787   if (ShAmt1.getOpcode() == ISD::SUB) {
20788     SDValue Sum = ShAmt1.getOperand(0);
20789     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20790       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20791       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20792         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20793       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20794         return DAG.getNode(Opc, DL, VT,
20795                            Op0, Op1,
20796                            DAG.getNode(ISD::TRUNCATE, DL,
20797                                        MVT::i8, ShAmt0));
20798     }
20799   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20800     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20801     if (ShAmt0C &&
20802         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20803       return DAG.getNode(Opc, DL, VT,
20804                          N0.getOperand(0), N1.getOperand(0),
20805                          DAG.getNode(ISD::TRUNCATE, DL,
20806                                        MVT::i8, ShAmt0));
20807   }
20808
20809   return SDValue();
20810 }
20811
20812 // Generate NEG and CMOV for integer abs.
20813 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20814   EVT VT = N->getValueType(0);
20815
20816   // Since X86 does not have CMOV for 8-bit integer, we don't convert
20817   // 8-bit integer abs to NEG and CMOV.
20818   if (VT.isInteger() && VT.getSizeInBits() == 8)
20819     return SDValue();
20820
20821   SDValue N0 = N->getOperand(0);
20822   SDValue N1 = N->getOperand(1);
20823   SDLoc DL(N);
20824
20825   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20826   // and change it to SUB and CMOV.
20827   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20828       N0.getOpcode() == ISD::ADD &&
20829       N0.getOperand(1) == N1 &&
20830       N1.getOpcode() == ISD::SRA &&
20831       N1.getOperand(0) == N0.getOperand(0))
20832     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20833       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20834         // Generate SUB & CMOV.
20835         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20836                                   DAG.getConstant(0, VT), N0.getOperand(0));
20837
20838         SDValue Ops[] = { N0.getOperand(0), Neg,
20839                           DAG.getConstant(X86::COND_GE, MVT::i8),
20840                           SDValue(Neg.getNode(), 1) };
20841         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20842       }
20843   return SDValue();
20844 }
20845
20846 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20847 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20848                                  TargetLowering::DAGCombinerInfo &DCI,
20849                                  const X86Subtarget *Subtarget) {
20850   if (DCI.isBeforeLegalizeOps())
20851     return SDValue();
20852
20853   if (Subtarget->hasCMov()) {
20854     SDValue RV = performIntegerAbsCombine(N, DAG);
20855     if (RV.getNode())
20856       return RV;
20857   }
20858
20859   return SDValue();
20860 }
20861
20862 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20863 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20864                                   TargetLowering::DAGCombinerInfo &DCI,
20865                                   const X86Subtarget *Subtarget) {
20866   LoadSDNode *Ld = cast<LoadSDNode>(N);
20867   EVT RegVT = Ld->getValueType(0);
20868   EVT MemVT = Ld->getMemoryVT();
20869   SDLoc dl(Ld);
20870   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20871   unsigned RegSz = RegVT.getSizeInBits();
20872
20873   // On Sandybridge unaligned 256bit loads are inefficient.
20874   ISD::LoadExtType Ext = Ld->getExtensionType();
20875   unsigned Alignment = Ld->getAlignment();
20876   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20877   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20878       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20879     unsigned NumElems = RegVT.getVectorNumElements();
20880     if (NumElems < 2)
20881       return SDValue();
20882
20883     SDValue Ptr = Ld->getBasePtr();
20884     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20885
20886     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20887                                   NumElems/2);
20888     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20889                                 Ld->getPointerInfo(), Ld->isVolatile(),
20890                                 Ld->isNonTemporal(), Ld->isInvariant(),
20891                                 Alignment);
20892     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20893     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20894                                 Ld->getPointerInfo(), Ld->isVolatile(),
20895                                 Ld->isNonTemporal(), Ld->isInvariant(),
20896                                 std::min(16U, Alignment));
20897     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20898                              Load1.getValue(1),
20899                              Load2.getValue(1));
20900
20901     SDValue NewVec = DAG.getUNDEF(RegVT);
20902     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20903     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20904     return DCI.CombineTo(N, NewVec, TF, true);
20905   }
20906
20907   // If this is a vector EXT Load then attempt to optimize it using a
20908   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20909   // expansion is still better than scalar code.
20910   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20911   // emit a shuffle and a arithmetic shift.
20912   // TODO: It is possible to support ZExt by zeroing the undef values
20913   // during the shuffle phase or after the shuffle.
20914   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20915       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20916     assert(MemVT != RegVT && "Cannot extend to the same type");
20917     assert(MemVT.isVector() && "Must load a vector from memory");
20918
20919     unsigned NumElems = RegVT.getVectorNumElements();
20920     unsigned MemSz = MemVT.getSizeInBits();
20921     assert(RegSz > MemSz && "Register size must be greater than the mem size");
20922
20923     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20924       return SDValue();
20925
20926     // All sizes must be a power of two.
20927     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20928       return SDValue();
20929
20930     // Attempt to load the original value using scalar loads.
20931     // Find the largest scalar type that divides the total loaded size.
20932     MVT SclrLoadTy = MVT::i8;
20933     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20934          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20935       MVT Tp = (MVT::SimpleValueType)tp;
20936       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20937         SclrLoadTy = Tp;
20938       }
20939     }
20940
20941     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20942     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20943         (64 <= MemSz))
20944       SclrLoadTy = MVT::f64;
20945
20946     // Calculate the number of scalar loads that we need to perform
20947     // in order to load our vector from memory.
20948     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20949     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20950       return SDValue();
20951
20952     unsigned loadRegZize = RegSz;
20953     if (Ext == ISD::SEXTLOAD && RegSz == 256)
20954       loadRegZize /= 2;
20955
20956     // Represent our vector as a sequence of elements which are the
20957     // largest scalar that we can load.
20958     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20959       loadRegZize/SclrLoadTy.getSizeInBits());
20960
20961     // Represent the data using the same element type that is stored in
20962     // memory. In practice, we ''widen'' MemVT.
20963     EVT WideVecVT =
20964           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20965                        loadRegZize/MemVT.getScalarType().getSizeInBits());
20966
20967     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20968       "Invalid vector type");
20969
20970     // We can't shuffle using an illegal type.
20971     if (!TLI.isTypeLegal(WideVecVT))
20972       return SDValue();
20973
20974     SmallVector<SDValue, 8> Chains;
20975     SDValue Ptr = Ld->getBasePtr();
20976     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20977                                         TLI.getPointerTy());
20978     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20979
20980     for (unsigned i = 0; i < NumLoads; ++i) {
20981       // Perform a single load.
20982       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20983                                        Ptr, Ld->getPointerInfo(),
20984                                        Ld->isVolatile(), Ld->isNonTemporal(),
20985                                        Ld->isInvariant(), Ld->getAlignment());
20986       Chains.push_back(ScalarLoad.getValue(1));
20987       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20988       // another round of DAGCombining.
20989       if (i == 0)
20990         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20991       else
20992         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20993                           ScalarLoad, DAG.getIntPtrConstant(i));
20994
20995       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20996     }
20997
20998     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20999
21000     // Bitcast the loaded value to a vector of the original element type, in
21001     // the size of the target vector type.
21002     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
21003     unsigned SizeRatio = RegSz/MemSz;
21004
21005     if (Ext == ISD::SEXTLOAD) {
21006       // If we have SSE4.1 we can directly emit a VSEXT node.
21007       if (Subtarget->hasSSE41()) {
21008         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
21009         return DCI.CombineTo(N, Sext, TF, true);
21010       }
21011
21012       // Otherwise we'll shuffle the small elements in the high bits of the
21013       // larger type and perform an arithmetic shift. If the shift is not legal
21014       // it's better to scalarize.
21015       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
21016         return SDValue();
21017
21018       // Redistribute the loaded elements into the different locations.
21019       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21020       for (unsigned i = 0; i != NumElems; ++i)
21021         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
21022
21023       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21024                                            DAG.getUNDEF(WideVecVT),
21025                                            &ShuffleVec[0]);
21026
21027       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21028
21029       // Build the arithmetic shift.
21030       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
21031                      MemVT.getVectorElementType().getSizeInBits();
21032       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
21033                           DAG.getConstant(Amt, RegVT));
21034
21035       return DCI.CombineTo(N, Shuff, TF, true);
21036     }
21037
21038     // Redistribute the loaded elements into the different locations.
21039     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21040     for (unsigned i = 0; i != NumElems; ++i)
21041       ShuffleVec[i*SizeRatio] = i;
21042
21043     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21044                                          DAG.getUNDEF(WideVecVT),
21045                                          &ShuffleVec[0]);
21046
21047     // Bitcast to the requested type.
21048     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21049     // Replace the original load with the new sequence
21050     // and return the new chain.
21051     return DCI.CombineTo(N, Shuff, TF, true);
21052   }
21053
21054   return SDValue();
21055 }
21056
21057 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21058 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21059                                    const X86Subtarget *Subtarget) {
21060   StoreSDNode *St = cast<StoreSDNode>(N);
21061   EVT VT = St->getValue().getValueType();
21062   EVT StVT = St->getMemoryVT();
21063   SDLoc dl(St);
21064   SDValue StoredVal = St->getOperand(1);
21065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21066
21067   // If we are saving a concatenation of two XMM registers, perform two stores.
21068   // On Sandy Bridge, 256-bit memory operations are executed by two
21069   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21070   // memory  operation.
21071   unsigned Alignment = St->getAlignment();
21072   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21073   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21074       StVT == VT && !IsAligned) {
21075     unsigned NumElems = VT.getVectorNumElements();
21076     if (NumElems < 2)
21077       return SDValue();
21078
21079     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21080     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21081
21082     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21083     SDValue Ptr0 = St->getBasePtr();
21084     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21085
21086     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21087                                 St->getPointerInfo(), St->isVolatile(),
21088                                 St->isNonTemporal(), Alignment);
21089     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21090                                 St->getPointerInfo(), St->isVolatile(),
21091                                 St->isNonTemporal(),
21092                                 std::min(16U, Alignment));
21093     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21094   }
21095
21096   // Optimize trunc store (of multiple scalars) to shuffle and store.
21097   // First, pack all of the elements in one place. Next, store to memory
21098   // in fewer chunks.
21099   if (St->isTruncatingStore() && VT.isVector()) {
21100     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21101     unsigned NumElems = VT.getVectorNumElements();
21102     assert(StVT != VT && "Cannot truncate to the same type");
21103     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21104     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21105
21106     // From, To sizes and ElemCount must be pow of two
21107     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21108     // We are going to use the original vector elt for storing.
21109     // Accumulated smaller vector elements must be a multiple of the store size.
21110     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21111
21112     unsigned SizeRatio  = FromSz / ToSz;
21113
21114     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21115
21116     // Create a type on which we perform the shuffle
21117     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21118             StVT.getScalarType(), NumElems*SizeRatio);
21119
21120     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21121
21122     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21123     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21124     for (unsigned i = 0; i != NumElems; ++i)
21125       ShuffleVec[i] = i * SizeRatio;
21126
21127     // Can't shuffle using an illegal type.
21128     if (!TLI.isTypeLegal(WideVecVT))
21129       return SDValue();
21130
21131     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21132                                          DAG.getUNDEF(WideVecVT),
21133                                          &ShuffleVec[0]);
21134     // At this point all of the data is stored at the bottom of the
21135     // register. We now need to save it to mem.
21136
21137     // Find the largest store unit
21138     MVT StoreType = MVT::i8;
21139     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21140          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21141       MVT Tp = (MVT::SimpleValueType)tp;
21142       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21143         StoreType = Tp;
21144     }
21145
21146     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21147     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21148         (64 <= NumElems * ToSz))
21149       StoreType = MVT::f64;
21150
21151     // Bitcast the original vector into a vector of store-size units
21152     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21153             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21154     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21155     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21156     SmallVector<SDValue, 8> Chains;
21157     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21158                                         TLI.getPointerTy());
21159     SDValue Ptr = St->getBasePtr();
21160
21161     // Perform one or more big stores into memory.
21162     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21163       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21164                                    StoreType, ShuffWide,
21165                                    DAG.getIntPtrConstant(i));
21166       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21167                                 St->getPointerInfo(), St->isVolatile(),
21168                                 St->isNonTemporal(), St->getAlignment());
21169       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21170       Chains.push_back(Ch);
21171     }
21172
21173     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21174   }
21175
21176   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21177   // the FP state in cases where an emms may be missing.
21178   // A preferable solution to the general problem is to figure out the right
21179   // places to insert EMMS.  This qualifies as a quick hack.
21180
21181   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21182   if (VT.getSizeInBits() != 64)
21183     return SDValue();
21184
21185   const Function *F = DAG.getMachineFunction().getFunction();
21186   bool NoImplicitFloatOps = F->getAttributes().
21187     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21188   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21189                      && Subtarget->hasSSE2();
21190   if ((VT.isVector() ||
21191        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21192       isa<LoadSDNode>(St->getValue()) &&
21193       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21194       St->getChain().hasOneUse() && !St->isVolatile()) {
21195     SDNode* LdVal = St->getValue().getNode();
21196     LoadSDNode *Ld = nullptr;
21197     int TokenFactorIndex = -1;
21198     SmallVector<SDValue, 8> Ops;
21199     SDNode* ChainVal = St->getChain().getNode();
21200     // Must be a store of a load.  We currently handle two cases:  the load
21201     // is a direct child, and it's under an intervening TokenFactor.  It is
21202     // possible to dig deeper under nested TokenFactors.
21203     if (ChainVal == LdVal)
21204       Ld = cast<LoadSDNode>(St->getChain());
21205     else if (St->getValue().hasOneUse() &&
21206              ChainVal->getOpcode() == ISD::TokenFactor) {
21207       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21208         if (ChainVal->getOperand(i).getNode() == LdVal) {
21209           TokenFactorIndex = i;
21210           Ld = cast<LoadSDNode>(St->getValue());
21211         } else
21212           Ops.push_back(ChainVal->getOperand(i));
21213       }
21214     }
21215
21216     if (!Ld || !ISD::isNormalLoad(Ld))
21217       return SDValue();
21218
21219     // If this is not the MMX case, i.e. we are just turning i64 load/store
21220     // into f64 load/store, avoid the transformation if there are multiple
21221     // uses of the loaded value.
21222     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21223       return SDValue();
21224
21225     SDLoc LdDL(Ld);
21226     SDLoc StDL(N);
21227     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21228     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21229     // pair instead.
21230     if (Subtarget->is64Bit() || F64IsLegal) {
21231       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21232       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21233                                   Ld->getPointerInfo(), Ld->isVolatile(),
21234                                   Ld->isNonTemporal(), Ld->isInvariant(),
21235                                   Ld->getAlignment());
21236       SDValue NewChain = NewLd.getValue(1);
21237       if (TokenFactorIndex != -1) {
21238         Ops.push_back(NewChain);
21239         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21240       }
21241       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21242                           St->getPointerInfo(),
21243                           St->isVolatile(), St->isNonTemporal(),
21244                           St->getAlignment());
21245     }
21246
21247     // Otherwise, lower to two pairs of 32-bit loads / stores.
21248     SDValue LoAddr = Ld->getBasePtr();
21249     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21250                                  DAG.getConstant(4, MVT::i32));
21251
21252     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21253                                Ld->getPointerInfo(),
21254                                Ld->isVolatile(), Ld->isNonTemporal(),
21255                                Ld->isInvariant(), Ld->getAlignment());
21256     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21257                                Ld->getPointerInfo().getWithOffset(4),
21258                                Ld->isVolatile(), Ld->isNonTemporal(),
21259                                Ld->isInvariant(),
21260                                MinAlign(Ld->getAlignment(), 4));
21261
21262     SDValue NewChain = LoLd.getValue(1);
21263     if (TokenFactorIndex != -1) {
21264       Ops.push_back(LoLd);
21265       Ops.push_back(HiLd);
21266       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21267     }
21268
21269     LoAddr = St->getBasePtr();
21270     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21271                          DAG.getConstant(4, MVT::i32));
21272
21273     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21274                                 St->getPointerInfo(),
21275                                 St->isVolatile(), St->isNonTemporal(),
21276                                 St->getAlignment());
21277     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21278                                 St->getPointerInfo().getWithOffset(4),
21279                                 St->isVolatile(),
21280                                 St->isNonTemporal(),
21281                                 MinAlign(St->getAlignment(), 4));
21282     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21283   }
21284   return SDValue();
21285 }
21286
21287 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21288 /// and return the operands for the horizontal operation in LHS and RHS.  A
21289 /// horizontal operation performs the binary operation on successive elements
21290 /// of its first operand, then on successive elements of its second operand,
21291 /// returning the resulting values in a vector.  For example, if
21292 ///   A = < float a0, float a1, float a2, float a3 >
21293 /// and
21294 ///   B = < float b0, float b1, float b2, float b3 >
21295 /// then the result of doing a horizontal operation on A and B is
21296 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21297 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21298 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21299 /// set to A, RHS to B, and the routine returns 'true'.
21300 /// Note that the binary operation should have the property that if one of the
21301 /// operands is UNDEF then the result is UNDEF.
21302 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21303   // Look for the following pattern: if
21304   //   A = < float a0, float a1, float a2, float a3 >
21305   //   B = < float b0, float b1, float b2, float b3 >
21306   // and
21307   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21308   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21309   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21310   // which is A horizontal-op B.
21311
21312   // At least one of the operands should be a vector shuffle.
21313   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21314       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21315     return false;
21316
21317   MVT VT = LHS.getSimpleValueType();
21318
21319   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21320          "Unsupported vector type for horizontal add/sub");
21321
21322   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21323   // operate independently on 128-bit lanes.
21324   unsigned NumElts = VT.getVectorNumElements();
21325   unsigned NumLanes = VT.getSizeInBits()/128;
21326   unsigned NumLaneElts = NumElts / NumLanes;
21327   assert((NumLaneElts % 2 == 0) &&
21328          "Vector type should have an even number of elements in each lane");
21329   unsigned HalfLaneElts = NumLaneElts/2;
21330
21331   // View LHS in the form
21332   //   LHS = VECTOR_SHUFFLE A, B, LMask
21333   // If LHS is not a shuffle then pretend it is the shuffle
21334   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21335   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21336   // type VT.
21337   SDValue A, B;
21338   SmallVector<int, 16> LMask(NumElts);
21339   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21340     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21341       A = LHS.getOperand(0);
21342     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21343       B = LHS.getOperand(1);
21344     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21345     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21346   } else {
21347     if (LHS.getOpcode() != ISD::UNDEF)
21348       A = LHS;
21349     for (unsigned i = 0; i != NumElts; ++i)
21350       LMask[i] = i;
21351   }
21352
21353   // Likewise, view RHS in the form
21354   //   RHS = VECTOR_SHUFFLE C, D, RMask
21355   SDValue C, D;
21356   SmallVector<int, 16> RMask(NumElts);
21357   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21358     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21359       C = RHS.getOperand(0);
21360     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21361       D = RHS.getOperand(1);
21362     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21363     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21364   } else {
21365     if (RHS.getOpcode() != ISD::UNDEF)
21366       C = RHS;
21367     for (unsigned i = 0; i != NumElts; ++i)
21368       RMask[i] = i;
21369   }
21370
21371   // Check that the shuffles are both shuffling the same vectors.
21372   if (!(A == C && B == D) && !(A == D && B == C))
21373     return false;
21374
21375   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21376   if (!A.getNode() && !B.getNode())
21377     return false;
21378
21379   // If A and B occur in reverse order in RHS, then "swap" them (which means
21380   // rewriting the mask).
21381   if (A != C)
21382     CommuteVectorShuffleMask(RMask, NumElts);
21383
21384   // At this point LHS and RHS are equivalent to
21385   //   LHS = VECTOR_SHUFFLE A, B, LMask
21386   //   RHS = VECTOR_SHUFFLE A, B, RMask
21387   // Check that the masks correspond to performing a horizontal operation.
21388   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21389     for (unsigned i = 0; i != NumLaneElts; ++i) {
21390       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21391
21392       // Ignore any UNDEF components.
21393       if (LIdx < 0 || RIdx < 0 ||
21394           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21395           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21396         continue;
21397
21398       // Check that successive elements are being operated on.  If not, this is
21399       // not a horizontal operation.
21400       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21401       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21402       if (!(LIdx == Index && RIdx == Index + 1) &&
21403           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21404         return false;
21405     }
21406   }
21407
21408   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21409   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21410   return true;
21411 }
21412
21413 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21414 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21415                                   const X86Subtarget *Subtarget) {
21416   EVT VT = N->getValueType(0);
21417   SDValue LHS = N->getOperand(0);
21418   SDValue RHS = N->getOperand(1);
21419
21420   // Try to synthesize horizontal adds from adds of shuffles.
21421   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21422        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21423       isHorizontalBinOp(LHS, RHS, true))
21424     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21425   return SDValue();
21426 }
21427
21428 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21429 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21430                                   const X86Subtarget *Subtarget) {
21431   EVT VT = N->getValueType(0);
21432   SDValue LHS = N->getOperand(0);
21433   SDValue RHS = N->getOperand(1);
21434
21435   // Try to synthesize horizontal subs from subs of shuffles.
21436   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21437        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21438       isHorizontalBinOp(LHS, RHS, false))
21439     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21440   return SDValue();
21441 }
21442
21443 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21444 /// X86ISD::FXOR nodes.
21445 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21446   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21447   // F[X]OR(0.0, x) -> x
21448   // F[X]OR(x, 0.0) -> x
21449   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21450     if (C->getValueAPF().isPosZero())
21451       return N->getOperand(1);
21452   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21453     if (C->getValueAPF().isPosZero())
21454       return N->getOperand(0);
21455   return SDValue();
21456 }
21457
21458 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21459 /// X86ISD::FMAX nodes.
21460 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21461   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21462
21463   // Only perform optimizations if UnsafeMath is used.
21464   if (!DAG.getTarget().Options.UnsafeFPMath)
21465     return SDValue();
21466
21467   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21468   // into FMINC and FMAXC, which are Commutative operations.
21469   unsigned NewOp = 0;
21470   switch (N->getOpcode()) {
21471     default: llvm_unreachable("unknown opcode");
21472     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21473     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21474   }
21475
21476   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21477                      N->getOperand(0), N->getOperand(1));
21478 }
21479
21480 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21481 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21482   // FAND(0.0, x) -> 0.0
21483   // FAND(x, 0.0) -> 0.0
21484   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21485     if (C->getValueAPF().isPosZero())
21486       return N->getOperand(0);
21487   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21488     if (C->getValueAPF().isPosZero())
21489       return N->getOperand(1);
21490   return SDValue();
21491 }
21492
21493 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21494 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21495   // FANDN(x, 0.0) -> 0.0
21496   // FANDN(0.0, x) -> x
21497   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21498     if (C->getValueAPF().isPosZero())
21499       return N->getOperand(1);
21500   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21501     if (C->getValueAPF().isPosZero())
21502       return N->getOperand(1);
21503   return SDValue();
21504 }
21505
21506 static SDValue PerformBTCombine(SDNode *N,
21507                                 SelectionDAG &DAG,
21508                                 TargetLowering::DAGCombinerInfo &DCI) {
21509   // BT ignores high bits in the bit index operand.
21510   SDValue Op1 = N->getOperand(1);
21511   if (Op1.hasOneUse()) {
21512     unsigned BitWidth = Op1.getValueSizeInBits();
21513     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21514     APInt KnownZero, KnownOne;
21515     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21516                                           !DCI.isBeforeLegalizeOps());
21517     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21518     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21519         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21520       DCI.CommitTargetLoweringOpt(TLO);
21521   }
21522   return SDValue();
21523 }
21524
21525 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21526   SDValue Op = N->getOperand(0);
21527   if (Op.getOpcode() == ISD::BITCAST)
21528     Op = Op.getOperand(0);
21529   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21530   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21531       VT.getVectorElementType().getSizeInBits() ==
21532       OpVT.getVectorElementType().getSizeInBits()) {
21533     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21534   }
21535   return SDValue();
21536 }
21537
21538 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21539                                                const X86Subtarget *Subtarget) {
21540   EVT VT = N->getValueType(0);
21541   if (!VT.isVector())
21542     return SDValue();
21543
21544   SDValue N0 = N->getOperand(0);
21545   SDValue N1 = N->getOperand(1);
21546   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21547   SDLoc dl(N);
21548
21549   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21550   // both SSE and AVX2 since there is no sign-extended shift right
21551   // operation on a vector with 64-bit elements.
21552   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21553   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21554   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21555       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21556     SDValue N00 = N0.getOperand(0);
21557
21558     // EXTLOAD has a better solution on AVX2,
21559     // it may be replaced with X86ISD::VSEXT node.
21560     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21561       if (!ISD::isNormalLoad(N00.getNode()))
21562         return SDValue();
21563
21564     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21565         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21566                                   N00, N1);
21567       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21568     }
21569   }
21570   return SDValue();
21571 }
21572
21573 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21574                                   TargetLowering::DAGCombinerInfo &DCI,
21575                                   const X86Subtarget *Subtarget) {
21576   if (!DCI.isBeforeLegalizeOps())
21577     return SDValue();
21578
21579   if (!Subtarget->hasFp256())
21580     return SDValue();
21581
21582   EVT VT = N->getValueType(0);
21583   if (VT.isVector() && VT.getSizeInBits() == 256) {
21584     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21585     if (R.getNode())
21586       return R;
21587   }
21588
21589   return SDValue();
21590 }
21591
21592 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21593                                  const X86Subtarget* Subtarget) {
21594   SDLoc dl(N);
21595   EVT VT = N->getValueType(0);
21596
21597   // Let legalize expand this if it isn't a legal type yet.
21598   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21599     return SDValue();
21600
21601   EVT ScalarVT = VT.getScalarType();
21602   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21603       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21604     return SDValue();
21605
21606   SDValue A = N->getOperand(0);
21607   SDValue B = N->getOperand(1);
21608   SDValue C = N->getOperand(2);
21609
21610   bool NegA = (A.getOpcode() == ISD::FNEG);
21611   bool NegB = (B.getOpcode() == ISD::FNEG);
21612   bool NegC = (C.getOpcode() == ISD::FNEG);
21613
21614   // Negative multiplication when NegA xor NegB
21615   bool NegMul = (NegA != NegB);
21616   if (NegA)
21617     A = A.getOperand(0);
21618   if (NegB)
21619     B = B.getOperand(0);
21620   if (NegC)
21621     C = C.getOperand(0);
21622
21623   unsigned Opcode;
21624   if (!NegMul)
21625     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21626   else
21627     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21628
21629   return DAG.getNode(Opcode, dl, VT, A, B, C);
21630 }
21631
21632 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21633                                   TargetLowering::DAGCombinerInfo &DCI,
21634                                   const X86Subtarget *Subtarget) {
21635   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21636   //           (and (i32 x86isd::setcc_carry), 1)
21637   // This eliminates the zext. This transformation is necessary because
21638   // ISD::SETCC is always legalized to i8.
21639   SDLoc dl(N);
21640   SDValue N0 = N->getOperand(0);
21641   EVT VT = N->getValueType(0);
21642
21643   if (N0.getOpcode() == ISD::AND &&
21644       N0.hasOneUse() &&
21645       N0.getOperand(0).hasOneUse()) {
21646     SDValue N00 = N0.getOperand(0);
21647     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21648       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21649       if (!C || C->getZExtValue() != 1)
21650         return SDValue();
21651       return DAG.getNode(ISD::AND, dl, VT,
21652                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21653                                      N00.getOperand(0), N00.getOperand(1)),
21654                          DAG.getConstant(1, VT));
21655     }
21656   }
21657
21658   if (N0.getOpcode() == ISD::TRUNCATE &&
21659       N0.hasOneUse() &&
21660       N0.getOperand(0).hasOneUse()) {
21661     SDValue N00 = N0.getOperand(0);
21662     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21663       return DAG.getNode(ISD::AND, dl, VT,
21664                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21665                                      N00.getOperand(0), N00.getOperand(1)),
21666                          DAG.getConstant(1, VT));
21667     }
21668   }
21669   if (VT.is256BitVector()) {
21670     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21671     if (R.getNode())
21672       return R;
21673   }
21674
21675   return SDValue();
21676 }
21677
21678 // Optimize x == -y --> x+y == 0
21679 //          x != -y --> x+y != 0
21680 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21681                                       const X86Subtarget* Subtarget) {
21682   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21683   SDValue LHS = N->getOperand(0);
21684   SDValue RHS = N->getOperand(1);
21685   EVT VT = N->getValueType(0);
21686   SDLoc DL(N);
21687
21688   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21689     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21690       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21691         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21692                                    LHS.getValueType(), RHS, LHS.getOperand(1));
21693         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21694                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21695       }
21696   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21697     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21698       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21699         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21700                                    RHS.getValueType(), LHS, RHS.getOperand(1));
21701         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21702                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21703       }
21704
21705   if (VT.getScalarType() == MVT::i1) {
21706     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21707       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21708     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21709     if (!IsSEXT0 && !IsVZero0)
21710       return SDValue();
21711     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21712       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21713     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21714
21715     if (!IsSEXT1 && !IsVZero1)
21716       return SDValue();
21717
21718     if (IsSEXT0 && IsVZero1) {
21719       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21720       if (CC == ISD::SETEQ)
21721         return DAG.getNOT(DL, LHS.getOperand(0), VT);
21722       return LHS.getOperand(0);
21723     }
21724     if (IsSEXT1 && IsVZero0) {
21725       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21726       if (CC == ISD::SETEQ)
21727         return DAG.getNOT(DL, RHS.getOperand(0), VT);
21728       return RHS.getOperand(0);
21729     }
21730   }
21731
21732   return SDValue();
21733 }
21734
21735 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21736                                       const X86Subtarget *Subtarget) {
21737   SDLoc dl(N);
21738   MVT VT = N->getOperand(1)->getSimpleValueType(0);
21739   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21740          "X86insertps is only defined for v4x32");
21741
21742   SDValue Ld = N->getOperand(1);
21743   if (MayFoldLoad(Ld)) {
21744     // Extract the countS bits from the immediate so we can get the proper
21745     // address when narrowing the vector load to a specific element.
21746     // When the second source op is a memory address, interps doesn't use
21747     // countS and just gets an f32 from that address.
21748     unsigned DestIndex =
21749         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21750     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21751   } else
21752     return SDValue();
21753
21754   // Create this as a scalar to vector to match the instruction pattern.
21755   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21756   // countS bits are ignored when loading from memory on insertps, which
21757   // means we don't need to explicitly set them to 0.
21758   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21759                      LoadScalarToVector, N->getOperand(2));
21760 }
21761
21762 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21763 // as "sbb reg,reg", since it can be extended without zext and produces
21764 // an all-ones bit which is more useful than 0/1 in some cases.
21765 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21766                                MVT VT) {
21767   if (VT == MVT::i8)
21768     return DAG.getNode(ISD::AND, DL, VT,
21769                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21770                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21771                        DAG.getConstant(1, VT));
21772   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21773   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21774                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21775                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21776 }
21777
21778 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21779 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21780                                    TargetLowering::DAGCombinerInfo &DCI,
21781                                    const X86Subtarget *Subtarget) {
21782   SDLoc DL(N);
21783   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21784   SDValue EFLAGS = N->getOperand(1);
21785
21786   if (CC == X86::COND_A) {
21787     // Try to convert COND_A into COND_B in an attempt to facilitate
21788     // materializing "setb reg".
21789     //
21790     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21791     // cannot take an immediate as its first operand.
21792     //
21793     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21794         EFLAGS.getValueType().isInteger() &&
21795         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21796       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21797                                    EFLAGS.getNode()->getVTList(),
21798                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21799       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21800       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21801     }
21802   }
21803
21804   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21805   // a zext and produces an all-ones bit which is more useful than 0/1 in some
21806   // cases.
21807   if (CC == X86::COND_B)
21808     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21809
21810   SDValue Flags;
21811
21812   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21813   if (Flags.getNode()) {
21814     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21815     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21816   }
21817
21818   return SDValue();
21819 }
21820
21821 // Optimize branch condition evaluation.
21822 //
21823 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21824                                     TargetLowering::DAGCombinerInfo &DCI,
21825                                     const X86Subtarget *Subtarget) {
21826   SDLoc DL(N);
21827   SDValue Chain = N->getOperand(0);
21828   SDValue Dest = N->getOperand(1);
21829   SDValue EFLAGS = N->getOperand(3);
21830   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21831
21832   SDValue Flags;
21833
21834   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21835   if (Flags.getNode()) {
21836     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21837     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21838                        Flags);
21839   }
21840
21841   return SDValue();
21842 }
21843
21844 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21845                                         const X86TargetLowering *XTLI) {
21846   SDValue Op0 = N->getOperand(0);
21847   EVT InVT = Op0->getValueType(0);
21848
21849   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21850   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21851     SDLoc dl(N);
21852     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21853     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21854     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21855   }
21856
21857   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21858   // a 32-bit target where SSE doesn't support i64->FP operations.
21859   if (Op0.getOpcode() == ISD::LOAD) {
21860     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21861     EVT VT = Ld->getValueType(0);
21862     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21863         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21864         !XTLI->getSubtarget()->is64Bit() &&
21865         VT == MVT::i64) {
21866       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21867                                           Ld->getChain(), Op0, DAG);
21868       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21869       return FILDChain;
21870     }
21871   }
21872   return SDValue();
21873 }
21874
21875 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21876 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21877                                  X86TargetLowering::DAGCombinerInfo &DCI) {
21878   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21879   // the result is either zero or one (depending on the input carry bit).
21880   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21881   if (X86::isZeroNode(N->getOperand(0)) &&
21882       X86::isZeroNode(N->getOperand(1)) &&
21883       // We don't have a good way to replace an EFLAGS use, so only do this when
21884       // dead right now.
21885       SDValue(N, 1).use_empty()) {
21886     SDLoc DL(N);
21887     EVT VT = N->getValueType(0);
21888     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21889     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21890                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21891                                            DAG.getConstant(X86::COND_B,MVT::i8),
21892                                            N->getOperand(2)),
21893                                DAG.getConstant(1, VT));
21894     return DCI.CombineTo(N, Res1, CarryOut);
21895   }
21896
21897   return SDValue();
21898 }
21899
21900 // fold (add Y, (sete  X, 0)) -> adc  0, Y
21901 //      (add Y, (setne X, 0)) -> sbb -1, Y
21902 //      (sub (sete  X, 0), Y) -> sbb  0, Y
21903 //      (sub (setne X, 0), Y) -> adc -1, Y
21904 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21905   SDLoc DL(N);
21906
21907   // Look through ZExts.
21908   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21909   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21910     return SDValue();
21911
21912   SDValue SetCC = Ext.getOperand(0);
21913   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21914     return SDValue();
21915
21916   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21917   if (CC != X86::COND_E && CC != X86::COND_NE)
21918     return SDValue();
21919
21920   SDValue Cmp = SetCC.getOperand(1);
21921   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21922       !X86::isZeroNode(Cmp.getOperand(1)) ||
21923       !Cmp.getOperand(0).getValueType().isInteger())
21924     return SDValue();
21925
21926   SDValue CmpOp0 = Cmp.getOperand(0);
21927   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21928                                DAG.getConstant(1, CmpOp0.getValueType()));
21929
21930   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21931   if (CC == X86::COND_NE)
21932     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21933                        DL, OtherVal.getValueType(), OtherVal,
21934                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21935   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21936                      DL, OtherVal.getValueType(), OtherVal,
21937                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21938 }
21939
21940 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21941 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21942                                  const X86Subtarget *Subtarget) {
21943   EVT VT = N->getValueType(0);
21944   SDValue Op0 = N->getOperand(0);
21945   SDValue Op1 = N->getOperand(1);
21946
21947   // Try to synthesize horizontal adds from adds of shuffles.
21948   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21949        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21950       isHorizontalBinOp(Op0, Op1, true))
21951     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21952
21953   return OptimizeConditionalInDecrement(N, DAG);
21954 }
21955
21956 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21957                                  const X86Subtarget *Subtarget) {
21958   SDValue Op0 = N->getOperand(0);
21959   SDValue Op1 = N->getOperand(1);
21960
21961   // X86 can't encode an immediate LHS of a sub. See if we can push the
21962   // negation into a preceding instruction.
21963   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21964     // If the RHS of the sub is a XOR with one use and a constant, invert the
21965     // immediate. Then add one to the LHS of the sub so we can turn
21966     // X-Y -> X+~Y+1, saving one register.
21967     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21968         isa<ConstantSDNode>(Op1.getOperand(1))) {
21969       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21970       EVT VT = Op0.getValueType();
21971       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21972                                    Op1.getOperand(0),
21973                                    DAG.getConstant(~XorC, VT));
21974       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21975                          DAG.getConstant(C->getAPIntValue()+1, VT));
21976     }
21977   }
21978
21979   // Try to synthesize horizontal adds from adds of shuffles.
21980   EVT VT = N->getValueType(0);
21981   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21982        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21983       isHorizontalBinOp(Op0, Op1, true))
21984     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21985
21986   return OptimizeConditionalInDecrement(N, DAG);
21987 }
21988
21989 /// performVZEXTCombine - Performs build vector combines
21990 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21991                                         TargetLowering::DAGCombinerInfo &DCI,
21992                                         const X86Subtarget *Subtarget) {
21993   // (vzext (bitcast (vzext (x)) -> (vzext x)
21994   SDValue In = N->getOperand(0);
21995   while (In.getOpcode() == ISD::BITCAST)
21996     In = In.getOperand(0);
21997
21998   if (In.getOpcode() != X86ISD::VZEXT)
21999     return SDValue();
22000
22001   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22002                      In.getOperand(0));
22003 }
22004
22005 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22006                                              DAGCombinerInfo &DCI) const {
22007   SelectionDAG &DAG = DCI.DAG;
22008   switch (N->getOpcode()) {
22009   default: break;
22010   case ISD::EXTRACT_VECTOR_ELT:
22011     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22012   case ISD::VSELECT:
22013   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22014   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22015   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22016   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22017   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22018   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22019   case ISD::SHL:
22020   case ISD::SRA:
22021   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22022   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22023   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22024   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22025   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22026   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22027   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22028   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22029   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22030   case X86ISD::FXOR:
22031   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22032   case X86ISD::FMIN:
22033   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22034   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22035   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22036   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22037   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22038   case ISD::ANY_EXTEND:
22039   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22040   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22041   case ISD::SIGN_EXTEND_INREG:
22042     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22043   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22044   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22045   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22046   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22047   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22048   case X86ISD::SHUFP:       // Handle all target specific shuffles
22049   case X86ISD::PALIGNR:
22050   case X86ISD::UNPCKH:
22051   case X86ISD::UNPCKL:
22052   case X86ISD::MOVHLPS:
22053   case X86ISD::MOVLHPS:
22054   case X86ISD::PSHUFD:
22055   case X86ISD::PSHUFHW:
22056   case X86ISD::PSHUFLW:
22057   case X86ISD::MOVSS:
22058   case X86ISD::MOVSD:
22059   case X86ISD::VPERMILP:
22060   case X86ISD::VPERM2X128:
22061   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22062   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22063   case ISD::INTRINSIC_WO_CHAIN:
22064     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22065   case X86ISD::INSERTPS:
22066     return PerformINSERTPSCombine(N, DAG, Subtarget);
22067   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22068   }
22069
22070   return SDValue();
22071 }
22072
22073 /// isTypeDesirableForOp - Return true if the target has native support for
22074 /// the specified value type and it is 'desirable' to use the type for the
22075 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22076 /// instruction encodings are longer and some i16 instructions are slow.
22077 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22078   if (!isTypeLegal(VT))
22079     return false;
22080   if (VT != MVT::i16)
22081     return true;
22082
22083   switch (Opc) {
22084   default:
22085     return true;
22086   case ISD::LOAD:
22087   case ISD::SIGN_EXTEND:
22088   case ISD::ZERO_EXTEND:
22089   case ISD::ANY_EXTEND:
22090   case ISD::SHL:
22091   case ISD::SRL:
22092   case ISD::SUB:
22093   case ISD::ADD:
22094   case ISD::MUL:
22095   case ISD::AND:
22096   case ISD::OR:
22097   case ISD::XOR:
22098     return false;
22099   }
22100 }
22101
22102 /// IsDesirableToPromoteOp - This method query the target whether it is
22103 /// beneficial for dag combiner to promote the specified node. If true, it
22104 /// should return the desired promotion type by reference.
22105 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22106   EVT VT = Op.getValueType();
22107   if (VT != MVT::i16)
22108     return false;
22109
22110   bool Promote = false;
22111   bool Commute = false;
22112   switch (Op.getOpcode()) {
22113   default: break;
22114   case ISD::LOAD: {
22115     LoadSDNode *LD = cast<LoadSDNode>(Op);
22116     // If the non-extending load has a single use and it's not live out, then it
22117     // might be folded.
22118     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22119                                                      Op.hasOneUse()*/) {
22120       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22121              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22122         // The only case where we'd want to promote LOAD (rather then it being
22123         // promoted as an operand is when it's only use is liveout.
22124         if (UI->getOpcode() != ISD::CopyToReg)
22125           return false;
22126       }
22127     }
22128     Promote = true;
22129     break;
22130   }
22131   case ISD::SIGN_EXTEND:
22132   case ISD::ZERO_EXTEND:
22133   case ISD::ANY_EXTEND:
22134     Promote = true;
22135     break;
22136   case ISD::SHL:
22137   case ISD::SRL: {
22138     SDValue N0 = Op.getOperand(0);
22139     // Look out for (store (shl (load), x)).
22140     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22141       return false;
22142     Promote = true;
22143     break;
22144   }
22145   case ISD::ADD:
22146   case ISD::MUL:
22147   case ISD::AND:
22148   case ISD::OR:
22149   case ISD::XOR:
22150     Commute = true;
22151     // fallthrough
22152   case ISD::SUB: {
22153     SDValue N0 = Op.getOperand(0);
22154     SDValue N1 = Op.getOperand(1);
22155     if (!Commute && MayFoldLoad(N1))
22156       return false;
22157     // Avoid disabling potential load folding opportunities.
22158     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22159       return false;
22160     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22161       return false;
22162     Promote = true;
22163   }
22164   }
22165
22166   PVT = MVT::i32;
22167   return Promote;
22168 }
22169
22170 //===----------------------------------------------------------------------===//
22171 //                           X86 Inline Assembly Support
22172 //===----------------------------------------------------------------------===//
22173
22174 namespace {
22175   // Helper to match a string separated by whitespace.
22176   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22177     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22178
22179     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22180       StringRef piece(*args[i]);
22181       if (!s.startswith(piece)) // Check if the piece matches.
22182         return false;
22183
22184       s = s.substr(piece.size());
22185       StringRef::size_type pos = s.find_first_not_of(" \t");
22186       if (pos == 0) // We matched a prefix.
22187         return false;
22188
22189       s = s.substr(pos);
22190     }
22191
22192     return s.empty();
22193   }
22194   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22195 }
22196
22197 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22198
22199   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22200     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22201         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22202         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22203
22204       if (AsmPieces.size() == 3)
22205         return true;
22206       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22207         return true;
22208     }
22209   }
22210   return false;
22211 }
22212
22213 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22214   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22215
22216   std::string AsmStr = IA->getAsmString();
22217
22218   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22219   if (!Ty || Ty->getBitWidth() % 16 != 0)
22220     return false;
22221
22222   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22223   SmallVector<StringRef, 4> AsmPieces;
22224   SplitString(AsmStr, AsmPieces, ";\n");
22225
22226   switch (AsmPieces.size()) {
22227   default: return false;
22228   case 1:
22229     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22230     // we will turn this bswap into something that will be lowered to logical
22231     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22232     // lower so don't worry about this.
22233     // bswap $0
22234     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22235         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22236         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22237         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22238         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22239         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22240       // No need to check constraints, nothing other than the equivalent of
22241       // "=r,0" would be valid here.
22242       return IntrinsicLowering::LowerToByteSwap(CI);
22243     }
22244
22245     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22246     if (CI->getType()->isIntegerTy(16) &&
22247         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22248         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22249          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22250       AsmPieces.clear();
22251       const std::string &ConstraintsStr = IA->getConstraintString();
22252       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22253       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22254       if (clobbersFlagRegisters(AsmPieces))
22255         return IntrinsicLowering::LowerToByteSwap(CI);
22256     }
22257     break;
22258   case 3:
22259     if (CI->getType()->isIntegerTy(32) &&
22260         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22261         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22262         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22263         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22264       AsmPieces.clear();
22265       const std::string &ConstraintsStr = IA->getConstraintString();
22266       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22267       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22268       if (clobbersFlagRegisters(AsmPieces))
22269         return IntrinsicLowering::LowerToByteSwap(CI);
22270     }
22271
22272     if (CI->getType()->isIntegerTy(64)) {
22273       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22274       if (Constraints.size() >= 2 &&
22275           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22276           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22277         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22278         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22279             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22280             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22281           return IntrinsicLowering::LowerToByteSwap(CI);
22282       }
22283     }
22284     break;
22285   }
22286   return false;
22287 }
22288
22289 /// getConstraintType - Given a constraint letter, return the type of
22290 /// constraint it is for this target.
22291 X86TargetLowering::ConstraintType
22292 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22293   if (Constraint.size() == 1) {
22294     switch (Constraint[0]) {
22295     case 'R':
22296     case 'q':
22297     case 'Q':
22298     case 'f':
22299     case 't':
22300     case 'u':
22301     case 'y':
22302     case 'x':
22303     case 'Y':
22304     case 'l':
22305       return C_RegisterClass;
22306     case 'a':
22307     case 'b':
22308     case 'c':
22309     case 'd':
22310     case 'S':
22311     case 'D':
22312     case 'A':
22313       return C_Register;
22314     case 'I':
22315     case 'J':
22316     case 'K':
22317     case 'L':
22318     case 'M':
22319     case 'N':
22320     case 'G':
22321     case 'C':
22322     case 'e':
22323     case 'Z':
22324       return C_Other;
22325     default:
22326       break;
22327     }
22328   }
22329   return TargetLowering::getConstraintType(Constraint);
22330 }
22331
22332 /// Examine constraint type and operand type and determine a weight value.
22333 /// This object must already have been set up with the operand type
22334 /// and the current alternative constraint selected.
22335 TargetLowering::ConstraintWeight
22336   X86TargetLowering::getSingleConstraintMatchWeight(
22337     AsmOperandInfo &info, const char *constraint) const {
22338   ConstraintWeight weight = CW_Invalid;
22339   Value *CallOperandVal = info.CallOperandVal;
22340     // If we don't have a value, we can't do a match,
22341     // but allow it at the lowest weight.
22342   if (!CallOperandVal)
22343     return CW_Default;
22344   Type *type = CallOperandVal->getType();
22345   // Look at the constraint type.
22346   switch (*constraint) {
22347   default:
22348     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22349   case 'R':
22350   case 'q':
22351   case 'Q':
22352   case 'a':
22353   case 'b':
22354   case 'c':
22355   case 'd':
22356   case 'S':
22357   case 'D':
22358   case 'A':
22359     if (CallOperandVal->getType()->isIntegerTy())
22360       weight = CW_SpecificReg;
22361     break;
22362   case 'f':
22363   case 't':
22364   case 'u':
22365     if (type->isFloatingPointTy())
22366       weight = CW_SpecificReg;
22367     break;
22368   case 'y':
22369     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22370       weight = CW_SpecificReg;
22371     break;
22372   case 'x':
22373   case 'Y':
22374     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22375         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22376       weight = CW_Register;
22377     break;
22378   case 'I':
22379     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22380       if (C->getZExtValue() <= 31)
22381         weight = CW_Constant;
22382     }
22383     break;
22384   case 'J':
22385     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22386       if (C->getZExtValue() <= 63)
22387         weight = CW_Constant;
22388     }
22389     break;
22390   case 'K':
22391     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22392       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22393         weight = CW_Constant;
22394     }
22395     break;
22396   case 'L':
22397     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22398       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22399         weight = CW_Constant;
22400     }
22401     break;
22402   case 'M':
22403     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22404       if (C->getZExtValue() <= 3)
22405         weight = CW_Constant;
22406     }
22407     break;
22408   case 'N':
22409     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22410       if (C->getZExtValue() <= 0xff)
22411         weight = CW_Constant;
22412     }
22413     break;
22414   case 'G':
22415   case 'C':
22416     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22417       weight = CW_Constant;
22418     }
22419     break;
22420   case 'e':
22421     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22422       if ((C->getSExtValue() >= -0x80000000LL) &&
22423           (C->getSExtValue() <= 0x7fffffffLL))
22424         weight = CW_Constant;
22425     }
22426     break;
22427   case 'Z':
22428     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22429       if (C->getZExtValue() <= 0xffffffff)
22430         weight = CW_Constant;
22431     }
22432     break;
22433   }
22434   return weight;
22435 }
22436
22437 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22438 /// with another that has more specific requirements based on the type of the
22439 /// corresponding operand.
22440 const char *X86TargetLowering::
22441 LowerXConstraint(EVT ConstraintVT) const {
22442   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22443   // 'f' like normal targets.
22444   if (ConstraintVT.isFloatingPoint()) {
22445     if (Subtarget->hasSSE2())
22446       return "Y";
22447     if (Subtarget->hasSSE1())
22448       return "x";
22449   }
22450
22451   return TargetLowering::LowerXConstraint(ConstraintVT);
22452 }
22453
22454 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22455 /// vector.  If it is invalid, don't add anything to Ops.
22456 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22457                                                      std::string &Constraint,
22458                                                      std::vector<SDValue>&Ops,
22459                                                      SelectionDAG &DAG) const {
22460   SDValue Result;
22461
22462   // Only support length 1 constraints for now.
22463   if (Constraint.length() > 1) return;
22464
22465   char ConstraintLetter = Constraint[0];
22466   switch (ConstraintLetter) {
22467   default: break;
22468   case 'I':
22469     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22470       if (C->getZExtValue() <= 31) {
22471         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22472         break;
22473       }
22474     }
22475     return;
22476   case 'J':
22477     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22478       if (C->getZExtValue() <= 63) {
22479         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22480         break;
22481       }
22482     }
22483     return;
22484   case 'K':
22485     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22486       if (isInt<8>(C->getSExtValue())) {
22487         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22488         break;
22489       }
22490     }
22491     return;
22492   case 'N':
22493     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22494       if (C->getZExtValue() <= 255) {
22495         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22496         break;
22497       }
22498     }
22499     return;
22500   case 'e': {
22501     // 32-bit signed value
22502     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22503       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22504                                            C->getSExtValue())) {
22505         // Widen to 64 bits here to get it sign extended.
22506         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22507         break;
22508       }
22509     // FIXME gcc accepts some relocatable values here too, but only in certain
22510     // memory models; it's complicated.
22511     }
22512     return;
22513   }
22514   case 'Z': {
22515     // 32-bit unsigned value
22516     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22517       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22518                                            C->getZExtValue())) {
22519         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22520         break;
22521       }
22522     }
22523     // FIXME gcc accepts some relocatable values here too, but only in certain
22524     // memory models; it's complicated.
22525     return;
22526   }
22527   case 'i': {
22528     // Literal immediates are always ok.
22529     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22530       // Widen to 64 bits here to get it sign extended.
22531       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22532       break;
22533     }
22534
22535     // In any sort of PIC mode addresses need to be computed at runtime by
22536     // adding in a register or some sort of table lookup.  These can't
22537     // be used as immediates.
22538     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22539       return;
22540
22541     // If we are in non-pic codegen mode, we allow the address of a global (with
22542     // an optional displacement) to be used with 'i'.
22543     GlobalAddressSDNode *GA = nullptr;
22544     int64_t Offset = 0;
22545
22546     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22547     while (1) {
22548       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22549         Offset += GA->getOffset();
22550         break;
22551       } else if (Op.getOpcode() == ISD::ADD) {
22552         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22553           Offset += C->getZExtValue();
22554           Op = Op.getOperand(0);
22555           continue;
22556         }
22557       } else if (Op.getOpcode() == ISD::SUB) {
22558         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22559           Offset += -C->getZExtValue();
22560           Op = Op.getOperand(0);
22561           continue;
22562         }
22563       }
22564
22565       // Otherwise, this isn't something we can handle, reject it.
22566       return;
22567     }
22568
22569     const GlobalValue *GV = GA->getGlobal();
22570     // If we require an extra load to get this address, as in PIC mode, we
22571     // can't accept it.
22572     if (isGlobalStubReference(
22573             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22574       return;
22575
22576     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22577                                         GA->getValueType(0), Offset);
22578     break;
22579   }
22580   }
22581
22582   if (Result.getNode()) {
22583     Ops.push_back(Result);
22584     return;
22585   }
22586   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22587 }
22588
22589 std::pair<unsigned, const TargetRegisterClass*>
22590 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22591                                                 MVT VT) const {
22592   // First, see if this is a constraint that directly corresponds to an LLVM
22593   // register class.
22594   if (Constraint.size() == 1) {
22595     // GCC Constraint Letters
22596     switch (Constraint[0]) {
22597     default: break;
22598       // TODO: Slight differences here in allocation order and leaving
22599       // RIP in the class. Do they matter any more here than they do
22600       // in the normal allocation?
22601     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22602       if (Subtarget->is64Bit()) {
22603         if (VT == MVT::i32 || VT == MVT::f32)
22604           return std::make_pair(0U, &X86::GR32RegClass);
22605         if (VT == MVT::i16)
22606           return std::make_pair(0U, &X86::GR16RegClass);
22607         if (VT == MVT::i8 || VT == MVT::i1)
22608           return std::make_pair(0U, &X86::GR8RegClass);
22609         if (VT == MVT::i64 || VT == MVT::f64)
22610           return std::make_pair(0U, &X86::GR64RegClass);
22611         break;
22612       }
22613       // 32-bit fallthrough
22614     case 'Q':   // Q_REGS
22615       if (VT == MVT::i32 || VT == MVT::f32)
22616         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22617       if (VT == MVT::i16)
22618         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22619       if (VT == MVT::i8 || VT == MVT::i1)
22620         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22621       if (VT == MVT::i64)
22622         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22623       break;
22624     case 'r':   // GENERAL_REGS
22625     case 'l':   // INDEX_REGS
22626       if (VT == MVT::i8 || VT == MVT::i1)
22627         return std::make_pair(0U, &X86::GR8RegClass);
22628       if (VT == MVT::i16)
22629         return std::make_pair(0U, &X86::GR16RegClass);
22630       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22631         return std::make_pair(0U, &X86::GR32RegClass);
22632       return std::make_pair(0U, &X86::GR64RegClass);
22633     case 'R':   // LEGACY_REGS
22634       if (VT == MVT::i8 || VT == MVT::i1)
22635         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22636       if (VT == MVT::i16)
22637         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22638       if (VT == MVT::i32 || !Subtarget->is64Bit())
22639         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22640       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22641     case 'f':  // FP Stack registers.
22642       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22643       // value to the correct fpstack register class.
22644       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22645         return std::make_pair(0U, &X86::RFP32RegClass);
22646       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22647         return std::make_pair(0U, &X86::RFP64RegClass);
22648       return std::make_pair(0U, &X86::RFP80RegClass);
22649     case 'y':   // MMX_REGS if MMX allowed.
22650       if (!Subtarget->hasMMX()) break;
22651       return std::make_pair(0U, &X86::VR64RegClass);
22652     case 'Y':   // SSE_REGS if SSE2 allowed
22653       if (!Subtarget->hasSSE2()) break;
22654       // FALL THROUGH.
22655     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22656       if (!Subtarget->hasSSE1()) break;
22657
22658       switch (VT.SimpleTy) {
22659       default: break;
22660       // Scalar SSE types.
22661       case MVT::f32:
22662       case MVT::i32:
22663         return std::make_pair(0U, &X86::FR32RegClass);
22664       case MVT::f64:
22665       case MVT::i64:
22666         return std::make_pair(0U, &X86::FR64RegClass);
22667       // Vector types.
22668       case MVT::v16i8:
22669       case MVT::v8i16:
22670       case MVT::v4i32:
22671       case MVT::v2i64:
22672       case MVT::v4f32:
22673       case MVT::v2f64:
22674         return std::make_pair(0U, &X86::VR128RegClass);
22675       // AVX types.
22676       case MVT::v32i8:
22677       case MVT::v16i16:
22678       case MVT::v8i32:
22679       case MVT::v4i64:
22680       case MVT::v8f32:
22681       case MVT::v4f64:
22682         return std::make_pair(0U, &X86::VR256RegClass);
22683       case MVT::v8f64:
22684       case MVT::v16f32:
22685       case MVT::v16i32:
22686       case MVT::v8i64:
22687         return std::make_pair(0U, &X86::VR512RegClass);
22688       }
22689       break;
22690     }
22691   }
22692
22693   // Use the default implementation in TargetLowering to convert the register
22694   // constraint into a member of a register class.
22695   std::pair<unsigned, const TargetRegisterClass*> Res;
22696   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22697
22698   // Not found as a standard register?
22699   if (!Res.second) {
22700     // Map st(0) -> st(7) -> ST0
22701     if (Constraint.size() == 7 && Constraint[0] == '{' &&
22702         tolower(Constraint[1]) == 's' &&
22703         tolower(Constraint[2]) == 't' &&
22704         Constraint[3] == '(' &&
22705         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22706         Constraint[5] == ')' &&
22707         Constraint[6] == '}') {
22708
22709       Res.first = X86::ST0+Constraint[4]-'0';
22710       Res.second = &X86::RFP80RegClass;
22711       return Res;
22712     }
22713
22714     // GCC allows "st(0)" to be called just plain "st".
22715     if (StringRef("{st}").equals_lower(Constraint)) {
22716       Res.first = X86::ST0;
22717       Res.second = &X86::RFP80RegClass;
22718       return Res;
22719     }
22720
22721     // flags -> EFLAGS
22722     if (StringRef("{flags}").equals_lower(Constraint)) {
22723       Res.first = X86::EFLAGS;
22724       Res.second = &X86::CCRRegClass;
22725       return Res;
22726     }
22727
22728     // 'A' means EAX + EDX.
22729     if (Constraint == "A") {
22730       Res.first = X86::EAX;
22731       Res.second = &X86::GR32_ADRegClass;
22732       return Res;
22733     }
22734     return Res;
22735   }
22736
22737   // Otherwise, check to see if this is a register class of the wrong value
22738   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22739   // turn into {ax},{dx}.
22740   if (Res.second->hasType(VT))
22741     return Res;   // Correct type already, nothing to do.
22742
22743   // All of the single-register GCC register classes map their values onto
22744   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
22745   // really want an 8-bit or 32-bit register, map to the appropriate register
22746   // class and return the appropriate register.
22747   if (Res.second == &X86::GR16RegClass) {
22748     if (VT == MVT::i8 || VT == MVT::i1) {
22749       unsigned DestReg = 0;
22750       switch (Res.first) {
22751       default: break;
22752       case X86::AX: DestReg = X86::AL; break;
22753       case X86::DX: DestReg = X86::DL; break;
22754       case X86::CX: DestReg = X86::CL; break;
22755       case X86::BX: DestReg = X86::BL; break;
22756       }
22757       if (DestReg) {
22758         Res.first = DestReg;
22759         Res.second = &X86::GR8RegClass;
22760       }
22761     } else if (VT == MVT::i32 || VT == MVT::f32) {
22762       unsigned DestReg = 0;
22763       switch (Res.first) {
22764       default: break;
22765       case X86::AX: DestReg = X86::EAX; break;
22766       case X86::DX: DestReg = X86::EDX; break;
22767       case X86::CX: DestReg = X86::ECX; break;
22768       case X86::BX: DestReg = X86::EBX; break;
22769       case X86::SI: DestReg = X86::ESI; break;
22770       case X86::DI: DestReg = X86::EDI; break;
22771       case X86::BP: DestReg = X86::EBP; break;
22772       case X86::SP: DestReg = X86::ESP; break;
22773       }
22774       if (DestReg) {
22775         Res.first = DestReg;
22776         Res.second = &X86::GR32RegClass;
22777       }
22778     } else if (VT == MVT::i64 || VT == MVT::f64) {
22779       unsigned DestReg = 0;
22780       switch (Res.first) {
22781       default: break;
22782       case X86::AX: DestReg = X86::RAX; break;
22783       case X86::DX: DestReg = X86::RDX; break;
22784       case X86::CX: DestReg = X86::RCX; break;
22785       case X86::BX: DestReg = X86::RBX; break;
22786       case X86::SI: DestReg = X86::RSI; break;
22787       case X86::DI: DestReg = X86::RDI; break;
22788       case X86::BP: DestReg = X86::RBP; break;
22789       case X86::SP: DestReg = X86::RSP; break;
22790       }
22791       if (DestReg) {
22792         Res.first = DestReg;
22793         Res.second = &X86::GR64RegClass;
22794       }
22795     }
22796   } else if (Res.second == &X86::FR32RegClass ||
22797              Res.second == &X86::FR64RegClass ||
22798              Res.second == &X86::VR128RegClass ||
22799              Res.second == &X86::VR256RegClass ||
22800              Res.second == &X86::FR32XRegClass ||
22801              Res.second == &X86::FR64XRegClass ||
22802              Res.second == &X86::VR128XRegClass ||
22803              Res.second == &X86::VR256XRegClass ||
22804              Res.second == &X86::VR512RegClass) {
22805     // Handle references to XMM physical registers that got mapped into the
22806     // wrong class.  This can happen with constraints like {xmm0} where the
22807     // target independent register mapper will just pick the first match it can
22808     // find, ignoring the required type.
22809
22810     if (VT == MVT::f32 || VT == MVT::i32)
22811       Res.second = &X86::FR32RegClass;
22812     else if (VT == MVT::f64 || VT == MVT::i64)
22813       Res.second = &X86::FR64RegClass;
22814     else if (X86::VR128RegClass.hasType(VT))
22815       Res.second = &X86::VR128RegClass;
22816     else if (X86::VR256RegClass.hasType(VT))
22817       Res.second = &X86::VR256RegClass;
22818     else if (X86::VR512RegClass.hasType(VT))
22819       Res.second = &X86::VR512RegClass;
22820   }
22821
22822   return Res;
22823 }
22824
22825 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22826                                             Type *Ty) const {
22827   // Scaling factors are not free at all.
22828   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22829   // will take 2 allocations in the out of order engine instead of 1
22830   // for plain addressing mode, i.e. inst (reg1).
22831   // E.g.,
22832   // vaddps (%rsi,%drx), %ymm0, %ymm1
22833   // Requires two allocations (one for the load, one for the computation)
22834   // whereas:
22835   // vaddps (%rsi), %ymm0, %ymm1
22836   // Requires just 1 allocation, i.e., freeing allocations for other operations
22837   // and having less micro operations to execute.
22838   //
22839   // For some X86 architectures, this is even worse because for instance for
22840   // stores, the complex addressing mode forces the instruction to use the
22841   // "load" ports instead of the dedicated "store" port.
22842   // E.g., on Haswell:
22843   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22844   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
22845   if (isLegalAddressingMode(AM, Ty))
22846     // Scale represents reg2 * scale, thus account for 1
22847     // as soon as we use a second register.
22848     return AM.Scale != 0;
22849   return -1;
22850 }
22851
22852 bool X86TargetLowering::isTargetFTOL() const {
22853   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
22854 }