abc80351ec4c892b97d50dd234aa4a14b184eaef
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
663
664   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
665     // f32 and f64 use SSE.
666     // Set up the FP register classes.
667     addRegisterClass(MVT::f32, &X86::FR32RegClass);
668     addRegisterClass(MVT::f64, &X86::FR64RegClass);
669
670     // Use ANDPD to simulate FABS.
671     setOperationAction(ISD::FABS , MVT::f64, Custom);
672     setOperationAction(ISD::FABS , MVT::f32, Custom);
673
674     // Use XORP to simulate FNEG.
675     setOperationAction(ISD::FNEG , MVT::f64, Custom);
676     setOperationAction(ISD::FNEG , MVT::f32, Custom);
677
678     // Use ANDPD and ORPD to simulate FCOPYSIGN.
679     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
680     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
681
682     // Lower this to FGETSIGNx86 plus an AND.
683     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
684     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
685
686     // We don't support sin/cos/fmod
687     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
688     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
689     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
690     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
691     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
692     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
693
694     // Expand FP immediates into loads from the stack, except for the special
695     // cases we handle.
696     addLegalFPImmediate(APFloat(+0.0)); // xorpd
697     addLegalFPImmediate(APFloat(+0.0f)); // xorps
698   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
699     // Use SSE for f32, x87 for f64.
700     // Set up the FP register classes.
701     addRegisterClass(MVT::f32, &X86::FR32RegClass);
702     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
703
704     // Use ANDPS to simulate FABS.
705     setOperationAction(ISD::FABS , MVT::f32, Custom);
706
707     // Use XORP to simulate FNEG.
708     setOperationAction(ISD::FNEG , MVT::f32, Custom);
709
710     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
711
712     // Use ANDPS and ORPS to simulate FCOPYSIGN.
713     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
714     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
715
716     // We don't support sin/cos/fmod
717     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
718     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
719     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
720
721     // Special cases we handle for FP constants.
722     addLegalFPImmediate(APFloat(+0.0f)); // xorps
723     addLegalFPImmediate(APFloat(+0.0)); // FLD0
724     addLegalFPImmediate(APFloat(+1.0)); // FLD1
725     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
726     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
727
728     if (!TM.Options.UnsafeFPMath) {
729       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
730       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
731       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
732     }
733   } else if (!TM.Options.UseSoftFloat) {
734     // f32 and f64 in x87.
735     // Set up the FP register classes.
736     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
737     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
738
739     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
740     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
741     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
743
744     if (!TM.Options.UnsafeFPMath) {
745       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
746       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
747       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
749       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
751     }
752     addLegalFPImmediate(APFloat(+0.0)); // FLD0
753     addLegalFPImmediate(APFloat(+1.0)); // FLD1
754     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
755     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
756     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
757     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
758     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
759     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
760   }
761
762   // We don't support FMA.
763   setOperationAction(ISD::FMA, MVT::f64, Expand);
764   setOperationAction(ISD::FMA, MVT::f32, Expand);
765
766   // Long double always uses X87.
767   if (!TM.Options.UseSoftFloat) {
768     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
769     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
770     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
771     {
772       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
773       addLegalFPImmediate(TmpFlt);  // FLD0
774       TmpFlt.changeSign();
775       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
776
777       bool ignored;
778       APFloat TmpFlt2(+1.0);
779       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
780                       &ignored);
781       addLegalFPImmediate(TmpFlt2);  // FLD1
782       TmpFlt2.changeSign();
783       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
784     }
785
786     if (!TM.Options.UnsafeFPMath) {
787       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
788       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
789       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
790     }
791
792     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
793     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
794     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
795     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
796     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
797     setOperationAction(ISD::FMA, MVT::f80, Expand);
798   }
799
800   // Always use a library call for pow.
801   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
802   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
804
805   setOperationAction(ISD::FLOG, MVT::f80, Expand);
806   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
808   setOperationAction(ISD::FEXP, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
810
811   // First set operation action for all vector types to either promote
812   // (for widening) or expand (for scalarization). Then we will selectively
813   // turn on ones that can be effectively codegen'd.
814   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
815            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
816     MVT VT = (MVT::SimpleValueType)i;
817     setOperationAction(ISD::ADD , VT, Expand);
818     setOperationAction(ISD::SUB , VT, Expand);
819     setOperationAction(ISD::FADD, VT, Expand);
820     setOperationAction(ISD::FNEG, VT, Expand);
821     setOperationAction(ISD::FSUB, VT, Expand);
822     setOperationAction(ISD::MUL , VT, Expand);
823     setOperationAction(ISD::FMUL, VT, Expand);
824     setOperationAction(ISD::SDIV, VT, Expand);
825     setOperationAction(ISD::UDIV, VT, Expand);
826     setOperationAction(ISD::FDIV, VT, Expand);
827     setOperationAction(ISD::SREM, VT, Expand);
828     setOperationAction(ISD::UREM, VT, Expand);
829     setOperationAction(ISD::LOAD, VT, Expand);
830     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
831     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
832     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
833     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
834     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::FABS, VT, Expand);
836     setOperationAction(ISD::FSIN, VT, Expand);
837     setOperationAction(ISD::FSINCOS, VT, Expand);
838     setOperationAction(ISD::FCOS, VT, Expand);
839     setOperationAction(ISD::FSINCOS, VT, Expand);
840     setOperationAction(ISD::FREM, VT, Expand);
841     setOperationAction(ISD::FMA,  VT, Expand);
842     setOperationAction(ISD::FPOWI, VT, Expand);
843     setOperationAction(ISD::FSQRT, VT, Expand);
844     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
845     setOperationAction(ISD::FFLOOR, VT, Expand);
846     setOperationAction(ISD::FCEIL, VT, Expand);
847     setOperationAction(ISD::FTRUNC, VT, Expand);
848     setOperationAction(ISD::FRINT, VT, Expand);
849     setOperationAction(ISD::FNEARBYINT, VT, Expand);
850     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
851     setOperationAction(ISD::MULHS, VT, Expand);
852     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
853     setOperationAction(ISD::MULHU, VT, Expand);
854     setOperationAction(ISD::SDIVREM, VT, Expand);
855     setOperationAction(ISD::UDIVREM, VT, Expand);
856     setOperationAction(ISD::FPOW, VT, Expand);
857     setOperationAction(ISD::CTPOP, VT, Expand);
858     setOperationAction(ISD::CTTZ, VT, Expand);
859     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
860     setOperationAction(ISD::CTLZ, VT, Expand);
861     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
862     setOperationAction(ISD::SHL, VT, Expand);
863     setOperationAction(ISD::SRA, VT, Expand);
864     setOperationAction(ISD::SRL, VT, Expand);
865     setOperationAction(ISD::ROTL, VT, Expand);
866     setOperationAction(ISD::ROTR, VT, Expand);
867     setOperationAction(ISD::BSWAP, VT, Expand);
868     setOperationAction(ISD::SETCC, VT, Expand);
869     setOperationAction(ISD::FLOG, VT, Expand);
870     setOperationAction(ISD::FLOG2, VT, Expand);
871     setOperationAction(ISD::FLOG10, VT, Expand);
872     setOperationAction(ISD::FEXP, VT, Expand);
873     setOperationAction(ISD::FEXP2, VT, Expand);
874     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
875     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
876     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
877     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
879     setOperationAction(ISD::TRUNCATE, VT, Expand);
880     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
881     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
882     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
883     setOperationAction(ISD::VSELECT, VT, Expand);
884     setOperationAction(ISD::SELECT_CC, VT, Expand);
885     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
886              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
887       setTruncStoreAction(VT,
888                           (MVT::SimpleValueType)InnerVT, Expand);
889     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
890     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
891
892     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
893     // we have to deal with them whether we ask for Expansion or not. Setting
894     // Expand causes its own optimisation problems though, so leave them legal.
895     if (VT.getVectorElementType() == MVT::i1)
896       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
897   }
898
899   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
900   // with -msoft-float, disable use of MMX as well.
901   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
902     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
903     // No operations on x86mmx supported, everything uses intrinsics.
904   }
905
906   // MMX-sized vectors (other than x86mmx) are expected to be expanded
907   // into smaller operations.
908   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
909   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
910   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
912   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
913   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
914   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
915   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
916   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
917   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
918   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
919   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
920   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
921   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
922   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
923   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
924   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
928   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
929   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
930   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
931   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
933   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
937
938   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
939     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
940
941     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
942     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
946     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
947     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
948     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
949     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
950     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
951     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
952     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
953   }
954
955   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
956     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
957
958     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
959     // registers cannot be used even for integer operations.
960     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
961     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
962     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
963     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
964
965     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
966     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
967     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
968     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
969     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
970     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
971     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
972     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
974     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
975     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
976     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
977     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
978     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
979     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
980     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
981     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
985     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
986     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
987
988     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
989     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
992
993     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
998
999     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1000     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001       MVT VT = (MVT::SimpleValueType)i;
1002       // Do not attempt to custom lower non-power-of-2 vectors
1003       if (!isPowerOf2_32(VT.getVectorNumElements()))
1004         continue;
1005       // Do not attempt to custom lower non-128-bit vectors
1006       if (!VT.is128BitVector())
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1011     }
1012
1013     // We support custom legalizing of sext and anyext loads for specific
1014     // memory vector types which we can load as a scalar (or sequence of
1015     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1016     // loads these must work with a single scalar load.
1017     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1018     if (Subtarget->is64Bit()) {
1019       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021     }
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1028
1029     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1031     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1033     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1034     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1035
1036     if (Subtarget->is64Bit()) {
1037       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1038       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1039     }
1040
1041     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1042     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1043       MVT VT = (MVT::SimpleValueType)i;
1044
1045       // Do not attempt to promote non-128-bit vectors
1046       if (!VT.is128BitVector())
1047         continue;
1048
1049       setOperationAction(ISD::AND,    VT, Promote);
1050       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1051       setOperationAction(ISD::OR,     VT, Promote);
1052       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1053       setOperationAction(ISD::XOR,    VT, Promote);
1054       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1055       setOperationAction(ISD::LOAD,   VT, Promote);
1056       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1057       setOperationAction(ISD::SELECT, VT, Promote);
1058       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1059     }
1060
1061     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1062
1063     // Custom lower v2i64 and v2f64 selects.
1064     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1065     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1066     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1067     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1068
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1070     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1071
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1074     // As there is no 64-bit GPR available, we need build a special custom
1075     // sequence to convert from v2i32 to v2f32.
1076     if (!Subtarget->is64Bit())
1077       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1078
1079     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1080     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1081
1082     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1083
1084     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1087   }
1088
1089   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1090     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1091     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1092     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1093     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1094     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1095     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1096     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1097     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1098     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1099     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1100
1101     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1102     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1103     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1104     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1105     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1106     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1107     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1108     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1109     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1110     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1111
1112     // FIXME: Do we need to handle scalar-to-vector here?
1113     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1114
1115     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1120     // There is no BLENDI for byte vectors. We don't need to custom lower
1121     // some vselects for now.
1122     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1123
1124     // SSE41 brings specific instructions for doing vector sign extend even in
1125     // cases where we don't have SRA.
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1129
1130     // i8 and i16 vectors are custom because the source register and source
1131     // source memory operand types are not the same width.  f32 vectors are
1132     // custom since the immediate controlling the insert encodes additional
1133     // information.
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1138
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1143
1144     // FIXME: these should be Legal, but that's only for the case where
1145     // the index is constant.  For now custom expand to deal with that.
1146     if (Subtarget->is64Bit()) {
1147       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1148       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1149     }
1150   }
1151
1152   if (Subtarget->hasSSE2()) {
1153     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1154     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1155
1156     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1157     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1158
1159     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1160     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1161
1162     // In the customized shift lowering, the legal cases in AVX2 will be
1163     // recognized.
1164     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1165     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1166
1167     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1168     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1169
1170     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1171   }
1172
1173   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1174     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1175     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1180
1181     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1184
1185     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1190     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1191     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1192     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1193     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1196     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1197
1198     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1203     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1204     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1205     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1206     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1209     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1210
1211     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1212     // even though v8i16 is a legal type.
1213     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1216
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1219     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1220
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1223
1224     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1225
1226     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1227     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1228
1229     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1230     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1231
1232     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1233     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1234
1235     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1239
1240     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1243
1244     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1248
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1261
1262     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1263       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1269     }
1270
1271     if (Subtarget->hasInt256()) {
1272       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1276
1277       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1281
1282       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1283       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1284       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1285       // Don't lower v32i8 because there is no 128-bit byte mul
1286
1287       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1290       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1291
1292       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1293       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1294     } else {
1295       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1299
1300       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1304
1305       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1308       // Don't lower v32i8 because there is no 128-bit byte mul
1309     }
1310
1311     // In the customized shift lowering, the legal cases in AVX2 will be
1312     // recognized.
1313     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1314     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1315
1316     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1317     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1318
1319     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1320
1321     // Custom lower several nodes for 256-bit types.
1322     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1323              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1324       MVT VT = (MVT::SimpleValueType)i;
1325
1326       // Extract subvector is special because the value type
1327       // (result) is 128-bit but the source is 256-bit wide.
1328       if (VT.is128BitVector())
1329         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1330
1331       // Do not attempt to custom lower other non-256-bit vectors
1332       if (!VT.is256BitVector())
1333         continue;
1334
1335       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1336       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1337       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1338       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1339       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1340       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1341       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1342     }
1343
1344     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1345     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1346       MVT VT = (MVT::SimpleValueType)i;
1347
1348       // Do not attempt to promote non-256-bit vectors
1349       if (!VT.is256BitVector())
1350         continue;
1351
1352       setOperationAction(ISD::AND,    VT, Promote);
1353       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1354       setOperationAction(ISD::OR,     VT, Promote);
1355       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1356       setOperationAction(ISD::XOR,    VT, Promote);
1357       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1358       setOperationAction(ISD::LOAD,   VT, Promote);
1359       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1360       setOperationAction(ISD::SELECT, VT, Promote);
1361       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1362     }
1363   }
1364
1365   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1366     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1370
1371     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1372     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1373     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1374
1375     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1376     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1377     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1378     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1379     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1380     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1386
1387     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1392     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1393
1394     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1399     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1400     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1401     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1402
1403     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1406     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1407     if (Subtarget->is64Bit()) {
1408       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1411       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1412     }
1413     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1417     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1421     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1422     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1423
1424     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1437
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1444
1445     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1446     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1447
1448     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1449
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1459
1460     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1461     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1469     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1470
1471     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1479     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1483
1484     if (Subtarget->hasCDI()) {
1485       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1486       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1487     }
1488
1489     // Custom lower several nodes.
1490     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1491              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1492       MVT VT = (MVT::SimpleValueType)i;
1493
1494       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1495       // Extract subvector is special because the value type
1496       // (result) is 256/128-bit but the source is 512-bit wide.
1497       if (VT.is128BitVector() || VT.is256BitVector())
1498         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1499
1500       if (VT.getVectorElementType() == MVT::i1)
1501         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1502
1503       // Do not attempt to custom lower other non-512-bit vectors
1504       if (!VT.is512BitVector())
1505         continue;
1506
1507       if ( EltSize >= 32) {
1508         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1509         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1510         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1511         setOperationAction(ISD::VSELECT,             VT, Legal);
1512         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1513         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1514         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1515       }
1516     }
1517     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1518       MVT VT = (MVT::SimpleValueType)i;
1519
1520       // Do not attempt to promote non-256-bit vectors
1521       if (!VT.is512BitVector())
1522         continue;
1523
1524       setOperationAction(ISD::SELECT, VT, Promote);
1525       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1526     }
1527   }// has  AVX-512
1528
1529   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1530     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1531     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1532   }
1533
1534   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1535   // of this type with custom code.
1536   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1537            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1538     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1539                        Custom);
1540   }
1541
1542   // We want to custom lower some of our intrinsics.
1543   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1544   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1546   if (!Subtarget->is64Bit())
1547     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1548
1549   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1550   // handle type legalization for these operations here.
1551   //
1552   // FIXME: We really should do custom legalization for addition and
1553   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1554   // than generic legalization for 64-bit multiplication-with-overflow, though.
1555   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1556     // Add/Sub/Mul with overflow operations are custom lowered.
1557     MVT VT = IntVTs[i];
1558     setOperationAction(ISD::SADDO, VT, Custom);
1559     setOperationAction(ISD::UADDO, VT, Custom);
1560     setOperationAction(ISD::SSUBO, VT, Custom);
1561     setOperationAction(ISD::USUBO, VT, Custom);
1562     setOperationAction(ISD::SMULO, VT, Custom);
1563     setOperationAction(ISD::UMULO, VT, Custom);
1564   }
1565
1566   // There are no 8-bit 3-address imul/mul instructions
1567   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1568   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1569
1570   if (!Subtarget->is64Bit()) {
1571     // These libcalls are not available in 32-bit.
1572     setLibcallName(RTLIB::SHL_I128, nullptr);
1573     setLibcallName(RTLIB::SRL_I128, nullptr);
1574     setLibcallName(RTLIB::SRA_I128, nullptr);
1575   }
1576
1577   // Combine sin / cos into one node or libcall if possible.
1578   if (Subtarget->hasSinCos()) {
1579     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1580     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1581     if (Subtarget->isTargetDarwin()) {
1582       // For MacOSX, we don't want to the normal expansion of a libcall to
1583       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1584       // traffic.
1585       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1586       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1587     }
1588   }
1589
1590   if (Subtarget->isTargetWin64()) {
1591     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1592     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::SREM, MVT::i128, Custom);
1594     setOperationAction(ISD::UREM, MVT::i128, Custom);
1595     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1596     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1597   }
1598
1599   // We have target-specific dag combine patterns for the following nodes:
1600   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1601   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1602   setTargetDAGCombine(ISD::VSELECT);
1603   setTargetDAGCombine(ISD::SELECT);
1604   setTargetDAGCombine(ISD::SHL);
1605   setTargetDAGCombine(ISD::SRA);
1606   setTargetDAGCombine(ISD::SRL);
1607   setTargetDAGCombine(ISD::OR);
1608   setTargetDAGCombine(ISD::AND);
1609   setTargetDAGCombine(ISD::ADD);
1610   setTargetDAGCombine(ISD::FADD);
1611   setTargetDAGCombine(ISD::FSUB);
1612   setTargetDAGCombine(ISD::FMA);
1613   setTargetDAGCombine(ISD::SUB);
1614   setTargetDAGCombine(ISD::LOAD);
1615   setTargetDAGCombine(ISD::STORE);
1616   setTargetDAGCombine(ISD::ZERO_EXTEND);
1617   setTargetDAGCombine(ISD::ANY_EXTEND);
1618   setTargetDAGCombine(ISD::SIGN_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1620   setTargetDAGCombine(ISD::TRUNCATE);
1621   setTargetDAGCombine(ISD::SINT_TO_FP);
1622   setTargetDAGCombine(ISD::SETCC);
1623   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1624   setTargetDAGCombine(ISD::BUILD_VECTOR);
1625   if (Subtarget->is64Bit())
1626     setTargetDAGCombine(ISD::MUL);
1627   setTargetDAGCombine(ISD::XOR);
1628
1629   computeRegisterProperties();
1630
1631   // On Darwin, -Os means optimize for size without hurting performance,
1632   // do not reduce the limit.
1633   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1634   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1635   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1636   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1637   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1638   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1639   setPrefLoopAlignment(4); // 2^4 bytes.
1640
1641   // Predictable cmov don't hurt on atom because it's in-order.
1642   PredictableSelectIsExpensive = !Subtarget->isAtom();
1643
1644   setPrefFunctionAlignment(4); // 2^4 bytes.
1645 }
1646
1647 // This has so far only been implemented for 64-bit MachO.
1648 bool X86TargetLowering::useLoadStackGuardNode() const {
1649   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1650          Subtarget->is64Bit();
1651 }
1652
1653 TargetLoweringBase::LegalizeTypeAction
1654 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1655   if (ExperimentalVectorWideningLegalization &&
1656       VT.getVectorNumElements() != 1 &&
1657       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1658     return TypeWidenVector;
1659
1660   return TargetLoweringBase::getPreferredVectorAction(VT);
1661 }
1662
1663 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1664   if (!VT.isVector())
1665     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1666
1667   if (Subtarget->hasAVX512())
1668     switch(VT.getVectorNumElements()) {
1669     case  8: return MVT::v8i1;
1670     case 16: return MVT::v16i1;
1671   }
1672
1673   return VT.changeVectorElementTypeToInteger();
1674 }
1675
1676 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1677 /// the desired ByVal argument alignment.
1678 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1679   if (MaxAlign == 16)
1680     return;
1681   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1682     if (VTy->getBitWidth() == 128)
1683       MaxAlign = 16;
1684   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1685     unsigned EltAlign = 0;
1686     getMaxByValAlign(ATy->getElementType(), EltAlign);
1687     if (EltAlign > MaxAlign)
1688       MaxAlign = EltAlign;
1689   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1690     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1691       unsigned EltAlign = 0;
1692       getMaxByValAlign(STy->getElementType(i), EltAlign);
1693       if (EltAlign > MaxAlign)
1694         MaxAlign = EltAlign;
1695       if (MaxAlign == 16)
1696         break;
1697     }
1698   }
1699 }
1700
1701 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1702 /// function arguments in the caller parameter area. For X86, aggregates
1703 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1704 /// are at 4-byte boundaries.
1705 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1706   if (Subtarget->is64Bit()) {
1707     // Max of 8 and alignment of type.
1708     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1709     if (TyAlign > 8)
1710       return TyAlign;
1711     return 8;
1712   }
1713
1714   unsigned Align = 4;
1715   if (Subtarget->hasSSE1())
1716     getMaxByValAlign(Ty, Align);
1717   return Align;
1718 }
1719
1720 /// getOptimalMemOpType - Returns the target specific optimal type for load
1721 /// and store operations as a result of memset, memcpy, and memmove
1722 /// lowering. If DstAlign is zero that means it's safe to destination
1723 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1724 /// means there isn't a need to check it against alignment requirement,
1725 /// probably because the source does not need to be loaded. If 'IsMemset' is
1726 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1727 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1728 /// source is constant so it does not need to be loaded.
1729 /// It returns EVT::Other if the type should be determined using generic
1730 /// target-independent logic.
1731 EVT
1732 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1733                                        unsigned DstAlign, unsigned SrcAlign,
1734                                        bool IsMemset, bool ZeroMemset,
1735                                        bool MemcpyStrSrc,
1736                                        MachineFunction &MF) const {
1737   const Function *F = MF.getFunction();
1738   if ((!IsMemset || ZeroMemset) &&
1739       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1740                                        Attribute::NoImplicitFloat)) {
1741     if (Size >= 16 &&
1742         (Subtarget->isUnalignedMemAccessFast() ||
1743          ((DstAlign == 0 || DstAlign >= 16) &&
1744           (SrcAlign == 0 || SrcAlign >= 16)))) {
1745       if (Size >= 32) {
1746         if (Subtarget->hasInt256())
1747           return MVT::v8i32;
1748         if (Subtarget->hasFp256())
1749           return MVT::v8f32;
1750       }
1751       if (Subtarget->hasSSE2())
1752         return MVT::v4i32;
1753       if (Subtarget->hasSSE1())
1754         return MVT::v4f32;
1755     } else if (!MemcpyStrSrc && Size >= 8 &&
1756                !Subtarget->is64Bit() &&
1757                Subtarget->hasSSE2()) {
1758       // Do not use f64 to lower memcpy if source is string constant. It's
1759       // better to use i32 to avoid the loads.
1760       return MVT::f64;
1761     }
1762   }
1763   if (Subtarget->is64Bit() && Size >= 8)
1764     return MVT::i64;
1765   return MVT::i32;
1766 }
1767
1768 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1769   if (VT == MVT::f32)
1770     return X86ScalarSSEf32;
1771   else if (VT == MVT::f64)
1772     return X86ScalarSSEf64;
1773   return true;
1774 }
1775
1776 bool
1777 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1778                                                   unsigned,
1779                                                   unsigned,
1780                                                   bool *Fast) const {
1781   if (Fast)
1782     *Fast = Subtarget->isUnalignedMemAccessFast();
1783   return true;
1784 }
1785
1786 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1787 /// current function.  The returned value is a member of the
1788 /// MachineJumpTableInfo::JTEntryKind enum.
1789 unsigned X86TargetLowering::getJumpTableEncoding() const {
1790   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1791   // symbol.
1792   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1793       Subtarget->isPICStyleGOT())
1794     return MachineJumpTableInfo::EK_Custom32;
1795
1796   // Otherwise, use the normal jump table encoding heuristics.
1797   return TargetLowering::getJumpTableEncoding();
1798 }
1799
1800 const MCExpr *
1801 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1802                                              const MachineBasicBlock *MBB,
1803                                              unsigned uid,MCContext &Ctx) const{
1804   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1805          Subtarget->isPICStyleGOT());
1806   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1807   // entries.
1808   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1809                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1810 }
1811
1812 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1813 /// jumptable.
1814 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1815                                                     SelectionDAG &DAG) const {
1816   if (!Subtarget->is64Bit())
1817     // This doesn't have SDLoc associated with it, but is not really the
1818     // same as a Register.
1819     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1820   return Table;
1821 }
1822
1823 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1824 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1825 /// MCExpr.
1826 const MCExpr *X86TargetLowering::
1827 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1828                              MCContext &Ctx) const {
1829   // X86-64 uses RIP relative addressing based on the jump table label.
1830   if (Subtarget->isPICStyleRIPRel())
1831     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1832
1833   // Otherwise, the reference is relative to the PIC base.
1834   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1835 }
1836
1837 // FIXME: Why this routine is here? Move to RegInfo!
1838 std::pair<const TargetRegisterClass*, uint8_t>
1839 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1840   const TargetRegisterClass *RRC = nullptr;
1841   uint8_t Cost = 1;
1842   switch (VT.SimpleTy) {
1843   default:
1844     return TargetLowering::findRepresentativeClass(VT);
1845   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1846     RRC = Subtarget->is64Bit() ?
1847       (const TargetRegisterClass*)&X86::GR64RegClass :
1848       (const TargetRegisterClass*)&X86::GR32RegClass;
1849     break;
1850   case MVT::x86mmx:
1851     RRC = &X86::VR64RegClass;
1852     break;
1853   case MVT::f32: case MVT::f64:
1854   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1855   case MVT::v4f32: case MVT::v2f64:
1856   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1857   case MVT::v4f64:
1858     RRC = &X86::VR128RegClass;
1859     break;
1860   }
1861   return std::make_pair(RRC, Cost);
1862 }
1863
1864 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1865                                                unsigned &Offset) const {
1866   if (!Subtarget->isTargetLinux())
1867     return false;
1868
1869   if (Subtarget->is64Bit()) {
1870     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1871     Offset = 0x28;
1872     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1873       AddressSpace = 256;
1874     else
1875       AddressSpace = 257;
1876   } else {
1877     // %gs:0x14 on i386
1878     Offset = 0x14;
1879     AddressSpace = 256;
1880   }
1881   return true;
1882 }
1883
1884 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1885                                             unsigned DestAS) const {
1886   assert(SrcAS != DestAS && "Expected different address spaces!");
1887
1888   return SrcAS < 256 && DestAS < 256;
1889 }
1890
1891 //===----------------------------------------------------------------------===//
1892 //               Return Value Calling Convention Implementation
1893 //===----------------------------------------------------------------------===//
1894
1895 #include "X86GenCallingConv.inc"
1896
1897 bool
1898 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1899                                   MachineFunction &MF, bool isVarArg,
1900                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1901                         LLVMContext &Context) const {
1902   SmallVector<CCValAssign, 16> RVLocs;
1903   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1904   return CCInfo.CheckReturn(Outs, RetCC_X86);
1905 }
1906
1907 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1908   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1909   return ScratchRegs;
1910 }
1911
1912 SDValue
1913 X86TargetLowering::LowerReturn(SDValue Chain,
1914                                CallingConv::ID CallConv, bool isVarArg,
1915                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1916                                const SmallVectorImpl<SDValue> &OutVals,
1917                                SDLoc dl, SelectionDAG &DAG) const {
1918   MachineFunction &MF = DAG.getMachineFunction();
1919   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1920
1921   SmallVector<CCValAssign, 16> RVLocs;
1922   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1923   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1924
1925   SDValue Flag;
1926   SmallVector<SDValue, 6> RetOps;
1927   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1928   // Operand #1 = Bytes To Pop
1929   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1930                    MVT::i16));
1931
1932   // Copy the result values into the output registers.
1933   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1934     CCValAssign &VA = RVLocs[i];
1935     assert(VA.isRegLoc() && "Can only return in registers!");
1936     SDValue ValToCopy = OutVals[i];
1937     EVT ValVT = ValToCopy.getValueType();
1938
1939     // Promote values to the appropriate types
1940     if (VA.getLocInfo() == CCValAssign::SExt)
1941       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1942     else if (VA.getLocInfo() == CCValAssign::ZExt)
1943       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1944     else if (VA.getLocInfo() == CCValAssign::AExt)
1945       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1946     else if (VA.getLocInfo() == CCValAssign::BCvt)
1947       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1948
1949     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1950            "Unexpected FP-extend for return value.");  
1951
1952     // If this is x86-64, and we disabled SSE, we can't return FP values,
1953     // or SSE or MMX vectors.
1954     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1955          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1956           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1957       report_fatal_error("SSE register return with SSE disabled");
1958     }
1959     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1960     // llvm-gcc has never done it right and no one has noticed, so this
1961     // should be OK for now.
1962     if (ValVT == MVT::f64 &&
1963         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1964       report_fatal_error("SSE2 register return with SSE2 disabled");
1965
1966     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1967     // the RET instruction and handled by the FP Stackifier.
1968     if (VA.getLocReg() == X86::FP0 ||
1969         VA.getLocReg() == X86::FP1) {
1970       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1971       // change the value to the FP stack register class.
1972       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1973         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1974       RetOps.push_back(ValToCopy);
1975       // Don't emit a copytoreg.
1976       continue;
1977     }
1978
1979     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1980     // which is returned in RAX / RDX.
1981     if (Subtarget->is64Bit()) {
1982       if (ValVT == MVT::x86mmx) {
1983         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1984           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1985           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1986                                   ValToCopy);
1987           // If we don't have SSE2 available, convert to v4f32 so the generated
1988           // register is legal.
1989           if (!Subtarget->hasSSE2())
1990             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1991         }
1992       }
1993     }
1994
1995     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1996     Flag = Chain.getValue(1);
1997     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1998   }
1999
2000   // The x86-64 ABIs require that for returning structs by value we copy
2001   // the sret argument into %rax/%eax (depending on ABI) for the return.
2002   // Win32 requires us to put the sret argument to %eax as well.
2003   // We saved the argument into a virtual register in the entry block,
2004   // so now we copy the value out and into %rax/%eax.
2005   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2006       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2007     MachineFunction &MF = DAG.getMachineFunction();
2008     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2009     unsigned Reg = FuncInfo->getSRetReturnReg();
2010     assert(Reg &&
2011            "SRetReturnReg should have been set in LowerFormalArguments().");
2012     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2013
2014     unsigned RetValReg
2015         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2016           X86::RAX : X86::EAX;
2017     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2018     Flag = Chain.getValue(1);
2019
2020     // RAX/EAX now acts like a return value.
2021     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2022   }
2023
2024   RetOps[0] = Chain;  // Update chain.
2025
2026   // Add the flag if we have it.
2027   if (Flag.getNode())
2028     RetOps.push_back(Flag);
2029
2030   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2031 }
2032
2033 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2034   if (N->getNumValues() != 1)
2035     return false;
2036   if (!N->hasNUsesOfValue(1, 0))
2037     return false;
2038
2039   SDValue TCChain = Chain;
2040   SDNode *Copy = *N->use_begin();
2041   if (Copy->getOpcode() == ISD::CopyToReg) {
2042     // If the copy has a glue operand, we conservatively assume it isn't safe to
2043     // perform a tail call.
2044     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2045       return false;
2046     TCChain = Copy->getOperand(0);
2047   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2048     return false;
2049
2050   bool HasRet = false;
2051   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2052        UI != UE; ++UI) {
2053     if (UI->getOpcode() != X86ISD::RET_FLAG)
2054       return false;
2055     // If we are returning more than one value, we can definitely
2056     // not make a tail call see PR19530
2057     if (UI->getNumOperands() > 4)
2058       return false;
2059     if (UI->getNumOperands() == 4 &&
2060         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2061       return false;
2062     HasRet = true;
2063   }
2064
2065   if (!HasRet)
2066     return false;
2067
2068   Chain = TCChain;
2069   return true;
2070 }
2071
2072 EVT
2073 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2074                                             ISD::NodeType ExtendKind) const {
2075   MVT ReturnMVT;
2076   // TODO: Is this also valid on 32-bit?
2077   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2078     ReturnMVT = MVT::i8;
2079   else
2080     ReturnMVT = MVT::i32;
2081
2082   EVT MinVT = getRegisterType(Context, ReturnMVT);
2083   return VT.bitsLT(MinVT) ? MinVT : VT;
2084 }
2085
2086 /// LowerCallResult - Lower the result values of a call into the
2087 /// appropriate copies out of appropriate physical registers.
2088 ///
2089 SDValue
2090 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2091                                    CallingConv::ID CallConv, bool isVarArg,
2092                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2093                                    SDLoc dl, SelectionDAG &DAG,
2094                                    SmallVectorImpl<SDValue> &InVals) const {
2095
2096   // Assign locations to each value returned by this call.
2097   SmallVector<CCValAssign, 16> RVLocs;
2098   bool Is64Bit = Subtarget->is64Bit();
2099   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2100                  *DAG.getContext());
2101   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2102
2103   // Copy all of the result registers out of their specified physreg.
2104   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2105     CCValAssign &VA = RVLocs[i];
2106     EVT CopyVT = VA.getValVT();
2107
2108     // If this is x86-64, and we disabled SSE, we can't return FP values
2109     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2110         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2111       report_fatal_error("SSE register return with SSE disabled");
2112     }
2113
2114     // If we prefer to use the value in xmm registers, copy it out as f80 and
2115     // use a truncate to move it from fp stack reg to xmm reg.
2116     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2117         isScalarFPTypeInSSEReg(VA.getValVT()))
2118       CopyVT = MVT::f80;
2119
2120     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2121                                CopyVT, InFlag).getValue(1);
2122     SDValue Val = Chain.getValue(0);
2123
2124     if (CopyVT != VA.getValVT())
2125       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2126                         // This truncation won't change the value.
2127                         DAG.getIntPtrConstant(1));
2128
2129     InFlag = Chain.getValue(2);
2130     InVals.push_back(Val);
2131   }
2132
2133   return Chain;
2134 }
2135
2136 //===----------------------------------------------------------------------===//
2137 //                C & StdCall & Fast Calling Convention implementation
2138 //===----------------------------------------------------------------------===//
2139 //  StdCall calling convention seems to be standard for many Windows' API
2140 //  routines and around. It differs from C calling convention just a little:
2141 //  callee should clean up the stack, not caller. Symbols should be also
2142 //  decorated in some fancy way :) It doesn't support any vector arguments.
2143 //  For info on fast calling convention see Fast Calling Convention (tail call)
2144 //  implementation LowerX86_32FastCCCallTo.
2145
2146 /// CallIsStructReturn - Determines whether a call uses struct return
2147 /// semantics.
2148 enum StructReturnType {
2149   NotStructReturn,
2150   RegStructReturn,
2151   StackStructReturn
2152 };
2153 static StructReturnType
2154 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2155   if (Outs.empty())
2156     return NotStructReturn;
2157
2158   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2159   if (!Flags.isSRet())
2160     return NotStructReturn;
2161   if (Flags.isInReg())
2162     return RegStructReturn;
2163   return StackStructReturn;
2164 }
2165
2166 /// ArgsAreStructReturn - Determines whether a function uses struct
2167 /// return semantics.
2168 static StructReturnType
2169 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2170   if (Ins.empty())
2171     return NotStructReturn;
2172
2173   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2174   if (!Flags.isSRet())
2175     return NotStructReturn;
2176   if (Flags.isInReg())
2177     return RegStructReturn;
2178   return StackStructReturn;
2179 }
2180
2181 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2182 /// by "Src" to address "Dst" with size and alignment information specified by
2183 /// the specific parameter attribute. The copy will be passed as a byval
2184 /// function parameter.
2185 static SDValue
2186 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2187                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2188                           SDLoc dl) {
2189   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2190
2191   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2192                        /*isVolatile*/false, /*AlwaysInline=*/true,
2193                        MachinePointerInfo(), MachinePointerInfo());
2194 }
2195
2196 /// IsTailCallConvention - Return true if the calling convention is one that
2197 /// supports tail call optimization.
2198 static bool IsTailCallConvention(CallingConv::ID CC) {
2199   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2200           CC == CallingConv::HiPE);
2201 }
2202
2203 /// \brief Return true if the calling convention is a C calling convention.
2204 static bool IsCCallConvention(CallingConv::ID CC) {
2205   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2206           CC == CallingConv::X86_64_SysV);
2207 }
2208
2209 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2210   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2211     return false;
2212
2213   CallSite CS(CI);
2214   CallingConv::ID CalleeCC = CS.getCallingConv();
2215   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2216     return false;
2217
2218   return true;
2219 }
2220
2221 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2222 /// a tailcall target by changing its ABI.
2223 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2224                                    bool GuaranteedTailCallOpt) {
2225   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2226 }
2227
2228 SDValue
2229 X86TargetLowering::LowerMemArgument(SDValue Chain,
2230                                     CallingConv::ID CallConv,
2231                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2232                                     SDLoc dl, SelectionDAG &DAG,
2233                                     const CCValAssign &VA,
2234                                     MachineFrameInfo *MFI,
2235                                     unsigned i) const {
2236   // Create the nodes corresponding to a load from this parameter slot.
2237   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2238   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2239       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2240   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2241   EVT ValVT;
2242
2243   // If value is passed by pointer we have address passed instead of the value
2244   // itself.
2245   if (VA.getLocInfo() == CCValAssign::Indirect)
2246     ValVT = VA.getLocVT();
2247   else
2248     ValVT = VA.getValVT();
2249
2250   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2251   // changed with more analysis.
2252   // In case of tail call optimization mark all arguments mutable. Since they
2253   // could be overwritten by lowering of arguments in case of a tail call.
2254   if (Flags.isByVal()) {
2255     unsigned Bytes = Flags.getByValSize();
2256     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2257     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2258     return DAG.getFrameIndex(FI, getPointerTy());
2259   } else {
2260     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2261                                     VA.getLocMemOffset(), isImmutable);
2262     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2263     return DAG.getLoad(ValVT, dl, Chain, FIN,
2264                        MachinePointerInfo::getFixedStack(FI),
2265                        false, false, false, 0);
2266   }
2267 }
2268
2269 SDValue
2270 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2271                                         CallingConv::ID CallConv,
2272                                         bool isVarArg,
2273                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2274                                         SDLoc dl,
2275                                         SelectionDAG &DAG,
2276                                         SmallVectorImpl<SDValue> &InVals)
2277                                           const {
2278   MachineFunction &MF = DAG.getMachineFunction();
2279   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2280
2281   const Function* Fn = MF.getFunction();
2282   if (Fn->hasExternalLinkage() &&
2283       Subtarget->isTargetCygMing() &&
2284       Fn->getName() == "main")
2285     FuncInfo->setForceFramePointer(true);
2286
2287   MachineFrameInfo *MFI = MF.getFrameInfo();
2288   bool Is64Bit = Subtarget->is64Bit();
2289   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2290
2291   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2292          "Var args not supported with calling convention fastcc, ghc or hipe");
2293
2294   // Assign locations to all of the incoming arguments.
2295   SmallVector<CCValAssign, 16> ArgLocs;
2296   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2297
2298   // Allocate shadow area for Win64
2299   if (IsWin64)
2300     CCInfo.AllocateStack(32, 8);
2301
2302   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2303   CCInfo.AlignStack(Is64Bit ? 8 : 4);
2304
2305   unsigned LastVal = ~0U;
2306   SDValue ArgValue;
2307   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2308     CCValAssign &VA = ArgLocs[i];
2309     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2310     // places.
2311     assert(VA.getValNo() != LastVal &&
2312            "Don't support value assigned to multiple locs yet");
2313     (void)LastVal;
2314     LastVal = VA.getValNo();
2315
2316     if (VA.isRegLoc()) {
2317       EVT RegVT = VA.getLocVT();
2318       const TargetRegisterClass *RC;
2319       if (RegVT == MVT::i32)
2320         RC = &X86::GR32RegClass;
2321       else if (Is64Bit && RegVT == MVT::i64)
2322         RC = &X86::GR64RegClass;
2323       else if (RegVT == MVT::f32)
2324         RC = &X86::FR32RegClass;
2325       else if (RegVT == MVT::f64)
2326         RC = &X86::FR64RegClass;
2327       else if (RegVT.is512BitVector())
2328         RC = &X86::VR512RegClass;
2329       else if (RegVT.is256BitVector())
2330         RC = &X86::VR256RegClass;
2331       else if (RegVT.is128BitVector())
2332         RC = &X86::VR128RegClass;
2333       else if (RegVT == MVT::x86mmx)
2334         RC = &X86::VR64RegClass;
2335       else if (RegVT == MVT::i1)
2336         RC = &X86::VK1RegClass;
2337       else if (RegVT == MVT::v8i1)
2338         RC = &X86::VK8RegClass;
2339       else if (RegVT == MVT::v16i1)
2340         RC = &X86::VK16RegClass;
2341       else if (RegVT == MVT::v32i1)
2342         RC = &X86::VK32RegClass;
2343       else if (RegVT == MVT::v64i1)
2344         RC = &X86::VK64RegClass;
2345       else
2346         llvm_unreachable("Unknown argument type!");
2347
2348       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2349       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2350
2351       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2352       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2353       // right size.
2354       if (VA.getLocInfo() == CCValAssign::SExt)
2355         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2356                                DAG.getValueType(VA.getValVT()));
2357       else if (VA.getLocInfo() == CCValAssign::ZExt)
2358         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2359                                DAG.getValueType(VA.getValVT()));
2360       else if (VA.getLocInfo() == CCValAssign::BCvt)
2361         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2362
2363       if (VA.isExtInLoc()) {
2364         // Handle MMX values passed in XMM regs.
2365         if (RegVT.isVector())
2366           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2367         else
2368           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2369       }
2370     } else {
2371       assert(VA.isMemLoc());
2372       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2373     }
2374
2375     // If value is passed via pointer - do a load.
2376     if (VA.getLocInfo() == CCValAssign::Indirect)
2377       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2378                              MachinePointerInfo(), false, false, false, 0);
2379
2380     InVals.push_back(ArgValue);
2381   }
2382
2383   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2384     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2385       // The x86-64 ABIs require that for returning structs by value we copy
2386       // the sret argument into %rax/%eax (depending on ABI) for the return.
2387       // Win32 requires us to put the sret argument to %eax as well.
2388       // Save the argument into a virtual register so that we can access it
2389       // from the return points.
2390       if (Ins[i].Flags.isSRet()) {
2391         unsigned Reg = FuncInfo->getSRetReturnReg();
2392         if (!Reg) {
2393           MVT PtrTy = getPointerTy();
2394           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2395           FuncInfo->setSRetReturnReg(Reg);
2396         }
2397         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2398         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2399         break;
2400       }
2401     }
2402   }
2403
2404   unsigned StackSize = CCInfo.getNextStackOffset();
2405   // Align stack specially for tail calls.
2406   if (FuncIsMadeTailCallSafe(CallConv,
2407                              MF.getTarget().Options.GuaranteedTailCallOpt))
2408     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2409
2410   // If the function takes variable number of arguments, make a frame index for
2411   // the start of the first vararg value... for expansion of llvm.va_start.
2412   if (isVarArg) {
2413     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2414                     CallConv != CallingConv::X86_ThisCall)) {
2415       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2416     }
2417     if (Is64Bit) {
2418       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2419
2420       // FIXME: We should really autogenerate these arrays
2421       static const MCPhysReg GPR64ArgRegsWin64[] = {
2422         X86::RCX, X86::RDX, X86::R8,  X86::R9
2423       };
2424       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2425         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2426       };
2427       static const MCPhysReg XMMArgRegs64Bit[] = {
2428         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2429         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2430       };
2431       const MCPhysReg *GPR64ArgRegs;
2432       unsigned NumXMMRegs = 0;
2433
2434       if (IsWin64) {
2435         // The XMM registers which might contain var arg parameters are shadowed
2436         // in their paired GPR.  So we only need to save the GPR to their home
2437         // slots.
2438         TotalNumIntRegs = 4;
2439         GPR64ArgRegs = GPR64ArgRegsWin64;
2440       } else {
2441         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2442         GPR64ArgRegs = GPR64ArgRegs64Bit;
2443
2444         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2445                                                 TotalNumXMMRegs);
2446       }
2447       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2448                                                        TotalNumIntRegs);
2449
2450       bool NoImplicitFloatOps = Fn->getAttributes().
2451         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2452       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2453              "SSE register cannot be used when SSE is disabled!");
2454       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2455                NoImplicitFloatOps) &&
2456              "SSE register cannot be used when SSE is disabled!");
2457       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2458           !Subtarget->hasSSE1())
2459         // Kernel mode asks for SSE to be disabled, so don't push them
2460         // on the stack.
2461         TotalNumXMMRegs = 0;
2462
2463       if (IsWin64) {
2464         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2465         // Get to the caller-allocated home save location.  Add 8 to account
2466         // for the return address.
2467         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2468         FuncInfo->setRegSaveFrameIndex(
2469           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2470         // Fixup to set vararg frame on shadow area (4 x i64).
2471         if (NumIntRegs < 4)
2472           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2473       } else {
2474         // For X86-64, if there are vararg parameters that are passed via
2475         // registers, then we must store them to their spots on the stack so
2476         // they may be loaded by deferencing the result of va_next.
2477         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2478         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2479         FuncInfo->setRegSaveFrameIndex(
2480           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2481                                false));
2482       }
2483
2484       // Store the integer parameter registers.
2485       SmallVector<SDValue, 8> MemOps;
2486       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2487                                         getPointerTy());
2488       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2489       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2490         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2491                                   DAG.getIntPtrConstant(Offset));
2492         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2493                                      &X86::GR64RegClass);
2494         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2495         SDValue Store =
2496           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2497                        MachinePointerInfo::getFixedStack(
2498                          FuncInfo->getRegSaveFrameIndex(), Offset),
2499                        false, false, 0);
2500         MemOps.push_back(Store);
2501         Offset += 8;
2502       }
2503
2504       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2505         // Now store the XMM (fp + vector) parameter registers.
2506         SmallVector<SDValue, 12> SaveXMMOps;
2507         SaveXMMOps.push_back(Chain);
2508
2509         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2510         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2511         SaveXMMOps.push_back(ALVal);
2512
2513         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2514                                FuncInfo->getRegSaveFrameIndex()));
2515         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2516                                FuncInfo->getVarArgsFPOffset()));
2517
2518         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2519           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2520                                        &X86::VR128RegClass);
2521           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2522           SaveXMMOps.push_back(Val);
2523         }
2524         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2525                                      MVT::Other, SaveXMMOps));
2526       }
2527
2528       if (!MemOps.empty())
2529         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2530     }
2531   }
2532
2533   // Some CCs need callee pop.
2534   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2535                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2536     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2537   } else {
2538     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2539     // If this is an sret function, the return should pop the hidden pointer.
2540     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2541         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2542         argsAreStructReturn(Ins) == StackStructReturn)
2543       FuncInfo->setBytesToPopOnReturn(4);
2544   }
2545
2546   if (!Is64Bit) {
2547     // RegSaveFrameIndex is X86-64 only.
2548     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2549     if (CallConv == CallingConv::X86_FastCall ||
2550         CallConv == CallingConv::X86_ThisCall)
2551       // fastcc functions can't have varargs.
2552       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2553   }
2554
2555   FuncInfo->setArgumentStackSize(StackSize);
2556
2557   return Chain;
2558 }
2559
2560 SDValue
2561 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2562                                     SDValue StackPtr, SDValue Arg,
2563                                     SDLoc dl, SelectionDAG &DAG,
2564                                     const CCValAssign &VA,
2565                                     ISD::ArgFlagsTy Flags) const {
2566   unsigned LocMemOffset = VA.getLocMemOffset();
2567   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2568   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2569   if (Flags.isByVal())
2570     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2571
2572   return DAG.getStore(Chain, dl, Arg, PtrOff,
2573                       MachinePointerInfo::getStack(LocMemOffset),
2574                       false, false, 0);
2575 }
2576
2577 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2578 /// optimization is performed and it is required.
2579 SDValue
2580 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2581                                            SDValue &OutRetAddr, SDValue Chain,
2582                                            bool IsTailCall, bool Is64Bit,
2583                                            int FPDiff, SDLoc dl) const {
2584   // Adjust the Return address stack slot.
2585   EVT VT = getPointerTy();
2586   OutRetAddr = getReturnAddressFrameIndex(DAG);
2587
2588   // Load the "old" Return address.
2589   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2590                            false, false, false, 0);
2591   return SDValue(OutRetAddr.getNode(), 1);
2592 }
2593
2594 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2595 /// optimization is performed and it is required (FPDiff!=0).
2596 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2597                                         SDValue Chain, SDValue RetAddrFrIdx,
2598                                         EVT PtrVT, unsigned SlotSize,
2599                                         int FPDiff, SDLoc dl) {
2600   // Store the return address to the appropriate stack slot.
2601   if (!FPDiff) return Chain;
2602   // Calculate the new stack slot for the return address.
2603   int NewReturnAddrFI =
2604     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2605                                          false);
2606   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2607   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2608                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2609                        false, false, 0);
2610   return Chain;
2611 }
2612
2613 SDValue
2614 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2615                              SmallVectorImpl<SDValue> &InVals) const {
2616   SelectionDAG &DAG                     = CLI.DAG;
2617   SDLoc &dl                             = CLI.DL;
2618   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2619   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2620   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2621   SDValue Chain                         = CLI.Chain;
2622   SDValue Callee                        = CLI.Callee;
2623   CallingConv::ID CallConv              = CLI.CallConv;
2624   bool &isTailCall                      = CLI.IsTailCall;
2625   bool isVarArg                         = CLI.IsVarArg;
2626
2627   MachineFunction &MF = DAG.getMachineFunction();
2628   bool Is64Bit        = Subtarget->is64Bit();
2629   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2630   StructReturnType SR = callIsStructReturn(Outs);
2631   bool IsSibcall      = false;
2632
2633   if (MF.getTarget().Options.DisableTailCalls)
2634     isTailCall = false;
2635
2636   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2637   if (IsMustTail) {
2638     // Force this to be a tail call.  The verifier rules are enough to ensure
2639     // that we can lower this successfully without moving the return address
2640     // around.
2641     isTailCall = true;
2642   } else if (isTailCall) {
2643     // Check if it's really possible to do a tail call.
2644     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2645                     isVarArg, SR != NotStructReturn,
2646                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2647                     Outs, OutVals, Ins, DAG);
2648
2649     // Sibcalls are automatically detected tailcalls which do not require
2650     // ABI changes.
2651     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2652       IsSibcall = true;
2653
2654     if (isTailCall)
2655       ++NumTailCalls;
2656   }
2657
2658   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2659          "Var args not supported with calling convention fastcc, ghc or hipe");
2660
2661   // Analyze operands of the call, assigning locations to each operand.
2662   SmallVector<CCValAssign, 16> ArgLocs;
2663   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2664
2665   // Allocate shadow area for Win64
2666   if (IsWin64)
2667     CCInfo.AllocateStack(32, 8);
2668
2669   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2670
2671   // Get a count of how many bytes are to be pushed on the stack.
2672   unsigned NumBytes = CCInfo.getNextStackOffset();
2673   if (IsSibcall)
2674     // This is a sibcall. The memory operands are available in caller's
2675     // own caller's stack.
2676     NumBytes = 0;
2677   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2678            IsTailCallConvention(CallConv))
2679     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2680
2681   int FPDiff = 0;
2682   if (isTailCall && !IsSibcall && !IsMustTail) {
2683     // Lower arguments at fp - stackoffset + fpdiff.
2684     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2685     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2686
2687     FPDiff = NumBytesCallerPushed - NumBytes;
2688
2689     // Set the delta of movement of the returnaddr stackslot.
2690     // But only set if delta is greater than previous delta.
2691     if (FPDiff < X86Info->getTCReturnAddrDelta())
2692       X86Info->setTCReturnAddrDelta(FPDiff);
2693   }
2694
2695   unsigned NumBytesToPush = NumBytes;
2696   unsigned NumBytesToPop = NumBytes;
2697
2698   // If we have an inalloca argument, all stack space has already been allocated
2699   // for us and be right at the top of the stack.  We don't support multiple
2700   // arguments passed in memory when using inalloca.
2701   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2702     NumBytesToPush = 0;
2703     if (!ArgLocs.back().isMemLoc())
2704       report_fatal_error("cannot use inalloca attribute on a register "
2705                          "parameter");
2706     if (ArgLocs.back().getLocMemOffset() != 0)
2707       report_fatal_error("any parameter with the inalloca attribute must be "
2708                          "the only memory argument");
2709   }
2710
2711   if (!IsSibcall)
2712     Chain = DAG.getCALLSEQ_START(
2713         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2714
2715   SDValue RetAddrFrIdx;
2716   // Load return address for tail calls.
2717   if (isTailCall && FPDiff)
2718     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2719                                     Is64Bit, FPDiff, dl);
2720
2721   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2722   SmallVector<SDValue, 8> MemOpChains;
2723   SDValue StackPtr;
2724
2725   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2726   // of tail call optimization arguments are handle later.
2727   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2728       DAG.getSubtarget().getRegisterInfo());
2729   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2730     // Skip inalloca arguments, they have already been written.
2731     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2732     if (Flags.isInAlloca())
2733       continue;
2734
2735     CCValAssign &VA = ArgLocs[i];
2736     EVT RegVT = VA.getLocVT();
2737     SDValue Arg = OutVals[i];
2738     bool isByVal = Flags.isByVal();
2739
2740     // Promote the value if needed.
2741     switch (VA.getLocInfo()) {
2742     default: llvm_unreachable("Unknown loc info!");
2743     case CCValAssign::Full: break;
2744     case CCValAssign::SExt:
2745       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2746       break;
2747     case CCValAssign::ZExt:
2748       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2749       break;
2750     case CCValAssign::AExt:
2751       if (RegVT.is128BitVector()) {
2752         // Special case: passing MMX values in XMM registers.
2753         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2754         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2755         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2756       } else
2757         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2758       break;
2759     case CCValAssign::BCvt:
2760       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2761       break;
2762     case CCValAssign::Indirect: {
2763       // Store the argument.
2764       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2765       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2766       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2767                            MachinePointerInfo::getFixedStack(FI),
2768                            false, false, 0);
2769       Arg = SpillSlot;
2770       break;
2771     }
2772     }
2773
2774     if (VA.isRegLoc()) {
2775       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2776       if (isVarArg && IsWin64) {
2777         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2778         // shadow reg if callee is a varargs function.
2779         unsigned ShadowReg = 0;
2780         switch (VA.getLocReg()) {
2781         case X86::XMM0: ShadowReg = X86::RCX; break;
2782         case X86::XMM1: ShadowReg = X86::RDX; break;
2783         case X86::XMM2: ShadowReg = X86::R8; break;
2784         case X86::XMM3: ShadowReg = X86::R9; break;
2785         }
2786         if (ShadowReg)
2787           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2788       }
2789     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2790       assert(VA.isMemLoc());
2791       if (!StackPtr.getNode())
2792         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2793                                       getPointerTy());
2794       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2795                                              dl, DAG, VA, Flags));
2796     }
2797   }
2798
2799   if (!MemOpChains.empty())
2800     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2801
2802   if (Subtarget->isPICStyleGOT()) {
2803     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2804     // GOT pointer.
2805     if (!isTailCall) {
2806       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2807                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2808     } else {
2809       // If we are tail calling and generating PIC/GOT style code load the
2810       // address of the callee into ECX. The value in ecx is used as target of
2811       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2812       // for tail calls on PIC/GOT architectures. Normally we would just put the
2813       // address of GOT into ebx and then call target@PLT. But for tail calls
2814       // ebx would be restored (since ebx is callee saved) before jumping to the
2815       // target@PLT.
2816
2817       // Note: The actual moving to ECX is done further down.
2818       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2819       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2820           !G->getGlobal()->hasProtectedVisibility())
2821         Callee = LowerGlobalAddress(Callee, DAG);
2822       else if (isa<ExternalSymbolSDNode>(Callee))
2823         Callee = LowerExternalSymbol(Callee, DAG);
2824     }
2825   }
2826
2827   if (Is64Bit && isVarArg && !IsWin64) {
2828     // From AMD64 ABI document:
2829     // For calls that may call functions that use varargs or stdargs
2830     // (prototype-less calls or calls to functions containing ellipsis (...) in
2831     // the declaration) %al is used as hidden argument to specify the number
2832     // of SSE registers used. The contents of %al do not need to match exactly
2833     // the number of registers, but must be an ubound on the number of SSE
2834     // registers used and is in the range 0 - 8 inclusive.
2835
2836     // Count the number of XMM registers allocated.
2837     static const MCPhysReg XMMArgRegs[] = {
2838       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2839       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2840     };
2841     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2842     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2843            && "SSE registers cannot be used when SSE is disabled");
2844
2845     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2846                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2847   }
2848
2849   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2850   // don't need this because the eligibility check rejects calls that require
2851   // shuffling arguments passed in memory.
2852   if (!IsSibcall && isTailCall) {
2853     // Force all the incoming stack arguments to be loaded from the stack
2854     // before any new outgoing arguments are stored to the stack, because the
2855     // outgoing stack slots may alias the incoming argument stack slots, and
2856     // the alias isn't otherwise explicit. This is slightly more conservative
2857     // than necessary, because it means that each store effectively depends
2858     // on every argument instead of just those arguments it would clobber.
2859     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2860
2861     SmallVector<SDValue, 8> MemOpChains2;
2862     SDValue FIN;
2863     int FI = 0;
2864     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2865       CCValAssign &VA = ArgLocs[i];
2866       if (VA.isRegLoc())
2867         continue;
2868       assert(VA.isMemLoc());
2869       SDValue Arg = OutVals[i];
2870       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2871       // Skip inalloca arguments.  They don't require any work.
2872       if (Flags.isInAlloca())
2873         continue;
2874       // Create frame index.
2875       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2876       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2877       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2878       FIN = DAG.getFrameIndex(FI, getPointerTy());
2879
2880       if (Flags.isByVal()) {
2881         // Copy relative to framepointer.
2882         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2883         if (!StackPtr.getNode())
2884           StackPtr = DAG.getCopyFromReg(Chain, dl,
2885                                         RegInfo->getStackRegister(),
2886                                         getPointerTy());
2887         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2888
2889         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2890                                                          ArgChain,
2891                                                          Flags, DAG, dl));
2892       } else {
2893         // Store relative to framepointer.
2894         MemOpChains2.push_back(
2895           DAG.getStore(ArgChain, dl, Arg, FIN,
2896                        MachinePointerInfo::getFixedStack(FI),
2897                        false, false, 0));
2898       }
2899     }
2900
2901     if (!MemOpChains2.empty())
2902       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2903
2904     // Store the return address to the appropriate stack slot.
2905     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2906                                      getPointerTy(), RegInfo->getSlotSize(),
2907                                      FPDiff, dl);
2908   }
2909
2910   // Build a sequence of copy-to-reg nodes chained together with token chain
2911   // and flag operands which copy the outgoing args into registers.
2912   SDValue InFlag;
2913   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2914     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2915                              RegsToPass[i].second, InFlag);
2916     InFlag = Chain.getValue(1);
2917   }
2918
2919   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2920     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2921     // In the 64-bit large code model, we have to make all calls
2922     // through a register, since the call instruction's 32-bit
2923     // pc-relative offset may not be large enough to hold the whole
2924     // address.
2925   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2926     // If the callee is a GlobalAddress node (quite common, every direct call
2927     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2928     // it.
2929
2930     // We should use extra load for direct calls to dllimported functions in
2931     // non-JIT mode.
2932     const GlobalValue *GV = G->getGlobal();
2933     if (!GV->hasDLLImportStorageClass()) {
2934       unsigned char OpFlags = 0;
2935       bool ExtraLoad = false;
2936       unsigned WrapperKind = ISD::DELETED_NODE;
2937
2938       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2939       // external symbols most go through the PLT in PIC mode.  If the symbol
2940       // has hidden or protected visibility, or if it is static or local, then
2941       // we don't need to use the PLT - we can directly call it.
2942       if (Subtarget->isTargetELF() &&
2943           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2944           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2945         OpFlags = X86II::MO_PLT;
2946       } else if (Subtarget->isPICStyleStubAny() &&
2947                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2948                  (!Subtarget->getTargetTriple().isMacOSX() ||
2949                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2950         // PC-relative references to external symbols should go through $stub,
2951         // unless we're building with the leopard linker or later, which
2952         // automatically synthesizes these stubs.
2953         OpFlags = X86II::MO_DARWIN_STUB;
2954       } else if (Subtarget->isPICStyleRIPRel() &&
2955                  isa<Function>(GV) &&
2956                  cast<Function>(GV)->getAttributes().
2957                    hasAttribute(AttributeSet::FunctionIndex,
2958                                 Attribute::NonLazyBind)) {
2959         // If the function is marked as non-lazy, generate an indirect call
2960         // which loads from the GOT directly. This avoids runtime overhead
2961         // at the cost of eager binding (and one extra byte of encoding).
2962         OpFlags = X86II::MO_GOTPCREL;
2963         WrapperKind = X86ISD::WrapperRIP;
2964         ExtraLoad = true;
2965       }
2966
2967       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2968                                           G->getOffset(), OpFlags);
2969
2970       // Add a wrapper if needed.
2971       if (WrapperKind != ISD::DELETED_NODE)
2972         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2973       // Add extra indirection if needed.
2974       if (ExtraLoad)
2975         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2976                              MachinePointerInfo::getGOT(),
2977                              false, false, false, 0);
2978     }
2979   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2980     unsigned char OpFlags = 0;
2981
2982     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2983     // external symbols should go through the PLT.
2984     if (Subtarget->isTargetELF() &&
2985         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2986       OpFlags = X86II::MO_PLT;
2987     } else if (Subtarget->isPICStyleStubAny() &&
2988                (!Subtarget->getTargetTriple().isMacOSX() ||
2989                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2990       // PC-relative references to external symbols should go through $stub,
2991       // unless we're building with the leopard linker or later, which
2992       // automatically synthesizes these stubs.
2993       OpFlags = X86II::MO_DARWIN_STUB;
2994     }
2995
2996     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2997                                          OpFlags);
2998   }
2999
3000   // Returns a chain & a flag for retval copy to use.
3001   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3002   SmallVector<SDValue, 8> Ops;
3003
3004   if (!IsSibcall && isTailCall) {
3005     Chain = DAG.getCALLSEQ_END(Chain,
3006                                DAG.getIntPtrConstant(NumBytesToPop, true),
3007                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3008     InFlag = Chain.getValue(1);
3009   }
3010
3011   Ops.push_back(Chain);
3012   Ops.push_back(Callee);
3013
3014   if (isTailCall)
3015     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3016
3017   // Add argument registers to the end of the list so that they are known live
3018   // into the call.
3019   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3020     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3021                                   RegsToPass[i].second.getValueType()));
3022
3023   // Add a register mask operand representing the call-preserved registers.
3024   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3025   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3026   assert(Mask && "Missing call preserved mask for calling convention");
3027   Ops.push_back(DAG.getRegisterMask(Mask));
3028
3029   if (InFlag.getNode())
3030     Ops.push_back(InFlag);
3031
3032   if (isTailCall) {
3033     // We used to do:
3034     //// If this is the first return lowered for this function, add the regs
3035     //// to the liveout set for the function.
3036     // This isn't right, although it's probably harmless on x86; liveouts
3037     // should be computed from returns not tail calls.  Consider a void
3038     // function making a tail call to a function returning int.
3039     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3040   }
3041
3042   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3043   InFlag = Chain.getValue(1);
3044
3045   // Create the CALLSEQ_END node.
3046   unsigned NumBytesForCalleeToPop;
3047   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3048                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3049     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3050   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3051            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3052            SR == StackStructReturn)
3053     // If this is a call to a struct-return function, the callee
3054     // pops the hidden struct pointer, so we have to push it back.
3055     // This is common for Darwin/X86, Linux & Mingw32 targets.
3056     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3057     NumBytesForCalleeToPop = 4;
3058   else
3059     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3060
3061   // Returns a flag for retval copy to use.
3062   if (!IsSibcall) {
3063     Chain = DAG.getCALLSEQ_END(Chain,
3064                                DAG.getIntPtrConstant(NumBytesToPop, true),
3065                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3066                                                      true),
3067                                InFlag, dl);
3068     InFlag = Chain.getValue(1);
3069   }
3070
3071   // Handle result values, copying them out of physregs into vregs that we
3072   // return.
3073   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3074                          Ins, dl, DAG, InVals);
3075 }
3076
3077 //===----------------------------------------------------------------------===//
3078 //                Fast Calling Convention (tail call) implementation
3079 //===----------------------------------------------------------------------===//
3080
3081 //  Like std call, callee cleans arguments, convention except that ECX is
3082 //  reserved for storing the tail called function address. Only 2 registers are
3083 //  free for argument passing (inreg). Tail call optimization is performed
3084 //  provided:
3085 //                * tailcallopt is enabled
3086 //                * caller/callee are fastcc
3087 //  On X86_64 architecture with GOT-style position independent code only local
3088 //  (within module) calls are supported at the moment.
3089 //  To keep the stack aligned according to platform abi the function
3090 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3091 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3092 //  If a tail called function callee has more arguments than the caller the
3093 //  caller needs to make sure that there is room to move the RETADDR to. This is
3094 //  achieved by reserving an area the size of the argument delta right after the
3095 //  original RETADDR, but before the saved framepointer or the spilled registers
3096 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3097 //  stack layout:
3098 //    arg1
3099 //    arg2
3100 //    RETADDR
3101 //    [ new RETADDR
3102 //      move area ]
3103 //    (possible EBP)
3104 //    ESI
3105 //    EDI
3106 //    local1 ..
3107
3108 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3109 /// for a 16 byte align requirement.
3110 unsigned
3111 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3112                                                SelectionDAG& DAG) const {
3113   MachineFunction &MF = DAG.getMachineFunction();
3114   const TargetMachine &TM = MF.getTarget();
3115   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3116       TM.getSubtargetImpl()->getRegisterInfo());
3117   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3118   unsigned StackAlignment = TFI.getStackAlignment();
3119   uint64_t AlignMask = StackAlignment - 1;
3120   int64_t Offset = StackSize;
3121   unsigned SlotSize = RegInfo->getSlotSize();
3122   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3123     // Number smaller than 12 so just add the difference.
3124     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3125   } else {
3126     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3127     Offset = ((~AlignMask) & Offset) + StackAlignment +
3128       (StackAlignment-SlotSize);
3129   }
3130   return Offset;
3131 }
3132
3133 /// MatchingStackOffset - Return true if the given stack call argument is
3134 /// already available in the same position (relatively) of the caller's
3135 /// incoming argument stack.
3136 static
3137 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3138                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3139                          const X86InstrInfo *TII) {
3140   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3141   int FI = INT_MAX;
3142   if (Arg.getOpcode() == ISD::CopyFromReg) {
3143     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3144     if (!TargetRegisterInfo::isVirtualRegister(VR))
3145       return false;
3146     MachineInstr *Def = MRI->getVRegDef(VR);
3147     if (!Def)
3148       return false;
3149     if (!Flags.isByVal()) {
3150       if (!TII->isLoadFromStackSlot(Def, FI))
3151         return false;
3152     } else {
3153       unsigned Opcode = Def->getOpcode();
3154       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3155           Def->getOperand(1).isFI()) {
3156         FI = Def->getOperand(1).getIndex();
3157         Bytes = Flags.getByValSize();
3158       } else
3159         return false;
3160     }
3161   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3162     if (Flags.isByVal())
3163       // ByVal argument is passed in as a pointer but it's now being
3164       // dereferenced. e.g.
3165       // define @foo(%struct.X* %A) {
3166       //   tail call @bar(%struct.X* byval %A)
3167       // }
3168       return false;
3169     SDValue Ptr = Ld->getBasePtr();
3170     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3171     if (!FINode)
3172       return false;
3173     FI = FINode->getIndex();
3174   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3175     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3176     FI = FINode->getIndex();
3177     Bytes = Flags.getByValSize();
3178   } else
3179     return false;
3180
3181   assert(FI != INT_MAX);
3182   if (!MFI->isFixedObjectIndex(FI))
3183     return false;
3184   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3185 }
3186
3187 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3188 /// for tail call optimization. Targets which want to do tail call
3189 /// optimization should implement this function.
3190 bool
3191 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3192                                                      CallingConv::ID CalleeCC,
3193                                                      bool isVarArg,
3194                                                      bool isCalleeStructRet,
3195                                                      bool isCallerStructRet,
3196                                                      Type *RetTy,
3197                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3198                                     const SmallVectorImpl<SDValue> &OutVals,
3199                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3200                                                      SelectionDAG &DAG) const {
3201   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3202     return false;
3203
3204   // If -tailcallopt is specified, make fastcc functions tail-callable.
3205   const MachineFunction &MF = DAG.getMachineFunction();
3206   const Function *CallerF = MF.getFunction();
3207
3208   // If the function return type is x86_fp80 and the callee return type is not,
3209   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3210   // perform a tailcall optimization here.
3211   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3212     return false;
3213
3214   CallingConv::ID CallerCC = CallerF->getCallingConv();
3215   bool CCMatch = CallerCC == CalleeCC;
3216   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3217   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3218
3219   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3220     if (IsTailCallConvention(CalleeCC) && CCMatch)
3221       return true;
3222     return false;
3223   }
3224
3225   // Look for obvious safe cases to perform tail call optimization that do not
3226   // require ABI changes. This is what gcc calls sibcall.
3227
3228   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3229   // emit a special epilogue.
3230   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3231       DAG.getSubtarget().getRegisterInfo());
3232   if (RegInfo->needsStackRealignment(MF))
3233     return false;
3234
3235   // Also avoid sibcall optimization if either caller or callee uses struct
3236   // return semantics.
3237   if (isCalleeStructRet || isCallerStructRet)
3238     return false;
3239
3240   // An stdcall/thiscall caller is expected to clean up its arguments; the
3241   // callee isn't going to do that.
3242   // FIXME: this is more restrictive than needed. We could produce a tailcall
3243   // when the stack adjustment matches. For example, with a thiscall that takes
3244   // only one argument.
3245   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3246                    CallerCC == CallingConv::X86_ThisCall))
3247     return false;
3248
3249   // Do not sibcall optimize vararg calls unless all arguments are passed via
3250   // registers.
3251   if (isVarArg && !Outs.empty()) {
3252
3253     // Optimizing for varargs on Win64 is unlikely to be safe without
3254     // additional testing.
3255     if (IsCalleeWin64 || IsCallerWin64)
3256       return false;
3257
3258     SmallVector<CCValAssign, 16> ArgLocs;
3259     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3260                    *DAG.getContext());
3261
3262     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3263     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3264       if (!ArgLocs[i].isRegLoc())
3265         return false;
3266   }
3267
3268   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3269   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3270   // this into a sibcall.
3271   bool Unused = false;
3272   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3273     if (!Ins[i].Used) {
3274       Unused = true;
3275       break;
3276     }
3277   }
3278   if (Unused) {
3279     SmallVector<CCValAssign, 16> RVLocs;
3280     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3281                    *DAG.getContext());
3282     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3283     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3284       CCValAssign &VA = RVLocs[i];
3285       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3286         return false;
3287     }
3288   }
3289
3290   // If the calling conventions do not match, then we'd better make sure the
3291   // results are returned in the same way as what the caller expects.
3292   if (!CCMatch) {
3293     SmallVector<CCValAssign, 16> RVLocs1;
3294     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3295                     *DAG.getContext());
3296     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3297
3298     SmallVector<CCValAssign, 16> RVLocs2;
3299     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3300                     *DAG.getContext());
3301     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3302
3303     if (RVLocs1.size() != RVLocs2.size())
3304       return false;
3305     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3306       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3307         return false;
3308       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3309         return false;
3310       if (RVLocs1[i].isRegLoc()) {
3311         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3312           return false;
3313       } else {
3314         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3315           return false;
3316       }
3317     }
3318   }
3319
3320   // If the callee takes no arguments then go on to check the results of the
3321   // call.
3322   if (!Outs.empty()) {
3323     // Check if stack adjustment is needed. For now, do not do this if any
3324     // argument is passed on the stack.
3325     SmallVector<CCValAssign, 16> ArgLocs;
3326     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3327                    *DAG.getContext());
3328
3329     // Allocate shadow area for Win64
3330     if (IsCalleeWin64)
3331       CCInfo.AllocateStack(32, 8);
3332
3333     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3334     if (CCInfo.getNextStackOffset()) {
3335       MachineFunction &MF = DAG.getMachineFunction();
3336       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3337         return false;
3338
3339       // Check if the arguments are already laid out in the right way as
3340       // the caller's fixed stack objects.
3341       MachineFrameInfo *MFI = MF.getFrameInfo();
3342       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3343       const X86InstrInfo *TII =
3344           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3345       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3346         CCValAssign &VA = ArgLocs[i];
3347         SDValue Arg = OutVals[i];
3348         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3349         if (VA.getLocInfo() == CCValAssign::Indirect)
3350           return false;
3351         if (!VA.isRegLoc()) {
3352           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3353                                    MFI, MRI, TII))
3354             return false;
3355         }
3356       }
3357     }
3358
3359     // If the tailcall address may be in a register, then make sure it's
3360     // possible to register allocate for it. In 32-bit, the call address can
3361     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3362     // callee-saved registers are restored. These happen to be the same
3363     // registers used to pass 'inreg' arguments so watch out for those.
3364     if (!Subtarget->is64Bit() &&
3365         ((!isa<GlobalAddressSDNode>(Callee) &&
3366           !isa<ExternalSymbolSDNode>(Callee)) ||
3367          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3368       unsigned NumInRegs = 0;
3369       // In PIC we need an extra register to formulate the address computation
3370       // for the callee.
3371       unsigned MaxInRegs =
3372         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3373
3374       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3375         CCValAssign &VA = ArgLocs[i];
3376         if (!VA.isRegLoc())
3377           continue;
3378         unsigned Reg = VA.getLocReg();
3379         switch (Reg) {
3380         default: break;
3381         case X86::EAX: case X86::EDX: case X86::ECX:
3382           if (++NumInRegs == MaxInRegs)
3383             return false;
3384           break;
3385         }
3386       }
3387     }
3388   }
3389
3390   return true;
3391 }
3392
3393 FastISel *
3394 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3395                                   const TargetLibraryInfo *libInfo) const {
3396   return X86::createFastISel(funcInfo, libInfo);
3397 }
3398
3399 //===----------------------------------------------------------------------===//
3400 //                           Other Lowering Hooks
3401 //===----------------------------------------------------------------------===//
3402
3403 static bool MayFoldLoad(SDValue Op) {
3404   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3405 }
3406
3407 static bool MayFoldIntoStore(SDValue Op) {
3408   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3409 }
3410
3411 static bool isTargetShuffle(unsigned Opcode) {
3412   switch(Opcode) {
3413   default: return false;
3414   case X86ISD::PSHUFB:
3415   case X86ISD::PSHUFD:
3416   case X86ISD::PSHUFHW:
3417   case X86ISD::PSHUFLW:
3418   case X86ISD::SHUFP:
3419   case X86ISD::PALIGNR:
3420   case X86ISD::MOVLHPS:
3421   case X86ISD::MOVLHPD:
3422   case X86ISD::MOVHLPS:
3423   case X86ISD::MOVLPS:
3424   case X86ISD::MOVLPD:
3425   case X86ISD::MOVSHDUP:
3426   case X86ISD::MOVSLDUP:
3427   case X86ISD::MOVDDUP:
3428   case X86ISD::MOVSS:
3429   case X86ISD::MOVSD:
3430   case X86ISD::UNPCKL:
3431   case X86ISD::UNPCKH:
3432   case X86ISD::VPERMILP:
3433   case X86ISD::VPERM2X128:
3434   case X86ISD::VPERMI:
3435     return true;
3436   }
3437 }
3438
3439 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3440                                     SDValue V1, SelectionDAG &DAG) {
3441   switch(Opc) {
3442   default: llvm_unreachable("Unknown x86 shuffle node");
3443   case X86ISD::MOVSHDUP:
3444   case X86ISD::MOVSLDUP:
3445   case X86ISD::MOVDDUP:
3446     return DAG.getNode(Opc, dl, VT, V1);
3447   }
3448 }
3449
3450 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3451                                     SDValue V1, unsigned TargetMask,
3452                                     SelectionDAG &DAG) {
3453   switch(Opc) {
3454   default: llvm_unreachable("Unknown x86 shuffle node");
3455   case X86ISD::PSHUFD:
3456   case X86ISD::PSHUFHW:
3457   case X86ISD::PSHUFLW:
3458   case X86ISD::VPERMILP:
3459   case X86ISD::VPERMI:
3460     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3461   }
3462 }
3463
3464 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3465                                     SDValue V1, SDValue V2, unsigned TargetMask,
3466                                     SelectionDAG &DAG) {
3467   switch(Opc) {
3468   default: llvm_unreachable("Unknown x86 shuffle node");
3469   case X86ISD::PALIGNR:
3470   case X86ISD::VALIGN:
3471   case X86ISD::SHUFP:
3472   case X86ISD::VPERM2X128:
3473     return DAG.getNode(Opc, dl, VT, V1, V2,
3474                        DAG.getConstant(TargetMask, MVT::i8));
3475   }
3476 }
3477
3478 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3479                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3480   switch(Opc) {
3481   default: llvm_unreachable("Unknown x86 shuffle node");
3482   case X86ISD::MOVLHPS:
3483   case X86ISD::MOVLHPD:
3484   case X86ISD::MOVHLPS:
3485   case X86ISD::MOVLPS:
3486   case X86ISD::MOVLPD:
3487   case X86ISD::MOVSS:
3488   case X86ISD::MOVSD:
3489   case X86ISD::UNPCKL:
3490   case X86ISD::UNPCKH:
3491     return DAG.getNode(Opc, dl, VT, V1, V2);
3492   }
3493 }
3494
3495 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3496   MachineFunction &MF = DAG.getMachineFunction();
3497   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3498       DAG.getSubtarget().getRegisterInfo());
3499   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3500   int ReturnAddrIndex = FuncInfo->getRAIndex();
3501
3502   if (ReturnAddrIndex == 0) {
3503     // Set up a frame object for the return address.
3504     unsigned SlotSize = RegInfo->getSlotSize();
3505     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3506                                                            -(int64_t)SlotSize,
3507                                                            false);
3508     FuncInfo->setRAIndex(ReturnAddrIndex);
3509   }
3510
3511   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3512 }
3513
3514 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3515                                        bool hasSymbolicDisplacement) {
3516   // Offset should fit into 32 bit immediate field.
3517   if (!isInt<32>(Offset))
3518     return false;
3519
3520   // If we don't have a symbolic displacement - we don't have any extra
3521   // restrictions.
3522   if (!hasSymbolicDisplacement)
3523     return true;
3524
3525   // FIXME: Some tweaks might be needed for medium code model.
3526   if (M != CodeModel::Small && M != CodeModel::Kernel)
3527     return false;
3528
3529   // For small code model we assume that latest object is 16MB before end of 31
3530   // bits boundary. We may also accept pretty large negative constants knowing
3531   // that all objects are in the positive half of address space.
3532   if (M == CodeModel::Small && Offset < 16*1024*1024)
3533     return true;
3534
3535   // For kernel code model we know that all object resist in the negative half
3536   // of 32bits address space. We may not accept negative offsets, since they may
3537   // be just off and we may accept pretty large positive ones.
3538   if (M == CodeModel::Kernel && Offset > 0)
3539     return true;
3540
3541   return false;
3542 }
3543
3544 /// isCalleePop - Determines whether the callee is required to pop its
3545 /// own arguments. Callee pop is necessary to support tail calls.
3546 bool X86::isCalleePop(CallingConv::ID CallingConv,
3547                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3548   if (IsVarArg)
3549     return false;
3550
3551   switch (CallingConv) {
3552   default:
3553     return false;
3554   case CallingConv::X86_StdCall:
3555     return !is64Bit;
3556   case CallingConv::X86_FastCall:
3557     return !is64Bit;
3558   case CallingConv::X86_ThisCall:
3559     return !is64Bit;
3560   case CallingConv::Fast:
3561     return TailCallOpt;
3562   case CallingConv::GHC:
3563     return TailCallOpt;
3564   case CallingConv::HiPE:
3565     return TailCallOpt;
3566   }
3567 }
3568
3569 /// \brief Return true if the condition is an unsigned comparison operation.
3570 static bool isX86CCUnsigned(unsigned X86CC) {
3571   switch (X86CC) {
3572   default: llvm_unreachable("Invalid integer condition!");
3573   case X86::COND_E:     return true;
3574   case X86::COND_G:     return false;
3575   case X86::COND_GE:    return false;
3576   case X86::COND_L:     return false;
3577   case X86::COND_LE:    return false;
3578   case X86::COND_NE:    return true;
3579   case X86::COND_B:     return true;
3580   case X86::COND_A:     return true;
3581   case X86::COND_BE:    return true;
3582   case X86::COND_AE:    return true;
3583   }
3584   llvm_unreachable("covered switch fell through?!");
3585 }
3586
3587 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3588 /// specific condition code, returning the condition code and the LHS/RHS of the
3589 /// comparison to make.
3590 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3591                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3592   if (!isFP) {
3593     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3594       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3595         // X > -1   -> X == 0, jump !sign.
3596         RHS = DAG.getConstant(0, RHS.getValueType());
3597         return X86::COND_NS;
3598       }
3599       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3600         // X < 0   -> X == 0, jump on sign.
3601         return X86::COND_S;
3602       }
3603       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3604         // X < 1   -> X <= 0
3605         RHS = DAG.getConstant(0, RHS.getValueType());
3606         return X86::COND_LE;
3607       }
3608     }
3609
3610     switch (SetCCOpcode) {
3611     default: llvm_unreachable("Invalid integer condition!");
3612     case ISD::SETEQ:  return X86::COND_E;
3613     case ISD::SETGT:  return X86::COND_G;
3614     case ISD::SETGE:  return X86::COND_GE;
3615     case ISD::SETLT:  return X86::COND_L;
3616     case ISD::SETLE:  return X86::COND_LE;
3617     case ISD::SETNE:  return X86::COND_NE;
3618     case ISD::SETULT: return X86::COND_B;
3619     case ISD::SETUGT: return X86::COND_A;
3620     case ISD::SETULE: return X86::COND_BE;
3621     case ISD::SETUGE: return X86::COND_AE;
3622     }
3623   }
3624
3625   // First determine if it is required or is profitable to flip the operands.
3626
3627   // If LHS is a foldable load, but RHS is not, flip the condition.
3628   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3629       !ISD::isNON_EXTLoad(RHS.getNode())) {
3630     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3631     std::swap(LHS, RHS);
3632   }
3633
3634   switch (SetCCOpcode) {
3635   default: break;
3636   case ISD::SETOLT:
3637   case ISD::SETOLE:
3638   case ISD::SETUGT:
3639   case ISD::SETUGE:
3640     std::swap(LHS, RHS);
3641     break;
3642   }
3643
3644   // On a floating point condition, the flags are set as follows:
3645   // ZF  PF  CF   op
3646   //  0 | 0 | 0 | X > Y
3647   //  0 | 0 | 1 | X < Y
3648   //  1 | 0 | 0 | X == Y
3649   //  1 | 1 | 1 | unordered
3650   switch (SetCCOpcode) {
3651   default: llvm_unreachable("Condcode should be pre-legalized away");
3652   case ISD::SETUEQ:
3653   case ISD::SETEQ:   return X86::COND_E;
3654   case ISD::SETOLT:              // flipped
3655   case ISD::SETOGT:
3656   case ISD::SETGT:   return X86::COND_A;
3657   case ISD::SETOLE:              // flipped
3658   case ISD::SETOGE:
3659   case ISD::SETGE:   return X86::COND_AE;
3660   case ISD::SETUGT:              // flipped
3661   case ISD::SETULT:
3662   case ISD::SETLT:   return X86::COND_B;
3663   case ISD::SETUGE:              // flipped
3664   case ISD::SETULE:
3665   case ISD::SETLE:   return X86::COND_BE;
3666   case ISD::SETONE:
3667   case ISD::SETNE:   return X86::COND_NE;
3668   case ISD::SETUO:   return X86::COND_P;
3669   case ISD::SETO:    return X86::COND_NP;
3670   case ISD::SETOEQ:
3671   case ISD::SETUNE:  return X86::COND_INVALID;
3672   }
3673 }
3674
3675 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3676 /// code. Current x86 isa includes the following FP cmov instructions:
3677 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3678 static bool hasFPCMov(unsigned X86CC) {
3679   switch (X86CC) {
3680   default:
3681     return false;
3682   case X86::COND_B:
3683   case X86::COND_BE:
3684   case X86::COND_E:
3685   case X86::COND_P:
3686   case X86::COND_A:
3687   case X86::COND_AE:
3688   case X86::COND_NE:
3689   case X86::COND_NP:
3690     return true;
3691   }
3692 }
3693
3694 /// isFPImmLegal - Returns true if the target can instruction select the
3695 /// specified FP immediate natively. If false, the legalizer will
3696 /// materialize the FP immediate as a load from a constant pool.
3697 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3698   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3699     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3700       return true;
3701   }
3702   return false;
3703 }
3704
3705 /// \brief Returns true if it is beneficial to convert a load of a constant
3706 /// to just the constant itself.
3707 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3708                                                           Type *Ty) const {
3709   assert(Ty->isIntegerTy());
3710
3711   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3712   if (BitSize == 0 || BitSize > 64)
3713     return false;
3714   return true;
3715 }
3716
3717 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3718 /// the specified range (L, H].
3719 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3720   return (Val < 0) || (Val >= Low && Val < Hi);
3721 }
3722
3723 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3724 /// specified value.
3725 static bool isUndefOrEqual(int Val, int CmpVal) {
3726   return (Val < 0 || Val == CmpVal);
3727 }
3728
3729 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3730 /// from position Pos and ending in Pos+Size, falls within the specified
3731 /// sequential range (L, L+Pos]. or is undef.
3732 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3733                                        unsigned Pos, unsigned Size, int Low) {
3734   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3735     if (!isUndefOrEqual(Mask[i], Low))
3736       return false;
3737   return true;
3738 }
3739
3740 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3741 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3742 /// the second operand.
3743 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3744   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3745     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3746   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3747     return (Mask[0] < 2 && Mask[1] < 2);
3748   return false;
3749 }
3750
3751 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3752 /// is suitable for input to PSHUFHW.
3753 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3754   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3755     return false;
3756
3757   // Lower quadword copied in order or undef.
3758   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3759     return false;
3760
3761   // Upper quadword shuffled.
3762   for (unsigned i = 4; i != 8; ++i)
3763     if (!isUndefOrInRange(Mask[i], 4, 8))
3764       return false;
3765
3766   if (VT == MVT::v16i16) {
3767     // Lower quadword copied in order or undef.
3768     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3769       return false;
3770
3771     // Upper quadword shuffled.
3772     for (unsigned i = 12; i != 16; ++i)
3773       if (!isUndefOrInRange(Mask[i], 12, 16))
3774         return false;
3775   }
3776
3777   return true;
3778 }
3779
3780 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3781 /// is suitable for input to PSHUFLW.
3782 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3783   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3784     return false;
3785
3786   // Upper quadword copied in order.
3787   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3788     return false;
3789
3790   // Lower quadword shuffled.
3791   for (unsigned i = 0; i != 4; ++i)
3792     if (!isUndefOrInRange(Mask[i], 0, 4))
3793       return false;
3794
3795   if (VT == MVT::v16i16) {
3796     // Upper quadword copied in order.
3797     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3798       return false;
3799
3800     // Lower quadword shuffled.
3801     for (unsigned i = 8; i != 12; ++i)
3802       if (!isUndefOrInRange(Mask[i], 8, 12))
3803         return false;
3804   }
3805
3806   return true;
3807 }
3808
3809 /// \brief Return true if the mask specifies a shuffle of elements that is
3810 /// suitable for input to intralane (palignr) or interlane (valign) vector
3811 /// right-shift.
3812 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3813   unsigned NumElts = VT.getVectorNumElements();
3814   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3815   unsigned NumLaneElts = NumElts/NumLanes;
3816
3817   // Do not handle 64-bit element shuffles with palignr.
3818   if (NumLaneElts == 2)
3819     return false;
3820
3821   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3822     unsigned i;
3823     for (i = 0; i != NumLaneElts; ++i) {
3824       if (Mask[i+l] >= 0)
3825         break;
3826     }
3827
3828     // Lane is all undef, go to next lane
3829     if (i == NumLaneElts)
3830       continue;
3831
3832     int Start = Mask[i+l];
3833
3834     // Make sure its in this lane in one of the sources
3835     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3836         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3837       return false;
3838
3839     // If not lane 0, then we must match lane 0
3840     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3841       return false;
3842
3843     // Correct second source to be contiguous with first source
3844     if (Start >= (int)NumElts)
3845       Start -= NumElts - NumLaneElts;
3846
3847     // Make sure we're shifting in the right direction.
3848     if (Start <= (int)(i+l))
3849       return false;
3850
3851     Start -= i;
3852
3853     // Check the rest of the elements to see if they are consecutive.
3854     for (++i; i != NumLaneElts; ++i) {
3855       int Idx = Mask[i+l];
3856
3857       // Make sure its in this lane
3858       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3859           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3860         return false;
3861
3862       // If not lane 0, then we must match lane 0
3863       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3864         return false;
3865
3866       if (Idx >= (int)NumElts)
3867         Idx -= NumElts - NumLaneElts;
3868
3869       if (!isUndefOrEqual(Idx, Start+i))
3870         return false;
3871
3872     }
3873   }
3874
3875   return true;
3876 }
3877
3878 /// \brief Return true if the node specifies a shuffle of elements that is
3879 /// suitable for input to PALIGNR.
3880 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3881                           const X86Subtarget *Subtarget) {
3882   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3883       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
3884       VT.is512BitVector())
3885     // FIXME: Add AVX512BW.
3886     return false;
3887
3888   return isAlignrMask(Mask, VT, false);
3889 }
3890
3891 /// \brief Return true if the node specifies a shuffle of elements that is
3892 /// suitable for input to VALIGN.
3893 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3894                           const X86Subtarget *Subtarget) {
3895   // FIXME: Add AVX512VL.
3896   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3897     return false;
3898   return isAlignrMask(Mask, VT, true);
3899 }
3900
3901 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3902 /// the two vector operands have swapped position.
3903 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3904                                      unsigned NumElems) {
3905   for (unsigned i = 0; i != NumElems; ++i) {
3906     int idx = Mask[i];
3907     if (idx < 0)
3908       continue;
3909     else if (idx < (int)NumElems)
3910       Mask[i] = idx + NumElems;
3911     else
3912       Mask[i] = idx - NumElems;
3913   }
3914 }
3915
3916 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3917 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3918 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3919 /// reverse of what x86 shuffles want.
3920 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3921
3922   unsigned NumElems = VT.getVectorNumElements();
3923   unsigned NumLanes = VT.getSizeInBits()/128;
3924   unsigned NumLaneElems = NumElems/NumLanes;
3925
3926   if (NumLaneElems != 2 && NumLaneElems != 4)
3927     return false;
3928
3929   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3930   bool symetricMaskRequired =
3931     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3932
3933   // VSHUFPSY divides the resulting vector into 4 chunks.
3934   // The sources are also splitted into 4 chunks, and each destination
3935   // chunk must come from a different source chunk.
3936   //
3937   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3938   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3939   //
3940   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3941   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3942   //
3943   // VSHUFPDY divides the resulting vector into 4 chunks.
3944   // The sources are also splitted into 4 chunks, and each destination
3945   // chunk must come from a different source chunk.
3946   //
3947   //  SRC1 =>      X3       X2       X1       X0
3948   //  SRC2 =>      Y3       Y2       Y1       Y0
3949   //
3950   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3951   //
3952   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3953   unsigned HalfLaneElems = NumLaneElems/2;
3954   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3955     for (unsigned i = 0; i != NumLaneElems; ++i) {
3956       int Idx = Mask[i+l];
3957       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3958       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3959         return false;
3960       // For VSHUFPSY, the mask of the second half must be the same as the
3961       // first but with the appropriate offsets. This works in the same way as
3962       // VPERMILPS works with masks.
3963       if (!symetricMaskRequired || Idx < 0)
3964         continue;
3965       if (MaskVal[i] < 0) {
3966         MaskVal[i] = Idx - l;
3967         continue;
3968       }
3969       if ((signed)(Idx - l) != MaskVal[i])
3970         return false;
3971     }
3972   }
3973
3974   return true;
3975 }
3976
3977 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3978 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3979 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3980   if (!VT.is128BitVector())
3981     return false;
3982
3983   unsigned NumElems = VT.getVectorNumElements();
3984
3985   if (NumElems != 4)
3986     return false;
3987
3988   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3989   return isUndefOrEqual(Mask[0], 6) &&
3990          isUndefOrEqual(Mask[1], 7) &&
3991          isUndefOrEqual(Mask[2], 2) &&
3992          isUndefOrEqual(Mask[3], 3);
3993 }
3994
3995 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3996 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3997 /// <2, 3, 2, 3>
3998 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3999   if (!VT.is128BitVector())
4000     return false;
4001
4002   unsigned NumElems = VT.getVectorNumElements();
4003
4004   if (NumElems != 4)
4005     return false;
4006
4007   return isUndefOrEqual(Mask[0], 2) &&
4008          isUndefOrEqual(Mask[1], 3) &&
4009          isUndefOrEqual(Mask[2], 2) &&
4010          isUndefOrEqual(Mask[3], 3);
4011 }
4012
4013 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4014 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4015 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4016   if (!VT.is128BitVector())
4017     return false;
4018
4019   unsigned NumElems = VT.getVectorNumElements();
4020
4021   if (NumElems != 2 && NumElems != 4)
4022     return false;
4023
4024   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4025     if (!isUndefOrEqual(Mask[i], i + NumElems))
4026       return false;
4027
4028   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4029     if (!isUndefOrEqual(Mask[i], i))
4030       return false;
4031
4032   return true;
4033 }
4034
4035 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4037 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4038   if (!VT.is128BitVector())
4039     return false;
4040
4041   unsigned NumElems = VT.getVectorNumElements();
4042
4043   if (NumElems != 2 && NumElems != 4)
4044     return false;
4045
4046   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4047     if (!isUndefOrEqual(Mask[i], i))
4048       return false;
4049
4050   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4051     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4052       return false;
4053
4054   return true;
4055 }
4056
4057 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4058 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4059 /// i. e: If all but one element come from the same vector.
4060 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4061   // TODO: Deal with AVX's VINSERTPS
4062   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4063     return false;
4064
4065   unsigned CorrectPosV1 = 0;
4066   unsigned CorrectPosV2 = 0;
4067   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4068     if (Mask[i] == -1) {
4069       ++CorrectPosV1;
4070       ++CorrectPosV2;
4071       continue;
4072     }
4073
4074     if (Mask[i] == i)
4075       ++CorrectPosV1;
4076     else if (Mask[i] == i + 4)
4077       ++CorrectPosV2;
4078   }
4079
4080   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4081     // We have 3 elements (undefs count as elements from any vector) from one
4082     // vector, and one from another.
4083     return true;
4084
4085   return false;
4086 }
4087
4088 //
4089 // Some special combinations that can be optimized.
4090 //
4091 static
4092 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4093                                SelectionDAG &DAG) {
4094   MVT VT = SVOp->getSimpleValueType(0);
4095   SDLoc dl(SVOp);
4096
4097   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4098     return SDValue();
4099
4100   ArrayRef<int> Mask = SVOp->getMask();
4101
4102   // These are the special masks that may be optimized.
4103   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4104   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4105   bool MatchEvenMask = true;
4106   bool MatchOddMask  = true;
4107   for (int i=0; i<8; ++i) {
4108     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4109       MatchEvenMask = false;
4110     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4111       MatchOddMask = false;
4112   }
4113
4114   if (!MatchEvenMask && !MatchOddMask)
4115     return SDValue();
4116
4117   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4118
4119   SDValue Op0 = SVOp->getOperand(0);
4120   SDValue Op1 = SVOp->getOperand(1);
4121
4122   if (MatchEvenMask) {
4123     // Shift the second operand right to 32 bits.
4124     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4125     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4126   } else {
4127     // Shift the first operand left to 32 bits.
4128     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4129     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4130   }
4131   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4132   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4133 }
4134
4135 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4136 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4137 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4138                          bool HasInt256, bool V2IsSplat = false) {
4139
4140   assert(VT.getSizeInBits() >= 128 &&
4141          "Unsupported vector type for unpckl");
4142
4143   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4144   unsigned NumLanes;
4145   unsigned NumOf256BitLanes;
4146   unsigned NumElts = VT.getVectorNumElements();
4147   if (VT.is256BitVector()) {
4148     if (NumElts != 4 && NumElts != 8 &&
4149         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4150     return false;
4151     NumLanes = 2;
4152     NumOf256BitLanes = 1;
4153   } else if (VT.is512BitVector()) {
4154     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4155            "Unsupported vector type for unpckh");
4156     NumLanes = 2;
4157     NumOf256BitLanes = 2;
4158   } else {
4159     NumLanes = 1;
4160     NumOf256BitLanes = 1;
4161   }
4162
4163   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4164   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4165
4166   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4167     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4168       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4169         int BitI  = Mask[l256*NumEltsInStride+l+i];
4170         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4171         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4172           return false;
4173         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4174           return false;
4175         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4176           return false;
4177       }
4178     }
4179   }
4180   return true;
4181 }
4182
4183 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4184 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4185 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4186                          bool HasInt256, bool V2IsSplat = false) {
4187   assert(VT.getSizeInBits() >= 128 &&
4188          "Unsupported vector type for unpckh");
4189
4190   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4191   unsigned NumLanes;
4192   unsigned NumOf256BitLanes;
4193   unsigned NumElts = VT.getVectorNumElements();
4194   if (VT.is256BitVector()) {
4195     if (NumElts != 4 && NumElts != 8 &&
4196         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4197     return false;
4198     NumLanes = 2;
4199     NumOf256BitLanes = 1;
4200   } else if (VT.is512BitVector()) {
4201     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4202            "Unsupported vector type for unpckh");
4203     NumLanes = 2;
4204     NumOf256BitLanes = 2;
4205   } else {
4206     NumLanes = 1;
4207     NumOf256BitLanes = 1;
4208   }
4209
4210   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4211   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4212
4213   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4214     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4215       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4216         int BitI  = Mask[l256*NumEltsInStride+l+i];
4217         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4218         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4219           return false;
4220         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4221           return false;
4222         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4223           return false;
4224       }
4225     }
4226   }
4227   return true;
4228 }
4229
4230 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4231 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4232 /// <0, 0, 1, 1>
4233 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4234   unsigned NumElts = VT.getVectorNumElements();
4235   bool Is256BitVec = VT.is256BitVector();
4236
4237   if (VT.is512BitVector())
4238     return false;
4239   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4240          "Unsupported vector type for unpckh");
4241
4242   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4243       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4244     return false;
4245
4246   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4247   // FIXME: Need a better way to get rid of this, there's no latency difference
4248   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4249   // the former later. We should also remove the "_undef" special mask.
4250   if (NumElts == 4 && Is256BitVec)
4251     return false;
4252
4253   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4254   // independently on 128-bit lanes.
4255   unsigned NumLanes = VT.getSizeInBits()/128;
4256   unsigned NumLaneElts = NumElts/NumLanes;
4257
4258   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4259     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4260       int BitI  = Mask[l+i];
4261       int BitI1 = Mask[l+i+1];
4262
4263       if (!isUndefOrEqual(BitI, j))
4264         return false;
4265       if (!isUndefOrEqual(BitI1, j))
4266         return false;
4267     }
4268   }
4269
4270   return true;
4271 }
4272
4273 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4274 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4275 /// <2, 2, 3, 3>
4276 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4277   unsigned NumElts = VT.getVectorNumElements();
4278
4279   if (VT.is512BitVector())
4280     return false;
4281
4282   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4283          "Unsupported vector type for unpckh");
4284
4285   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4286       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4287     return false;
4288
4289   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4290   // independently on 128-bit lanes.
4291   unsigned NumLanes = VT.getSizeInBits()/128;
4292   unsigned NumLaneElts = NumElts/NumLanes;
4293
4294   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4295     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4296       int BitI  = Mask[l+i];
4297       int BitI1 = Mask[l+i+1];
4298       if (!isUndefOrEqual(BitI, j))
4299         return false;
4300       if (!isUndefOrEqual(BitI1, j))
4301         return false;
4302     }
4303   }
4304   return true;
4305 }
4306
4307 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4308 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4309 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4310   if (!VT.is512BitVector())
4311     return false;
4312
4313   unsigned NumElts = VT.getVectorNumElements();
4314   unsigned HalfSize = NumElts/2;
4315   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4316     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4317       *Imm = 1;
4318       return true;
4319     }
4320   }
4321   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4322     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4323       *Imm = 0;
4324       return true;
4325     }
4326   }
4327   return false;
4328 }
4329
4330 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4331 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4332 /// MOVSD, and MOVD, i.e. setting the lowest element.
4333 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4334   if (VT.getVectorElementType().getSizeInBits() < 32)
4335     return false;
4336   if (!VT.is128BitVector())
4337     return false;
4338
4339   unsigned NumElts = VT.getVectorNumElements();
4340
4341   if (!isUndefOrEqual(Mask[0], NumElts))
4342     return false;
4343
4344   for (unsigned i = 1; i != NumElts; ++i)
4345     if (!isUndefOrEqual(Mask[i], i))
4346       return false;
4347
4348   return true;
4349 }
4350
4351 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4352 /// as permutations between 128-bit chunks or halves. As an example: this
4353 /// shuffle bellow:
4354 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4355 /// The first half comes from the second half of V1 and the second half from the
4356 /// the second half of V2.
4357 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4358   if (!HasFp256 || !VT.is256BitVector())
4359     return false;
4360
4361   // The shuffle result is divided into half A and half B. In total the two
4362   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4363   // B must come from C, D, E or F.
4364   unsigned HalfSize = VT.getVectorNumElements()/2;
4365   bool MatchA = false, MatchB = false;
4366
4367   // Check if A comes from one of C, D, E, F.
4368   for (unsigned Half = 0; Half != 4; ++Half) {
4369     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4370       MatchA = true;
4371       break;
4372     }
4373   }
4374
4375   // Check if B comes from one of C, D, E, F.
4376   for (unsigned Half = 0; Half != 4; ++Half) {
4377     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4378       MatchB = true;
4379       break;
4380     }
4381   }
4382
4383   return MatchA && MatchB;
4384 }
4385
4386 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4387 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4388 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4389   MVT VT = SVOp->getSimpleValueType(0);
4390
4391   unsigned HalfSize = VT.getVectorNumElements()/2;
4392
4393   unsigned FstHalf = 0, SndHalf = 0;
4394   for (unsigned i = 0; i < HalfSize; ++i) {
4395     if (SVOp->getMaskElt(i) > 0) {
4396       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4397       break;
4398     }
4399   }
4400   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4401     if (SVOp->getMaskElt(i) > 0) {
4402       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4403       break;
4404     }
4405   }
4406
4407   return (FstHalf | (SndHalf << 4));
4408 }
4409
4410 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4411 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4412   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4413   if (EltSize < 32)
4414     return false;
4415
4416   unsigned NumElts = VT.getVectorNumElements();
4417   Imm8 = 0;
4418   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4419     for (unsigned i = 0; i != NumElts; ++i) {
4420       if (Mask[i] < 0)
4421         continue;
4422       Imm8 |= Mask[i] << (i*2);
4423     }
4424     return true;
4425   }
4426
4427   unsigned LaneSize = 4;
4428   SmallVector<int, 4> MaskVal(LaneSize, -1);
4429
4430   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4431     for (unsigned i = 0; i != LaneSize; ++i) {
4432       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4433         return false;
4434       if (Mask[i+l] < 0)
4435         continue;
4436       if (MaskVal[i] < 0) {
4437         MaskVal[i] = Mask[i+l] - l;
4438         Imm8 |= MaskVal[i] << (i*2);
4439         continue;
4440       }
4441       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4442         return false;
4443     }
4444   }
4445   return true;
4446 }
4447
4448 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4449 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4450 /// Note that VPERMIL mask matching is different depending whether theunderlying
4451 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4452 /// to the same elements of the low, but to the higher half of the source.
4453 /// In VPERMILPD the two lanes could be shuffled independently of each other
4454 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4455 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4456   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4457   if (VT.getSizeInBits() < 256 || EltSize < 32)
4458     return false;
4459   bool symetricMaskRequired = (EltSize == 32);
4460   unsigned NumElts = VT.getVectorNumElements();
4461
4462   unsigned NumLanes = VT.getSizeInBits()/128;
4463   unsigned LaneSize = NumElts/NumLanes;
4464   // 2 or 4 elements in one lane
4465
4466   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4467   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4468     for (unsigned i = 0; i != LaneSize; ++i) {
4469       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4470         return false;
4471       if (symetricMaskRequired) {
4472         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4473           ExpectedMaskVal[i] = Mask[i+l] - l;
4474           continue;
4475         }
4476         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4477           return false;
4478       }
4479     }
4480   }
4481   return true;
4482 }
4483
4484 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4485 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4486 /// element of vector 2 and the other elements to come from vector 1 in order.
4487 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4488                                bool V2IsSplat = false, bool V2IsUndef = false) {
4489   if (!VT.is128BitVector())
4490     return false;
4491
4492   unsigned NumOps = VT.getVectorNumElements();
4493   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4494     return false;
4495
4496   if (!isUndefOrEqual(Mask[0], 0))
4497     return false;
4498
4499   for (unsigned i = 1; i != NumOps; ++i)
4500     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4501           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4502           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4503       return false;
4504
4505   return true;
4506 }
4507
4508 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4509 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4510 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4511 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4512                            const X86Subtarget *Subtarget) {
4513   if (!Subtarget->hasSSE3())
4514     return false;
4515
4516   unsigned NumElems = VT.getVectorNumElements();
4517
4518   if ((VT.is128BitVector() && NumElems != 4) ||
4519       (VT.is256BitVector() && NumElems != 8) ||
4520       (VT.is512BitVector() && NumElems != 16))
4521     return false;
4522
4523   // "i+1" is the value the indexed mask element must have
4524   for (unsigned i = 0; i != NumElems; i += 2)
4525     if (!isUndefOrEqual(Mask[i], i+1) ||
4526         !isUndefOrEqual(Mask[i+1], i+1))
4527       return false;
4528
4529   return true;
4530 }
4531
4532 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4533 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4534 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4535 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4536                            const X86Subtarget *Subtarget) {
4537   if (!Subtarget->hasSSE3())
4538     return false;
4539
4540   unsigned NumElems = VT.getVectorNumElements();
4541
4542   if ((VT.is128BitVector() && NumElems != 4) ||
4543       (VT.is256BitVector() && NumElems != 8) ||
4544       (VT.is512BitVector() && NumElems != 16))
4545     return false;
4546
4547   // "i" is the value the indexed mask element must have
4548   for (unsigned i = 0; i != NumElems; i += 2)
4549     if (!isUndefOrEqual(Mask[i], i) ||
4550         !isUndefOrEqual(Mask[i+1], i))
4551       return false;
4552
4553   return true;
4554 }
4555
4556 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4557 /// specifies a shuffle of elements that is suitable for input to 256-bit
4558 /// version of MOVDDUP.
4559 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4560   if (!HasFp256 || !VT.is256BitVector())
4561     return false;
4562
4563   unsigned NumElts = VT.getVectorNumElements();
4564   if (NumElts != 4)
4565     return false;
4566
4567   for (unsigned i = 0; i != NumElts/2; ++i)
4568     if (!isUndefOrEqual(Mask[i], 0))
4569       return false;
4570   for (unsigned i = NumElts/2; i != NumElts; ++i)
4571     if (!isUndefOrEqual(Mask[i], NumElts/2))
4572       return false;
4573   return true;
4574 }
4575
4576 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4577 /// specifies a shuffle of elements that is suitable for input to 128-bit
4578 /// version of MOVDDUP.
4579 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4580   if (!VT.is128BitVector())
4581     return false;
4582
4583   unsigned e = VT.getVectorNumElements() / 2;
4584   for (unsigned i = 0; i != e; ++i)
4585     if (!isUndefOrEqual(Mask[i], i))
4586       return false;
4587   for (unsigned i = 0; i != e; ++i)
4588     if (!isUndefOrEqual(Mask[e+i], i))
4589       return false;
4590   return true;
4591 }
4592
4593 /// isVEXTRACTIndex - Return true if the specified
4594 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4595 /// suitable for instruction that extract 128 or 256 bit vectors
4596 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4597   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4598   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4599     return false;
4600
4601   // The index should be aligned on a vecWidth-bit boundary.
4602   uint64_t Index =
4603     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4604
4605   MVT VT = N->getSimpleValueType(0);
4606   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4607   bool Result = (Index * ElSize) % vecWidth == 0;
4608
4609   return Result;
4610 }
4611
4612 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4613 /// operand specifies a subvector insert that is suitable for input to
4614 /// insertion of 128 or 256-bit subvectors
4615 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4616   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4617   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4618     return false;
4619   // The index should be aligned on a vecWidth-bit boundary.
4620   uint64_t Index =
4621     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4622
4623   MVT VT = N->getSimpleValueType(0);
4624   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4625   bool Result = (Index * ElSize) % vecWidth == 0;
4626
4627   return Result;
4628 }
4629
4630 bool X86::isVINSERT128Index(SDNode *N) {
4631   return isVINSERTIndex(N, 128);
4632 }
4633
4634 bool X86::isVINSERT256Index(SDNode *N) {
4635   return isVINSERTIndex(N, 256);
4636 }
4637
4638 bool X86::isVEXTRACT128Index(SDNode *N) {
4639   return isVEXTRACTIndex(N, 128);
4640 }
4641
4642 bool X86::isVEXTRACT256Index(SDNode *N) {
4643   return isVEXTRACTIndex(N, 256);
4644 }
4645
4646 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4647 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4648 /// Handles 128-bit and 256-bit.
4649 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4650   MVT VT = N->getSimpleValueType(0);
4651
4652   assert((VT.getSizeInBits() >= 128) &&
4653          "Unsupported vector type for PSHUF/SHUFP");
4654
4655   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4656   // independently on 128-bit lanes.
4657   unsigned NumElts = VT.getVectorNumElements();
4658   unsigned NumLanes = VT.getSizeInBits()/128;
4659   unsigned NumLaneElts = NumElts/NumLanes;
4660
4661   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4662          "Only supports 2, 4 or 8 elements per lane");
4663
4664   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4665   unsigned Mask = 0;
4666   for (unsigned i = 0; i != NumElts; ++i) {
4667     int Elt = N->getMaskElt(i);
4668     if (Elt < 0) continue;
4669     Elt &= NumLaneElts - 1;
4670     unsigned ShAmt = (i << Shift) % 8;
4671     Mask |= Elt << ShAmt;
4672   }
4673
4674   return Mask;
4675 }
4676
4677 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4678 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4679 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4680   MVT VT = N->getSimpleValueType(0);
4681
4682   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4683          "Unsupported vector type for PSHUFHW");
4684
4685   unsigned NumElts = VT.getVectorNumElements();
4686
4687   unsigned Mask = 0;
4688   for (unsigned l = 0; l != NumElts; l += 8) {
4689     // 8 nodes per lane, but we only care about the last 4.
4690     for (unsigned i = 0; i < 4; ++i) {
4691       int Elt = N->getMaskElt(l+i+4);
4692       if (Elt < 0) continue;
4693       Elt &= 0x3; // only 2-bits.
4694       Mask |= Elt << (i * 2);
4695     }
4696   }
4697
4698   return Mask;
4699 }
4700
4701 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4702 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4703 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4704   MVT VT = N->getSimpleValueType(0);
4705
4706   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4707          "Unsupported vector type for PSHUFHW");
4708
4709   unsigned NumElts = VT.getVectorNumElements();
4710
4711   unsigned Mask = 0;
4712   for (unsigned l = 0; l != NumElts; l += 8) {
4713     // 8 nodes per lane, but we only care about the first 4.
4714     for (unsigned i = 0; i < 4; ++i) {
4715       int Elt = N->getMaskElt(l+i);
4716       if (Elt < 0) continue;
4717       Elt &= 0x3; // only 2-bits
4718       Mask |= Elt << (i * 2);
4719     }
4720   }
4721
4722   return Mask;
4723 }
4724
4725 /// \brief Return the appropriate immediate to shuffle the specified
4726 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4727 /// VALIGN (if Interlane is true) instructions.
4728 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4729                                            bool InterLane) {
4730   MVT VT = SVOp->getSimpleValueType(0);
4731   unsigned EltSize = InterLane ? 1 :
4732     VT.getVectorElementType().getSizeInBits() >> 3;
4733
4734   unsigned NumElts = VT.getVectorNumElements();
4735   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4736   unsigned NumLaneElts = NumElts/NumLanes;
4737
4738   int Val = 0;
4739   unsigned i;
4740   for (i = 0; i != NumElts; ++i) {
4741     Val = SVOp->getMaskElt(i);
4742     if (Val >= 0)
4743       break;
4744   }
4745   if (Val >= (int)NumElts)
4746     Val -= NumElts - NumLaneElts;
4747
4748   assert(Val - i > 0 && "PALIGNR imm should be positive");
4749   return (Val - i) * EltSize;
4750 }
4751
4752 /// \brief Return the appropriate immediate to shuffle the specified
4753 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4754 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4755   return getShuffleAlignrImmediate(SVOp, false);
4756 }
4757
4758 /// \brief Return the appropriate immediate to shuffle the specified
4759 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4760 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4761   return getShuffleAlignrImmediate(SVOp, true);
4762 }
4763
4764
4765 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4766   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4767   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4768     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4769
4770   uint64_t Index =
4771     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4772
4773   MVT VecVT = N->getOperand(0).getSimpleValueType();
4774   MVT ElVT = VecVT.getVectorElementType();
4775
4776   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4777   return Index / NumElemsPerChunk;
4778 }
4779
4780 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4781   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4782   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4783     llvm_unreachable("Illegal insert subvector for VINSERT");
4784
4785   uint64_t Index =
4786     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4787
4788   MVT VecVT = N->getSimpleValueType(0);
4789   MVT ElVT = VecVT.getVectorElementType();
4790
4791   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4792   return Index / NumElemsPerChunk;
4793 }
4794
4795 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4796 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4797 /// and VINSERTI128 instructions.
4798 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4799   return getExtractVEXTRACTImmediate(N, 128);
4800 }
4801
4802 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4803 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4804 /// and VINSERTI64x4 instructions.
4805 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4806   return getExtractVEXTRACTImmediate(N, 256);
4807 }
4808
4809 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4810 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4811 /// and VINSERTI128 instructions.
4812 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4813   return getInsertVINSERTImmediate(N, 128);
4814 }
4815
4816 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4817 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4818 /// and VINSERTI64x4 instructions.
4819 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4820   return getInsertVINSERTImmediate(N, 256);
4821 }
4822
4823 /// isZero - Returns true if Elt is a constant integer zero
4824 static bool isZero(SDValue V) {
4825   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4826   return C && C->isNullValue();
4827 }
4828
4829 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4830 /// constant +0.0.
4831 bool X86::isZeroNode(SDValue Elt) {
4832   if (isZero(Elt))
4833     return true;
4834   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4835     return CFP->getValueAPF().isPosZero();
4836   return false;
4837 }
4838
4839 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4840 /// match movhlps. The lower half elements should come from upper half of
4841 /// V1 (and in order), and the upper half elements should come from the upper
4842 /// half of V2 (and in order).
4843 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4844   if (!VT.is128BitVector())
4845     return false;
4846   if (VT.getVectorNumElements() != 4)
4847     return false;
4848   for (unsigned i = 0, e = 2; i != e; ++i)
4849     if (!isUndefOrEqual(Mask[i], i+2))
4850       return false;
4851   for (unsigned i = 2; i != 4; ++i)
4852     if (!isUndefOrEqual(Mask[i], i+4))
4853       return false;
4854   return true;
4855 }
4856
4857 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4858 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4859 /// required.
4860 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4861   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4862     return false;
4863   N = N->getOperand(0).getNode();
4864   if (!ISD::isNON_EXTLoad(N))
4865     return false;
4866   if (LD)
4867     *LD = cast<LoadSDNode>(N);
4868   return true;
4869 }
4870
4871 // Test whether the given value is a vector value which will be legalized
4872 // into a load.
4873 static bool WillBeConstantPoolLoad(SDNode *N) {
4874   if (N->getOpcode() != ISD::BUILD_VECTOR)
4875     return false;
4876
4877   // Check for any non-constant elements.
4878   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4879     switch (N->getOperand(i).getNode()->getOpcode()) {
4880     case ISD::UNDEF:
4881     case ISD::ConstantFP:
4882     case ISD::Constant:
4883       break;
4884     default:
4885       return false;
4886     }
4887
4888   // Vectors of all-zeros and all-ones are materialized with special
4889   // instructions rather than being loaded.
4890   return !ISD::isBuildVectorAllZeros(N) &&
4891          !ISD::isBuildVectorAllOnes(N);
4892 }
4893
4894 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4895 /// match movlp{s|d}. The lower half elements should come from lower half of
4896 /// V1 (and in order), and the upper half elements should come from the upper
4897 /// half of V2 (and in order). And since V1 will become the source of the
4898 /// MOVLP, it must be either a vector load or a scalar load to vector.
4899 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4900                                ArrayRef<int> Mask, MVT VT) {
4901   if (!VT.is128BitVector())
4902     return false;
4903
4904   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4905     return false;
4906   // Is V2 is a vector load, don't do this transformation. We will try to use
4907   // load folding shufps op.
4908   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4909     return false;
4910
4911   unsigned NumElems = VT.getVectorNumElements();
4912
4913   if (NumElems != 2 && NumElems != 4)
4914     return false;
4915   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4916     if (!isUndefOrEqual(Mask[i], i))
4917       return false;
4918   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4919     if (!isUndefOrEqual(Mask[i], i+NumElems))
4920       return false;
4921   return true;
4922 }
4923
4924 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4925 /// to an zero vector.
4926 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4927 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4928   SDValue V1 = N->getOperand(0);
4929   SDValue V2 = N->getOperand(1);
4930   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4931   for (unsigned i = 0; i != NumElems; ++i) {
4932     int Idx = N->getMaskElt(i);
4933     if (Idx >= (int)NumElems) {
4934       unsigned Opc = V2.getOpcode();
4935       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4936         continue;
4937       if (Opc != ISD::BUILD_VECTOR ||
4938           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4939         return false;
4940     } else if (Idx >= 0) {
4941       unsigned Opc = V1.getOpcode();
4942       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4943         continue;
4944       if (Opc != ISD::BUILD_VECTOR ||
4945           !X86::isZeroNode(V1.getOperand(Idx)))
4946         return false;
4947     }
4948   }
4949   return true;
4950 }
4951
4952 /// getZeroVector - Returns a vector of specified type with all zero elements.
4953 ///
4954 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4955                              SelectionDAG &DAG, SDLoc dl) {
4956   assert(VT.isVector() && "Expected a vector type");
4957
4958   // Always build SSE zero vectors as <4 x i32> bitcasted
4959   // to their dest type. This ensures they get CSE'd.
4960   SDValue Vec;
4961   if (VT.is128BitVector()) {  // SSE
4962     if (Subtarget->hasSSE2()) {  // SSE2
4963       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4964       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4965     } else { // SSE1
4966       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4967       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4968     }
4969   } else if (VT.is256BitVector()) { // AVX
4970     if (Subtarget->hasInt256()) { // AVX2
4971       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4972       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4973       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4974     } else {
4975       // 256-bit logic and arithmetic instructions in AVX are all
4976       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4977       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4978       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4979       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4980     }
4981   } else if (VT.is512BitVector()) { // AVX-512
4982       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4983       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4984                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4985       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4986   } else if (VT.getScalarType() == MVT::i1) {
4987     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4988     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4989     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4990     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4991   } else
4992     llvm_unreachable("Unexpected vector type");
4993
4994   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4995 }
4996
4997 /// getOnesVector - Returns a vector of specified type with all bits set.
4998 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4999 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5000 /// Then bitcast to their original type, ensuring they get CSE'd.
5001 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5002                              SDLoc dl) {
5003   assert(VT.isVector() && "Expected a vector type");
5004
5005   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5006   SDValue Vec;
5007   if (VT.is256BitVector()) {
5008     if (HasInt256) { // AVX2
5009       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5010       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5011     } else { // AVX
5012       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5013       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5014     }
5015   } else if (VT.is128BitVector()) {
5016     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5017   } else
5018     llvm_unreachable("Unexpected vector type");
5019
5020   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5021 }
5022
5023 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5024 /// that point to V2 points to its first element.
5025 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5026   for (unsigned i = 0; i != NumElems; ++i) {
5027     if (Mask[i] > (int)NumElems) {
5028       Mask[i] = NumElems;
5029     }
5030   }
5031 }
5032
5033 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5034 /// operation of specified width.
5035 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5036                        SDValue V2) {
5037   unsigned NumElems = VT.getVectorNumElements();
5038   SmallVector<int, 8> Mask;
5039   Mask.push_back(NumElems);
5040   for (unsigned i = 1; i != NumElems; ++i)
5041     Mask.push_back(i);
5042   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5043 }
5044
5045 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5046 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5047                           SDValue V2) {
5048   unsigned NumElems = VT.getVectorNumElements();
5049   SmallVector<int, 8> Mask;
5050   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5051     Mask.push_back(i);
5052     Mask.push_back(i + NumElems);
5053   }
5054   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5055 }
5056
5057 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5058 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5059                           SDValue V2) {
5060   unsigned NumElems = VT.getVectorNumElements();
5061   SmallVector<int, 8> Mask;
5062   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5063     Mask.push_back(i + Half);
5064     Mask.push_back(i + NumElems + Half);
5065   }
5066   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5067 }
5068
5069 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5070 // a generic shuffle instruction because the target has no such instructions.
5071 // Generate shuffles which repeat i16 and i8 several times until they can be
5072 // represented by v4f32 and then be manipulated by target suported shuffles.
5073 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5074   MVT VT = V.getSimpleValueType();
5075   int NumElems = VT.getVectorNumElements();
5076   SDLoc dl(V);
5077
5078   while (NumElems > 4) {
5079     if (EltNo < NumElems/2) {
5080       V = getUnpackl(DAG, dl, VT, V, V);
5081     } else {
5082       V = getUnpackh(DAG, dl, VT, V, V);
5083       EltNo -= NumElems/2;
5084     }
5085     NumElems >>= 1;
5086   }
5087   return V;
5088 }
5089
5090 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5091 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5092   MVT VT = V.getSimpleValueType();
5093   SDLoc dl(V);
5094
5095   if (VT.is128BitVector()) {
5096     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5097     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5098     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5099                              &SplatMask[0]);
5100   } else if (VT.is256BitVector()) {
5101     // To use VPERMILPS to splat scalars, the second half of indicies must
5102     // refer to the higher part, which is a duplication of the lower one,
5103     // because VPERMILPS can only handle in-lane permutations.
5104     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5105                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5106
5107     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5108     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5109                              &SplatMask[0]);
5110   } else
5111     llvm_unreachable("Vector size not supported");
5112
5113   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5114 }
5115
5116 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5117 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5118   MVT SrcVT = SV->getSimpleValueType(0);
5119   SDValue V1 = SV->getOperand(0);
5120   SDLoc dl(SV);
5121
5122   int EltNo = SV->getSplatIndex();
5123   int NumElems = SrcVT.getVectorNumElements();
5124   bool Is256BitVec = SrcVT.is256BitVector();
5125
5126   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5127          "Unknown how to promote splat for type");
5128
5129   // Extract the 128-bit part containing the splat element and update
5130   // the splat element index when it refers to the higher register.
5131   if (Is256BitVec) {
5132     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5133     if (EltNo >= NumElems/2)
5134       EltNo -= NumElems/2;
5135   }
5136
5137   // All i16 and i8 vector types can't be used directly by a generic shuffle
5138   // instruction because the target has no such instruction. Generate shuffles
5139   // which repeat i16 and i8 several times until they fit in i32, and then can
5140   // be manipulated by target suported shuffles.
5141   MVT EltVT = SrcVT.getVectorElementType();
5142   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5143     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5144
5145   // Recreate the 256-bit vector and place the same 128-bit vector
5146   // into the low and high part. This is necessary because we want
5147   // to use VPERM* to shuffle the vectors
5148   if (Is256BitVec) {
5149     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5150   }
5151
5152   return getLegalSplat(DAG, V1, EltNo);
5153 }
5154
5155 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5156 /// vector of zero or undef vector.  This produces a shuffle where the low
5157 /// element of V2 is swizzled into the zero/undef vector, landing at element
5158 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5159 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5160                                            bool IsZero,
5161                                            const X86Subtarget *Subtarget,
5162                                            SelectionDAG &DAG) {
5163   MVT VT = V2.getSimpleValueType();
5164   SDValue V1 = IsZero
5165     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5166   unsigned NumElems = VT.getVectorNumElements();
5167   SmallVector<int, 16> MaskVec;
5168   for (unsigned i = 0; i != NumElems; ++i)
5169     // If this is the insertion idx, put the low elt of V2 here.
5170     MaskVec.push_back(i == Idx ? NumElems : i);
5171   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5172 }
5173
5174 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5175 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5176 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5177 /// shuffles which use a single input multiple times, and in those cases it will
5178 /// adjust the mask to only have indices within that single input.
5179 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5180                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5181   unsigned NumElems = VT.getVectorNumElements();
5182   SDValue ImmN;
5183
5184   IsUnary = false;
5185   bool IsFakeUnary = false;
5186   switch(N->getOpcode()) {
5187   case X86ISD::SHUFP:
5188     ImmN = N->getOperand(N->getNumOperands()-1);
5189     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5190     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5191     break;
5192   case X86ISD::UNPCKH:
5193     DecodeUNPCKHMask(VT, Mask);
5194     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5195     break;
5196   case X86ISD::UNPCKL:
5197     DecodeUNPCKLMask(VT, Mask);
5198     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5199     break;
5200   case X86ISD::MOVHLPS:
5201     DecodeMOVHLPSMask(NumElems, Mask);
5202     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5203     break;
5204   case X86ISD::MOVLHPS:
5205     DecodeMOVLHPSMask(NumElems, Mask);
5206     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5207     break;
5208   case X86ISD::PALIGNR:
5209     ImmN = N->getOperand(N->getNumOperands()-1);
5210     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5211     break;
5212   case X86ISD::PSHUFD:
5213   case X86ISD::VPERMILP:
5214     ImmN = N->getOperand(N->getNumOperands()-1);
5215     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5216     IsUnary = true;
5217     break;
5218   case X86ISD::PSHUFHW:
5219     ImmN = N->getOperand(N->getNumOperands()-1);
5220     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5221     IsUnary = true;
5222     break;
5223   case X86ISD::PSHUFLW:
5224     ImmN = N->getOperand(N->getNumOperands()-1);
5225     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5226     IsUnary = true;
5227     break;
5228   case X86ISD::PSHUFB: {
5229     IsUnary = true;
5230     SDValue MaskNode = N->getOperand(1);
5231     while (MaskNode->getOpcode() == ISD::BITCAST)
5232       MaskNode = MaskNode->getOperand(0);
5233
5234     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5235       // If we have a build-vector, then things are easy.
5236       EVT VT = MaskNode.getValueType();
5237       assert(VT.isVector() &&
5238              "Can't produce a non-vector with a build_vector!");
5239       if (!VT.isInteger())
5240         return false;
5241
5242       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5243
5244       SmallVector<uint64_t, 32> RawMask;
5245       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5246         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5247         if (!CN)
5248           return false;
5249         APInt MaskElement = CN->getAPIntValue();
5250
5251         // We now have to decode the element which could be any integer size and
5252         // extract each byte of it.
5253         for (int j = 0; j < NumBytesPerElement; ++j) {
5254           // Note that this is x86 and so always little endian: the low byte is
5255           // the first byte of the mask.
5256           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5257           MaskElement = MaskElement.lshr(8);
5258         }
5259       }
5260       DecodePSHUFBMask(RawMask, Mask);
5261       break;
5262     }
5263
5264     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5265     if (!MaskLoad)
5266       return false;
5267
5268     SDValue Ptr = MaskLoad->getBasePtr();
5269     if (Ptr->getOpcode() == X86ISD::Wrapper)
5270       Ptr = Ptr->getOperand(0);
5271
5272     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5273     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5274       return false;
5275
5276     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5277       // FIXME: Support AVX-512 here.
5278       if (!C->getType()->isVectorTy() ||
5279           (C->getNumElements() != 16 && C->getNumElements() != 32))
5280         return false;
5281
5282       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5283       DecodePSHUFBMask(C, Mask);
5284       break;
5285     }
5286
5287     return false;
5288   }
5289   case X86ISD::VPERMI:
5290     ImmN = N->getOperand(N->getNumOperands()-1);
5291     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5292     IsUnary = true;
5293     break;
5294   case X86ISD::MOVSS:
5295   case X86ISD::MOVSD: {
5296     // The index 0 always comes from the first element of the second source,
5297     // this is why MOVSS and MOVSD are used in the first place. The other
5298     // elements come from the other positions of the first source vector
5299     Mask.push_back(NumElems);
5300     for (unsigned i = 1; i != NumElems; ++i) {
5301       Mask.push_back(i);
5302     }
5303     break;
5304   }
5305   case X86ISD::VPERM2X128:
5306     ImmN = N->getOperand(N->getNumOperands()-1);
5307     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5308     if (Mask.empty()) return false;
5309     break;
5310   case X86ISD::MOVDDUP:
5311   case X86ISD::MOVLHPD:
5312   case X86ISD::MOVLPD:
5313   case X86ISD::MOVLPS:
5314   case X86ISD::MOVSHDUP:
5315   case X86ISD::MOVSLDUP:
5316     // Not yet implemented
5317     return false;
5318   default: llvm_unreachable("unknown target shuffle node");
5319   }
5320
5321   // If we have a fake unary shuffle, the shuffle mask is spread across two
5322   // inputs that are actually the same node. Re-map the mask to always point
5323   // into the first input.
5324   if (IsFakeUnary)
5325     for (int &M : Mask)
5326       if (M >= (int)Mask.size())
5327         M -= Mask.size();
5328
5329   return true;
5330 }
5331
5332 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5333 /// element of the result of the vector shuffle.
5334 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5335                                    unsigned Depth) {
5336   if (Depth == 6)
5337     return SDValue();  // Limit search depth.
5338
5339   SDValue V = SDValue(N, 0);
5340   EVT VT = V.getValueType();
5341   unsigned Opcode = V.getOpcode();
5342
5343   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5344   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5345     int Elt = SV->getMaskElt(Index);
5346
5347     if (Elt < 0)
5348       return DAG.getUNDEF(VT.getVectorElementType());
5349
5350     unsigned NumElems = VT.getVectorNumElements();
5351     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5352                                          : SV->getOperand(1);
5353     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5354   }
5355
5356   // Recurse into target specific vector shuffles to find scalars.
5357   if (isTargetShuffle(Opcode)) {
5358     MVT ShufVT = V.getSimpleValueType();
5359     unsigned NumElems = ShufVT.getVectorNumElements();
5360     SmallVector<int, 16> ShuffleMask;
5361     bool IsUnary;
5362
5363     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5364       return SDValue();
5365
5366     int Elt = ShuffleMask[Index];
5367     if (Elt < 0)
5368       return DAG.getUNDEF(ShufVT.getVectorElementType());
5369
5370     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5371                                          : N->getOperand(1);
5372     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5373                                Depth+1);
5374   }
5375
5376   // Actual nodes that may contain scalar elements
5377   if (Opcode == ISD::BITCAST) {
5378     V = V.getOperand(0);
5379     EVT SrcVT = V.getValueType();
5380     unsigned NumElems = VT.getVectorNumElements();
5381
5382     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5383       return SDValue();
5384   }
5385
5386   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5387     return (Index == 0) ? V.getOperand(0)
5388                         : DAG.getUNDEF(VT.getVectorElementType());
5389
5390   if (V.getOpcode() == ISD::BUILD_VECTOR)
5391     return V.getOperand(Index);
5392
5393   return SDValue();
5394 }
5395
5396 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5397 /// shuffle operation which come from a consecutively from a zero. The
5398 /// search can start in two different directions, from left or right.
5399 /// We count undefs as zeros until PreferredNum is reached.
5400 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5401                                          unsigned NumElems, bool ZerosFromLeft,
5402                                          SelectionDAG &DAG,
5403                                          unsigned PreferredNum = -1U) {
5404   unsigned NumZeros = 0;
5405   for (unsigned i = 0; i != NumElems; ++i) {
5406     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5407     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5408     if (!Elt.getNode())
5409       break;
5410
5411     if (X86::isZeroNode(Elt))
5412       ++NumZeros;
5413     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5414       NumZeros = std::min(NumZeros + 1, PreferredNum);
5415     else
5416       break;
5417   }
5418
5419   return NumZeros;
5420 }
5421
5422 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5423 /// correspond consecutively to elements from one of the vector operands,
5424 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5425 static
5426 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5427                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5428                               unsigned NumElems, unsigned &OpNum) {
5429   bool SeenV1 = false;
5430   bool SeenV2 = false;
5431
5432   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5433     int Idx = SVOp->getMaskElt(i);
5434     // Ignore undef indicies
5435     if (Idx < 0)
5436       continue;
5437
5438     if (Idx < (int)NumElems)
5439       SeenV1 = true;
5440     else
5441       SeenV2 = true;
5442
5443     // Only accept consecutive elements from the same vector
5444     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5445       return false;
5446   }
5447
5448   OpNum = SeenV1 ? 0 : 1;
5449   return true;
5450 }
5451
5452 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5453 /// logical left shift of a vector.
5454 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5455                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5456   unsigned NumElems =
5457     SVOp->getSimpleValueType(0).getVectorNumElements();
5458   unsigned NumZeros = getNumOfConsecutiveZeros(
5459       SVOp, NumElems, false /* check zeros from right */, DAG,
5460       SVOp->getMaskElt(0));
5461   unsigned OpSrc;
5462
5463   if (!NumZeros)
5464     return false;
5465
5466   // Considering the elements in the mask that are not consecutive zeros,
5467   // check if they consecutively come from only one of the source vectors.
5468   //
5469   //               V1 = {X, A, B, C}     0
5470   //                         \  \  \    /
5471   //   vector_shuffle V1, V2 <1, 2, 3, X>
5472   //
5473   if (!isShuffleMaskConsecutive(SVOp,
5474             0,                   // Mask Start Index
5475             NumElems-NumZeros,   // Mask End Index(exclusive)
5476             NumZeros,            // Where to start looking in the src vector
5477             NumElems,            // Number of elements in vector
5478             OpSrc))              // Which source operand ?
5479     return false;
5480
5481   isLeft = false;
5482   ShAmt = NumZeros;
5483   ShVal = SVOp->getOperand(OpSrc);
5484   return true;
5485 }
5486
5487 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5488 /// logical left shift of a vector.
5489 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5490                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5491   unsigned NumElems =
5492     SVOp->getSimpleValueType(0).getVectorNumElements();
5493   unsigned NumZeros = getNumOfConsecutiveZeros(
5494       SVOp, NumElems, true /* check zeros from left */, DAG,
5495       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5496   unsigned OpSrc;
5497
5498   if (!NumZeros)
5499     return false;
5500
5501   // Considering the elements in the mask that are not consecutive zeros,
5502   // check if they consecutively come from only one of the source vectors.
5503   //
5504   //                           0    { A, B, X, X } = V2
5505   //                          / \    /  /
5506   //   vector_shuffle V1, V2 <X, X, 4, 5>
5507   //
5508   if (!isShuffleMaskConsecutive(SVOp,
5509             NumZeros,     // Mask Start Index
5510             NumElems,     // Mask End Index(exclusive)
5511             0,            // Where to start looking in the src vector
5512             NumElems,     // Number of elements in vector
5513             OpSrc))       // Which source operand ?
5514     return false;
5515
5516   isLeft = true;
5517   ShAmt = NumZeros;
5518   ShVal = SVOp->getOperand(OpSrc);
5519   return true;
5520 }
5521
5522 /// isVectorShift - Returns true if the shuffle can be implemented as a
5523 /// logical left or right shift of a vector.
5524 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5525                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5526   // Although the logic below support any bitwidth size, there are no
5527   // shift instructions which handle more than 128-bit vectors.
5528   if (!SVOp->getSimpleValueType(0).is128BitVector())
5529     return false;
5530
5531   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5532       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5533     return true;
5534
5535   return false;
5536 }
5537
5538 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5539 ///
5540 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5541                                        unsigned NumNonZero, unsigned NumZero,
5542                                        SelectionDAG &DAG,
5543                                        const X86Subtarget* Subtarget,
5544                                        const TargetLowering &TLI) {
5545   if (NumNonZero > 8)
5546     return SDValue();
5547
5548   SDLoc dl(Op);
5549   SDValue V;
5550   bool First = true;
5551   for (unsigned i = 0; i < 16; ++i) {
5552     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5553     if (ThisIsNonZero && First) {
5554       if (NumZero)
5555         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5556       else
5557         V = DAG.getUNDEF(MVT::v8i16);
5558       First = false;
5559     }
5560
5561     if ((i & 1) != 0) {
5562       SDValue ThisElt, LastElt;
5563       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5564       if (LastIsNonZero) {
5565         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5566                               MVT::i16, Op.getOperand(i-1));
5567       }
5568       if (ThisIsNonZero) {
5569         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5570         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5571                               ThisElt, DAG.getConstant(8, MVT::i8));
5572         if (LastIsNonZero)
5573           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5574       } else
5575         ThisElt = LastElt;
5576
5577       if (ThisElt.getNode())
5578         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5579                         DAG.getIntPtrConstant(i/2));
5580     }
5581   }
5582
5583   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5584 }
5585
5586 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5587 ///
5588 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5589                                      unsigned NumNonZero, unsigned NumZero,
5590                                      SelectionDAG &DAG,
5591                                      const X86Subtarget* Subtarget,
5592                                      const TargetLowering &TLI) {
5593   if (NumNonZero > 4)
5594     return SDValue();
5595
5596   SDLoc dl(Op);
5597   SDValue V;
5598   bool First = true;
5599   for (unsigned i = 0; i < 8; ++i) {
5600     bool isNonZero = (NonZeros & (1 << i)) != 0;
5601     if (isNonZero) {
5602       if (First) {
5603         if (NumZero)
5604           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5605         else
5606           V = DAG.getUNDEF(MVT::v8i16);
5607         First = false;
5608       }
5609       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5610                       MVT::v8i16, V, Op.getOperand(i),
5611                       DAG.getIntPtrConstant(i));
5612     }
5613   }
5614
5615   return V;
5616 }
5617
5618 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5619 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5620                                      unsigned NonZeros, unsigned NumNonZero,
5621                                      unsigned NumZero, SelectionDAG &DAG,
5622                                      const X86Subtarget *Subtarget,
5623                                      const TargetLowering &TLI) {
5624   // We know there's at least one non-zero element
5625   unsigned FirstNonZeroIdx = 0;
5626   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5627   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5628          X86::isZeroNode(FirstNonZero)) {
5629     ++FirstNonZeroIdx;
5630     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5631   }
5632
5633   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5634       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5635     return SDValue();
5636
5637   SDValue V = FirstNonZero.getOperand(0);
5638   MVT VVT = V.getSimpleValueType();
5639   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5640     return SDValue();
5641
5642   unsigned FirstNonZeroDst =
5643       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5644   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5645   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5646   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5647
5648   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5649     SDValue Elem = Op.getOperand(Idx);
5650     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5651       continue;
5652
5653     // TODO: What else can be here? Deal with it.
5654     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5655       return SDValue();
5656
5657     // TODO: Some optimizations are still possible here
5658     // ex: Getting one element from a vector, and the rest from another.
5659     if (Elem.getOperand(0) != V)
5660       return SDValue();
5661
5662     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5663     if (Dst == Idx)
5664       ++CorrectIdx;
5665     else if (IncorrectIdx == -1U) {
5666       IncorrectIdx = Idx;
5667       IncorrectDst = Dst;
5668     } else
5669       // There was already one element with an incorrect index.
5670       // We can't optimize this case to an insertps.
5671       return SDValue();
5672   }
5673
5674   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5675     SDLoc dl(Op);
5676     EVT VT = Op.getSimpleValueType();
5677     unsigned ElementMoveMask = 0;
5678     if (IncorrectIdx == -1U)
5679       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5680     else
5681       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5682
5683     SDValue InsertpsMask =
5684         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5685     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5686   }
5687
5688   return SDValue();
5689 }
5690
5691 /// getVShift - Return a vector logical shift node.
5692 ///
5693 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5694                          unsigned NumBits, SelectionDAG &DAG,
5695                          const TargetLowering &TLI, SDLoc dl) {
5696   assert(VT.is128BitVector() && "Unknown type for VShift");
5697   EVT ShVT = MVT::v2i64;
5698   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5699   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5700   return DAG.getNode(ISD::BITCAST, dl, VT,
5701                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5702                              DAG.getConstant(NumBits,
5703                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5704 }
5705
5706 static SDValue
5707 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5708
5709   // Check if the scalar load can be widened into a vector load. And if
5710   // the address is "base + cst" see if the cst can be "absorbed" into
5711   // the shuffle mask.
5712   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5713     SDValue Ptr = LD->getBasePtr();
5714     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5715       return SDValue();
5716     EVT PVT = LD->getValueType(0);
5717     if (PVT != MVT::i32 && PVT != MVT::f32)
5718       return SDValue();
5719
5720     int FI = -1;
5721     int64_t Offset = 0;
5722     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5723       FI = FINode->getIndex();
5724       Offset = 0;
5725     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5726                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5727       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5728       Offset = Ptr.getConstantOperandVal(1);
5729       Ptr = Ptr.getOperand(0);
5730     } else {
5731       return SDValue();
5732     }
5733
5734     // FIXME: 256-bit vector instructions don't require a strict alignment,
5735     // improve this code to support it better.
5736     unsigned RequiredAlign = VT.getSizeInBits()/8;
5737     SDValue Chain = LD->getChain();
5738     // Make sure the stack object alignment is at least 16 or 32.
5739     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5740     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5741       if (MFI->isFixedObjectIndex(FI)) {
5742         // Can't change the alignment. FIXME: It's possible to compute
5743         // the exact stack offset and reference FI + adjust offset instead.
5744         // If someone *really* cares about this. That's the way to implement it.
5745         return SDValue();
5746       } else {
5747         MFI->setObjectAlignment(FI, RequiredAlign);
5748       }
5749     }
5750
5751     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5752     // Ptr + (Offset & ~15).
5753     if (Offset < 0)
5754       return SDValue();
5755     if ((Offset % RequiredAlign) & 3)
5756       return SDValue();
5757     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5758     if (StartOffset)
5759       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5760                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5761
5762     int EltNo = (Offset - StartOffset) >> 2;
5763     unsigned NumElems = VT.getVectorNumElements();
5764
5765     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5766     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5767                              LD->getPointerInfo().getWithOffset(StartOffset),
5768                              false, false, false, 0);
5769
5770     SmallVector<int, 8> Mask;
5771     for (unsigned i = 0; i != NumElems; ++i)
5772       Mask.push_back(EltNo);
5773
5774     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5775   }
5776
5777   return SDValue();
5778 }
5779
5780 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5781 /// vector of type 'VT', see if the elements can be replaced by a single large
5782 /// load which has the same value as a build_vector whose operands are 'elts'.
5783 ///
5784 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5785 ///
5786 /// FIXME: we'd also like to handle the case where the last elements are zero
5787 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5788 /// There's even a handy isZeroNode for that purpose.
5789 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5790                                         SDLoc &DL, SelectionDAG &DAG,
5791                                         bool isAfterLegalize) {
5792   EVT EltVT = VT.getVectorElementType();
5793   unsigned NumElems = Elts.size();
5794
5795   LoadSDNode *LDBase = nullptr;
5796   unsigned LastLoadedElt = -1U;
5797
5798   // For each element in the initializer, see if we've found a load or an undef.
5799   // If we don't find an initial load element, or later load elements are
5800   // non-consecutive, bail out.
5801   for (unsigned i = 0; i < NumElems; ++i) {
5802     SDValue Elt = Elts[i];
5803
5804     if (!Elt.getNode() ||
5805         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5806       return SDValue();
5807     if (!LDBase) {
5808       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5809         return SDValue();
5810       LDBase = cast<LoadSDNode>(Elt.getNode());
5811       LastLoadedElt = i;
5812       continue;
5813     }
5814     if (Elt.getOpcode() == ISD::UNDEF)
5815       continue;
5816
5817     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5818     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5819       return SDValue();
5820     LastLoadedElt = i;
5821   }
5822
5823   // If we have found an entire vector of loads and undefs, then return a large
5824   // load of the entire vector width starting at the base pointer.  If we found
5825   // consecutive loads for the low half, generate a vzext_load node.
5826   if (LastLoadedElt == NumElems - 1) {
5827
5828     if (isAfterLegalize &&
5829         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5830       return SDValue();
5831
5832     SDValue NewLd = SDValue();
5833
5834     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5835       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5836                           LDBase->getPointerInfo(),
5837                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5838                           LDBase->isInvariant(), 0);
5839     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5840                         LDBase->getPointerInfo(),
5841                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5842                         LDBase->isInvariant(), LDBase->getAlignment());
5843
5844     if (LDBase->hasAnyUseOfValue(1)) {
5845       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5846                                      SDValue(LDBase, 1),
5847                                      SDValue(NewLd.getNode(), 1));
5848       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5849       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5850                              SDValue(NewLd.getNode(), 1));
5851     }
5852
5853     return NewLd;
5854   }
5855   if (NumElems == 4 && LastLoadedElt == 1 &&
5856       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5857     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5858     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5859     SDValue ResNode =
5860         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5861                                 LDBase->getPointerInfo(),
5862                                 LDBase->getAlignment(),
5863                                 false/*isVolatile*/, true/*ReadMem*/,
5864                                 false/*WriteMem*/);
5865
5866     // Make sure the newly-created LOAD is in the same position as LDBase in
5867     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5868     // update uses of LDBase's output chain to use the TokenFactor.
5869     if (LDBase->hasAnyUseOfValue(1)) {
5870       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5871                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5872       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5873       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5874                              SDValue(ResNode.getNode(), 1));
5875     }
5876
5877     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5878   }
5879   return SDValue();
5880 }
5881
5882 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5883 /// to generate a splat value for the following cases:
5884 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5885 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5886 /// a scalar load, or a constant.
5887 /// The VBROADCAST node is returned when a pattern is found,
5888 /// or SDValue() otherwise.
5889 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5890                                     SelectionDAG &DAG) {
5891   if (!Subtarget->hasFp256())
5892     return SDValue();
5893
5894   MVT VT = Op.getSimpleValueType();
5895   SDLoc dl(Op);
5896
5897   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5898          "Unsupported vector type for broadcast.");
5899
5900   SDValue Ld;
5901   bool ConstSplatVal;
5902
5903   switch (Op.getOpcode()) {
5904     default:
5905       // Unknown pattern found.
5906       return SDValue();
5907
5908     case ISD::BUILD_VECTOR: {
5909       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5910       BitVector UndefElements;
5911       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5912
5913       // We need a splat of a single value to use broadcast, and it doesn't
5914       // make any sense if the value is only in one element of the vector.
5915       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5916         return SDValue();
5917
5918       Ld = Splat;
5919       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5920                        Ld.getOpcode() == ISD::ConstantFP);
5921
5922       // Make sure that all of the users of a non-constant load are from the
5923       // BUILD_VECTOR node.
5924       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5925         return SDValue();
5926       break;
5927     }
5928
5929     case ISD::VECTOR_SHUFFLE: {
5930       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5931
5932       // Shuffles must have a splat mask where the first element is
5933       // broadcasted.
5934       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5935         return SDValue();
5936
5937       SDValue Sc = Op.getOperand(0);
5938       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5939           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5940
5941         if (!Subtarget->hasInt256())
5942           return SDValue();
5943
5944         // Use the register form of the broadcast instruction available on AVX2.
5945         if (VT.getSizeInBits() >= 256)
5946           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5947         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5948       }
5949
5950       Ld = Sc.getOperand(0);
5951       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5952                        Ld.getOpcode() == ISD::ConstantFP);
5953
5954       // The scalar_to_vector node and the suspected
5955       // load node must have exactly one user.
5956       // Constants may have multiple users.
5957
5958       // AVX-512 has register version of the broadcast
5959       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5960         Ld.getValueType().getSizeInBits() >= 32;
5961       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5962           !hasRegVer))
5963         return SDValue();
5964       break;
5965     }
5966   }
5967
5968   bool IsGE256 = (VT.getSizeInBits() >= 256);
5969
5970   // Handle the broadcasting a single constant scalar from the constant pool
5971   // into a vector. On Sandybridge it is still better to load a constant vector
5972   // from the constant pool and not to broadcast it from a scalar.
5973   if (ConstSplatVal && Subtarget->hasInt256()) {
5974     EVT CVT = Ld.getValueType();
5975     assert(!CVT.isVector() && "Must not broadcast a vector type");
5976     unsigned ScalarSize = CVT.getSizeInBits();
5977
5978     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5979       const Constant *C = nullptr;
5980       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5981         C = CI->getConstantIntValue();
5982       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5983         C = CF->getConstantFPValue();
5984
5985       assert(C && "Invalid constant type");
5986
5987       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5988       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5989       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5990       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5991                        MachinePointerInfo::getConstantPool(),
5992                        false, false, false, Alignment);
5993
5994       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5995     }
5996   }
5997
5998   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5999   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6000
6001   // Handle AVX2 in-register broadcasts.
6002   if (!IsLoad && Subtarget->hasInt256() &&
6003       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6004     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6005
6006   // The scalar source must be a normal load.
6007   if (!IsLoad)
6008     return SDValue();
6009
6010   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6011     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6012
6013   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6014   // double since there is no vbroadcastsd xmm
6015   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6016     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6017       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6018   }
6019
6020   // Unsupported broadcast.
6021   return SDValue();
6022 }
6023
6024 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6025 /// underlying vector and index.
6026 ///
6027 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6028 /// index.
6029 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6030                                          SDValue ExtIdx) {
6031   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6032   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6033     return Idx;
6034
6035   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6036   // lowered this:
6037   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6038   // to:
6039   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6040   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6041   //                           undef)
6042   //                       Constant<0>)
6043   // In this case the vector is the extract_subvector expression and the index
6044   // is 2, as specified by the shuffle.
6045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6046   SDValue ShuffleVec = SVOp->getOperand(0);
6047   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6048   assert(ShuffleVecVT.getVectorElementType() ==
6049          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6050
6051   int ShuffleIdx = SVOp->getMaskElt(Idx);
6052   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6053     ExtractedFromVec = ShuffleVec;
6054     return ShuffleIdx;
6055   }
6056   return Idx;
6057 }
6058
6059 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6060   MVT VT = Op.getSimpleValueType();
6061
6062   // Skip if insert_vec_elt is not supported.
6063   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6064   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6065     return SDValue();
6066
6067   SDLoc DL(Op);
6068   unsigned NumElems = Op.getNumOperands();
6069
6070   SDValue VecIn1;
6071   SDValue VecIn2;
6072   SmallVector<unsigned, 4> InsertIndices;
6073   SmallVector<int, 8> Mask(NumElems, -1);
6074
6075   for (unsigned i = 0; i != NumElems; ++i) {
6076     unsigned Opc = Op.getOperand(i).getOpcode();
6077
6078     if (Opc == ISD::UNDEF)
6079       continue;
6080
6081     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6082       // Quit if more than 1 elements need inserting.
6083       if (InsertIndices.size() > 1)
6084         return SDValue();
6085
6086       InsertIndices.push_back(i);
6087       continue;
6088     }
6089
6090     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6091     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6092     // Quit if non-constant index.
6093     if (!isa<ConstantSDNode>(ExtIdx))
6094       return SDValue();
6095     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6096
6097     // Quit if extracted from vector of different type.
6098     if (ExtractedFromVec.getValueType() != VT)
6099       return SDValue();
6100
6101     if (!VecIn1.getNode())
6102       VecIn1 = ExtractedFromVec;
6103     else if (VecIn1 != ExtractedFromVec) {
6104       if (!VecIn2.getNode())
6105         VecIn2 = ExtractedFromVec;
6106       else if (VecIn2 != ExtractedFromVec)
6107         // Quit if more than 2 vectors to shuffle
6108         return SDValue();
6109     }
6110
6111     if (ExtractedFromVec == VecIn1)
6112       Mask[i] = Idx;
6113     else if (ExtractedFromVec == VecIn2)
6114       Mask[i] = Idx + NumElems;
6115   }
6116
6117   if (!VecIn1.getNode())
6118     return SDValue();
6119
6120   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6121   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6122   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6123     unsigned Idx = InsertIndices[i];
6124     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6125                      DAG.getIntPtrConstant(Idx));
6126   }
6127
6128   return NV;
6129 }
6130
6131 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6132 SDValue
6133 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6134
6135   MVT VT = Op.getSimpleValueType();
6136   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6137          "Unexpected type in LowerBUILD_VECTORvXi1!");
6138
6139   SDLoc dl(Op);
6140   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6141     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6142     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6143     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6144   }
6145
6146   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6147     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6148     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6149     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6150   }
6151
6152   bool AllContants = true;
6153   uint64_t Immediate = 0;
6154   int NonConstIdx = -1;
6155   bool IsSplat = true;
6156   unsigned NumNonConsts = 0;
6157   unsigned NumConsts = 0;
6158   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6159     SDValue In = Op.getOperand(idx);
6160     if (In.getOpcode() == ISD::UNDEF)
6161       continue;
6162     if (!isa<ConstantSDNode>(In)) {
6163       AllContants = false;
6164       NonConstIdx = idx;
6165       NumNonConsts++;
6166     }
6167     else {
6168       NumConsts++;
6169       if (cast<ConstantSDNode>(In)->getZExtValue())
6170       Immediate |= (1ULL << idx);
6171     }
6172     if (In != Op.getOperand(0))
6173       IsSplat = false;
6174   }
6175
6176   if (AllContants) {
6177     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6178       DAG.getConstant(Immediate, MVT::i16));
6179     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6180                        DAG.getIntPtrConstant(0));
6181   }
6182
6183   if (NumNonConsts == 1 && NonConstIdx != 0) {
6184     SDValue DstVec;
6185     if (NumConsts) {
6186       SDValue VecAsImm = DAG.getConstant(Immediate,
6187                                          MVT::getIntegerVT(VT.getSizeInBits()));
6188       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6189     }
6190     else 
6191       DstVec = DAG.getUNDEF(VT);
6192     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6193                        Op.getOperand(NonConstIdx),
6194                        DAG.getIntPtrConstant(NonConstIdx));
6195   }
6196   if (!IsSplat && (NonConstIdx != 0))
6197     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6198   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6199   SDValue Select;
6200   if (IsSplat)
6201     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6202                           DAG.getConstant(-1, SelectVT),
6203                           DAG.getConstant(0, SelectVT));
6204   else
6205     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6206                          DAG.getConstant((Immediate | 1), SelectVT),
6207                          DAG.getConstant(Immediate, SelectVT));
6208   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6209 }
6210
6211 /// \brief Return true if \p N implements a horizontal binop and return the
6212 /// operands for the horizontal binop into V0 and V1.
6213 /// 
6214 /// This is a helper function of PerformBUILD_VECTORCombine.
6215 /// This function checks that the build_vector \p N in input implements a
6216 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6217 /// operation to match.
6218 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6219 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6220 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6221 /// arithmetic sub.
6222 ///
6223 /// This function only analyzes elements of \p N whose indices are
6224 /// in range [BaseIdx, LastIdx).
6225 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6226                               SelectionDAG &DAG,
6227                               unsigned BaseIdx, unsigned LastIdx,
6228                               SDValue &V0, SDValue &V1) {
6229   EVT VT = N->getValueType(0);
6230
6231   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6232   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6233          "Invalid Vector in input!");
6234   
6235   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6236   bool CanFold = true;
6237   unsigned ExpectedVExtractIdx = BaseIdx;
6238   unsigned NumElts = LastIdx - BaseIdx;
6239   V0 = DAG.getUNDEF(VT);
6240   V1 = DAG.getUNDEF(VT);
6241
6242   // Check if N implements a horizontal binop.
6243   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6244     SDValue Op = N->getOperand(i + BaseIdx);
6245
6246     // Skip UNDEFs.
6247     if (Op->getOpcode() == ISD::UNDEF) {
6248       // Update the expected vector extract index.
6249       if (i * 2 == NumElts)
6250         ExpectedVExtractIdx = BaseIdx;
6251       ExpectedVExtractIdx += 2;
6252       continue;
6253     }
6254
6255     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6256
6257     if (!CanFold)
6258       break;
6259
6260     SDValue Op0 = Op.getOperand(0);
6261     SDValue Op1 = Op.getOperand(1);
6262
6263     // Try to match the following pattern:
6264     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6265     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6266         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6267         Op0.getOperand(0) == Op1.getOperand(0) &&
6268         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6269         isa<ConstantSDNode>(Op1.getOperand(1)));
6270     if (!CanFold)
6271       break;
6272
6273     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6274     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6275
6276     if (i * 2 < NumElts) {
6277       if (V0.getOpcode() == ISD::UNDEF)
6278         V0 = Op0.getOperand(0);
6279     } else {
6280       if (V1.getOpcode() == ISD::UNDEF)
6281         V1 = Op0.getOperand(0);
6282       if (i * 2 == NumElts)
6283         ExpectedVExtractIdx = BaseIdx;
6284     }
6285
6286     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6287     if (I0 == ExpectedVExtractIdx)
6288       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6289     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6290       // Try to match the following dag sequence:
6291       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6292       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6293     } else
6294       CanFold = false;
6295
6296     ExpectedVExtractIdx += 2;
6297   }
6298
6299   return CanFold;
6300 }
6301
6302 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6303 /// a concat_vector. 
6304 ///
6305 /// This is a helper function of PerformBUILD_VECTORCombine.
6306 /// This function expects two 256-bit vectors called V0 and V1.
6307 /// At first, each vector is split into two separate 128-bit vectors.
6308 /// Then, the resulting 128-bit vectors are used to implement two
6309 /// horizontal binary operations. 
6310 ///
6311 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6312 ///
6313 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6314 /// the two new horizontal binop.
6315 /// When Mode is set, the first horizontal binop dag node would take as input
6316 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6317 /// horizontal binop dag node would take as input the lower 128-bit of V1
6318 /// and the upper 128-bit of V1.
6319 ///   Example:
6320 ///     HADD V0_LO, V0_HI
6321 ///     HADD V1_LO, V1_HI
6322 ///
6323 /// Otherwise, the first horizontal binop dag node takes as input the lower
6324 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6325 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6326 ///   Example:
6327 ///     HADD V0_LO, V1_LO
6328 ///     HADD V0_HI, V1_HI
6329 ///
6330 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6331 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6332 /// the upper 128-bits of the result.
6333 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6334                                      SDLoc DL, SelectionDAG &DAG,
6335                                      unsigned X86Opcode, bool Mode,
6336                                      bool isUndefLO, bool isUndefHI) {
6337   EVT VT = V0.getValueType();
6338   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6339          "Invalid nodes in input!");
6340
6341   unsigned NumElts = VT.getVectorNumElements();
6342   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6343   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6344   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6345   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6346   EVT NewVT = V0_LO.getValueType();
6347
6348   SDValue LO = DAG.getUNDEF(NewVT);
6349   SDValue HI = DAG.getUNDEF(NewVT);
6350
6351   if (Mode) {
6352     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6353     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6354       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6355     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6356       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6357   } else {
6358     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6359     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6360                        V1_LO->getOpcode() != ISD::UNDEF))
6361       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6362
6363     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6364                        V1_HI->getOpcode() != ISD::UNDEF))
6365       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6366   }
6367
6368   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6369 }
6370
6371 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6372 /// sequence of 'vadd + vsub + blendi'.
6373 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6374                            const X86Subtarget *Subtarget) {
6375   SDLoc DL(BV);
6376   EVT VT = BV->getValueType(0);
6377   unsigned NumElts = VT.getVectorNumElements();
6378   SDValue InVec0 = DAG.getUNDEF(VT);
6379   SDValue InVec1 = DAG.getUNDEF(VT);
6380
6381   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6382           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6383
6384   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6385   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6386   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6387     return SDValue();
6388
6389   // Odd-numbered elements in the input build vector are obtained from
6390   // adding two integer/float elements.
6391   // Even-numbered elements in the input build vector are obtained from
6392   // subtracting two integer/float elements.
6393   unsigned ExpectedOpcode = ISD::FSUB;
6394   unsigned NextExpectedOpcode = ISD::FADD;
6395   bool AddFound = false;
6396   bool SubFound = false;
6397
6398   for (unsigned i = 0, e = NumElts; i != e; i++) {
6399     SDValue Op = BV->getOperand(i);
6400       
6401     // Skip 'undef' values.
6402     unsigned Opcode = Op.getOpcode();
6403     if (Opcode == ISD::UNDEF) {
6404       std::swap(ExpectedOpcode, NextExpectedOpcode);
6405       continue;
6406     }
6407       
6408     // Early exit if we found an unexpected opcode.
6409     if (Opcode != ExpectedOpcode)
6410       return SDValue();
6411
6412     SDValue Op0 = Op.getOperand(0);
6413     SDValue Op1 = Op.getOperand(1);
6414
6415     // Try to match the following pattern:
6416     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6417     // Early exit if we cannot match that sequence.
6418     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6419         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6420         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6421         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6422         Op0.getOperand(1) != Op1.getOperand(1))
6423       return SDValue();
6424
6425     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6426     if (I0 != i)
6427       return SDValue();
6428
6429     // We found a valid add/sub node. Update the information accordingly.
6430     if (i & 1)
6431       AddFound = true;
6432     else
6433       SubFound = true;
6434
6435     // Update InVec0 and InVec1.
6436     if (InVec0.getOpcode() == ISD::UNDEF)
6437       InVec0 = Op0.getOperand(0);
6438     if (InVec1.getOpcode() == ISD::UNDEF)
6439       InVec1 = Op1.getOperand(0);
6440
6441     // Make sure that operands in input to each add/sub node always
6442     // come from a same pair of vectors.
6443     if (InVec0 != Op0.getOperand(0)) {
6444       if (ExpectedOpcode == ISD::FSUB)
6445         return SDValue();
6446
6447       // FADD is commutable. Try to commute the operands
6448       // and then test again.
6449       std::swap(Op0, Op1);
6450       if (InVec0 != Op0.getOperand(0))
6451         return SDValue();
6452     }
6453
6454     if (InVec1 != Op1.getOperand(0))
6455       return SDValue();
6456
6457     // Update the pair of expected opcodes.
6458     std::swap(ExpectedOpcode, NextExpectedOpcode);
6459   }
6460
6461   // Don't try to fold this build_vector into a VSELECT if it has
6462   // too many UNDEF operands.
6463   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6464       InVec1.getOpcode() != ISD::UNDEF) {
6465     // Emit a sequence of vector add and sub followed by a VSELECT.
6466     // The new VSELECT will be lowered into a BLENDI.
6467     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6468     // and emit a single ADDSUB instruction.
6469     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6470     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6471
6472     // Construct the VSELECT mask.
6473     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6474     EVT SVT = MaskVT.getVectorElementType();
6475     unsigned SVTBits = SVT.getSizeInBits();
6476     SmallVector<SDValue, 8> Ops;
6477
6478     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6479       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6480                             APInt::getAllOnesValue(SVTBits);
6481       SDValue Constant = DAG.getConstant(Value, SVT);
6482       Ops.push_back(Constant);
6483     }
6484
6485     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6486     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6487   }
6488   
6489   return SDValue();
6490 }
6491
6492 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6493                                           const X86Subtarget *Subtarget) {
6494   SDLoc DL(N);
6495   EVT VT = N->getValueType(0);
6496   unsigned NumElts = VT.getVectorNumElements();
6497   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6498   SDValue InVec0, InVec1;
6499
6500   // Try to match an ADDSUB.
6501   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6502       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6503     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6504     if (Value.getNode())
6505       return Value;
6506   }
6507
6508   // Try to match horizontal ADD/SUB.
6509   unsigned NumUndefsLO = 0;
6510   unsigned NumUndefsHI = 0;
6511   unsigned Half = NumElts/2;
6512
6513   // Count the number of UNDEF operands in the build_vector in input.
6514   for (unsigned i = 0, e = Half; i != e; ++i)
6515     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6516       NumUndefsLO++;
6517
6518   for (unsigned i = Half, e = NumElts; i != e; ++i)
6519     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6520       NumUndefsHI++;
6521
6522   // Early exit if this is either a build_vector of all UNDEFs or all the
6523   // operands but one are UNDEF.
6524   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6525     return SDValue();
6526
6527   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6528     // Try to match an SSE3 float HADD/HSUB.
6529     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6530       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6531     
6532     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6533       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6534   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6535     // Try to match an SSSE3 integer HADD/HSUB.
6536     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6537       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6538     
6539     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6540       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6541   }
6542   
6543   if (!Subtarget->hasAVX())
6544     return SDValue();
6545
6546   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6547     // Try to match an AVX horizontal add/sub of packed single/double
6548     // precision floating point values from 256-bit vectors.
6549     SDValue InVec2, InVec3;
6550     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6551         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6552         ((InVec0.getOpcode() == ISD::UNDEF ||
6553           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6554         ((InVec1.getOpcode() == ISD::UNDEF ||
6555           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6556       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6557
6558     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6559         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6560         ((InVec0.getOpcode() == ISD::UNDEF ||
6561           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6562         ((InVec1.getOpcode() == ISD::UNDEF ||
6563           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6564       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6565   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6566     // Try to match an AVX2 horizontal add/sub of signed integers.
6567     SDValue InVec2, InVec3;
6568     unsigned X86Opcode;
6569     bool CanFold = true;
6570
6571     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6572         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6573         ((InVec0.getOpcode() == ISD::UNDEF ||
6574           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6575         ((InVec1.getOpcode() == ISD::UNDEF ||
6576           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6577       X86Opcode = X86ISD::HADD;
6578     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6579         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6580         ((InVec0.getOpcode() == ISD::UNDEF ||
6581           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6582         ((InVec1.getOpcode() == ISD::UNDEF ||
6583           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6584       X86Opcode = X86ISD::HSUB;
6585     else
6586       CanFold = false;
6587
6588     if (CanFold) {
6589       // Fold this build_vector into a single horizontal add/sub.
6590       // Do this only if the target has AVX2.
6591       if (Subtarget->hasAVX2())
6592         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6593  
6594       // Do not try to expand this build_vector into a pair of horizontal
6595       // add/sub if we can emit a pair of scalar add/sub.
6596       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6597         return SDValue();
6598
6599       // Convert this build_vector into a pair of horizontal binop followed by
6600       // a concat vector.
6601       bool isUndefLO = NumUndefsLO == Half;
6602       bool isUndefHI = NumUndefsHI == Half;
6603       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6604                                    isUndefLO, isUndefHI);
6605     }
6606   }
6607
6608   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6609        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6610     unsigned X86Opcode;
6611     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6612       X86Opcode = X86ISD::HADD;
6613     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6614       X86Opcode = X86ISD::HSUB;
6615     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6616       X86Opcode = X86ISD::FHADD;
6617     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6618       X86Opcode = X86ISD::FHSUB;
6619     else
6620       return SDValue();
6621
6622     // Don't try to expand this build_vector into a pair of horizontal add/sub
6623     // if we can simply emit a pair of scalar add/sub.
6624     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6625       return SDValue();
6626
6627     // Convert this build_vector into two horizontal add/sub followed by
6628     // a concat vector.
6629     bool isUndefLO = NumUndefsLO == Half;
6630     bool isUndefHI = NumUndefsHI == Half;
6631     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6632                                  isUndefLO, isUndefHI);
6633   }
6634
6635   return SDValue();
6636 }
6637
6638 SDValue
6639 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6640   SDLoc dl(Op);
6641
6642   MVT VT = Op.getSimpleValueType();
6643   MVT ExtVT = VT.getVectorElementType();
6644   unsigned NumElems = Op.getNumOperands();
6645
6646   // Generate vectors for predicate vectors.
6647   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6648     return LowerBUILD_VECTORvXi1(Op, DAG);
6649
6650   // Vectors containing all zeros can be matched by pxor and xorps later
6651   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6652     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6653     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6654     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6655       return Op;
6656
6657     return getZeroVector(VT, Subtarget, DAG, dl);
6658   }
6659
6660   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6661   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6662   // vpcmpeqd on 256-bit vectors.
6663   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6664     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6665       return Op;
6666
6667     if (!VT.is512BitVector())
6668       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6669   }
6670
6671   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6672   if (Broadcast.getNode())
6673     return Broadcast;
6674
6675   unsigned EVTBits = ExtVT.getSizeInBits();
6676
6677   unsigned NumZero  = 0;
6678   unsigned NumNonZero = 0;
6679   unsigned NonZeros = 0;
6680   bool IsAllConstants = true;
6681   SmallSet<SDValue, 8> Values;
6682   for (unsigned i = 0; i < NumElems; ++i) {
6683     SDValue Elt = Op.getOperand(i);
6684     if (Elt.getOpcode() == ISD::UNDEF)
6685       continue;
6686     Values.insert(Elt);
6687     if (Elt.getOpcode() != ISD::Constant &&
6688         Elt.getOpcode() != ISD::ConstantFP)
6689       IsAllConstants = false;
6690     if (X86::isZeroNode(Elt))
6691       NumZero++;
6692     else {
6693       NonZeros |= (1 << i);
6694       NumNonZero++;
6695     }
6696   }
6697
6698   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6699   if (NumNonZero == 0)
6700     return DAG.getUNDEF(VT);
6701
6702   // Special case for single non-zero, non-undef, element.
6703   if (NumNonZero == 1) {
6704     unsigned Idx = countTrailingZeros(NonZeros);
6705     SDValue Item = Op.getOperand(Idx);
6706
6707     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6708     // the value are obviously zero, truncate the value to i32 and do the
6709     // insertion that way.  Only do this if the value is non-constant or if the
6710     // value is a constant being inserted into element 0.  It is cheaper to do
6711     // a constant pool load than it is to do a movd + shuffle.
6712     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6713         (!IsAllConstants || Idx == 0)) {
6714       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6715         // Handle SSE only.
6716         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6717         EVT VecVT = MVT::v4i32;
6718         unsigned VecElts = 4;
6719
6720         // Truncate the value (which may itself be a constant) to i32, and
6721         // convert it to a vector with movd (S2V+shuffle to zero extend).
6722         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6723         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6724         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6725
6726         // Now we have our 32-bit value zero extended in the low element of
6727         // a vector.  If Idx != 0, swizzle it into place.
6728         if (Idx != 0) {
6729           SmallVector<int, 4> Mask;
6730           Mask.push_back(Idx);
6731           for (unsigned i = 1; i != VecElts; ++i)
6732             Mask.push_back(i);
6733           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6734                                       &Mask[0]);
6735         }
6736         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6737       }
6738     }
6739
6740     // If we have a constant or non-constant insertion into the low element of
6741     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6742     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6743     // depending on what the source datatype is.
6744     if (Idx == 0) {
6745       if (NumZero == 0)
6746         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6747
6748       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6749           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6750         if (VT.is256BitVector() || VT.is512BitVector()) {
6751           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6752           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6753                              Item, DAG.getIntPtrConstant(0));
6754         }
6755         assert(VT.is128BitVector() && "Expected an SSE value type!");
6756         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6757         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6758         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6759       }
6760
6761       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6762         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6763         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6764         if (VT.is256BitVector()) {
6765           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6766           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6767         } else {
6768           assert(VT.is128BitVector() && "Expected an SSE value type!");
6769           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6770         }
6771         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6772       }
6773     }
6774
6775     // Is it a vector logical left shift?
6776     if (NumElems == 2 && Idx == 1 &&
6777         X86::isZeroNode(Op.getOperand(0)) &&
6778         !X86::isZeroNode(Op.getOperand(1))) {
6779       unsigned NumBits = VT.getSizeInBits();
6780       return getVShift(true, VT,
6781                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6782                                    VT, Op.getOperand(1)),
6783                        NumBits/2, DAG, *this, dl);
6784     }
6785
6786     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6787       return SDValue();
6788
6789     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6790     // is a non-constant being inserted into an element other than the low one,
6791     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6792     // movd/movss) to move this into the low element, then shuffle it into
6793     // place.
6794     if (EVTBits == 32) {
6795       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6796
6797       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6798       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6799       SmallVector<int, 8> MaskVec;
6800       for (unsigned i = 0; i != NumElems; ++i)
6801         MaskVec.push_back(i == Idx ? 0 : 1);
6802       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6803     }
6804   }
6805
6806   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6807   if (Values.size() == 1) {
6808     if (EVTBits == 32) {
6809       // Instead of a shuffle like this:
6810       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6811       // Check if it's possible to issue this instead.
6812       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6813       unsigned Idx = countTrailingZeros(NonZeros);
6814       SDValue Item = Op.getOperand(Idx);
6815       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6816         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6817     }
6818     return SDValue();
6819   }
6820
6821   // A vector full of immediates; various special cases are already
6822   // handled, so this is best done with a single constant-pool load.
6823   if (IsAllConstants)
6824     return SDValue();
6825
6826   // For AVX-length vectors, build the individual 128-bit pieces and use
6827   // shuffles to put them in place.
6828   if (VT.is256BitVector() || VT.is512BitVector()) {
6829     SmallVector<SDValue, 64> V;
6830     for (unsigned i = 0; i != NumElems; ++i)
6831       V.push_back(Op.getOperand(i));
6832
6833     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6834
6835     // Build both the lower and upper subvector.
6836     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6837                                 makeArrayRef(&V[0], NumElems/2));
6838     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6839                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6840
6841     // Recreate the wider vector with the lower and upper part.
6842     if (VT.is256BitVector())
6843       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6844     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6845   }
6846
6847   // Let legalizer expand 2-wide build_vectors.
6848   if (EVTBits == 64) {
6849     if (NumNonZero == 1) {
6850       // One half is zero or undef.
6851       unsigned Idx = countTrailingZeros(NonZeros);
6852       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6853                                  Op.getOperand(Idx));
6854       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6855     }
6856     return SDValue();
6857   }
6858
6859   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6860   if (EVTBits == 8 && NumElems == 16) {
6861     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6862                                         Subtarget, *this);
6863     if (V.getNode()) return V;
6864   }
6865
6866   if (EVTBits == 16 && NumElems == 8) {
6867     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6868                                       Subtarget, *this);
6869     if (V.getNode()) return V;
6870   }
6871
6872   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6873   if (EVTBits == 32 && NumElems == 4) {
6874     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6875                                       NumZero, DAG, Subtarget, *this);
6876     if (V.getNode())
6877       return V;
6878   }
6879
6880   // If element VT is == 32 bits, turn it into a number of shuffles.
6881   SmallVector<SDValue, 8> V(NumElems);
6882   if (NumElems == 4 && NumZero > 0) {
6883     for (unsigned i = 0; i < 4; ++i) {
6884       bool isZero = !(NonZeros & (1 << i));
6885       if (isZero)
6886         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6887       else
6888         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6889     }
6890
6891     for (unsigned i = 0; i < 2; ++i) {
6892       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6893         default: break;
6894         case 0:
6895           V[i] = V[i*2];  // Must be a zero vector.
6896           break;
6897         case 1:
6898           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6899           break;
6900         case 2:
6901           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6902           break;
6903         case 3:
6904           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6905           break;
6906       }
6907     }
6908
6909     bool Reverse1 = (NonZeros & 0x3) == 2;
6910     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6911     int MaskVec[] = {
6912       Reverse1 ? 1 : 0,
6913       Reverse1 ? 0 : 1,
6914       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6915       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6916     };
6917     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6918   }
6919
6920   if (Values.size() > 1 && VT.is128BitVector()) {
6921     // Check for a build vector of consecutive loads.
6922     for (unsigned i = 0; i < NumElems; ++i)
6923       V[i] = Op.getOperand(i);
6924
6925     // Check for elements which are consecutive loads.
6926     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6927     if (LD.getNode())
6928       return LD;
6929
6930     // Check for a build vector from mostly shuffle plus few inserting.
6931     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6932     if (Sh.getNode())
6933       return Sh;
6934
6935     // For SSE 4.1, use insertps to put the high elements into the low element.
6936     if (getSubtarget()->hasSSE41()) {
6937       SDValue Result;
6938       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6939         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6940       else
6941         Result = DAG.getUNDEF(VT);
6942
6943       for (unsigned i = 1; i < NumElems; ++i) {
6944         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6945         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6946                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6947       }
6948       return Result;
6949     }
6950
6951     // Otherwise, expand into a number of unpckl*, start by extending each of
6952     // our (non-undef) elements to the full vector width with the element in the
6953     // bottom slot of the vector (which generates no code for SSE).
6954     for (unsigned i = 0; i < NumElems; ++i) {
6955       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6956         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6957       else
6958         V[i] = DAG.getUNDEF(VT);
6959     }
6960
6961     // Next, we iteratively mix elements, e.g. for v4f32:
6962     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6963     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6964     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6965     unsigned EltStride = NumElems >> 1;
6966     while (EltStride != 0) {
6967       for (unsigned i = 0; i < EltStride; ++i) {
6968         // If V[i+EltStride] is undef and this is the first round of mixing,
6969         // then it is safe to just drop this shuffle: V[i] is already in the
6970         // right place, the one element (since it's the first round) being
6971         // inserted as undef can be dropped.  This isn't safe for successive
6972         // rounds because they will permute elements within both vectors.
6973         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6974             EltStride == NumElems/2)
6975           continue;
6976
6977         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6978       }
6979       EltStride >>= 1;
6980     }
6981     return V[0];
6982   }
6983   return SDValue();
6984 }
6985
6986 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6987 // to create 256-bit vectors from two other 128-bit ones.
6988 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6989   SDLoc dl(Op);
6990   MVT ResVT = Op.getSimpleValueType();
6991
6992   assert((ResVT.is256BitVector() ||
6993           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6994
6995   SDValue V1 = Op.getOperand(0);
6996   SDValue V2 = Op.getOperand(1);
6997   unsigned NumElems = ResVT.getVectorNumElements();
6998   if(ResVT.is256BitVector())
6999     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7000
7001   if (Op.getNumOperands() == 4) {
7002     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7003                                 ResVT.getVectorNumElements()/2);
7004     SDValue V3 = Op.getOperand(2);
7005     SDValue V4 = Op.getOperand(3);
7006     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7007       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7008   }
7009   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7010 }
7011
7012 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7013   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7014   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7015          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7016           Op.getNumOperands() == 4)));
7017
7018   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7019   // from two other 128-bit ones.
7020
7021   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7022   return LowerAVXCONCAT_VECTORS(Op, DAG);
7023 }
7024
7025
7026 //===----------------------------------------------------------------------===//
7027 // Vector shuffle lowering
7028 //
7029 // This is an experimental code path for lowering vector shuffles on x86. It is
7030 // designed to handle arbitrary vector shuffles and blends, gracefully
7031 // degrading performance as necessary. It works hard to recognize idiomatic
7032 // shuffles and lower them to optimal instruction patterns without leaving
7033 // a framework that allows reasonably efficient handling of all vector shuffle
7034 // patterns.
7035 //===----------------------------------------------------------------------===//
7036
7037 /// \brief Tiny helper function to identify a no-op mask.
7038 ///
7039 /// This is a somewhat boring predicate function. It checks whether the mask
7040 /// array input, which is assumed to be a single-input shuffle mask of the kind
7041 /// used by the X86 shuffle instructions (not a fully general
7042 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7043 /// in-place shuffle are 'no-op's.
7044 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7045   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7046     if (Mask[i] != -1 && Mask[i] != i)
7047       return false;
7048   return true;
7049 }
7050
7051 /// \brief Helper function to classify a mask as a single-input mask.
7052 ///
7053 /// This isn't a generic single-input test because in the vector shuffle
7054 /// lowering we canonicalize single inputs to be the first input operand. This
7055 /// means we can more quickly test for a single input by only checking whether
7056 /// an input from the second operand exists. We also assume that the size of
7057 /// mask corresponds to the size of the input vectors which isn't true in the
7058 /// fully general case.
7059 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7060   for (int M : Mask)
7061     if (M >= (int)Mask.size())
7062       return false;
7063   return true;
7064 }
7065
7066 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7067 // 2013 will allow us to use it as a non-type template parameter.
7068 namespace {
7069
7070 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7071 ///
7072 /// See its documentation for details.
7073 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7074   if (Mask.size() != Args.size())
7075     return false;
7076   for (int i = 0, e = Mask.size(); i < e; ++i) {
7077     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7078     assert(*Args[i] < (int)Args.size() * 2 &&
7079            "Argument outside the range of possible shuffle inputs!");
7080     if (Mask[i] != -1 && Mask[i] != *Args[i])
7081       return false;
7082   }
7083   return true;
7084 }
7085
7086 } // namespace
7087
7088 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7089 /// arguments.
7090 ///
7091 /// This is a fast way to test a shuffle mask against a fixed pattern:
7092 ///
7093 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7094 ///
7095 /// It returns true if the mask is exactly as wide as the argument list, and
7096 /// each element of the mask is either -1 (signifying undef) or the value given
7097 /// in the argument.
7098 static const VariadicFunction1<
7099     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7100
7101 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7102 ///
7103 /// This helper function produces an 8-bit shuffle immediate corresponding to
7104 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7105 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7106 /// example.
7107 ///
7108 /// NB: We rely heavily on "undef" masks preserving the input lane.
7109 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7110                                           SelectionDAG &DAG) {
7111   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7112   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7113   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7114   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7115   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7116
7117   unsigned Imm = 0;
7118   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7119   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7120   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7121   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7122   return DAG.getConstant(Imm, MVT::i8);
7123 }
7124
7125 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7126 ///
7127 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7128 /// support for floating point shuffles but not integer shuffles. These
7129 /// instructions will incur a domain crossing penalty on some chips though so
7130 /// it is better to avoid lowering through this for integer vectors where
7131 /// possible.
7132 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7133                                        const X86Subtarget *Subtarget,
7134                                        SelectionDAG &DAG) {
7135   SDLoc DL(Op);
7136   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7137   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7138   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7139   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7140   ArrayRef<int> Mask = SVOp->getMask();
7141   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7142
7143   if (isSingleInputShuffleMask(Mask)) {
7144     // Straight shuffle of a single input vector. Simulate this by using the
7145     // single input as both of the "inputs" to this instruction..
7146     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7147     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7148                        DAG.getConstant(SHUFPDMask, MVT::i8));
7149   }
7150   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7151   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7152
7153   // Use dedicated unpack instructions for masks that match their pattern.
7154   if (isShuffleEquivalent(Mask, 0, 2))
7155     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7156   if (isShuffleEquivalent(Mask, 1, 3))
7157     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7158
7159   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7160   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7161                      DAG.getConstant(SHUFPDMask, MVT::i8));
7162 }
7163
7164 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7165 ///
7166 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7167 /// the integer unit to minimize domain crossing penalties. However, for blends
7168 /// it falls back to the floating point shuffle operation with appropriate bit
7169 /// casting.
7170 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7171                                        const X86Subtarget *Subtarget,
7172                                        SelectionDAG &DAG) {
7173   SDLoc DL(Op);
7174   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7175   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7176   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7177   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7178   ArrayRef<int> Mask = SVOp->getMask();
7179   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7180
7181   if (isSingleInputShuffleMask(Mask)) {
7182     // Straight shuffle of a single input vector. For everything from SSE2
7183     // onward this has a single fast instruction with no scary immediates.
7184     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7185     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7186     int WidenedMask[4] = {
7187         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7188         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7189     return DAG.getNode(
7190         ISD::BITCAST, DL, MVT::v2i64,
7191         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7192                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7193   }
7194
7195   // Use dedicated unpack instructions for masks that match their pattern.
7196   if (isShuffleEquivalent(Mask, 0, 2))
7197     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7198   if (isShuffleEquivalent(Mask, 1, 3))
7199     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7200
7201   // We implement this with SHUFPD which is pretty lame because it will likely
7202   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7203   // However, all the alternatives are still more cycles and newer chips don't
7204   // have this problem. It would be really nice if x86 had better shuffles here.
7205   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7206   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7207   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7208                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7209 }
7210
7211 /// \brief Lower 4-lane 32-bit floating point shuffles.
7212 ///
7213 /// Uses instructions exclusively from the floating point unit to minimize
7214 /// domain crossing penalties, as these are sufficient to implement all v4f32
7215 /// shuffles.
7216 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7217                                        const X86Subtarget *Subtarget,
7218                                        SelectionDAG &DAG) {
7219   SDLoc DL(Op);
7220   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7221   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7222   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7223   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7224   ArrayRef<int> Mask = SVOp->getMask();
7225   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7226
7227   SDValue LowV = V1, HighV = V2;
7228   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7229
7230   int NumV2Elements =
7231       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7232
7233   if (NumV2Elements == 0)
7234     // Straight shuffle of a single input vector. We pass the input vector to
7235     // both operands to simulate this with a SHUFPS.
7236     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7237                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7238
7239   // Use dedicated unpack instructions for masks that match their pattern.
7240   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7241     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7242   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7243     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7244
7245   if (NumV2Elements == 1) {
7246     int V2Index =
7247         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7248         Mask.begin();
7249     // Compute the index adjacent to V2Index and in the same half by toggling
7250     // the low bit.
7251     int V2AdjIndex = V2Index ^ 1;
7252
7253     if (Mask[V2AdjIndex] == -1) {
7254       // Handles all the cases where we have a single V2 element and an undef.
7255       // This will only ever happen in the high lanes because we commute the
7256       // vector otherwise.
7257       if (V2Index < 2)
7258         std::swap(LowV, HighV);
7259       NewMask[V2Index] -= 4;
7260     } else {
7261       // Handle the case where the V2 element ends up adjacent to a V1 element.
7262       // To make this work, blend them together as the first step.
7263       int V1Index = V2AdjIndex;
7264       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7265       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7266                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7267
7268       // Now proceed to reconstruct the final blend as we have the necessary
7269       // high or low half formed.
7270       if (V2Index < 2) {
7271         LowV = V2;
7272         HighV = V1;
7273       } else {
7274         HighV = V2;
7275       }
7276       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7277       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7278     }
7279   } else if (NumV2Elements == 2) {
7280     if (Mask[0] < 4 && Mask[1] < 4) {
7281       // Handle the easy case where we have V1 in the low lanes and V2 in the
7282       // high lanes. We never see this reversed because we sort the shuffle.
7283       NewMask[2] -= 4;
7284       NewMask[3] -= 4;
7285     } else {
7286       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7287       // trying to place elements directly, just blend them and set up the final
7288       // shuffle to place them.
7289
7290       // The first two blend mask elements are for V1, the second two are for
7291       // V2.
7292       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7293                           Mask[2] < 4 ? Mask[2] : Mask[3],
7294                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7295                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7296       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7297                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7298
7299       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7300       // a blend.
7301       LowV = HighV = V1;
7302       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7303       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7304       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7305       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7306     }
7307   }
7308   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7309                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7310 }
7311
7312 /// \brief Lower 4-lane i32 vector shuffles.
7313 ///
7314 /// We try to handle these with integer-domain shuffles where we can, but for
7315 /// blends we use the floating point domain blend instructions.
7316 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7317                                        const X86Subtarget *Subtarget,
7318                                        SelectionDAG &DAG) {
7319   SDLoc DL(Op);
7320   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7321   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7322   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7323   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7324   ArrayRef<int> Mask = SVOp->getMask();
7325   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7326
7327   if (isSingleInputShuffleMask(Mask))
7328     // Straight shuffle of a single input vector. For everything from SSE2
7329     // onward this has a single fast instruction with no scary immediates.
7330     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7331                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7332
7333   // Use dedicated unpack instructions for masks that match their pattern.
7334   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7335     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7336   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7337     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7338
7339   // We implement this with SHUFPS because it can blend from two vectors.
7340   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7341   // up the inputs, bypassing domain shift penalties that we would encur if we
7342   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7343   // relevant.
7344   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7345                      DAG.getVectorShuffle(
7346                          MVT::v4f32, DL,
7347                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7348                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7349 }
7350
7351 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7352 /// shuffle lowering, and the most complex part.
7353 ///
7354 /// The lowering strategy is to try to form pairs of input lanes which are
7355 /// targeted at the same half of the final vector, and then use a dword shuffle
7356 /// to place them onto the right half, and finally unpack the paired lanes into
7357 /// their final position.
7358 ///
7359 /// The exact breakdown of how to form these dword pairs and align them on the
7360 /// correct sides is really tricky. See the comments within the function for
7361 /// more of the details.
7362 static SDValue lowerV8I16SingleInputVectorShuffle(
7363     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7364     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7365   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7366   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7367   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7368
7369   SmallVector<int, 4> LoInputs;
7370   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7371                [](int M) { return M >= 0; });
7372   std::sort(LoInputs.begin(), LoInputs.end());
7373   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7374   SmallVector<int, 4> HiInputs;
7375   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7376                [](int M) { return M >= 0; });
7377   std::sort(HiInputs.begin(), HiInputs.end());
7378   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7379   int NumLToL =
7380       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7381   int NumHToL = LoInputs.size() - NumLToL;
7382   int NumLToH =
7383       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7384   int NumHToH = HiInputs.size() - NumLToH;
7385   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7386   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7387   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7388   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7389
7390   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7391   // such inputs we can swap two of the dwords across the half mark and end up
7392   // with <=2 inputs to each half in each half. Once there, we can fall through
7393   // to the generic code below. For example:
7394   //
7395   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7396   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7397   //
7398   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7399   // and an existing 2-into-2 on the other half. In this case we may have to
7400   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7401   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7402   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7403   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7404   // half than the one we target for fixing) will be fixed when we re-enter this
7405   // path. We will also combine away any sequence of PSHUFD instructions that
7406   // result into a single instruction. Here is an example of the tricky case:
7407   //
7408   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7409   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7410   //
7411   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7412   //
7413   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7414   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7415   //
7416   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7417   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7418   //
7419   // The result is fine to be handled by the generic logic.
7420   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7421                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7422                           int AOffset, int BOffset) {
7423     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7424            "Must call this with A having 3 or 1 inputs from the A half.");
7425     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7426            "Must call this with B having 1 or 3 inputs from the B half.");
7427     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7428            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7429
7430     // Compute the index of dword with only one word among the three inputs in
7431     // a half by taking the sum of the half with three inputs and subtracting
7432     // the sum of the actual three inputs. The difference is the remaining
7433     // slot.
7434     int ADWord, BDWord;
7435     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7436     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7437     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7438     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7439     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7440     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7441     int TripleNonInputIdx =
7442         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7443     TripleDWord = TripleNonInputIdx / 2;
7444
7445     // We use xor with one to compute the adjacent DWord to whichever one the
7446     // OneInput is in.
7447     OneInputDWord = (OneInput / 2) ^ 1;
7448
7449     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7450     // and BToA inputs. If there is also such a problem with the BToB and AToB
7451     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7452     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7453     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7454     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7455       // Compute how many inputs will be flipped by swapping these DWords. We
7456       // need
7457       // to balance this to ensure we don't form a 3-1 shuffle in the other
7458       // half.
7459       int NumFlippedAToBInputs =
7460           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7461           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7462       int NumFlippedBToBInputs =
7463           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7464           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7465       if ((NumFlippedAToBInputs == 1 &&
7466            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7467           (NumFlippedBToBInputs == 1 &&
7468            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7469         // We choose whether to fix the A half or B half based on whether that
7470         // half has zero flipped inputs. At zero, we may not be able to fix it
7471         // with that half. We also bias towards fixing the B half because that
7472         // will more commonly be the high half, and we have to bias one way.
7473         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7474                                                        ArrayRef<int> Inputs) {
7475           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7476           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7477                                          PinnedIdx ^ 1) != Inputs.end();
7478           // Determine whether the free index is in the flipped dword or the
7479           // unflipped dword based on where the pinned index is. We use this bit
7480           // in an xor to conditionally select the adjacent dword.
7481           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7482           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7483                                              FixFreeIdx) != Inputs.end();
7484           if (IsFixIdxInput == IsFixFreeIdxInput)
7485             FixFreeIdx += 1;
7486           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7487                                         FixFreeIdx) != Inputs.end();
7488           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7489                  "We need to be changing the number of flipped inputs!");
7490           int PSHUFHalfMask[] = {0, 1, 2, 3};
7491           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7492           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7493                           MVT::v8i16, V,
7494                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7495
7496           for (int &M : Mask)
7497             if (M != -1 && M == FixIdx)
7498               M = FixFreeIdx;
7499             else if (M != -1 && M == FixFreeIdx)
7500               M = FixIdx;
7501         };
7502         if (NumFlippedBToBInputs != 0) {
7503           int BPinnedIdx =
7504               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7505           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7506         } else {
7507           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7508           int APinnedIdx =
7509               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7510           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7511         }
7512       }
7513     }
7514
7515     int PSHUFDMask[] = {0, 1, 2, 3};
7516     PSHUFDMask[ADWord] = BDWord;
7517     PSHUFDMask[BDWord] = ADWord;
7518     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7519                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7520                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7521                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7522
7523     // Adjust the mask to match the new locations of A and B.
7524     for (int &M : Mask)
7525       if (M != -1 && M/2 == ADWord)
7526         M = 2 * BDWord + M % 2;
7527       else if (M != -1 && M/2 == BDWord)
7528         M = 2 * ADWord + M % 2;
7529
7530     // Recurse back into this routine to re-compute state now that this isn't
7531     // a 3 and 1 problem.
7532     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7533                                 Mask);
7534   };
7535   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7536     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7537   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7538     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7539
7540   // At this point there are at most two inputs to the low and high halves from
7541   // each half. That means the inputs can always be grouped into dwords and
7542   // those dwords can then be moved to the correct half with a dword shuffle.
7543   // We use at most one low and one high word shuffle to collect these paired
7544   // inputs into dwords, and finally a dword shuffle to place them.
7545   int PSHUFLMask[4] = {-1, -1, -1, -1};
7546   int PSHUFHMask[4] = {-1, -1, -1, -1};
7547   int PSHUFDMask[4] = {-1, -1, -1, -1};
7548
7549   // First fix the masks for all the inputs that are staying in their
7550   // original halves. This will then dictate the targets of the cross-half
7551   // shuffles.
7552   auto fixInPlaceInputs =
7553       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7554                     MutableArrayRef<int> SourceHalfMask,
7555                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7556     if (InPlaceInputs.empty())
7557       return;
7558     if (InPlaceInputs.size() == 1) {
7559       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7560           InPlaceInputs[0] - HalfOffset;
7561       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7562       return;
7563     }
7564     if (IncomingInputs.empty()) {
7565       // Just fix all of the in place inputs.
7566       for (int Input : InPlaceInputs) {
7567         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7568         PSHUFDMask[Input / 2] = Input / 2;
7569       }
7570       return;
7571     }
7572
7573     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7574     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7575         InPlaceInputs[0] - HalfOffset;
7576     // Put the second input next to the first so that they are packed into
7577     // a dword. We find the adjacent index by toggling the low bit.
7578     int AdjIndex = InPlaceInputs[0] ^ 1;
7579     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7580     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7581     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7582   };
7583   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7584   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7585
7586   // Now gather the cross-half inputs and place them into a free dword of
7587   // their target half.
7588   // FIXME: This operation could almost certainly be simplified dramatically to
7589   // look more like the 3-1 fixing operation.
7590   auto moveInputsToRightHalf = [&PSHUFDMask](
7591       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7592       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7593       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7594       int DestOffset) {
7595     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7596       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7597     };
7598     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7599                                                int Word) {
7600       int LowWord = Word & ~1;
7601       int HighWord = Word | 1;
7602       return isWordClobbered(SourceHalfMask, LowWord) ||
7603              isWordClobbered(SourceHalfMask, HighWord);
7604     };
7605
7606     if (IncomingInputs.empty())
7607       return;
7608
7609     if (ExistingInputs.empty()) {
7610       // Map any dwords with inputs from them into the right half.
7611       for (int Input : IncomingInputs) {
7612         // If the source half mask maps over the inputs, turn those into
7613         // swaps and use the swapped lane.
7614         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7615           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7616             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7617                 Input - SourceOffset;
7618             // We have to swap the uses in our half mask in one sweep.
7619             for (int &M : HalfMask)
7620               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7621                 M = Input;
7622               else if (M == Input)
7623                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7624           } else {
7625             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7626                        Input - SourceOffset &&
7627                    "Previous placement doesn't match!");
7628           }
7629           // Note that this correctly re-maps both when we do a swap and when
7630           // we observe the other side of the swap above. We rely on that to
7631           // avoid swapping the members of the input list directly.
7632           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7633         }
7634
7635         // Map the input's dword into the correct half.
7636         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7637           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7638         else
7639           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7640                      Input / 2 &&
7641                  "Previous placement doesn't match!");
7642       }
7643
7644       // And just directly shift any other-half mask elements to be same-half
7645       // as we will have mirrored the dword containing the element into the
7646       // same position within that half.
7647       for (int &M : HalfMask)
7648         if (M >= SourceOffset && M < SourceOffset + 4) {
7649           M = M - SourceOffset + DestOffset;
7650           assert(M >= 0 && "This should never wrap below zero!");
7651         }
7652       return;
7653     }
7654
7655     // Ensure we have the input in a viable dword of its current half. This
7656     // is particularly tricky because the original position may be clobbered
7657     // by inputs being moved and *staying* in that half.
7658     if (IncomingInputs.size() == 1) {
7659       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7660         int InputFixed = std::find(std::begin(SourceHalfMask),
7661                                    std::end(SourceHalfMask), -1) -
7662                          std::begin(SourceHalfMask) + SourceOffset;
7663         SourceHalfMask[InputFixed - SourceOffset] =
7664             IncomingInputs[0] - SourceOffset;
7665         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7666                      InputFixed);
7667         IncomingInputs[0] = InputFixed;
7668       }
7669     } else if (IncomingInputs.size() == 2) {
7670       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7671           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7672         // We have two non-adjacent or clobbered inputs we need to extract from
7673         // the source half. To do this, we need to map them into some adjacent
7674         // dword slot in the source mask.
7675         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7676                               IncomingInputs[1] - SourceOffset};
7677
7678         // If there is a free slot in the source half mask adjacent to one of
7679         // the inputs, place the other input in it. We use (Index XOR 1) to
7680         // compute an adjacent index.
7681         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7682             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7683           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7684           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7685           InputsFixed[1] = InputsFixed[0] ^ 1;
7686         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7687                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7688           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7689           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7690           InputsFixed[0] = InputsFixed[1] ^ 1;
7691         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7692                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7693           // The two inputs are in the same DWord but it is clobbered and the
7694           // adjacent DWord isn't used at all. Move both inputs to the free
7695           // slot.
7696           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7697           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7698           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7699           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7700         } else {
7701           // The only way we hit this point is if there is no clobbering
7702           // (because there are no off-half inputs to this half) and there is no
7703           // free slot adjacent to one of the inputs. In this case, we have to
7704           // swap an input with a non-input.
7705           for (int i = 0; i < 4; ++i)
7706             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7707                    "We can't handle any clobbers here!");
7708           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7709                  "Cannot have adjacent inputs here!");
7710
7711           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7712           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7713
7714           // We also have to update the final source mask in this case because
7715           // it may need to undo the above swap.
7716           for (int &M : FinalSourceHalfMask)
7717             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7718               M = InputsFixed[1] + SourceOffset;
7719             else if (M == InputsFixed[1] + SourceOffset)
7720               M = (InputsFixed[0] ^ 1) + SourceOffset;
7721
7722           InputsFixed[1] = InputsFixed[0] ^ 1;
7723         }
7724
7725         // Point everything at the fixed inputs.
7726         for (int &M : HalfMask)
7727           if (M == IncomingInputs[0])
7728             M = InputsFixed[0] + SourceOffset;
7729           else if (M == IncomingInputs[1])
7730             M = InputsFixed[1] + SourceOffset;
7731
7732         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7733         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7734       }
7735     } else {
7736       llvm_unreachable("Unhandled input size!");
7737     }
7738
7739     // Now hoist the DWord down to the right half.
7740     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7741     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7742     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7743     for (int &M : HalfMask)
7744       for (int Input : IncomingInputs)
7745         if (M == Input)
7746           M = FreeDWord * 2 + Input % 2;
7747   };
7748   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7749                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7750   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7751                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7752
7753   // Now enact all the shuffles we've computed to move the inputs into their
7754   // target half.
7755   if (!isNoopShuffleMask(PSHUFLMask))
7756     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7757                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7758   if (!isNoopShuffleMask(PSHUFHMask))
7759     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7760                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7761   if (!isNoopShuffleMask(PSHUFDMask))
7762     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7763                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7764                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7765                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7766
7767   // At this point, each half should contain all its inputs, and we can then
7768   // just shuffle them into their final position.
7769   assert(std::count_if(LoMask.begin(), LoMask.end(),
7770                        [](int M) { return M >= 4; }) == 0 &&
7771          "Failed to lift all the high half inputs to the low mask!");
7772   assert(std::count_if(HiMask.begin(), HiMask.end(),
7773                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7774          "Failed to lift all the low half inputs to the high mask!");
7775
7776   // Do a half shuffle for the low mask.
7777   if (!isNoopShuffleMask(LoMask))
7778     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7779                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7780
7781   // Do a half shuffle with the high mask after shifting its values down.
7782   for (int &M : HiMask)
7783     if (M >= 0)
7784       M -= 4;
7785   if (!isNoopShuffleMask(HiMask))
7786     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7787                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7788
7789   return V;
7790 }
7791
7792 /// \brief Detect whether the mask pattern should be lowered through
7793 /// interleaving.
7794 ///
7795 /// This essentially tests whether viewing the mask as an interleaving of two
7796 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7797 /// lowering it through interleaving is a significantly better strategy.
7798 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7799   int NumEvenInputs[2] = {0, 0};
7800   int NumOddInputs[2] = {0, 0};
7801   int NumLoInputs[2] = {0, 0};
7802   int NumHiInputs[2] = {0, 0};
7803   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7804     if (Mask[i] < 0)
7805       continue;
7806
7807     int InputIdx = Mask[i] >= Size;
7808
7809     if (i < Size / 2)
7810       ++NumLoInputs[InputIdx];
7811     else
7812       ++NumHiInputs[InputIdx];
7813
7814     if ((i % 2) == 0)
7815       ++NumEvenInputs[InputIdx];
7816     else
7817       ++NumOddInputs[InputIdx];
7818   }
7819
7820   // The minimum number of cross-input results for both the interleaved and
7821   // split cases. If interleaving results in fewer cross-input results, return
7822   // true.
7823   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7824                                     NumEvenInputs[0] + NumOddInputs[1]);
7825   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7826                               NumLoInputs[0] + NumHiInputs[1]);
7827   return InterleavedCrosses < SplitCrosses;
7828 }
7829
7830 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7831 ///
7832 /// This strategy only works when the inputs from each vector fit into a single
7833 /// half of that vector, and generally there are not so many inputs as to leave
7834 /// the in-place shuffles required highly constrained (and thus expensive). It
7835 /// shifts all the inputs into a single side of both input vectors and then
7836 /// uses an unpack to interleave these inputs in a single vector. At that
7837 /// point, we will fall back on the generic single input shuffle lowering.
7838 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7839                                                  SDValue V2,
7840                                                  MutableArrayRef<int> Mask,
7841                                                  const X86Subtarget *Subtarget,
7842                                                  SelectionDAG &DAG) {
7843   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7844   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7845   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7846   for (int i = 0; i < 8; ++i)
7847     if (Mask[i] >= 0 && Mask[i] < 4)
7848       LoV1Inputs.push_back(i);
7849     else if (Mask[i] >= 4 && Mask[i] < 8)
7850       HiV1Inputs.push_back(i);
7851     else if (Mask[i] >= 8 && Mask[i] < 12)
7852       LoV2Inputs.push_back(i);
7853     else if (Mask[i] >= 12)
7854       HiV2Inputs.push_back(i);
7855
7856   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7857   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7858   (void)NumV1Inputs;
7859   (void)NumV2Inputs;
7860   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7861   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7862   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7863
7864   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7865                      HiV1Inputs.size() + HiV2Inputs.size();
7866
7867   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7868                               ArrayRef<int> HiInputs, bool MoveToLo,
7869                               int MaskOffset) {
7870     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7871     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7872     if (BadInputs.empty())
7873       return V;
7874
7875     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7876     int MoveOffset = MoveToLo ? 0 : 4;
7877
7878     if (GoodInputs.empty()) {
7879       for (int BadInput : BadInputs) {
7880         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7881         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7882       }
7883     } else {
7884       if (GoodInputs.size() == 2) {
7885         // If the low inputs are spread across two dwords, pack them into
7886         // a single dword.
7887         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7888         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7889         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7890         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7891       } else {
7892         // Otherwise pin the good inputs.
7893         for (int GoodInput : GoodInputs)
7894           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7895       }
7896
7897       if (BadInputs.size() == 2) {
7898         // If we have two bad inputs then there may be either one or two good
7899         // inputs fixed in place. Find a fixed input, and then find the *other*
7900         // two adjacent indices by using modular arithmetic.
7901         int GoodMaskIdx =
7902             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7903                          [](int M) { return M >= 0; }) -
7904             std::begin(MoveMask);
7905         int MoveMaskIdx =
7906             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
7907         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7908         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7909         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7910         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7911         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7912         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7913       } else {
7914         assert(BadInputs.size() == 1 && "All sizes handled");
7915         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7916                                     std::end(MoveMask), -1) -
7917                           std::begin(MoveMask);
7918         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7919         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7920       }
7921     }
7922
7923     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7924                                 MoveMask);
7925   };
7926   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7927                         /*MaskOffset*/ 0);
7928   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7929                         /*MaskOffset*/ 8);
7930
7931   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7932   // cross-half traffic in the final shuffle.
7933
7934   // Munge the mask to be a single-input mask after the unpack merges the
7935   // results.
7936   for (int &M : Mask)
7937     if (M != -1)
7938       M = 2 * (M % 4) + (M / 8);
7939
7940   return DAG.getVectorShuffle(
7941       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7942                                   DL, MVT::v8i16, V1, V2),
7943       DAG.getUNDEF(MVT::v8i16), Mask);
7944 }
7945
7946 /// \brief Generic lowering of 8-lane i16 shuffles.
7947 ///
7948 /// This handles both single-input shuffles and combined shuffle/blends with
7949 /// two inputs. The single input shuffles are immediately delegated to
7950 /// a dedicated lowering routine.
7951 ///
7952 /// The blends are lowered in one of three fundamental ways. If there are few
7953 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7954 /// of the input is significantly cheaper when lowered as an interleaving of
7955 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7956 /// halves of the inputs separately (making them have relatively few inputs)
7957 /// and then concatenate them.
7958 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7959                                        const X86Subtarget *Subtarget,
7960                                        SelectionDAG &DAG) {
7961   SDLoc DL(Op);
7962   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7963   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7964   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7965   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7966   ArrayRef<int> OrigMask = SVOp->getMask();
7967   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7968                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7969   MutableArrayRef<int> Mask(MaskStorage);
7970
7971   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7972
7973   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7974   auto isV2 = [](int M) { return M >= 8; };
7975
7976   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7977   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7978
7979   if (NumV2Inputs == 0)
7980     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7981
7982   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7983                             "to be V1-input shuffles.");
7984
7985   if (NumV1Inputs + NumV2Inputs <= 4)
7986     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7987
7988   // Check whether an interleaving lowering is likely to be more efficient.
7989   // This isn't perfect but it is a strong heuristic that tends to work well on
7990   // the kinds of shuffles that show up in practice.
7991   //
7992   // FIXME: Handle 1x, 2x, and 4x interleaving.
7993   if (shouldLowerAsInterleaving(Mask)) {
7994     // FIXME: Figure out whether we should pack these into the low or high
7995     // halves.
7996
7997     int EMask[8], OMask[8];
7998     for (int i = 0; i < 4; ++i) {
7999       EMask[i] = Mask[2*i];
8000       OMask[i] = Mask[2*i + 1];
8001       EMask[i + 4] = -1;
8002       OMask[i + 4] = -1;
8003     }
8004
8005     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8006     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8007
8008     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8009   }
8010
8011   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8012   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8013
8014   for (int i = 0; i < 4; ++i) {
8015     LoBlendMask[i] = Mask[i];
8016     HiBlendMask[i] = Mask[i + 4];
8017   }
8018
8019   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8020   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8021   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8022   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8023
8024   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8025                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8026 }
8027
8028 /// \brief Check whether a compaction lowering can be done by dropping even
8029 /// elements and compute how many times even elements must be dropped.
8030 ///
8031 /// This handles shuffles which take every Nth element where N is a power of
8032 /// two. Example shuffle masks:
8033 ///
8034 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8035 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8036 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8037 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8038 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8039 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8040 ///
8041 /// Any of these lanes can of course be undef.
8042 ///
8043 /// This routine only supports N <= 3.
8044 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8045 /// for larger N.
8046 ///
8047 /// \returns N above, or the number of times even elements must be dropped if
8048 /// there is such a number. Otherwise returns zero.
8049 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8050   // Figure out whether we're looping over two inputs or just one.
8051   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8052
8053   // The modulus for the shuffle vector entries is based on whether this is
8054   // a single input or not.
8055   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8056   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8057          "We should only be called with masks with a power-of-2 size!");
8058
8059   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8060
8061   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8062   // and 2^3 simultaneously. This is because we may have ambiguity with
8063   // partially undef inputs.
8064   bool ViableForN[3] = {true, true, true};
8065
8066   for (int i = 0, e = Mask.size(); i < e; ++i) {
8067     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8068     // want.
8069     if (Mask[i] == -1)
8070       continue;
8071
8072     bool IsAnyViable = false;
8073     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8074       if (ViableForN[j]) {
8075         uint64_t N = j + 1;
8076
8077         // The shuffle mask must be equal to (i * 2^N) % M.
8078         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8079           IsAnyViable = true;
8080         else
8081           ViableForN[j] = false;
8082       }
8083     // Early exit if we exhaust the possible powers of two.
8084     if (!IsAnyViable)
8085       break;
8086   }
8087
8088   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8089     if (ViableForN[j])
8090       return j + 1;
8091
8092   // Return 0 as there is no viable power of two.
8093   return 0;
8094 }
8095
8096 /// \brief Generic lowering of v16i8 shuffles.
8097 ///
8098 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8099 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8100 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8101 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8102 /// back together.
8103 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8104                                        const X86Subtarget *Subtarget,
8105                                        SelectionDAG &DAG) {
8106   SDLoc DL(Op);
8107   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8108   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8109   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8110   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8111   ArrayRef<int> OrigMask = SVOp->getMask();
8112   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8113   int MaskStorage[16] = {
8114       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8115       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8116       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8117       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8118   MutableArrayRef<int> Mask(MaskStorage);
8119   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8120   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8121
8122   // For single-input shuffles, there are some nicer lowering tricks we can use.
8123   if (isSingleInputShuffleMask(Mask)) {
8124     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8125     // Notably, this handles splat and partial-splat shuffles more efficiently.
8126     // However, it only makes sense if the pre-duplication shuffle simplifies
8127     // things significantly. Currently, this means we need to be able to
8128     // express the pre-duplication shuffle as an i16 shuffle.
8129     //
8130     // FIXME: We should check for other patterns which can be widened into an
8131     // i16 shuffle as well.
8132     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8133       for (int i = 0; i < 16; i += 2) {
8134         if (Mask[i] != Mask[i + 1])
8135           return false;
8136       }
8137       return true;
8138     };
8139     auto tryToWidenViaDuplication = [&]() -> SDValue {
8140       if (!canWidenViaDuplication(Mask))
8141         return SDValue();
8142       SmallVector<int, 4> LoInputs;
8143       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8144                    [](int M) { return M >= 0 && M < 8; });
8145       std::sort(LoInputs.begin(), LoInputs.end());
8146       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8147                      LoInputs.end());
8148       SmallVector<int, 4> HiInputs;
8149       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8150                    [](int M) { return M >= 8; });
8151       std::sort(HiInputs.begin(), HiInputs.end());
8152       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8153                      HiInputs.end());
8154
8155       bool TargetLo = LoInputs.size() >= HiInputs.size();
8156       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8157       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8158
8159       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8160       SmallDenseMap<int, int, 8> LaneMap;
8161       for (int I : InPlaceInputs) {
8162         PreDupI16Shuffle[I/2] = I/2;
8163         LaneMap[I] = I;
8164       }
8165       int j = TargetLo ? 0 : 4, je = j + 4;
8166       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8167         // Check if j is already a shuffle of this input. This happens when
8168         // there are two adjacent bytes after we move the low one.
8169         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8170           // If we haven't yet mapped the input, search for a slot into which
8171           // we can map it.
8172           while (j < je && PreDupI16Shuffle[j] != -1)
8173             ++j;
8174
8175           if (j == je)
8176             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8177             return SDValue();
8178
8179           // Map this input with the i16 shuffle.
8180           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8181         }
8182
8183         // Update the lane map based on the mapping we ended up with.
8184         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8185       }
8186       V1 = DAG.getNode(
8187           ISD::BITCAST, DL, MVT::v16i8,
8188           DAG.getVectorShuffle(MVT::v8i16, DL,
8189                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8190                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8191
8192       // Unpack the bytes to form the i16s that will be shuffled into place.
8193       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8194                        MVT::v16i8, V1, V1);
8195
8196       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8197       for (int i = 0; i < 16; i += 2) {
8198         if (Mask[i] != -1)
8199           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8200         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8201       }
8202       return DAG.getNode(
8203           ISD::BITCAST, DL, MVT::v16i8,
8204           DAG.getVectorShuffle(MVT::v8i16, DL,
8205                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8206                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8207     };
8208     if (SDValue V = tryToWidenViaDuplication())
8209       return V;
8210   }
8211
8212   // Check whether an interleaving lowering is likely to be more efficient.
8213   // This isn't perfect but it is a strong heuristic that tends to work well on
8214   // the kinds of shuffles that show up in practice.
8215   //
8216   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8217   if (shouldLowerAsInterleaving(Mask)) {
8218     // FIXME: Figure out whether we should pack these into the low or high
8219     // halves.
8220
8221     int EMask[16], OMask[16];
8222     for (int i = 0; i < 8; ++i) {
8223       EMask[i] = Mask[2*i];
8224       OMask[i] = Mask[2*i + 1];
8225       EMask[i + 8] = -1;
8226       OMask[i + 8] = -1;
8227     }
8228
8229     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8230     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8231
8232     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8233   }
8234
8235   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8236   // with PSHUFB. It is important to do this before we attempt to generate any
8237   // blends but after all of the single-input lowerings. If the single input
8238   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8239   // want to preserve that and we can DAG combine any longer sequences into
8240   // a PSHUFB in the end. But once we start blending from multiple inputs,
8241   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8242   // and there are *very* few patterns that would actually be faster than the
8243   // PSHUFB approach because of its ability to zero lanes.
8244   //
8245   // FIXME: The only exceptions to the above are blends which are exact
8246   // interleavings with direct instructions supporting them. We currently don't
8247   // handle those well here.
8248   if (Subtarget->hasSSSE3()) {
8249     SDValue V1Mask[16];
8250     SDValue V2Mask[16];
8251     for (int i = 0; i < 16; ++i)
8252       if (Mask[i] == -1) {
8253         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8254       } else {
8255         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8256         V2Mask[i] =
8257             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8258       }
8259     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8260                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8261     if (isSingleInputShuffleMask(Mask))
8262       return V1; // Single inputs are easy.
8263
8264     // Otherwise, blend the two.
8265     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8266                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8267     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8268   }
8269
8270   // Check whether a compaction lowering can be done. This handles shuffles
8271   // which take every Nth element for some even N. See the helper function for
8272   // details.
8273   //
8274   // We special case these as they can be particularly efficiently handled with
8275   // the PACKUSB instruction on x86 and they show up in common patterns of
8276   // rearranging bytes to truncate wide elements.
8277   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8278     // NumEvenDrops is the power of two stride of the elements. Another way of
8279     // thinking about it is that we need to drop the even elements this many
8280     // times to get the original input.
8281     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8282
8283     // First we need to zero all the dropped bytes.
8284     assert(NumEvenDrops <= 3 &&
8285            "No support for dropping even elements more than 3 times.");
8286     // We use the mask type to pick which bytes are preserved based on how many
8287     // elements are dropped.
8288     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8289     SDValue ByteClearMask =
8290         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8291                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8292     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8293     if (!IsSingleInput)
8294       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8295
8296     // Now pack things back together.
8297     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8298     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8299     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8300     for (int i = 1; i < NumEvenDrops; ++i) {
8301       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8302       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8303     }
8304
8305     return Result;
8306   }
8307
8308   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8309   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8310   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8311   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8312
8313   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8314                             MutableArrayRef<int> V1HalfBlendMask,
8315                             MutableArrayRef<int> V2HalfBlendMask) {
8316     for (int i = 0; i < 8; ++i)
8317       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8318         V1HalfBlendMask[i] = HalfMask[i];
8319         HalfMask[i] = i;
8320       } else if (HalfMask[i] >= 16) {
8321         V2HalfBlendMask[i] = HalfMask[i] - 16;
8322         HalfMask[i] = i + 8;
8323       }
8324   };
8325   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8326   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8327
8328   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8329
8330   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8331                              MutableArrayRef<int> HiBlendMask) {
8332     SDValue V1, V2;
8333     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8334     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8335     // i16s.
8336     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8337                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8338         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8339                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8340       // Use a mask to drop the high bytes.
8341       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8342       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8343                        DAG.getConstant(0x00FF, MVT::v8i16));
8344
8345       // This will be a single vector shuffle instead of a blend so nuke V2.
8346       V2 = DAG.getUNDEF(MVT::v8i16);
8347
8348       // Squash the masks to point directly into V1.
8349       for (int &M : LoBlendMask)
8350         if (M >= 0)
8351           M /= 2;
8352       for (int &M : HiBlendMask)
8353         if (M >= 0)
8354           M /= 2;
8355     } else {
8356       // Otherwise just unpack the low half of V into V1 and the high half into
8357       // V2 so that we can blend them as i16s.
8358       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8359                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8360       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8361                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8362     }
8363
8364     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8365     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8366     return std::make_pair(BlendedLo, BlendedHi);
8367   };
8368   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8369   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8370   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8371
8372   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8373   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8374
8375   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8376 }
8377
8378 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8379 ///
8380 /// This routine breaks down the specific type of 128-bit shuffle and
8381 /// dispatches to the lowering routines accordingly.
8382 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8383                                         MVT VT, const X86Subtarget *Subtarget,
8384                                         SelectionDAG &DAG) {
8385   switch (VT.SimpleTy) {
8386   case MVT::v2i64:
8387     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8388   case MVT::v2f64:
8389     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8390   case MVT::v4i32:
8391     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8392   case MVT::v4f32:
8393     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8394   case MVT::v8i16:
8395     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8396   case MVT::v16i8:
8397     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8398
8399   default:
8400     llvm_unreachable("Unimplemented!");
8401   }
8402 }
8403
8404 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8405   int Size = Mask.size();
8406   for (int M : Mask.slice(0, Size / 2))
8407     if (M >= 0 && (M % Size) >= Size / 2)
8408       return true;
8409   for (int M : Mask.slice(Size / 2, Size / 2))
8410     if (M >= 0 && (M % Size) < Size / 2)
8411       return true;
8412   return false;
8413 }
8414
8415 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8416 /// shuffles.
8417 ///
8418 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8419 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8420 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8421 /// we encode the logic here for specific shuffle lowering routines to bail to
8422 /// when they exhaust the features avaible to more directly handle the shuffle.
8423 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8424                                                 SDValue V2,
8425                                                 const X86Subtarget *Subtarget,
8426                                                 SelectionDAG &DAG) {
8427   SDLoc DL(Op);
8428   MVT VT = Op.getSimpleValueType();
8429   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8430   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8431   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8432   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8433   ArrayRef<int> Mask = SVOp->getMask();
8434
8435   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8436   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8437
8438   int NumElements = VT.getVectorNumElements();
8439   int SplitNumElements = NumElements / 2;
8440   MVT ScalarVT = VT.getScalarType();
8441   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8442
8443   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8444                              DAG.getIntPtrConstant(0));
8445   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8446                              DAG.getIntPtrConstant(SplitNumElements));
8447   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8448                              DAG.getIntPtrConstant(0));
8449   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8450                              DAG.getIntPtrConstant(SplitNumElements));
8451
8452   // Now create two 4-way blends of these half-width vectors.
8453   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8454     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8455     for (int i = 0; i < SplitNumElements; ++i) {
8456       int M = HalfMask[i];
8457       if (M >= NumElements) {
8458         V2BlendMask.push_back(M - NumElements);
8459         V1BlendMask.push_back(-1);
8460         BlendMask.push_back(SplitNumElements + i);
8461       } else if (M >= 0) {
8462         V2BlendMask.push_back(-1);
8463         V1BlendMask.push_back(M);
8464         BlendMask.push_back(i);
8465       } else {
8466         V2BlendMask.push_back(-1);
8467         V1BlendMask.push_back(-1);
8468         BlendMask.push_back(-1);
8469       }
8470     }
8471     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8472     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8473     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8474   };
8475   SDValue Lo = HalfBlend(LoMask);
8476   SDValue Hi = HalfBlend(HiMask);
8477   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8478 }
8479
8480 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8481 ///
8482 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8483 /// isn't available.
8484 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8485                                        const X86Subtarget *Subtarget,
8486                                        SelectionDAG &DAG) {
8487   SDLoc DL(Op);
8488   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8489   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8490   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8491   ArrayRef<int> Mask = SVOp->getMask();
8492   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8493
8494   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8495   // shuffles aren't a problem and FP and int have the same patterns.
8496
8497   // FIXME: We can handle these more cleverly than splitting for v4f64.
8498   if (isHalfCrossingShuffleMask(Mask))
8499     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8500
8501   if (isSingleInputShuffleMask(Mask)) {
8502     // Non-half-crossing single input shuffles can be lowerid with an
8503     // interleaved permutation.
8504     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8505                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8506     return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8507                        DAG.getConstant(VPERMILPMask, MVT::i8));
8508   }
8509
8510   // X86 has dedicated unpack instructions that can handle specific blend
8511   // operations: UNPCKH and UNPCKL.
8512   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8513     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8514   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8515     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8516   // FIXME: It would be nice to find a way to get canonicalization to commute
8517   // these patterns.
8518   if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8519     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8520   if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8521     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8522
8523   // Check if the blend happens to exactly fit that of SHUFPD.
8524   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8525       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8526     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8527                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8528     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8529                        DAG.getConstant(SHUFPDMask, MVT::i8));
8530   }
8531   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8532       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8533     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8534                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8535     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8536                        DAG.getConstant(SHUFPDMask, MVT::i8));
8537   }
8538
8539   // Shuffle the input elements into the desired positions in V1 and V2 and
8540   // blend them together.
8541   int V1Mask[] = {-1, -1, -1, -1};
8542   int V2Mask[] = {-1, -1, -1, -1};
8543   for (int i = 0; i < 4; ++i)
8544     if (Mask[i] >= 0 && Mask[i] < 4)
8545       V1Mask[i] = Mask[i];
8546     else if (Mask[i] >= 4)
8547       V2Mask[i] = Mask[i] - 4;
8548
8549   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8550   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8551
8552   unsigned BlendMask = 0;
8553   for (int i = 0; i < 4; ++i)
8554     if (Mask[i] >= 4)
8555       BlendMask |= 1 << i;
8556
8557   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8558                      DAG.getConstant(BlendMask, MVT::i8));
8559 }
8560
8561 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8562 ///
8563 /// Largely delegates to common code when we have AVX2 and to the floating-point
8564 /// code when we only have AVX.
8565 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8566                                        const X86Subtarget *Subtarget,
8567                                        SelectionDAG &DAG) {
8568   SDLoc DL(Op);
8569   assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8570   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8571   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8572   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8573   ArrayRef<int> Mask = SVOp->getMask();
8574   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8575
8576   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8577   // shuffles aren't a problem and FP and int have the same patterns.
8578
8579   if (isHalfCrossingShuffleMask(Mask))
8580     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8581
8582   // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8583   // delegate to floating point code.
8584   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8585   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8586   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8587                      lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8588 }
8589
8590 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8591 ///
8592 /// This routine either breaks down the specific type of a 256-bit x86 vector
8593 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8594 /// together based on the available instructions.
8595 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8596                                         MVT VT, const X86Subtarget *Subtarget,
8597                                         SelectionDAG &DAG) {
8598   switch (VT.SimpleTy) {
8599   case MVT::v4f64:
8600     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8601   case MVT::v4i64:
8602     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8603   case MVT::v8i32:
8604   case MVT::v8f32:
8605   case MVT::v16i16:
8606   case MVT::v32i8:
8607     // Fall back to the basic pattern of extracting the high half and forming
8608     // a 4-way blend.
8609     // FIXME: Add targeted lowering for each type that can document rationale
8610     // for delegating to this when necessary.
8611     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8612
8613   default:
8614     llvm_unreachable("Not a valid 256-bit x86 vector type!");
8615   }
8616 }
8617
8618 /// \brief Tiny helper function to test whether a shuffle mask could be
8619 /// simplified by widening the elements being shuffled.
8620 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8621   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8622     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8623       return false;
8624
8625   return true;
8626 }
8627
8628 /// \brief Top-level lowering for x86 vector shuffles.
8629 ///
8630 /// This handles decomposition, canonicalization, and lowering of all x86
8631 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8632 /// above in helper routines. The canonicalization attempts to widen shuffles
8633 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8634 /// s.t. only one of the two inputs needs to be tested, etc.
8635 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8636                                   SelectionDAG &DAG) {
8637   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8638   ArrayRef<int> Mask = SVOp->getMask();
8639   SDValue V1 = Op.getOperand(0);
8640   SDValue V2 = Op.getOperand(1);
8641   MVT VT = Op.getSimpleValueType();
8642   int NumElements = VT.getVectorNumElements();
8643   SDLoc dl(Op);
8644
8645   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8646
8647   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8648   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8649   if (V1IsUndef && V2IsUndef)
8650     return DAG.getUNDEF(VT);
8651
8652   // When we create a shuffle node we put the UNDEF node to second operand,
8653   // but in some cases the first operand may be transformed to UNDEF.
8654   // In this case we should just commute the node.
8655   if (V1IsUndef)
8656     return DAG.getCommutedVectorShuffle(*SVOp);
8657
8658   // Check for non-undef masks pointing at an undef vector and make the masks
8659   // undef as well. This makes it easier to match the shuffle based solely on
8660   // the mask.
8661   if (V2IsUndef)
8662     for (int M : Mask)
8663       if (M >= NumElements) {
8664         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8665         for (int &M : NewMask)
8666           if (M >= NumElements)
8667             M = -1;
8668         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8669       }
8670
8671   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8672   // lanes but wider integers. We cap this to not form integers larger than i64
8673   // but it might be interesting to form i128 integers to handle flipping the
8674   // low and high halves of AVX 256-bit vectors.
8675   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8676       canWidenShuffleElements(Mask)) {
8677     SmallVector<int, 8> NewMask;
8678     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8679       NewMask.push_back(Mask[i] / 2);
8680     MVT NewVT =
8681         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8682                          VT.getVectorNumElements() / 2);
8683     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8684     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8685     return DAG.getNode(ISD::BITCAST, dl, VT,
8686                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8687   }
8688
8689   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8690   for (int M : SVOp->getMask())
8691     if (M < 0)
8692       ++NumUndefElements;
8693     else if (M < NumElements)
8694       ++NumV1Elements;
8695     else
8696       ++NumV2Elements;
8697
8698   // Commute the shuffle as needed such that more elements come from V1 than
8699   // V2. This allows us to match the shuffle pattern strictly on how many
8700   // elements come from V1 without handling the symmetric cases.
8701   if (NumV2Elements > NumV1Elements)
8702     return DAG.getCommutedVectorShuffle(*SVOp);
8703
8704   // When the number of V1 and V2 elements are the same, try to minimize the
8705   // number of uses of V2 in the low half of the vector.
8706   if (NumV1Elements == NumV2Elements) {
8707     int LowV1Elements = 0, LowV2Elements = 0;
8708     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8709       if (M >= NumElements)
8710         ++LowV2Elements;
8711       else if (M >= 0)
8712         ++LowV1Elements;
8713     if (LowV2Elements > LowV1Elements)
8714       return DAG.getCommutedVectorShuffle(*SVOp);
8715   }
8716
8717   // For each vector width, delegate to a specialized lowering routine.
8718   if (VT.getSizeInBits() == 128)
8719     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8720
8721   if (VT.getSizeInBits() == 256)
8722     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8723
8724   llvm_unreachable("Unimplemented!");
8725 }
8726
8727
8728 //===----------------------------------------------------------------------===//
8729 // Legacy vector shuffle lowering
8730 //
8731 // This code is the legacy code handling vector shuffles until the above
8732 // replaces its functionality and performance.
8733 //===----------------------------------------------------------------------===//
8734
8735 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8736                         bool hasInt256, unsigned *MaskOut = nullptr) {
8737   MVT EltVT = VT.getVectorElementType();
8738
8739   // There is no blend with immediate in AVX-512.
8740   if (VT.is512BitVector())
8741     return false;
8742
8743   if (!hasSSE41 || EltVT == MVT::i8)
8744     return false;
8745   if (!hasInt256 && VT == MVT::v16i16)
8746     return false;
8747
8748   unsigned MaskValue = 0;
8749   unsigned NumElems = VT.getVectorNumElements();
8750   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8751   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8752   unsigned NumElemsInLane = NumElems / NumLanes;
8753
8754   // Blend for v16i16 should be symetric for the both lanes.
8755   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8756
8757     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8758     int EltIdx = MaskVals[i];
8759
8760     if ((EltIdx < 0 || EltIdx == (int)i) &&
8761         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8762       continue;
8763
8764     if (((unsigned)EltIdx == (i + NumElems)) &&
8765         (SndLaneEltIdx < 0 ||
8766          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8767       MaskValue |= (1 << i);
8768     else
8769       return false;
8770   }
8771
8772   if (MaskOut)
8773     *MaskOut = MaskValue;
8774   return true;
8775 }
8776
8777 // Try to lower a shuffle node into a simple blend instruction.
8778 // This function assumes isBlendMask returns true for this
8779 // SuffleVectorSDNode
8780 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8781                                           unsigned MaskValue,
8782                                           const X86Subtarget *Subtarget,
8783                                           SelectionDAG &DAG) {
8784   MVT VT = SVOp->getSimpleValueType(0);
8785   MVT EltVT = VT.getVectorElementType();
8786   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8787                      Subtarget->hasInt256() && "Trying to lower a "
8788                                                "VECTOR_SHUFFLE to a Blend but "
8789                                                "with the wrong mask"));
8790   SDValue V1 = SVOp->getOperand(0);
8791   SDValue V2 = SVOp->getOperand(1);
8792   SDLoc dl(SVOp);
8793   unsigned NumElems = VT.getVectorNumElements();
8794
8795   // Convert i32 vectors to floating point if it is not AVX2.
8796   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8797   MVT BlendVT = VT;
8798   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8799     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8800                                NumElems);
8801     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8802     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8803   }
8804
8805   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8806                             DAG.getConstant(MaskValue, MVT::i32));
8807   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8808 }
8809
8810 /// In vector type \p VT, return true if the element at index \p InputIdx
8811 /// falls on a different 128-bit lane than \p OutputIdx.
8812 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8813                                      unsigned OutputIdx) {
8814   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8815   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8816 }
8817
8818 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8819 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8820 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8821 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8822 /// zero.
8823 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8824                          SelectionDAG &DAG) {
8825   MVT VT = V1.getSimpleValueType();
8826   assert(VT.is128BitVector() || VT.is256BitVector());
8827
8828   MVT EltVT = VT.getVectorElementType();
8829   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8830   unsigned NumElts = VT.getVectorNumElements();
8831
8832   SmallVector<SDValue, 32> PshufbMask;
8833   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8834     int InputIdx = MaskVals[OutputIdx];
8835     unsigned InputByteIdx;
8836
8837     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8838       InputByteIdx = 0x80;
8839     else {
8840       // Cross lane is not allowed.
8841       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8842         return SDValue();
8843       InputByteIdx = InputIdx * EltSizeInBytes;
8844       // Index is an byte offset within the 128-bit lane.
8845       InputByteIdx &= 0xf;
8846     }
8847
8848     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8849       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8850       if (InputByteIdx != 0x80)
8851         ++InputByteIdx;
8852     }
8853   }
8854
8855   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8856   if (ShufVT != VT)
8857     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8858   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8859                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8860 }
8861
8862 // v8i16 shuffles - Prefer shuffles in the following order:
8863 // 1. [all]   pshuflw, pshufhw, optional move
8864 // 2. [ssse3] 1 x pshufb
8865 // 3. [ssse3] 2 x pshufb + 1 x por
8866 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8867 static SDValue
8868 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8869                          SelectionDAG &DAG) {
8870   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8871   SDValue V1 = SVOp->getOperand(0);
8872   SDValue V2 = SVOp->getOperand(1);
8873   SDLoc dl(SVOp);
8874   SmallVector<int, 8> MaskVals;
8875
8876   // Determine if more than 1 of the words in each of the low and high quadwords
8877   // of the result come from the same quadword of one of the two inputs.  Undef
8878   // mask values count as coming from any quadword, for better codegen.
8879   //
8880   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8881   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8882   unsigned LoQuad[] = { 0, 0, 0, 0 };
8883   unsigned HiQuad[] = { 0, 0, 0, 0 };
8884   // Indices of quads used.
8885   std::bitset<4> InputQuads;
8886   for (unsigned i = 0; i < 8; ++i) {
8887     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8888     int EltIdx = SVOp->getMaskElt(i);
8889     MaskVals.push_back(EltIdx);
8890     if (EltIdx < 0) {
8891       ++Quad[0];
8892       ++Quad[1];
8893       ++Quad[2];
8894       ++Quad[3];
8895       continue;
8896     }
8897     ++Quad[EltIdx / 4];
8898     InputQuads.set(EltIdx / 4);
8899   }
8900
8901   int BestLoQuad = -1;
8902   unsigned MaxQuad = 1;
8903   for (unsigned i = 0; i < 4; ++i) {
8904     if (LoQuad[i] > MaxQuad) {
8905       BestLoQuad = i;
8906       MaxQuad = LoQuad[i];
8907     }
8908   }
8909
8910   int BestHiQuad = -1;
8911   MaxQuad = 1;
8912   for (unsigned i = 0; i < 4; ++i) {
8913     if (HiQuad[i] > MaxQuad) {
8914       BestHiQuad = i;
8915       MaxQuad = HiQuad[i];
8916     }
8917   }
8918
8919   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8920   // of the two input vectors, shuffle them into one input vector so only a
8921   // single pshufb instruction is necessary. If there are more than 2 input
8922   // quads, disable the next transformation since it does not help SSSE3.
8923   bool V1Used = InputQuads[0] || InputQuads[1];
8924   bool V2Used = InputQuads[2] || InputQuads[3];
8925   if (Subtarget->hasSSSE3()) {
8926     if (InputQuads.count() == 2 && V1Used && V2Used) {
8927       BestLoQuad = InputQuads[0] ? 0 : 1;
8928       BestHiQuad = InputQuads[2] ? 2 : 3;
8929     }
8930     if (InputQuads.count() > 2) {
8931       BestLoQuad = -1;
8932       BestHiQuad = -1;
8933     }
8934   }
8935
8936   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8937   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8938   // words from all 4 input quadwords.
8939   SDValue NewV;
8940   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8941     int MaskV[] = {
8942       BestLoQuad < 0 ? 0 : BestLoQuad,
8943       BestHiQuad < 0 ? 1 : BestHiQuad
8944     };
8945     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8946                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8947                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8948     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8949
8950     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8951     // source words for the shuffle, to aid later transformations.
8952     bool AllWordsInNewV = true;
8953     bool InOrder[2] = { true, true };
8954     for (unsigned i = 0; i != 8; ++i) {
8955       int idx = MaskVals[i];
8956       if (idx != (int)i)
8957         InOrder[i/4] = false;
8958       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8959         continue;
8960       AllWordsInNewV = false;
8961       break;
8962     }
8963
8964     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8965     if (AllWordsInNewV) {
8966       for (int i = 0; i != 8; ++i) {
8967         int idx = MaskVals[i];
8968         if (idx < 0)
8969           continue;
8970         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8971         if ((idx != i) && idx < 4)
8972           pshufhw = false;
8973         if ((idx != i) && idx > 3)
8974           pshuflw = false;
8975       }
8976       V1 = NewV;
8977       V2Used = false;
8978       BestLoQuad = 0;
8979       BestHiQuad = 1;
8980     }
8981
8982     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8983     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8984     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8985       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8986       unsigned TargetMask = 0;
8987       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8988                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8989       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8990       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8991                              getShufflePSHUFLWImmediate(SVOp);
8992       V1 = NewV.getOperand(0);
8993       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8994     }
8995   }
8996
8997   // Promote splats to a larger type which usually leads to more efficient code.
8998   // FIXME: Is this true if pshufb is available?
8999   if (SVOp->isSplat())
9000     return PromoteSplat(SVOp, DAG);
9001
9002   // If we have SSSE3, and all words of the result are from 1 input vector,
9003   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
9004   // is present, fall back to case 4.
9005   if (Subtarget->hasSSSE3()) {
9006     SmallVector<SDValue,16> pshufbMask;
9007
9008     // If we have elements from both input vectors, set the high bit of the
9009     // shuffle mask element to zero out elements that come from V2 in the V1
9010     // mask, and elements that come from V1 in the V2 mask, so that the two
9011     // results can be OR'd together.
9012     bool TwoInputs = V1Used && V2Used;
9013     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9014     if (!TwoInputs)
9015       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9016
9017     // Calculate the shuffle mask for the second input, shuffle it, and
9018     // OR it with the first shuffled input.
9019     CommuteVectorShuffleMask(MaskVals, 8);
9020     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9021     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9022     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9023   }
9024
9025   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9026   // and update MaskVals with new element order.
9027   std::bitset<8> InOrder;
9028   if (BestLoQuad >= 0) {
9029     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9030     for (int i = 0; i != 4; ++i) {
9031       int idx = MaskVals[i];
9032       if (idx < 0) {
9033         InOrder.set(i);
9034       } else if ((idx / 4) == BestLoQuad) {
9035         MaskV[i] = idx & 3;
9036         InOrder.set(i);
9037       }
9038     }
9039     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9040                                 &MaskV[0]);
9041
9042     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9043       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9044       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9045                                   NewV.getOperand(0),
9046                                   getShufflePSHUFLWImmediate(SVOp), DAG);
9047     }
9048   }
9049
9050   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9051   // and update MaskVals with the new element order.
9052   if (BestHiQuad >= 0) {
9053     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9054     for (unsigned i = 4; i != 8; ++i) {
9055       int idx = MaskVals[i];
9056       if (idx < 0) {
9057         InOrder.set(i);
9058       } else if ((idx / 4) == BestHiQuad) {
9059         MaskV[i] = (idx & 3) + 4;
9060         InOrder.set(i);
9061       }
9062     }
9063     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9064                                 &MaskV[0]);
9065
9066     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9067       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9068       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9069                                   NewV.getOperand(0),
9070                                   getShufflePSHUFHWImmediate(SVOp), DAG);
9071     }
9072   }
9073
9074   // In case BestHi & BestLo were both -1, which means each quadword has a word
9075   // from each of the four input quadwords, calculate the InOrder bitvector now
9076   // before falling through to the insert/extract cleanup.
9077   if (BestLoQuad == -1 && BestHiQuad == -1) {
9078     NewV = V1;
9079     for (int i = 0; i != 8; ++i)
9080       if (MaskVals[i] < 0 || MaskVals[i] == i)
9081         InOrder.set(i);
9082   }
9083
9084   // The other elements are put in the right place using pextrw and pinsrw.
9085   for (unsigned i = 0; i != 8; ++i) {
9086     if (InOrder[i])
9087       continue;
9088     int EltIdx = MaskVals[i];
9089     if (EltIdx < 0)
9090       continue;
9091     SDValue ExtOp = (EltIdx < 8) ?
9092       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9093                   DAG.getIntPtrConstant(EltIdx)) :
9094       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9095                   DAG.getIntPtrConstant(EltIdx - 8));
9096     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9097                        DAG.getIntPtrConstant(i));
9098   }
9099   return NewV;
9100 }
9101
9102 /// \brief v16i16 shuffles
9103 ///
9104 /// FIXME: We only support generation of a single pshufb currently.  We can
9105 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9106 /// well (e.g 2 x pshufb + 1 x por).
9107 static SDValue
9108 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9109   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9110   SDValue V1 = SVOp->getOperand(0);
9111   SDValue V2 = SVOp->getOperand(1);
9112   SDLoc dl(SVOp);
9113
9114   if (V2.getOpcode() != ISD::UNDEF)
9115     return SDValue();
9116
9117   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9118   return getPSHUFB(MaskVals, V1, dl, DAG);
9119 }
9120
9121 // v16i8 shuffles - Prefer shuffles in the following order:
9122 // 1. [ssse3] 1 x pshufb
9123 // 2. [ssse3] 2 x pshufb + 1 x por
9124 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
9125 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9126                                         const X86Subtarget* Subtarget,
9127                                         SelectionDAG &DAG) {
9128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9129   SDValue V1 = SVOp->getOperand(0);
9130   SDValue V2 = SVOp->getOperand(1);
9131   SDLoc dl(SVOp);
9132   ArrayRef<int> MaskVals = SVOp->getMask();
9133
9134   // Promote splats to a larger type which usually leads to more efficient code.
9135   // FIXME: Is this true if pshufb is available?
9136   if (SVOp->isSplat())
9137     return PromoteSplat(SVOp, DAG);
9138
9139   // If we have SSSE3, case 1 is generated when all result bytes come from
9140   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
9141   // present, fall back to case 3.
9142
9143   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9144   if (Subtarget->hasSSSE3()) {
9145     SmallVector<SDValue,16> pshufbMask;
9146
9147     // If all result elements are from one input vector, then only translate
9148     // undef mask values to 0x80 (zero out result) in the pshufb mask.
9149     //
9150     // Otherwise, we have elements from both input vectors, and must zero out
9151     // elements that come from V2 in the first mask, and V1 in the second mask
9152     // so that we can OR them together.
9153     for (unsigned i = 0; i != 16; ++i) {
9154       int EltIdx = MaskVals[i];
9155       if (EltIdx < 0 || EltIdx >= 16)
9156         EltIdx = 0x80;
9157       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9158     }
9159     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9160                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9161                                  MVT::v16i8, pshufbMask));
9162
9163     // As PSHUFB will zero elements with negative indices, it's safe to ignore
9164     // the 2nd operand if it's undefined or zero.
9165     if (V2.getOpcode() == ISD::UNDEF ||
9166         ISD::isBuildVectorAllZeros(V2.getNode()))
9167       return V1;
9168
9169     // Calculate the shuffle mask for the second input, shuffle it, and
9170     // OR it with the first shuffled input.
9171     pshufbMask.clear();
9172     for (unsigned i = 0; i != 16; ++i) {
9173       int EltIdx = MaskVals[i];
9174       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9175       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9176     }
9177     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9178                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9179                                  MVT::v16i8, pshufbMask));
9180     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9181   }
9182
9183   // No SSSE3 - Calculate in place words and then fix all out of place words
9184   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
9185   // the 16 different words that comprise the two doublequadword input vectors.
9186   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9187   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9188   SDValue NewV = V1;
9189   for (int i = 0; i != 8; ++i) {
9190     int Elt0 = MaskVals[i*2];
9191     int Elt1 = MaskVals[i*2+1];
9192
9193     // This word of the result is all undef, skip it.
9194     if (Elt0 < 0 && Elt1 < 0)
9195       continue;
9196
9197     // This word of the result is already in the correct place, skip it.
9198     if ((Elt0 == i*2) && (Elt1 == i*2+1))
9199       continue;
9200
9201     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9202     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9203     SDValue InsElt;
9204
9205     // If Elt0 and Elt1 are defined, are consecutive, and can be load
9206     // using a single extract together, load it and store it.
9207     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9208       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9209                            DAG.getIntPtrConstant(Elt1 / 2));
9210       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9211                         DAG.getIntPtrConstant(i));
9212       continue;
9213     }
9214
9215     // If Elt1 is defined, extract it from the appropriate source.  If the
9216     // source byte is not also odd, shift the extracted word left 8 bits
9217     // otherwise clear the bottom 8 bits if we need to do an or.
9218     if (Elt1 >= 0) {
9219       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9220                            DAG.getIntPtrConstant(Elt1 / 2));
9221       if ((Elt1 & 1) == 0)
9222         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9223                              DAG.getConstant(8,
9224                                   TLI.getShiftAmountTy(InsElt.getValueType())));
9225       else if (Elt0 >= 0)
9226         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9227                              DAG.getConstant(0xFF00, MVT::i16));
9228     }
9229     // If Elt0 is defined, extract it from the appropriate source.  If the
9230     // source byte is not also even, shift the extracted word right 8 bits. If
9231     // Elt1 was also defined, OR the extracted values together before
9232     // inserting them in the result.
9233     if (Elt0 >= 0) {
9234       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9235                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9236       if ((Elt0 & 1) != 0)
9237         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9238                               DAG.getConstant(8,
9239                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
9240       else if (Elt1 >= 0)
9241         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9242                              DAG.getConstant(0x00FF, MVT::i16));
9243       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9244                          : InsElt0;
9245     }
9246     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9247                        DAG.getIntPtrConstant(i));
9248   }
9249   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9250 }
9251
9252 // v32i8 shuffles - Translate to VPSHUFB if possible.
9253 static
9254 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9255                                  const X86Subtarget *Subtarget,
9256                                  SelectionDAG &DAG) {
9257   MVT VT = SVOp->getSimpleValueType(0);
9258   SDValue V1 = SVOp->getOperand(0);
9259   SDValue V2 = SVOp->getOperand(1);
9260   SDLoc dl(SVOp);
9261   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9262
9263   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9264   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9265   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9266
9267   // VPSHUFB may be generated if
9268   // (1) one of input vector is undefined or zeroinitializer.
9269   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9270   // And (2) the mask indexes don't cross the 128-bit lane.
9271   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9272       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9273     return SDValue();
9274
9275   if (V1IsAllZero && !V2IsAllZero) {
9276     CommuteVectorShuffleMask(MaskVals, 32);
9277     V1 = V2;
9278   }
9279   return getPSHUFB(MaskVals, V1, dl, DAG);
9280 }
9281
9282 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9283 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9284 /// done when every pair / quad of shuffle mask elements point to elements in
9285 /// the right sequence. e.g.
9286 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9287 static
9288 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9289                                  SelectionDAG &DAG) {
9290   MVT VT = SVOp->getSimpleValueType(0);
9291   SDLoc dl(SVOp);
9292   unsigned NumElems = VT.getVectorNumElements();
9293   MVT NewVT;
9294   unsigned Scale;
9295   switch (VT.SimpleTy) {
9296   default: llvm_unreachable("Unexpected!");
9297   case MVT::v2i64:
9298   case MVT::v2f64:
9299            return SDValue(SVOp, 0);
9300   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9301   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9302   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9303   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9304   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9305   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9306   }
9307
9308   SmallVector<int, 8> MaskVec;
9309   for (unsigned i = 0; i != NumElems; i += Scale) {
9310     int StartIdx = -1;
9311     for (unsigned j = 0; j != Scale; ++j) {
9312       int EltIdx = SVOp->getMaskElt(i+j);
9313       if (EltIdx < 0)
9314         continue;
9315       if (StartIdx < 0)
9316         StartIdx = (EltIdx / Scale);
9317       if (EltIdx != (int)(StartIdx*Scale + j))
9318         return SDValue();
9319     }
9320     MaskVec.push_back(StartIdx);
9321   }
9322
9323   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9324   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9325   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9326 }
9327
9328 /// getVZextMovL - Return a zero-extending vector move low node.
9329 ///
9330 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9331                             SDValue SrcOp, SelectionDAG &DAG,
9332                             const X86Subtarget *Subtarget, SDLoc dl) {
9333   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9334     LoadSDNode *LD = nullptr;
9335     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9336       LD = dyn_cast<LoadSDNode>(SrcOp);
9337     if (!LD) {
9338       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9339       // instead.
9340       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9341       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9342           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9343           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9344           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9345         // PR2108
9346         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9347         return DAG.getNode(ISD::BITCAST, dl, VT,
9348                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9349                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9350                                                    OpVT,
9351                                                    SrcOp.getOperand(0)
9352                                                           .getOperand(0))));
9353       }
9354     }
9355   }
9356
9357   return DAG.getNode(ISD::BITCAST, dl, VT,
9358                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9359                                  DAG.getNode(ISD::BITCAST, dl,
9360                                              OpVT, SrcOp)));
9361 }
9362
9363 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9364 /// which could not be matched by any known target speficic shuffle
9365 static SDValue
9366 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9367
9368   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9369   if (NewOp.getNode())
9370     return NewOp;
9371
9372   MVT VT = SVOp->getSimpleValueType(0);
9373
9374   unsigned NumElems = VT.getVectorNumElements();
9375   unsigned NumLaneElems = NumElems / 2;
9376
9377   SDLoc dl(SVOp);
9378   MVT EltVT = VT.getVectorElementType();
9379   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9380   SDValue Output[2];
9381
9382   SmallVector<int, 16> Mask;
9383   for (unsigned l = 0; l < 2; ++l) {
9384     // Build a shuffle mask for the output, discovering on the fly which
9385     // input vectors to use as shuffle operands (recorded in InputUsed).
9386     // If building a suitable shuffle vector proves too hard, then bail
9387     // out with UseBuildVector set.
9388     bool UseBuildVector = false;
9389     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9390     unsigned LaneStart = l * NumLaneElems;
9391     for (unsigned i = 0; i != NumLaneElems; ++i) {
9392       // The mask element.  This indexes into the input.
9393       int Idx = SVOp->getMaskElt(i+LaneStart);
9394       if (Idx < 0) {
9395         // the mask element does not index into any input vector.
9396         Mask.push_back(-1);
9397         continue;
9398       }
9399
9400       // The input vector this mask element indexes into.
9401       int Input = Idx / NumLaneElems;
9402
9403       // Turn the index into an offset from the start of the input vector.
9404       Idx -= Input * NumLaneElems;
9405
9406       // Find or create a shuffle vector operand to hold this input.
9407       unsigned OpNo;
9408       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9409         if (InputUsed[OpNo] == Input)
9410           // This input vector is already an operand.
9411           break;
9412         if (InputUsed[OpNo] < 0) {
9413           // Create a new operand for this input vector.
9414           InputUsed[OpNo] = Input;
9415           break;
9416         }
9417       }
9418
9419       if (OpNo >= array_lengthof(InputUsed)) {
9420         // More than two input vectors used!  Give up on trying to create a
9421         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9422         UseBuildVector = true;
9423         break;
9424       }
9425
9426       // Add the mask index for the new shuffle vector.
9427       Mask.push_back(Idx + OpNo * NumLaneElems);
9428     }
9429
9430     if (UseBuildVector) {
9431       SmallVector<SDValue, 16> SVOps;
9432       for (unsigned i = 0; i != NumLaneElems; ++i) {
9433         // The mask element.  This indexes into the input.
9434         int Idx = SVOp->getMaskElt(i+LaneStart);
9435         if (Idx < 0) {
9436           SVOps.push_back(DAG.getUNDEF(EltVT));
9437           continue;
9438         }
9439
9440         // The input vector this mask element indexes into.
9441         int Input = Idx / NumElems;
9442
9443         // Turn the index into an offset from the start of the input vector.
9444         Idx -= Input * NumElems;
9445
9446         // Extract the vector element by hand.
9447         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9448                                     SVOp->getOperand(Input),
9449                                     DAG.getIntPtrConstant(Idx)));
9450       }
9451
9452       // Construct the output using a BUILD_VECTOR.
9453       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9454     } else if (InputUsed[0] < 0) {
9455       // No input vectors were used! The result is undefined.
9456       Output[l] = DAG.getUNDEF(NVT);
9457     } else {
9458       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9459                                         (InputUsed[0] % 2) * NumLaneElems,
9460                                         DAG, dl);
9461       // If only one input was used, use an undefined vector for the other.
9462       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9463         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9464                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9465       // At least one input vector was used. Create a new shuffle vector.
9466       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9467     }
9468
9469     Mask.clear();
9470   }
9471
9472   // Concatenate the result back
9473   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9474 }
9475
9476 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9477 /// 4 elements, and match them with several different shuffle types.
9478 static SDValue
9479 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9480   SDValue V1 = SVOp->getOperand(0);
9481   SDValue V2 = SVOp->getOperand(1);
9482   SDLoc dl(SVOp);
9483   MVT VT = SVOp->getSimpleValueType(0);
9484
9485   assert(VT.is128BitVector() && "Unsupported vector size");
9486
9487   std::pair<int, int> Locs[4];
9488   int Mask1[] = { -1, -1, -1, -1 };
9489   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9490
9491   unsigned NumHi = 0;
9492   unsigned NumLo = 0;
9493   for (unsigned i = 0; i != 4; ++i) {
9494     int Idx = PermMask[i];
9495     if (Idx < 0) {
9496       Locs[i] = std::make_pair(-1, -1);
9497     } else {
9498       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9499       if (Idx < 4) {
9500         Locs[i] = std::make_pair(0, NumLo);
9501         Mask1[NumLo] = Idx;
9502         NumLo++;
9503       } else {
9504         Locs[i] = std::make_pair(1, NumHi);
9505         if (2+NumHi < 4)
9506           Mask1[2+NumHi] = Idx;
9507         NumHi++;
9508       }
9509     }
9510   }
9511
9512   if (NumLo <= 2 && NumHi <= 2) {
9513     // If no more than two elements come from either vector. This can be
9514     // implemented with two shuffles. First shuffle gather the elements.
9515     // The second shuffle, which takes the first shuffle as both of its
9516     // vector operands, put the elements into the right order.
9517     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9518
9519     int Mask2[] = { -1, -1, -1, -1 };
9520
9521     for (unsigned i = 0; i != 4; ++i)
9522       if (Locs[i].first != -1) {
9523         unsigned Idx = (i < 2) ? 0 : 4;
9524         Idx += Locs[i].first * 2 + Locs[i].second;
9525         Mask2[i] = Idx;
9526       }
9527
9528     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9529   }
9530
9531   if (NumLo == 3 || NumHi == 3) {
9532     // Otherwise, we must have three elements from one vector, call it X, and
9533     // one element from the other, call it Y.  First, use a shufps to build an
9534     // intermediate vector with the one element from Y and the element from X
9535     // that will be in the same half in the final destination (the indexes don't
9536     // matter). Then, use a shufps to build the final vector, taking the half
9537     // containing the element from Y from the intermediate, and the other half
9538     // from X.
9539     if (NumHi == 3) {
9540       // Normalize it so the 3 elements come from V1.
9541       CommuteVectorShuffleMask(PermMask, 4);
9542       std::swap(V1, V2);
9543     }
9544
9545     // Find the element from V2.
9546     unsigned HiIndex;
9547     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9548       int Val = PermMask[HiIndex];
9549       if (Val < 0)
9550         continue;
9551       if (Val >= 4)
9552         break;
9553     }
9554
9555     Mask1[0] = PermMask[HiIndex];
9556     Mask1[1] = -1;
9557     Mask1[2] = PermMask[HiIndex^1];
9558     Mask1[3] = -1;
9559     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9560
9561     if (HiIndex >= 2) {
9562       Mask1[0] = PermMask[0];
9563       Mask1[1] = PermMask[1];
9564       Mask1[2] = HiIndex & 1 ? 6 : 4;
9565       Mask1[3] = HiIndex & 1 ? 4 : 6;
9566       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9567     }
9568
9569     Mask1[0] = HiIndex & 1 ? 2 : 0;
9570     Mask1[1] = HiIndex & 1 ? 0 : 2;
9571     Mask1[2] = PermMask[2];
9572     Mask1[3] = PermMask[3];
9573     if (Mask1[2] >= 0)
9574       Mask1[2] += 4;
9575     if (Mask1[3] >= 0)
9576       Mask1[3] += 4;
9577     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9578   }
9579
9580   // Break it into (shuffle shuffle_hi, shuffle_lo).
9581   int LoMask[] = { -1, -1, -1, -1 };
9582   int HiMask[] = { -1, -1, -1, -1 };
9583
9584   int *MaskPtr = LoMask;
9585   unsigned MaskIdx = 0;
9586   unsigned LoIdx = 0;
9587   unsigned HiIdx = 2;
9588   for (unsigned i = 0; i != 4; ++i) {
9589     if (i == 2) {
9590       MaskPtr = HiMask;
9591       MaskIdx = 1;
9592       LoIdx = 0;
9593       HiIdx = 2;
9594     }
9595     int Idx = PermMask[i];
9596     if (Idx < 0) {
9597       Locs[i] = std::make_pair(-1, -1);
9598     } else if (Idx < 4) {
9599       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9600       MaskPtr[LoIdx] = Idx;
9601       LoIdx++;
9602     } else {
9603       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9604       MaskPtr[HiIdx] = Idx;
9605       HiIdx++;
9606     }
9607   }
9608
9609   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9610   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9611   int MaskOps[] = { -1, -1, -1, -1 };
9612   for (unsigned i = 0; i != 4; ++i)
9613     if (Locs[i].first != -1)
9614       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9615   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9616 }
9617
9618 static bool MayFoldVectorLoad(SDValue V) {
9619   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9620     V = V.getOperand(0);
9621
9622   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9623     V = V.getOperand(0);
9624   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9625       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9626     // BUILD_VECTOR (load), undef
9627     V = V.getOperand(0);
9628
9629   return MayFoldLoad(V);
9630 }
9631
9632 static
9633 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9634   MVT VT = Op.getSimpleValueType();
9635
9636   // Canonizalize to v2f64.
9637   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9638   return DAG.getNode(ISD::BITCAST, dl, VT,
9639                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9640                                           V1, DAG));
9641 }
9642
9643 static
9644 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9645                         bool HasSSE2) {
9646   SDValue V1 = Op.getOperand(0);
9647   SDValue V2 = Op.getOperand(1);
9648   MVT VT = Op.getSimpleValueType();
9649
9650   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9651
9652   if (HasSSE2 && VT == MVT::v2f64)
9653     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9654
9655   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9656   return DAG.getNode(ISD::BITCAST, dl, VT,
9657                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9658                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9659                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9660 }
9661
9662 static
9663 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9664   SDValue V1 = Op.getOperand(0);
9665   SDValue V2 = Op.getOperand(1);
9666   MVT VT = Op.getSimpleValueType();
9667
9668   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9669          "unsupported shuffle type");
9670
9671   if (V2.getOpcode() == ISD::UNDEF)
9672     V2 = V1;
9673
9674   // v4i32 or v4f32
9675   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9676 }
9677
9678 static
9679 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9680   SDValue V1 = Op.getOperand(0);
9681   SDValue V2 = Op.getOperand(1);
9682   MVT VT = Op.getSimpleValueType();
9683   unsigned NumElems = VT.getVectorNumElements();
9684
9685   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9686   // operand of these instructions is only memory, so check if there's a
9687   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9688   // same masks.
9689   bool CanFoldLoad = false;
9690
9691   // Trivial case, when V2 comes from a load.
9692   if (MayFoldVectorLoad(V2))
9693     CanFoldLoad = true;
9694
9695   // When V1 is a load, it can be folded later into a store in isel, example:
9696   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9697   //    turns into:
9698   //  (MOVLPSmr addr:$src1, VR128:$src2)
9699   // So, recognize this potential and also use MOVLPS or MOVLPD
9700   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9701     CanFoldLoad = true;
9702
9703   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9704   if (CanFoldLoad) {
9705     if (HasSSE2 && NumElems == 2)
9706       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9707
9708     if (NumElems == 4)
9709       // If we don't care about the second element, proceed to use movss.
9710       if (SVOp->getMaskElt(1) != -1)
9711         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9712   }
9713
9714   // movl and movlp will both match v2i64, but v2i64 is never matched by
9715   // movl earlier because we make it strict to avoid messing with the movlp load
9716   // folding logic (see the code above getMOVLP call). Match it here then,
9717   // this is horrible, but will stay like this until we move all shuffle
9718   // matching to x86 specific nodes. Note that for the 1st condition all
9719   // types are matched with movsd.
9720   if (HasSSE2) {
9721     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9722     // as to remove this logic from here, as much as possible
9723     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9724       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9725     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9726   }
9727
9728   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9729
9730   // Invert the operand order and use SHUFPS to match it.
9731   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9732                               getShuffleSHUFImmediate(SVOp), DAG);
9733 }
9734
9735 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9736                                          SelectionDAG &DAG) {
9737   SDLoc dl(Load);
9738   MVT VT = Load->getSimpleValueType(0);
9739   MVT EVT = VT.getVectorElementType();
9740   SDValue Addr = Load->getOperand(1);
9741   SDValue NewAddr = DAG.getNode(
9742       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9743       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9744
9745   SDValue NewLoad =
9746       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9747                   DAG.getMachineFunction().getMachineMemOperand(
9748                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9749   return NewLoad;
9750 }
9751
9752 // It is only safe to call this function if isINSERTPSMask is true for
9753 // this shufflevector mask.
9754 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9755                            SelectionDAG &DAG) {
9756   // Generate an insertps instruction when inserting an f32 from memory onto a
9757   // v4f32 or when copying a member from one v4f32 to another.
9758   // We also use it for transferring i32 from one register to another,
9759   // since it simply copies the same bits.
9760   // If we're transferring an i32 from memory to a specific element in a
9761   // register, we output a generic DAG that will match the PINSRD
9762   // instruction.
9763   MVT VT = SVOp->getSimpleValueType(0);
9764   MVT EVT = VT.getVectorElementType();
9765   SDValue V1 = SVOp->getOperand(0);
9766   SDValue V2 = SVOp->getOperand(1);
9767   auto Mask = SVOp->getMask();
9768   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9769          "unsupported vector type for insertps/pinsrd");
9770
9771   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9772   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9773   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9774
9775   SDValue From;
9776   SDValue To;
9777   unsigned DestIndex;
9778   if (FromV1 == 1) {
9779     From = V1;
9780     To = V2;
9781     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9782                 Mask.begin();
9783
9784     // If we have 1 element from each vector, we have to check if we're
9785     // changing V1's element's place. If so, we're done. Otherwise, we
9786     // should assume we're changing V2's element's place and behave
9787     // accordingly.
9788     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9789     assert(DestIndex <= INT32_MAX && "truncated destination index");
9790     if (FromV1 == FromV2 &&
9791         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9792       From = V2;
9793       To = V1;
9794       DestIndex =
9795           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9796     }
9797   } else {
9798     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9799            "More than one element from V1 and from V2, or no elements from one "
9800            "of the vectors. This case should not have returned true from "
9801            "isINSERTPSMask");
9802     From = V2;
9803     To = V1;
9804     DestIndex =
9805         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9806   }
9807
9808   // Get an index into the source vector in the range [0,4) (the mask is
9809   // in the range [0,8) because it can address V1 and V2)
9810   unsigned SrcIndex = Mask[DestIndex] % 4;
9811   if (MayFoldLoad(From)) {
9812     // Trivial case, when From comes from a load and is only used by the
9813     // shuffle. Make it use insertps from the vector that we need from that
9814     // load.
9815     SDValue NewLoad =
9816         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9817     if (!NewLoad.getNode())
9818       return SDValue();
9819
9820     if (EVT == MVT::f32) {
9821       // Create this as a scalar to vector to match the instruction pattern.
9822       SDValue LoadScalarToVector =
9823           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9824       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9825       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9826                          InsertpsMask);
9827     } else { // EVT == MVT::i32
9828       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9829       // instruction, to match the PINSRD instruction, which loads an i32 to a
9830       // certain vector element.
9831       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9832                          DAG.getConstant(DestIndex, MVT::i32));
9833     }
9834   }
9835
9836   // Vector-element-to-vector
9837   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9838   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9839 }
9840
9841 // Reduce a vector shuffle to zext.
9842 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9843                                     SelectionDAG &DAG) {
9844   // PMOVZX is only available from SSE41.
9845   if (!Subtarget->hasSSE41())
9846     return SDValue();
9847
9848   MVT VT = Op.getSimpleValueType();
9849
9850   // Only AVX2 support 256-bit vector integer extending.
9851   if (!Subtarget->hasInt256() && VT.is256BitVector())
9852     return SDValue();
9853
9854   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9855   SDLoc DL(Op);
9856   SDValue V1 = Op.getOperand(0);
9857   SDValue V2 = Op.getOperand(1);
9858   unsigned NumElems = VT.getVectorNumElements();
9859
9860   // Extending is an unary operation and the element type of the source vector
9861   // won't be equal to or larger than i64.
9862   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9863       VT.getVectorElementType() == MVT::i64)
9864     return SDValue();
9865
9866   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9867   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9868   while ((1U << Shift) < NumElems) {
9869     if (SVOp->getMaskElt(1U << Shift) == 1)
9870       break;
9871     Shift += 1;
9872     // The maximal ratio is 8, i.e. from i8 to i64.
9873     if (Shift > 3)
9874       return SDValue();
9875   }
9876
9877   // Check the shuffle mask.
9878   unsigned Mask = (1U << Shift) - 1;
9879   for (unsigned i = 0; i != NumElems; ++i) {
9880     int EltIdx = SVOp->getMaskElt(i);
9881     if ((i & Mask) != 0 && EltIdx != -1)
9882       return SDValue();
9883     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9884       return SDValue();
9885   }
9886
9887   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9888   MVT NeVT = MVT::getIntegerVT(NBits);
9889   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9890
9891   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9892     return SDValue();
9893
9894   // Simplify the operand as it's prepared to be fed into shuffle.
9895   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9896   if (V1.getOpcode() == ISD::BITCAST &&
9897       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9898       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9899       V1.getOperand(0).getOperand(0)
9900         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9901     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9902     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9903     ConstantSDNode *CIdx =
9904       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9905     // If it's foldable, i.e. normal load with single use, we will let code
9906     // selection to fold it. Otherwise, we will short the conversion sequence.
9907     if (CIdx && CIdx->getZExtValue() == 0 &&
9908         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9909       MVT FullVT = V.getSimpleValueType();
9910       MVT V1VT = V1.getSimpleValueType();
9911       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9912         // The "ext_vec_elt" node is wider than the result node.
9913         // In this case we should extract subvector from V.
9914         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9915         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9916         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9917                                         FullVT.getVectorNumElements()/Ratio);
9918         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9919                         DAG.getIntPtrConstant(0));
9920       }
9921       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9922     }
9923   }
9924
9925   return DAG.getNode(ISD::BITCAST, DL, VT,
9926                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9927 }
9928
9929 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9930                                       SelectionDAG &DAG) {
9931   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9932   MVT VT = Op.getSimpleValueType();
9933   SDLoc dl(Op);
9934   SDValue V1 = Op.getOperand(0);
9935   SDValue V2 = Op.getOperand(1);
9936
9937   if (isZeroShuffle(SVOp))
9938     return getZeroVector(VT, Subtarget, DAG, dl);
9939
9940   // Handle splat operations
9941   if (SVOp->isSplat()) {
9942     // Use vbroadcast whenever the splat comes from a foldable load
9943     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9944     if (Broadcast.getNode())
9945       return Broadcast;
9946   }
9947
9948   // Check integer expanding shuffles.
9949   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9950   if (NewOp.getNode())
9951     return NewOp;
9952
9953   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9954   // do it!
9955   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9956       VT == MVT::v32i8) {
9957     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9958     if (NewOp.getNode())
9959       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9960   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9961     // FIXME: Figure out a cleaner way to do this.
9962     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9963       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9964       if (NewOp.getNode()) {
9965         MVT NewVT = NewOp.getSimpleValueType();
9966         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9967                                NewVT, true, false))
9968           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9969                               dl);
9970       }
9971     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9972       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9973       if (NewOp.getNode()) {
9974         MVT NewVT = NewOp.getSimpleValueType();
9975         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9976           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9977                               dl);
9978       }
9979     }
9980   }
9981   return SDValue();
9982 }
9983
9984 SDValue
9985 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9986   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9987   SDValue V1 = Op.getOperand(0);
9988   SDValue V2 = Op.getOperand(1);
9989   MVT VT = Op.getSimpleValueType();
9990   SDLoc dl(Op);
9991   unsigned NumElems = VT.getVectorNumElements();
9992   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9993   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9994   bool V1IsSplat = false;
9995   bool V2IsSplat = false;
9996   bool HasSSE2 = Subtarget->hasSSE2();
9997   bool HasFp256    = Subtarget->hasFp256();
9998   bool HasInt256   = Subtarget->hasInt256();
9999   MachineFunction &MF = DAG.getMachineFunction();
10000   bool OptForSize = MF.getFunction()->getAttributes().
10001     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10002
10003   // Check if we should use the experimental vector shuffle lowering. If so,
10004   // delegate completely to that code path.
10005   if (ExperimentalVectorShuffleLowering)
10006     return lowerVectorShuffle(Op, Subtarget, DAG);
10007
10008   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10009
10010   if (V1IsUndef && V2IsUndef)
10011     return DAG.getUNDEF(VT);
10012
10013   // When we create a shuffle node we put the UNDEF node to second operand,
10014   // but in some cases the first operand may be transformed to UNDEF.
10015   // In this case we should just commute the node.
10016   if (V1IsUndef)
10017     return DAG.getCommutedVectorShuffle(*SVOp);
10018
10019   // Vector shuffle lowering takes 3 steps:
10020   //
10021   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10022   //    narrowing and commutation of operands should be handled.
10023   // 2) Matching of shuffles with known shuffle masks to x86 target specific
10024   //    shuffle nodes.
10025   // 3) Rewriting of unmatched masks into new generic shuffle operations,
10026   //    so the shuffle can be broken into other shuffles and the legalizer can
10027   //    try the lowering again.
10028   //
10029   // The general idea is that no vector_shuffle operation should be left to
10030   // be matched during isel, all of them must be converted to a target specific
10031   // node here.
10032
10033   // Normalize the input vectors. Here splats, zeroed vectors, profitable
10034   // narrowing and commutation of operands should be handled. The actual code
10035   // doesn't include all of those, work in progress...
10036   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10037   if (NewOp.getNode())
10038     return NewOp;
10039
10040   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10041
10042   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10043   // unpckh_undef). Only use pshufd if speed is more important than size.
10044   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10045     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10046   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10047     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10048
10049   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10050       V2IsUndef && MayFoldVectorLoad(V1))
10051     return getMOVDDup(Op, dl, V1, DAG);
10052
10053   if (isMOVHLPS_v_undef_Mask(M, VT))
10054     return getMOVHighToLow(Op, dl, DAG);
10055
10056   // Use to match splats
10057   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10058       (VT == MVT::v2f64 || VT == MVT::v2i64))
10059     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10060
10061   if (isPSHUFDMask(M, VT)) {
10062     // The actual implementation will match the mask in the if above and then
10063     // during isel it can match several different instructions, not only pshufd
10064     // as its name says, sad but true, emulate the behavior for now...
10065     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10066       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10067
10068     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10069
10070     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10071       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10072
10073     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10074       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10075                                   DAG);
10076
10077     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10078                                 TargetMask, DAG);
10079   }
10080
10081   if (isPALIGNRMask(M, VT, Subtarget))
10082     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10083                                 getShufflePALIGNRImmediate(SVOp),
10084                                 DAG);
10085
10086   if (isVALIGNMask(M, VT, Subtarget))
10087     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10088                                 getShuffleVALIGNImmediate(SVOp),
10089                                 DAG);
10090
10091   // Check if this can be converted into a logical shift.
10092   bool isLeft = false;
10093   unsigned ShAmt = 0;
10094   SDValue ShVal;
10095   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10096   if (isShift && ShVal.hasOneUse()) {
10097     // If the shifted value has multiple uses, it may be cheaper to use
10098     // v_set0 + movlhps or movhlps, etc.
10099     MVT EltVT = VT.getVectorElementType();
10100     ShAmt *= EltVT.getSizeInBits();
10101     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10102   }
10103
10104   if (isMOVLMask(M, VT)) {
10105     if (ISD::isBuildVectorAllZeros(V1.getNode()))
10106       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10107     if (!isMOVLPMask(M, VT)) {
10108       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10109         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10110
10111       if (VT == MVT::v4i32 || VT == MVT::v4f32)
10112         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10113     }
10114   }
10115
10116   // FIXME: fold these into legal mask.
10117   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10118     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10119
10120   if (isMOVHLPSMask(M, VT))
10121     return getMOVHighToLow(Op, dl, DAG);
10122
10123   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10124     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10125
10126   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10127     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10128
10129   if (isMOVLPMask(M, VT))
10130     return getMOVLP(Op, dl, DAG, HasSSE2);
10131
10132   if (ShouldXformToMOVHLPS(M, VT) ||
10133       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10134     return DAG.getCommutedVectorShuffle(*SVOp);
10135
10136   if (isShift) {
10137     // No better options. Use a vshldq / vsrldq.
10138     MVT EltVT = VT.getVectorElementType();
10139     ShAmt *= EltVT.getSizeInBits();
10140     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10141   }
10142
10143   bool Commuted = false;
10144   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
10145   // 1,1,1,1 -> v8i16 though.
10146   BitVector UndefElements;
10147   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10148     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10149       V1IsSplat = true;
10150   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10151     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10152       V2IsSplat = true;
10153
10154   // Canonicalize the splat or undef, if present, to be on the RHS.
10155   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10156     CommuteVectorShuffleMask(M, NumElems);
10157     std::swap(V1, V2);
10158     std::swap(V1IsSplat, V2IsSplat);
10159     Commuted = true;
10160   }
10161
10162   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10163     // Shuffling low element of v1 into undef, just return v1.
10164     if (V2IsUndef)
10165       return V1;
10166     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10167     // the instruction selector will not match, so get a canonical MOVL with
10168     // swapped operands to undo the commute.
10169     return getMOVL(DAG, dl, VT, V2, V1);
10170   }
10171
10172   if (isUNPCKLMask(M, VT, HasInt256))
10173     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10174
10175   if (isUNPCKHMask(M, VT, HasInt256))
10176     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10177
10178   if (V2IsSplat) {
10179     // Normalize mask so all entries that point to V2 points to its first
10180     // element then try to match unpck{h|l} again. If match, return a
10181     // new vector_shuffle with the corrected mask.p
10182     SmallVector<int, 8> NewMask(M.begin(), M.end());
10183     NormalizeMask(NewMask, NumElems);
10184     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10185       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10186     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10187       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10188   }
10189
10190   if (Commuted) {
10191     // Commute is back and try unpck* again.
10192     // FIXME: this seems wrong.
10193     CommuteVectorShuffleMask(M, NumElems);
10194     std::swap(V1, V2);
10195     std::swap(V1IsSplat, V2IsSplat);
10196
10197     if (isUNPCKLMask(M, VT, HasInt256))
10198       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10199
10200     if (isUNPCKHMask(M, VT, HasInt256))
10201       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10202   }
10203
10204   // Normalize the node to match x86 shuffle ops if needed
10205   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10206     return DAG.getCommutedVectorShuffle(*SVOp);
10207
10208   // The checks below are all present in isShuffleMaskLegal, but they are
10209   // inlined here right now to enable us to directly emit target specific
10210   // nodes, and remove one by one until they don't return Op anymore.
10211
10212   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10213       SVOp->getSplatIndex() == 0 && V2IsUndef) {
10214     if (VT == MVT::v2f64 || VT == MVT::v2i64)
10215       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10216   }
10217
10218   if (isPSHUFHWMask(M, VT, HasInt256))
10219     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10220                                 getShufflePSHUFHWImmediate(SVOp),
10221                                 DAG);
10222
10223   if (isPSHUFLWMask(M, VT, HasInt256))
10224     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10225                                 getShufflePSHUFLWImmediate(SVOp),
10226                                 DAG);
10227
10228   unsigned MaskValue;
10229   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10230                   &MaskValue))
10231     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10232
10233   if (isSHUFPMask(M, VT))
10234     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10235                                 getShuffleSHUFImmediate(SVOp), DAG);
10236
10237   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10238     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10239   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10240     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10241
10242   //===--------------------------------------------------------------------===//
10243   // Generate target specific nodes for 128 or 256-bit shuffles only
10244   // supported in the AVX instruction set.
10245   //
10246
10247   // Handle VMOVDDUPY permutations
10248   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10249     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10250
10251   // Handle VPERMILPS/D* permutations
10252   if (isVPERMILPMask(M, VT)) {
10253     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10254       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10255                                   getShuffleSHUFImmediate(SVOp), DAG);
10256     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10257                                 getShuffleSHUFImmediate(SVOp), DAG);
10258   }
10259
10260   unsigned Idx;
10261   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10262     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10263                               Idx*(NumElems/2), DAG, dl);
10264
10265   // Handle VPERM2F128/VPERM2I128 permutations
10266   if (isVPERM2X128Mask(M, VT, HasFp256))
10267     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10268                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10269
10270   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10271     return getINSERTPS(SVOp, dl, DAG);
10272
10273   unsigned Imm8;
10274   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10275     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10276
10277   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10278       VT.is512BitVector()) {
10279     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10280     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10281     SmallVector<SDValue, 16> permclMask;
10282     for (unsigned i = 0; i != NumElems; ++i) {
10283       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10284     }
10285
10286     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10287     if (V2IsUndef)
10288       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10289       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10290                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10291     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10292                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10293   }
10294
10295   //===--------------------------------------------------------------------===//
10296   // Since no target specific shuffle was selected for this generic one,
10297   // lower it into other known shuffles. FIXME: this isn't true yet, but
10298   // this is the plan.
10299   //
10300
10301   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10302   if (VT == MVT::v8i16) {
10303     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10304     if (NewOp.getNode())
10305       return NewOp;
10306   }
10307
10308   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10309     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10310     if (NewOp.getNode())
10311       return NewOp;
10312   }
10313
10314   if (VT == MVT::v16i8) {
10315     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10316     if (NewOp.getNode())
10317       return NewOp;
10318   }
10319
10320   if (VT == MVT::v32i8) {
10321     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10322     if (NewOp.getNode())
10323       return NewOp;
10324   }
10325
10326   // Handle all 128-bit wide vectors with 4 elements, and match them with
10327   // several different shuffle types.
10328   if (NumElems == 4 && VT.is128BitVector())
10329     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10330
10331   // Handle general 256-bit shuffles
10332   if (VT.is256BitVector())
10333     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10334
10335   return SDValue();
10336 }
10337
10338 // This function assumes its argument is a BUILD_VECTOR of constants or
10339 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10340 // true.
10341 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10342                                     unsigned &MaskValue) {
10343   MaskValue = 0;
10344   unsigned NumElems = BuildVector->getNumOperands();
10345   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10346   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10347   unsigned NumElemsInLane = NumElems / NumLanes;
10348
10349   // Blend for v16i16 should be symetric for the both lanes.
10350   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10351     SDValue EltCond = BuildVector->getOperand(i);
10352     SDValue SndLaneEltCond =
10353         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10354
10355     int Lane1Cond = -1, Lane2Cond = -1;
10356     if (isa<ConstantSDNode>(EltCond))
10357       Lane1Cond = !isZero(EltCond);
10358     if (isa<ConstantSDNode>(SndLaneEltCond))
10359       Lane2Cond = !isZero(SndLaneEltCond);
10360
10361     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10362       // Lane1Cond != 0, means we want the first argument.
10363       // Lane1Cond == 0, means we want the second argument.
10364       // The encoding of this argument is 0 for the first argument, 1
10365       // for the second. Therefore, invert the condition.
10366       MaskValue |= !Lane1Cond << i;
10367     else if (Lane1Cond < 0)
10368       MaskValue |= !Lane2Cond << i;
10369     else
10370       return false;
10371   }
10372   return true;
10373 }
10374
10375 // Try to lower a vselect node into a simple blend instruction.
10376 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10377                                    SelectionDAG &DAG) {
10378   SDValue Cond = Op.getOperand(0);
10379   SDValue LHS = Op.getOperand(1);
10380   SDValue RHS = Op.getOperand(2);
10381   SDLoc dl(Op);
10382   MVT VT = Op.getSimpleValueType();
10383   MVT EltVT = VT.getVectorElementType();
10384   unsigned NumElems = VT.getVectorNumElements();
10385
10386   // There is no blend with immediate in AVX-512.
10387   if (VT.is512BitVector())
10388     return SDValue();
10389
10390   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10391     return SDValue();
10392   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10393     return SDValue();
10394
10395   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10396     return SDValue();
10397
10398   // Check the mask for BLEND and build the value.
10399   unsigned MaskValue = 0;
10400   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10401     return SDValue();
10402
10403   // Convert i32 vectors to floating point if it is not AVX2.
10404   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10405   MVT BlendVT = VT;
10406   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10407     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10408                                NumElems);
10409     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10410     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10411   }
10412
10413   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10414                             DAG.getConstant(MaskValue, MVT::i32));
10415   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10416 }
10417
10418 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10419   // A vselect where all conditions and data are constants can be optimized into
10420   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10421   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10422       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10423       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10424     return SDValue();
10425   
10426   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10427   if (BlendOp.getNode())
10428     return BlendOp;
10429
10430   // Some types for vselect were previously set to Expand, not Legal or
10431   // Custom. Return an empty SDValue so we fall-through to Expand, after
10432   // the Custom lowering phase.
10433   MVT VT = Op.getSimpleValueType();
10434   switch (VT.SimpleTy) {
10435   default:
10436     break;
10437   case MVT::v8i16:
10438   case MVT::v16i16:
10439     return SDValue();
10440   }
10441
10442   // We couldn't create a "Blend with immediate" node.
10443   // This node should still be legal, but we'll have to emit a blendv*
10444   // instruction.
10445   return Op;
10446 }
10447
10448 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10449   MVT VT = Op.getSimpleValueType();
10450   SDLoc dl(Op);
10451
10452   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10453     return SDValue();
10454
10455   if (VT.getSizeInBits() == 8) {
10456     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10457                                   Op.getOperand(0), Op.getOperand(1));
10458     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10459                                   DAG.getValueType(VT));
10460     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10461   }
10462
10463   if (VT.getSizeInBits() == 16) {
10464     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10465     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10466     if (Idx == 0)
10467       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10468                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10469                                      DAG.getNode(ISD::BITCAST, dl,
10470                                                  MVT::v4i32,
10471                                                  Op.getOperand(0)),
10472                                      Op.getOperand(1)));
10473     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10474                                   Op.getOperand(0), Op.getOperand(1));
10475     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10476                                   DAG.getValueType(VT));
10477     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10478   }
10479
10480   if (VT == MVT::f32) {
10481     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10482     // the result back to FR32 register. It's only worth matching if the
10483     // result has a single use which is a store or a bitcast to i32.  And in
10484     // the case of a store, it's not worth it if the index is a constant 0,
10485     // because a MOVSSmr can be used instead, which is smaller and faster.
10486     if (!Op.hasOneUse())
10487       return SDValue();
10488     SDNode *User = *Op.getNode()->use_begin();
10489     if ((User->getOpcode() != ISD::STORE ||
10490          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10491           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10492         (User->getOpcode() != ISD::BITCAST ||
10493          User->getValueType(0) != MVT::i32))
10494       return SDValue();
10495     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10496                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10497                                               Op.getOperand(0)),
10498                                               Op.getOperand(1));
10499     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10500   }
10501
10502   if (VT == MVT::i32 || VT == MVT::i64) {
10503     // ExtractPS/pextrq works with constant index.
10504     if (isa<ConstantSDNode>(Op.getOperand(1)))
10505       return Op;
10506   }
10507   return SDValue();
10508 }
10509
10510 /// Extract one bit from mask vector, like v16i1 or v8i1.
10511 /// AVX-512 feature.
10512 SDValue
10513 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10514   SDValue Vec = Op.getOperand(0);
10515   SDLoc dl(Vec);
10516   MVT VecVT = Vec.getSimpleValueType();
10517   SDValue Idx = Op.getOperand(1);
10518   MVT EltVT = Op.getSimpleValueType();
10519
10520   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10521
10522   // variable index can't be handled in mask registers,
10523   // extend vector to VR512
10524   if (!isa<ConstantSDNode>(Idx)) {
10525     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10526     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10527     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10528                               ExtVT.getVectorElementType(), Ext, Idx);
10529     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10530   }
10531
10532   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10533   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10534   unsigned MaxSift = rc->getSize()*8 - 1;
10535   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10536                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10537   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10538                     DAG.getConstant(MaxSift, MVT::i8));
10539   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10540                        DAG.getIntPtrConstant(0));
10541 }
10542
10543 SDValue
10544 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10545                                            SelectionDAG &DAG) const {
10546   SDLoc dl(Op);
10547   SDValue Vec = Op.getOperand(0);
10548   MVT VecVT = Vec.getSimpleValueType();
10549   SDValue Idx = Op.getOperand(1);
10550
10551   if (Op.getSimpleValueType() == MVT::i1)
10552     return ExtractBitFromMaskVector(Op, DAG);
10553
10554   if (!isa<ConstantSDNode>(Idx)) {
10555     if (VecVT.is512BitVector() ||
10556         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10557          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10558
10559       MVT MaskEltVT =
10560         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10561       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10562                                     MaskEltVT.getSizeInBits());
10563
10564       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10565       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10566                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10567                                 Idx, DAG.getConstant(0, getPointerTy()));
10568       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10569       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10570                         Perm, DAG.getConstant(0, getPointerTy()));
10571     }
10572     return SDValue();
10573   }
10574
10575   // If this is a 256-bit vector result, first extract the 128-bit vector and
10576   // then extract the element from the 128-bit vector.
10577   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10578
10579     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10580     // Get the 128-bit vector.
10581     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10582     MVT EltVT = VecVT.getVectorElementType();
10583
10584     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10585
10586     //if (IdxVal >= NumElems/2)
10587     //  IdxVal -= NumElems/2;
10588     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10589     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10590                        DAG.getConstant(IdxVal, MVT::i32));
10591   }
10592
10593   assert(VecVT.is128BitVector() && "Unexpected vector length");
10594
10595   if (Subtarget->hasSSE41()) {
10596     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10597     if (Res.getNode())
10598       return Res;
10599   }
10600
10601   MVT VT = Op.getSimpleValueType();
10602   // TODO: handle v16i8.
10603   if (VT.getSizeInBits() == 16) {
10604     SDValue Vec = Op.getOperand(0);
10605     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10606     if (Idx == 0)
10607       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10608                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10609                                      DAG.getNode(ISD::BITCAST, dl,
10610                                                  MVT::v4i32, Vec),
10611                                      Op.getOperand(1)));
10612     // Transform it so it match pextrw which produces a 32-bit result.
10613     MVT EltVT = MVT::i32;
10614     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10615                                   Op.getOperand(0), Op.getOperand(1));
10616     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10617                                   DAG.getValueType(VT));
10618     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10619   }
10620
10621   if (VT.getSizeInBits() == 32) {
10622     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10623     if (Idx == 0)
10624       return Op;
10625
10626     // SHUFPS the element to the lowest double word, then movss.
10627     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10628     MVT VVT = Op.getOperand(0).getSimpleValueType();
10629     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10630                                        DAG.getUNDEF(VVT), Mask);
10631     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10632                        DAG.getIntPtrConstant(0));
10633   }
10634
10635   if (VT.getSizeInBits() == 64) {
10636     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10637     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10638     //        to match extract_elt for f64.
10639     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10640     if (Idx == 0)
10641       return Op;
10642
10643     // UNPCKHPD the element to the lowest double word, then movsd.
10644     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10645     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10646     int Mask[2] = { 1, -1 };
10647     MVT VVT = Op.getOperand(0).getSimpleValueType();
10648     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10649                                        DAG.getUNDEF(VVT), Mask);
10650     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10651                        DAG.getIntPtrConstant(0));
10652   }
10653
10654   return SDValue();
10655 }
10656
10657 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10658   MVT VT = Op.getSimpleValueType();
10659   MVT EltVT = VT.getVectorElementType();
10660   SDLoc dl(Op);
10661
10662   SDValue N0 = Op.getOperand(0);
10663   SDValue N1 = Op.getOperand(1);
10664   SDValue N2 = Op.getOperand(2);
10665
10666   if (!VT.is128BitVector())
10667     return SDValue();
10668
10669   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10670       isa<ConstantSDNode>(N2)) {
10671     unsigned Opc;
10672     if (VT == MVT::v8i16)
10673       Opc = X86ISD::PINSRW;
10674     else if (VT == MVT::v16i8)
10675       Opc = X86ISD::PINSRB;
10676     else
10677       Opc = X86ISD::PINSRB;
10678
10679     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10680     // argument.
10681     if (N1.getValueType() != MVT::i32)
10682       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10683     if (N2.getValueType() != MVT::i32)
10684       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10685     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10686   }
10687
10688   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10689     // Bits [7:6] of the constant are the source select.  This will always be
10690     //  zero here.  The DAG Combiner may combine an extract_elt index into these
10691     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
10692     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10693     // Bits [5:4] of the constant are the destination select.  This is the
10694     //  value of the incoming immediate.
10695     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10696     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10697     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10698     // Create this as a scalar to vector..
10699     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10700     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10701   }
10702
10703   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10704     // PINSR* works with constant index.
10705     return Op;
10706   }
10707   return SDValue();
10708 }
10709
10710 /// Insert one bit to mask vector, like v16i1 or v8i1.
10711 /// AVX-512 feature.
10712 SDValue 
10713 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10714   SDLoc dl(Op);
10715   SDValue Vec = Op.getOperand(0);
10716   SDValue Elt = Op.getOperand(1);
10717   SDValue Idx = Op.getOperand(2);
10718   MVT VecVT = Vec.getSimpleValueType();
10719
10720   if (!isa<ConstantSDNode>(Idx)) {
10721     // Non constant index. Extend source and destination,
10722     // insert element and then truncate the result.
10723     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10724     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10725     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10726       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10727       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10728     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10729   }
10730
10731   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10732   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10733   if (Vec.getOpcode() == ISD::UNDEF)
10734     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10735                        DAG.getConstant(IdxVal, MVT::i8));
10736   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10737   unsigned MaxSift = rc->getSize()*8 - 1;
10738   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10739                     DAG.getConstant(MaxSift, MVT::i8));
10740   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10741                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10742   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10743 }
10744 SDValue
10745 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10746   MVT VT = Op.getSimpleValueType();
10747   MVT EltVT = VT.getVectorElementType();
10748   
10749   if (EltVT == MVT::i1)
10750     return InsertBitToMaskVector(Op, DAG);
10751
10752   SDLoc dl(Op);
10753   SDValue N0 = Op.getOperand(0);
10754   SDValue N1 = Op.getOperand(1);
10755   SDValue N2 = Op.getOperand(2);
10756
10757   // If this is a 256-bit vector result, first extract the 128-bit vector,
10758   // insert the element into the extracted half and then place it back.
10759   if (VT.is256BitVector() || VT.is512BitVector()) {
10760     if (!isa<ConstantSDNode>(N2))
10761       return SDValue();
10762
10763     // Get the desired 128-bit vector half.
10764     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10765     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10766
10767     // Insert the element into the desired half.
10768     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10769     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10770
10771     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10772                     DAG.getConstant(IdxIn128, MVT::i32));
10773
10774     // Insert the changed part back to the 256-bit vector
10775     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10776   }
10777
10778   if (Subtarget->hasSSE41())
10779     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10780
10781   if (EltVT == MVT::i8)
10782     return SDValue();
10783
10784   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10785     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10786     // as its second argument.
10787     if (N1.getValueType() != MVT::i32)
10788       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10789     if (N2.getValueType() != MVT::i32)
10790       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10791     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10792   }
10793   return SDValue();
10794 }
10795
10796 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10797   SDLoc dl(Op);
10798   MVT OpVT = Op.getSimpleValueType();
10799
10800   // If this is a 256-bit vector result, first insert into a 128-bit
10801   // vector and then insert into the 256-bit vector.
10802   if (!OpVT.is128BitVector()) {
10803     // Insert into a 128-bit vector.
10804     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10805     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10806                                  OpVT.getVectorNumElements() / SizeFactor);
10807
10808     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10809
10810     // Insert the 128-bit vector.
10811     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10812   }
10813
10814   if (OpVT == MVT::v1i64 &&
10815       Op.getOperand(0).getValueType() == MVT::i64)
10816     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10817
10818   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10819   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10820   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10821                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10822 }
10823
10824 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10825 // a simple subregister reference or explicit instructions to grab
10826 // upper bits of a vector.
10827 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10828                                       SelectionDAG &DAG) {
10829   SDLoc dl(Op);
10830   SDValue In =  Op.getOperand(0);
10831   SDValue Idx = Op.getOperand(1);
10832   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10833   MVT ResVT   = Op.getSimpleValueType();
10834   MVT InVT    = In.getSimpleValueType();
10835
10836   if (Subtarget->hasFp256()) {
10837     if (ResVT.is128BitVector() &&
10838         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10839         isa<ConstantSDNode>(Idx)) {
10840       return Extract128BitVector(In, IdxVal, DAG, dl);
10841     }
10842     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10843         isa<ConstantSDNode>(Idx)) {
10844       return Extract256BitVector(In, IdxVal, DAG, dl);
10845     }
10846   }
10847   return SDValue();
10848 }
10849
10850 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10851 // simple superregister reference or explicit instructions to insert
10852 // the upper bits of a vector.
10853 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10854                                      SelectionDAG &DAG) {
10855   if (Subtarget->hasFp256()) {
10856     SDLoc dl(Op.getNode());
10857     SDValue Vec = Op.getNode()->getOperand(0);
10858     SDValue SubVec = Op.getNode()->getOperand(1);
10859     SDValue Idx = Op.getNode()->getOperand(2);
10860
10861     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10862          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10863         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10864         isa<ConstantSDNode>(Idx)) {
10865       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10866       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10867     }
10868
10869     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10870         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10871         isa<ConstantSDNode>(Idx)) {
10872       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10873       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10874     }
10875   }
10876   return SDValue();
10877 }
10878
10879 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10880 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10881 // one of the above mentioned nodes. It has to be wrapped because otherwise
10882 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10883 // be used to form addressing mode. These wrapped nodes will be selected
10884 // into MOV32ri.
10885 SDValue
10886 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10887   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10888
10889   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10890   // global base reg.
10891   unsigned char OpFlag = 0;
10892   unsigned WrapperKind = X86ISD::Wrapper;
10893   CodeModel::Model M = DAG.getTarget().getCodeModel();
10894
10895   if (Subtarget->isPICStyleRIPRel() &&
10896       (M == CodeModel::Small || M == CodeModel::Kernel))
10897     WrapperKind = X86ISD::WrapperRIP;
10898   else if (Subtarget->isPICStyleGOT())
10899     OpFlag = X86II::MO_GOTOFF;
10900   else if (Subtarget->isPICStyleStubPIC())
10901     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10902
10903   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10904                                              CP->getAlignment(),
10905                                              CP->getOffset(), OpFlag);
10906   SDLoc DL(CP);
10907   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10908   // With PIC, the address is actually $g + Offset.
10909   if (OpFlag) {
10910     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10911                          DAG.getNode(X86ISD::GlobalBaseReg,
10912                                      SDLoc(), getPointerTy()),
10913                          Result);
10914   }
10915
10916   return Result;
10917 }
10918
10919 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10920   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10921
10922   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10923   // global base reg.
10924   unsigned char OpFlag = 0;
10925   unsigned WrapperKind = X86ISD::Wrapper;
10926   CodeModel::Model M = DAG.getTarget().getCodeModel();
10927
10928   if (Subtarget->isPICStyleRIPRel() &&
10929       (M == CodeModel::Small || M == CodeModel::Kernel))
10930     WrapperKind = X86ISD::WrapperRIP;
10931   else if (Subtarget->isPICStyleGOT())
10932     OpFlag = X86II::MO_GOTOFF;
10933   else if (Subtarget->isPICStyleStubPIC())
10934     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10935
10936   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10937                                           OpFlag);
10938   SDLoc DL(JT);
10939   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10940
10941   // With PIC, the address is actually $g + Offset.
10942   if (OpFlag)
10943     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10944                          DAG.getNode(X86ISD::GlobalBaseReg,
10945                                      SDLoc(), getPointerTy()),
10946                          Result);
10947
10948   return Result;
10949 }
10950
10951 SDValue
10952 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10953   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10954
10955   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10956   // global base reg.
10957   unsigned char OpFlag = 0;
10958   unsigned WrapperKind = X86ISD::Wrapper;
10959   CodeModel::Model M = DAG.getTarget().getCodeModel();
10960
10961   if (Subtarget->isPICStyleRIPRel() &&
10962       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10963     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10964       OpFlag = X86II::MO_GOTPCREL;
10965     WrapperKind = X86ISD::WrapperRIP;
10966   } else if (Subtarget->isPICStyleGOT()) {
10967     OpFlag = X86II::MO_GOT;
10968   } else if (Subtarget->isPICStyleStubPIC()) {
10969     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10970   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10971     OpFlag = X86II::MO_DARWIN_NONLAZY;
10972   }
10973
10974   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10975
10976   SDLoc DL(Op);
10977   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10978
10979   // With PIC, the address is actually $g + Offset.
10980   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10981       !Subtarget->is64Bit()) {
10982     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10983                          DAG.getNode(X86ISD::GlobalBaseReg,
10984                                      SDLoc(), getPointerTy()),
10985                          Result);
10986   }
10987
10988   // For symbols that require a load from a stub to get the address, emit the
10989   // load.
10990   if (isGlobalStubReference(OpFlag))
10991     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10992                          MachinePointerInfo::getGOT(), false, false, false, 0);
10993
10994   return Result;
10995 }
10996
10997 SDValue
10998 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10999   // Create the TargetBlockAddressAddress node.
11000   unsigned char OpFlags =
11001     Subtarget->ClassifyBlockAddressReference();
11002   CodeModel::Model M = DAG.getTarget().getCodeModel();
11003   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11004   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11005   SDLoc dl(Op);
11006   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11007                                              OpFlags);
11008
11009   if (Subtarget->isPICStyleRIPRel() &&
11010       (M == CodeModel::Small || M == CodeModel::Kernel))
11011     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11012   else
11013     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11014
11015   // With PIC, the address is actually $g + Offset.
11016   if (isGlobalRelativeToPICBase(OpFlags)) {
11017     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11018                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11019                          Result);
11020   }
11021
11022   return Result;
11023 }
11024
11025 SDValue
11026 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11027                                       int64_t Offset, SelectionDAG &DAG) const {
11028   // Create the TargetGlobalAddress node, folding in the constant
11029   // offset if it is legal.
11030   unsigned char OpFlags =
11031       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11032   CodeModel::Model M = DAG.getTarget().getCodeModel();
11033   SDValue Result;
11034   if (OpFlags == X86II::MO_NO_FLAG &&
11035       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11036     // A direct static reference to a global.
11037     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11038     Offset = 0;
11039   } else {
11040     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11041   }
11042
11043   if (Subtarget->isPICStyleRIPRel() &&
11044       (M == CodeModel::Small || M == CodeModel::Kernel))
11045     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11046   else
11047     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11048
11049   // With PIC, the address is actually $g + Offset.
11050   if (isGlobalRelativeToPICBase(OpFlags)) {
11051     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11052                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11053                          Result);
11054   }
11055
11056   // For globals that require a load from a stub to get the address, emit the
11057   // load.
11058   if (isGlobalStubReference(OpFlags))
11059     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11060                          MachinePointerInfo::getGOT(), false, false, false, 0);
11061
11062   // If there was a non-zero offset that we didn't fold, create an explicit
11063   // addition for it.
11064   if (Offset != 0)
11065     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11066                          DAG.getConstant(Offset, getPointerTy()));
11067
11068   return Result;
11069 }
11070
11071 SDValue
11072 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11073   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11074   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11075   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11076 }
11077
11078 static SDValue
11079 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11080            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11081            unsigned char OperandFlags, bool LocalDynamic = false) {
11082   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11083   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11084   SDLoc dl(GA);
11085   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11086                                            GA->getValueType(0),
11087                                            GA->getOffset(),
11088                                            OperandFlags);
11089
11090   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11091                                            : X86ISD::TLSADDR;
11092
11093   if (InFlag) {
11094     SDValue Ops[] = { Chain,  TGA, *InFlag };
11095     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11096   } else {
11097     SDValue Ops[]  = { Chain, TGA };
11098     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11099   }
11100
11101   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11102   MFI->setAdjustsStack(true);
11103
11104   SDValue Flag = Chain.getValue(1);
11105   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11106 }
11107
11108 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11109 static SDValue
11110 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11111                                 const EVT PtrVT) {
11112   SDValue InFlag;
11113   SDLoc dl(GA);  // ? function entry point might be better
11114   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11115                                    DAG.getNode(X86ISD::GlobalBaseReg,
11116                                                SDLoc(), PtrVT), InFlag);
11117   InFlag = Chain.getValue(1);
11118
11119   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11120 }
11121
11122 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11123 static SDValue
11124 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11125                                 const EVT PtrVT) {
11126   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11127                     X86::RAX, X86II::MO_TLSGD);
11128 }
11129
11130 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11131                                            SelectionDAG &DAG,
11132                                            const EVT PtrVT,
11133                                            bool is64Bit) {
11134   SDLoc dl(GA);
11135
11136   // Get the start address of the TLS block for this module.
11137   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11138       .getInfo<X86MachineFunctionInfo>();
11139   MFI->incNumLocalDynamicTLSAccesses();
11140
11141   SDValue Base;
11142   if (is64Bit) {
11143     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11144                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11145   } else {
11146     SDValue InFlag;
11147     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11148         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11149     InFlag = Chain.getValue(1);
11150     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11151                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11152   }
11153
11154   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11155   // of Base.
11156
11157   // Build x@dtpoff.
11158   unsigned char OperandFlags = X86II::MO_DTPOFF;
11159   unsigned WrapperKind = X86ISD::Wrapper;
11160   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11161                                            GA->getValueType(0),
11162                                            GA->getOffset(), OperandFlags);
11163   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11164
11165   // Add x@dtpoff with the base.
11166   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11167 }
11168
11169 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11170 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11171                                    const EVT PtrVT, TLSModel::Model model,
11172                                    bool is64Bit, bool isPIC) {
11173   SDLoc dl(GA);
11174
11175   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11176   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11177                                                          is64Bit ? 257 : 256));
11178
11179   SDValue ThreadPointer =
11180       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11181                   MachinePointerInfo(Ptr), false, false, false, 0);
11182
11183   unsigned char OperandFlags = 0;
11184   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11185   // initialexec.
11186   unsigned WrapperKind = X86ISD::Wrapper;
11187   if (model == TLSModel::LocalExec) {
11188     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11189   } else if (model == TLSModel::InitialExec) {
11190     if (is64Bit) {
11191       OperandFlags = X86II::MO_GOTTPOFF;
11192       WrapperKind = X86ISD::WrapperRIP;
11193     } else {
11194       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11195     }
11196   } else {
11197     llvm_unreachable("Unexpected model");
11198   }
11199
11200   // emit "addl x@ntpoff,%eax" (local exec)
11201   // or "addl x@indntpoff,%eax" (initial exec)
11202   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11203   SDValue TGA =
11204       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11205                                  GA->getOffset(), OperandFlags);
11206   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11207
11208   if (model == TLSModel::InitialExec) {
11209     if (isPIC && !is64Bit) {
11210       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11211                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11212                            Offset);
11213     }
11214
11215     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11216                          MachinePointerInfo::getGOT(), false, false, false, 0);
11217   }
11218
11219   // The address of the thread local variable is the add of the thread
11220   // pointer with the offset of the variable.
11221   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11222 }
11223
11224 SDValue
11225 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11226
11227   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11228   const GlobalValue *GV = GA->getGlobal();
11229
11230   if (Subtarget->isTargetELF()) {
11231     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11232
11233     switch (model) {
11234       case TLSModel::GeneralDynamic:
11235         if (Subtarget->is64Bit())
11236           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11237         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11238       case TLSModel::LocalDynamic:
11239         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11240                                            Subtarget->is64Bit());
11241       case TLSModel::InitialExec:
11242       case TLSModel::LocalExec:
11243         return LowerToTLSExecModel(
11244             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11245             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11246     }
11247     llvm_unreachable("Unknown TLS model.");
11248   }
11249
11250   if (Subtarget->isTargetDarwin()) {
11251     // Darwin only has one model of TLS.  Lower to that.
11252     unsigned char OpFlag = 0;
11253     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11254                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11255
11256     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11257     // global base reg.
11258     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11259                  !Subtarget->is64Bit();
11260     if (PIC32)
11261       OpFlag = X86II::MO_TLVP_PIC_BASE;
11262     else
11263       OpFlag = X86II::MO_TLVP;
11264     SDLoc DL(Op);
11265     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11266                                                 GA->getValueType(0),
11267                                                 GA->getOffset(), OpFlag);
11268     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11269
11270     // With PIC32, the address is actually $g + Offset.
11271     if (PIC32)
11272       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11273                            DAG.getNode(X86ISD::GlobalBaseReg,
11274                                        SDLoc(), getPointerTy()),
11275                            Offset);
11276
11277     // Lowering the machine isd will make sure everything is in the right
11278     // location.
11279     SDValue Chain = DAG.getEntryNode();
11280     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11281     SDValue Args[] = { Chain, Offset };
11282     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11283
11284     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11285     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11286     MFI->setAdjustsStack(true);
11287
11288     // And our return value (tls address) is in the standard call return value
11289     // location.
11290     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11291     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11292                               Chain.getValue(1));
11293   }
11294
11295   if (Subtarget->isTargetKnownWindowsMSVC() ||
11296       Subtarget->isTargetWindowsGNU()) {
11297     // Just use the implicit TLS architecture
11298     // Need to generate someting similar to:
11299     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11300     //                                  ; from TEB
11301     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11302     //   mov     rcx, qword [rdx+rcx*8]
11303     //   mov     eax, .tls$:tlsvar
11304     //   [rax+rcx] contains the address
11305     // Windows 64bit: gs:0x58
11306     // Windows 32bit: fs:__tls_array
11307
11308     SDLoc dl(GA);
11309     SDValue Chain = DAG.getEntryNode();
11310
11311     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11312     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11313     // use its literal value of 0x2C.
11314     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11315                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11316                                                              256)
11317                                         : Type::getInt32PtrTy(*DAG.getContext(),
11318                                                               257));
11319
11320     SDValue TlsArray =
11321         Subtarget->is64Bit()
11322             ? DAG.getIntPtrConstant(0x58)
11323             : (Subtarget->isTargetWindowsGNU()
11324                    ? DAG.getIntPtrConstant(0x2C)
11325                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11326
11327     SDValue ThreadPointer =
11328         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11329                     MachinePointerInfo(Ptr), false, false, false, 0);
11330
11331     // Load the _tls_index variable
11332     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11333     if (Subtarget->is64Bit())
11334       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11335                            IDX, MachinePointerInfo(), MVT::i32,
11336                            false, false, false, 0);
11337     else
11338       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11339                         false, false, false, 0);
11340
11341     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11342                                     getPointerTy());
11343     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11344
11345     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11346     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11347                       false, false, false, 0);
11348
11349     // Get the offset of start of .tls section
11350     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11351                                              GA->getValueType(0),
11352                                              GA->getOffset(), X86II::MO_SECREL);
11353     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11354
11355     // The address of the thread local variable is the add of the thread
11356     // pointer with the offset of the variable.
11357     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11358   }
11359
11360   llvm_unreachable("TLS not implemented for this target.");
11361 }
11362
11363 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11364 /// and take a 2 x i32 value to shift plus a shift amount.
11365 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11366   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11367   MVT VT = Op.getSimpleValueType();
11368   unsigned VTBits = VT.getSizeInBits();
11369   SDLoc dl(Op);
11370   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11371   SDValue ShOpLo = Op.getOperand(0);
11372   SDValue ShOpHi = Op.getOperand(1);
11373   SDValue ShAmt  = Op.getOperand(2);
11374   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11375   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11376   // during isel.
11377   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11378                                   DAG.getConstant(VTBits - 1, MVT::i8));
11379   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11380                                      DAG.getConstant(VTBits - 1, MVT::i8))
11381                        : DAG.getConstant(0, VT);
11382
11383   SDValue Tmp2, Tmp3;
11384   if (Op.getOpcode() == ISD::SHL_PARTS) {
11385     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11386     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11387   } else {
11388     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11389     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11390   }
11391
11392   // If the shift amount is larger or equal than the width of a part we can't
11393   // rely on the results of shld/shrd. Insert a test and select the appropriate
11394   // values for large shift amounts.
11395   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11396                                 DAG.getConstant(VTBits, MVT::i8));
11397   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11398                              AndNode, DAG.getConstant(0, MVT::i8));
11399
11400   SDValue Hi, Lo;
11401   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11402   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11403   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11404
11405   if (Op.getOpcode() == ISD::SHL_PARTS) {
11406     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11407     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11408   } else {
11409     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11410     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11411   }
11412
11413   SDValue Ops[2] = { Lo, Hi };
11414   return DAG.getMergeValues(Ops, dl);
11415 }
11416
11417 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11418                                            SelectionDAG &DAG) const {
11419   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11420
11421   if (SrcVT.isVector())
11422     return SDValue();
11423
11424   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11425          "Unknown SINT_TO_FP to lower!");
11426
11427   // These are really Legal; return the operand so the caller accepts it as
11428   // Legal.
11429   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11430     return Op;
11431   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11432       Subtarget->is64Bit()) {
11433     return Op;
11434   }
11435
11436   SDLoc dl(Op);
11437   unsigned Size = SrcVT.getSizeInBits()/8;
11438   MachineFunction &MF = DAG.getMachineFunction();
11439   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11440   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11441   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11442                                StackSlot,
11443                                MachinePointerInfo::getFixedStack(SSFI),
11444                                false, false, 0);
11445   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11446 }
11447
11448 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11449                                      SDValue StackSlot,
11450                                      SelectionDAG &DAG) const {
11451   // Build the FILD
11452   SDLoc DL(Op);
11453   SDVTList Tys;
11454   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11455   if (useSSE)
11456     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11457   else
11458     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11459
11460   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11461
11462   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11463   MachineMemOperand *MMO;
11464   if (FI) {
11465     int SSFI = FI->getIndex();
11466     MMO =
11467       DAG.getMachineFunction()
11468       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11469                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11470   } else {
11471     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11472     StackSlot = StackSlot.getOperand(1);
11473   }
11474   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11475   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11476                                            X86ISD::FILD, DL,
11477                                            Tys, Ops, SrcVT, MMO);
11478
11479   if (useSSE) {
11480     Chain = Result.getValue(1);
11481     SDValue InFlag = Result.getValue(2);
11482
11483     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11484     // shouldn't be necessary except that RFP cannot be live across
11485     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11486     MachineFunction &MF = DAG.getMachineFunction();
11487     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11488     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11489     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11490     Tys = DAG.getVTList(MVT::Other);
11491     SDValue Ops[] = {
11492       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11493     };
11494     MachineMemOperand *MMO =
11495       DAG.getMachineFunction()
11496       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11497                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11498
11499     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11500                                     Ops, Op.getValueType(), MMO);
11501     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11502                          MachinePointerInfo::getFixedStack(SSFI),
11503                          false, false, false, 0);
11504   }
11505
11506   return Result;
11507 }
11508
11509 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11510 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11511                                                SelectionDAG &DAG) const {
11512   // This algorithm is not obvious. Here it is what we're trying to output:
11513   /*
11514      movq       %rax,  %xmm0
11515      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11516      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11517      #ifdef __SSE3__
11518        haddpd   %xmm0, %xmm0
11519      #else
11520        pshufd   $0x4e, %xmm0, %xmm1
11521        addpd    %xmm1, %xmm0
11522      #endif
11523   */
11524
11525   SDLoc dl(Op);
11526   LLVMContext *Context = DAG.getContext();
11527
11528   // Build some magic constants.
11529   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11530   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11531   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11532
11533   SmallVector<Constant*,2> CV1;
11534   CV1.push_back(
11535     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11536                                       APInt(64, 0x4330000000000000ULL))));
11537   CV1.push_back(
11538     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11539                                       APInt(64, 0x4530000000000000ULL))));
11540   Constant *C1 = ConstantVector::get(CV1);
11541   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11542
11543   // Load the 64-bit value into an XMM register.
11544   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11545                             Op.getOperand(0));
11546   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11547                               MachinePointerInfo::getConstantPool(),
11548                               false, false, false, 16);
11549   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11550                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11551                               CLod0);
11552
11553   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11554                               MachinePointerInfo::getConstantPool(),
11555                               false, false, false, 16);
11556   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11557   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11558   SDValue Result;
11559
11560   if (Subtarget->hasSSE3()) {
11561     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11562     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11563   } else {
11564     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11565     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11566                                            S2F, 0x4E, DAG);
11567     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11568                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11569                          Sub);
11570   }
11571
11572   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11573                      DAG.getIntPtrConstant(0));
11574 }
11575
11576 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11577 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11578                                                SelectionDAG &DAG) const {
11579   SDLoc dl(Op);
11580   // FP constant to bias correct the final result.
11581   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11582                                    MVT::f64);
11583
11584   // Load the 32-bit value into an XMM register.
11585   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11586                              Op.getOperand(0));
11587
11588   // Zero out the upper parts of the register.
11589   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11590
11591   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11592                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11593                      DAG.getIntPtrConstant(0));
11594
11595   // Or the load with the bias.
11596   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11597                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11598                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11599                                                    MVT::v2f64, Load)),
11600                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11601                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11602                                                    MVT::v2f64, Bias)));
11603   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11604                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11605                    DAG.getIntPtrConstant(0));
11606
11607   // Subtract the bias.
11608   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11609
11610   // Handle final rounding.
11611   EVT DestVT = Op.getValueType();
11612
11613   if (DestVT.bitsLT(MVT::f64))
11614     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11615                        DAG.getIntPtrConstant(0));
11616   if (DestVT.bitsGT(MVT::f64))
11617     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11618
11619   // Handle final rounding.
11620   return Sub;
11621 }
11622
11623 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11624                                                SelectionDAG &DAG) const {
11625   SDValue N0 = Op.getOperand(0);
11626   MVT SVT = N0.getSimpleValueType();
11627   SDLoc dl(Op);
11628
11629   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11630           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11631          "Custom UINT_TO_FP is not supported!");
11632
11633   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11634   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11635                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11636 }
11637
11638 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11639                                            SelectionDAG &DAG) const {
11640   SDValue N0 = Op.getOperand(0);
11641   SDLoc dl(Op);
11642
11643   if (Op.getValueType().isVector())
11644     return lowerUINT_TO_FP_vec(Op, DAG);
11645
11646   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11647   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11648   // the optimization here.
11649   if (DAG.SignBitIsZero(N0))
11650     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11651
11652   MVT SrcVT = N0.getSimpleValueType();
11653   MVT DstVT = Op.getSimpleValueType();
11654   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11655     return LowerUINT_TO_FP_i64(Op, DAG);
11656   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11657     return LowerUINT_TO_FP_i32(Op, DAG);
11658   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11659     return SDValue();
11660
11661   // Make a 64-bit buffer, and use it to build an FILD.
11662   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11663   if (SrcVT == MVT::i32) {
11664     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11665     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11666                                      getPointerTy(), StackSlot, WordOff);
11667     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11668                                   StackSlot, MachinePointerInfo(),
11669                                   false, false, 0);
11670     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11671                                   OffsetSlot, MachinePointerInfo(),
11672                                   false, false, 0);
11673     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11674     return Fild;
11675   }
11676
11677   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11678   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11679                                StackSlot, MachinePointerInfo(),
11680                                false, false, 0);
11681   // For i64 source, we need to add the appropriate power of 2 if the input
11682   // was negative.  This is the same as the optimization in
11683   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11684   // we must be careful to do the computation in x87 extended precision, not
11685   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11686   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11687   MachineMemOperand *MMO =
11688     DAG.getMachineFunction()
11689     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11690                           MachineMemOperand::MOLoad, 8, 8);
11691
11692   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11693   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11694   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11695                                          MVT::i64, MMO);
11696
11697   APInt FF(32, 0x5F800000ULL);
11698
11699   // Check whether the sign bit is set.
11700   SDValue SignSet = DAG.getSetCC(dl,
11701                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11702                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11703                                  ISD::SETLT);
11704
11705   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11706   SDValue FudgePtr = DAG.getConstantPool(
11707                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11708                                          getPointerTy());
11709
11710   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11711   SDValue Zero = DAG.getIntPtrConstant(0);
11712   SDValue Four = DAG.getIntPtrConstant(4);
11713   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11714                                Zero, Four);
11715   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11716
11717   // Load the value out, extending it from f32 to f80.
11718   // FIXME: Avoid the extend by constructing the right constant pool?
11719   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11720                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11721                                  MVT::f32, false, false, false, 4);
11722   // Extend everything to 80 bits to force it to be done on x87.
11723   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11724   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11725 }
11726
11727 std::pair<SDValue,SDValue>
11728 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11729                                     bool IsSigned, bool IsReplace) const {
11730   SDLoc DL(Op);
11731
11732   EVT DstTy = Op.getValueType();
11733
11734   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11735     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11736     DstTy = MVT::i64;
11737   }
11738
11739   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11740          DstTy.getSimpleVT() >= MVT::i16 &&
11741          "Unknown FP_TO_INT to lower!");
11742
11743   // These are really Legal.
11744   if (DstTy == MVT::i32 &&
11745       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11746     return std::make_pair(SDValue(), SDValue());
11747   if (Subtarget->is64Bit() &&
11748       DstTy == MVT::i64 &&
11749       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11750     return std::make_pair(SDValue(), SDValue());
11751
11752   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11753   // stack slot, or into the FTOL runtime function.
11754   MachineFunction &MF = DAG.getMachineFunction();
11755   unsigned MemSize = DstTy.getSizeInBits()/8;
11756   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11757   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11758
11759   unsigned Opc;
11760   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11761     Opc = X86ISD::WIN_FTOL;
11762   else
11763     switch (DstTy.getSimpleVT().SimpleTy) {
11764     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11765     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11766     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11767     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11768     }
11769
11770   SDValue Chain = DAG.getEntryNode();
11771   SDValue Value = Op.getOperand(0);
11772   EVT TheVT = Op.getOperand(0).getValueType();
11773   // FIXME This causes a redundant load/store if the SSE-class value is already
11774   // in memory, such as if it is on the callstack.
11775   if (isScalarFPTypeInSSEReg(TheVT)) {
11776     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11777     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11778                          MachinePointerInfo::getFixedStack(SSFI),
11779                          false, false, 0);
11780     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11781     SDValue Ops[] = {
11782       Chain, StackSlot, DAG.getValueType(TheVT)
11783     };
11784
11785     MachineMemOperand *MMO =
11786       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11787                               MachineMemOperand::MOLoad, MemSize, MemSize);
11788     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11789     Chain = Value.getValue(1);
11790     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11791     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11792   }
11793
11794   MachineMemOperand *MMO =
11795     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11796                             MachineMemOperand::MOStore, MemSize, MemSize);
11797
11798   if (Opc != X86ISD::WIN_FTOL) {
11799     // Build the FP_TO_INT*_IN_MEM
11800     SDValue Ops[] = { Chain, Value, StackSlot };
11801     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11802                                            Ops, DstTy, MMO);
11803     return std::make_pair(FIST, StackSlot);
11804   } else {
11805     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11806       DAG.getVTList(MVT::Other, MVT::Glue),
11807       Chain, Value);
11808     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11809       MVT::i32, ftol.getValue(1));
11810     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11811       MVT::i32, eax.getValue(2));
11812     SDValue Ops[] = { eax, edx };
11813     SDValue pair = IsReplace
11814       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11815       : DAG.getMergeValues(Ops, DL);
11816     return std::make_pair(pair, SDValue());
11817   }
11818 }
11819
11820 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11821                               const X86Subtarget *Subtarget) {
11822   MVT VT = Op->getSimpleValueType(0);
11823   SDValue In = Op->getOperand(0);
11824   MVT InVT = In.getSimpleValueType();
11825   SDLoc dl(Op);
11826
11827   // Optimize vectors in AVX mode:
11828   //
11829   //   v8i16 -> v8i32
11830   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11831   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11832   //   Concat upper and lower parts.
11833   //
11834   //   v4i32 -> v4i64
11835   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11836   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11837   //   Concat upper and lower parts.
11838   //
11839
11840   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11841       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11842       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11843     return SDValue();
11844
11845   if (Subtarget->hasInt256())
11846     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11847
11848   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11849   SDValue Undef = DAG.getUNDEF(InVT);
11850   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11851   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11852   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11853
11854   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11855                              VT.getVectorNumElements()/2);
11856
11857   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11858   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11859
11860   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11861 }
11862
11863 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11864                                         SelectionDAG &DAG) {
11865   MVT VT = Op->getSimpleValueType(0);
11866   SDValue In = Op->getOperand(0);
11867   MVT InVT = In.getSimpleValueType();
11868   SDLoc DL(Op);
11869   unsigned int NumElts = VT.getVectorNumElements();
11870   if (NumElts != 8 && NumElts != 16)
11871     return SDValue();
11872
11873   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11874     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11875
11876   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11878   // Now we have only mask extension
11879   assert(InVT.getVectorElementType() == MVT::i1);
11880   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11881   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11882   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11883   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11884   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11885                            MachinePointerInfo::getConstantPool(),
11886                            false, false, false, Alignment);
11887
11888   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11889   if (VT.is512BitVector())
11890     return Brcst;
11891   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11892 }
11893
11894 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11895                                SelectionDAG &DAG) {
11896   if (Subtarget->hasFp256()) {
11897     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11898     if (Res.getNode())
11899       return Res;
11900   }
11901
11902   return SDValue();
11903 }
11904
11905 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11906                                 SelectionDAG &DAG) {
11907   SDLoc DL(Op);
11908   MVT VT = Op.getSimpleValueType();
11909   SDValue In = Op.getOperand(0);
11910   MVT SVT = In.getSimpleValueType();
11911
11912   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11913     return LowerZERO_EXTEND_AVX512(Op, DAG);
11914
11915   if (Subtarget->hasFp256()) {
11916     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11917     if (Res.getNode())
11918       return Res;
11919   }
11920
11921   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11922          VT.getVectorNumElements() != SVT.getVectorNumElements());
11923   return SDValue();
11924 }
11925
11926 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11927   SDLoc DL(Op);
11928   MVT VT = Op.getSimpleValueType();
11929   SDValue In = Op.getOperand(0);
11930   MVT InVT = In.getSimpleValueType();
11931
11932   if (VT == MVT::i1) {
11933     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11934            "Invalid scalar TRUNCATE operation");
11935     if (InVT.getSizeInBits() >= 32)
11936       return SDValue();
11937     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11938     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11939   }
11940   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11941          "Invalid TRUNCATE operation");
11942
11943   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11944     if (VT.getVectorElementType().getSizeInBits() >=8)
11945       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11946
11947     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11948     unsigned NumElts = InVT.getVectorNumElements();
11949     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11950     if (InVT.getSizeInBits() < 512) {
11951       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11952       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11953       InVT = ExtVT;
11954     }
11955     
11956     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11957     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11958     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11959     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11960     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11961                            MachinePointerInfo::getConstantPool(),
11962                            false, false, false, Alignment);
11963     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11964     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11965     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11966   }
11967
11968   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11969     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11970     if (Subtarget->hasInt256()) {
11971       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11972       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11973       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11974                                 ShufMask);
11975       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11976                          DAG.getIntPtrConstant(0));
11977     }
11978
11979     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11980                                DAG.getIntPtrConstant(0));
11981     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11982                                DAG.getIntPtrConstant(2));
11983     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11984     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11985     static const int ShufMask[] = {0, 2, 4, 6};
11986     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11987   }
11988
11989   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11990     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11991     if (Subtarget->hasInt256()) {
11992       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11993
11994       SmallVector<SDValue,32> pshufbMask;
11995       for (unsigned i = 0; i < 2; ++i) {
11996         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11997         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11998         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11999         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12000         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12001         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12002         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12003         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12004         for (unsigned j = 0; j < 8; ++j)
12005           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12006       }
12007       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12008       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12009       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12010
12011       static const int ShufMask[] = {0,  2,  -1,  -1};
12012       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12013                                 &ShufMask[0]);
12014       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12015                        DAG.getIntPtrConstant(0));
12016       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12017     }
12018
12019     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12020                                DAG.getIntPtrConstant(0));
12021
12022     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12023                                DAG.getIntPtrConstant(4));
12024
12025     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12026     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12027
12028     // The PSHUFB mask:
12029     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12030                                    -1, -1, -1, -1, -1, -1, -1, -1};
12031
12032     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12033     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12034     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12035
12036     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12037     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12038
12039     // The MOVLHPS Mask:
12040     static const int ShufMask2[] = {0, 1, 4, 5};
12041     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12042     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12043   }
12044
12045   // Handle truncation of V256 to V128 using shuffles.
12046   if (!VT.is128BitVector() || !InVT.is256BitVector())
12047     return SDValue();
12048
12049   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12050
12051   unsigned NumElems = VT.getVectorNumElements();
12052   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12053
12054   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12055   // Prepare truncation shuffle mask
12056   for (unsigned i = 0; i != NumElems; ++i)
12057     MaskVec[i] = i * 2;
12058   SDValue V = DAG.getVectorShuffle(NVT, DL,
12059                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12060                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12061   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12062                      DAG.getIntPtrConstant(0));
12063 }
12064
12065 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12066                                            SelectionDAG &DAG) const {
12067   assert(!Op.getSimpleValueType().isVector());
12068
12069   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12070     /*IsSigned=*/ true, /*IsReplace=*/ false);
12071   SDValue FIST = Vals.first, StackSlot = Vals.second;
12072   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12073   if (!FIST.getNode()) return Op;
12074
12075   if (StackSlot.getNode())
12076     // Load the result.
12077     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12078                        FIST, StackSlot, MachinePointerInfo(),
12079                        false, false, false, 0);
12080
12081   // The node is the result.
12082   return FIST;
12083 }
12084
12085 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12086                                            SelectionDAG &DAG) const {
12087   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12088     /*IsSigned=*/ false, /*IsReplace=*/ false);
12089   SDValue FIST = Vals.first, StackSlot = Vals.second;
12090   assert(FIST.getNode() && "Unexpected failure");
12091
12092   if (StackSlot.getNode())
12093     // Load the result.
12094     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12095                        FIST, StackSlot, MachinePointerInfo(),
12096                        false, false, false, 0);
12097
12098   // The node is the result.
12099   return FIST;
12100 }
12101
12102 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12103   SDLoc DL(Op);
12104   MVT VT = Op.getSimpleValueType();
12105   SDValue In = Op.getOperand(0);
12106   MVT SVT = In.getSimpleValueType();
12107
12108   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12109
12110   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12111                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12112                                  In, DAG.getUNDEF(SVT)));
12113 }
12114
12115 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
12116   LLVMContext *Context = DAG.getContext();
12117   SDLoc dl(Op);
12118   MVT VT = Op.getSimpleValueType();
12119   MVT EltVT = VT;
12120   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12121   if (VT.isVector()) {
12122     EltVT = VT.getVectorElementType();
12123     NumElts = VT.getVectorNumElements();
12124   }
12125   Constant *C;
12126   if (EltVT == MVT::f64)
12127     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12128                                           APInt(64, ~(1ULL << 63))));
12129   else
12130     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12131                                           APInt(32, ~(1U << 31))));
12132   C = ConstantVector::getSplat(NumElts, C);
12133   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12134   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12135   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12136   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12137                              MachinePointerInfo::getConstantPool(),
12138                              false, false, false, Alignment);
12139   if (VT.isVector()) {
12140     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12141     return DAG.getNode(ISD::BITCAST, dl, VT,
12142                        DAG.getNode(ISD::AND, dl, ANDVT,
12143                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
12144                                                Op.getOperand(0)),
12145                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
12146   }
12147   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
12148 }
12149
12150 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
12151   LLVMContext *Context = DAG.getContext();
12152   SDLoc dl(Op);
12153   MVT VT = Op.getSimpleValueType();
12154   MVT EltVT = VT;
12155   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12156   if (VT.isVector()) {
12157     EltVT = VT.getVectorElementType();
12158     NumElts = VT.getVectorNumElements();
12159   }
12160   Constant *C;
12161   if (EltVT == MVT::f64)
12162     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12163                                           APInt(64, 1ULL << 63)));
12164   else
12165     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12166                                           APInt(32, 1U << 31)));
12167   C = ConstantVector::getSplat(NumElts, C);
12168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12169   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12170   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12171   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12172                              MachinePointerInfo::getConstantPool(),
12173                              false, false, false, Alignment);
12174   if (VT.isVector()) {
12175     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
12176     return DAG.getNode(ISD::BITCAST, dl, VT,
12177                        DAG.getNode(ISD::XOR, dl, XORVT,
12178                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
12179                                                Op.getOperand(0)),
12180                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
12181   }
12182
12183   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
12184 }
12185
12186 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12187   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12188   LLVMContext *Context = DAG.getContext();
12189   SDValue Op0 = Op.getOperand(0);
12190   SDValue Op1 = Op.getOperand(1);
12191   SDLoc dl(Op);
12192   MVT VT = Op.getSimpleValueType();
12193   MVT SrcVT = Op1.getSimpleValueType();
12194
12195   // If second operand is smaller, extend it first.
12196   if (SrcVT.bitsLT(VT)) {
12197     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12198     SrcVT = VT;
12199   }
12200   // And if it is bigger, shrink it first.
12201   if (SrcVT.bitsGT(VT)) {
12202     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12203     SrcVT = VT;
12204   }
12205
12206   // At this point the operands and the result should have the same
12207   // type, and that won't be f80 since that is not custom lowered.
12208
12209   // First get the sign bit of second operand.
12210   SmallVector<Constant*,4> CV;
12211   if (SrcVT == MVT::f64) {
12212     const fltSemantics &Sem = APFloat::IEEEdouble;
12213     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12214     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12215   } else {
12216     const fltSemantics &Sem = APFloat::IEEEsingle;
12217     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12218     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12219     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12220     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12221   }
12222   Constant *C = ConstantVector::get(CV);
12223   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12224   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12225                               MachinePointerInfo::getConstantPool(),
12226                               false, false, false, 16);
12227   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12228
12229   // Shift sign bit right or left if the two operands have different types.
12230   if (SrcVT.bitsGT(VT)) {
12231     // Op0 is MVT::f32, Op1 is MVT::f64.
12232     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12233     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12234                           DAG.getConstant(32, MVT::i32));
12235     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12236     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12237                           DAG.getIntPtrConstant(0));
12238   }
12239
12240   // Clear first operand sign bit.
12241   CV.clear();
12242   if (VT == MVT::f64) {
12243     const fltSemantics &Sem = APFloat::IEEEdouble;
12244     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12245                                                    APInt(64, ~(1ULL << 63)))));
12246     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12247   } else {
12248     const fltSemantics &Sem = APFloat::IEEEsingle;
12249     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12250                                                    APInt(32, ~(1U << 31)))));
12251     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12252     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12253     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12254   }
12255   C = ConstantVector::get(CV);
12256   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12257   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12258                               MachinePointerInfo::getConstantPool(),
12259                               false, false, false, 16);
12260   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12261
12262   // Or the value with the sign bit.
12263   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12264 }
12265
12266 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12267   SDValue N0 = Op.getOperand(0);
12268   SDLoc dl(Op);
12269   MVT VT = Op.getSimpleValueType();
12270
12271   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12272   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12273                                   DAG.getConstant(1, VT));
12274   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12275 }
12276
12277 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12278 //
12279 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12280                                       SelectionDAG &DAG) {
12281   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12282
12283   if (!Subtarget->hasSSE41())
12284     return SDValue();
12285
12286   if (!Op->hasOneUse())
12287     return SDValue();
12288
12289   SDNode *N = Op.getNode();
12290   SDLoc DL(N);
12291
12292   SmallVector<SDValue, 8> Opnds;
12293   DenseMap<SDValue, unsigned> VecInMap;
12294   SmallVector<SDValue, 8> VecIns;
12295   EVT VT = MVT::Other;
12296
12297   // Recognize a special case where a vector is casted into wide integer to
12298   // test all 0s.
12299   Opnds.push_back(N->getOperand(0));
12300   Opnds.push_back(N->getOperand(1));
12301
12302   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12303     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12304     // BFS traverse all OR'd operands.
12305     if (I->getOpcode() == ISD::OR) {
12306       Opnds.push_back(I->getOperand(0));
12307       Opnds.push_back(I->getOperand(1));
12308       // Re-evaluate the number of nodes to be traversed.
12309       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12310       continue;
12311     }
12312
12313     // Quit if a non-EXTRACT_VECTOR_ELT
12314     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12315       return SDValue();
12316
12317     // Quit if without a constant index.
12318     SDValue Idx = I->getOperand(1);
12319     if (!isa<ConstantSDNode>(Idx))
12320       return SDValue();
12321
12322     SDValue ExtractedFromVec = I->getOperand(0);
12323     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12324     if (M == VecInMap.end()) {
12325       VT = ExtractedFromVec.getValueType();
12326       // Quit if not 128/256-bit vector.
12327       if (!VT.is128BitVector() && !VT.is256BitVector())
12328         return SDValue();
12329       // Quit if not the same type.
12330       if (VecInMap.begin() != VecInMap.end() &&
12331           VT != VecInMap.begin()->first.getValueType())
12332         return SDValue();
12333       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12334       VecIns.push_back(ExtractedFromVec);
12335     }
12336     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12337   }
12338
12339   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12340          "Not extracted from 128-/256-bit vector.");
12341
12342   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12343
12344   for (DenseMap<SDValue, unsigned>::const_iterator
12345         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12346     // Quit if not all elements are used.
12347     if (I->second != FullMask)
12348       return SDValue();
12349   }
12350
12351   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12352
12353   // Cast all vectors into TestVT for PTEST.
12354   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12355     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12356
12357   // If more than one full vectors are evaluated, OR them first before PTEST.
12358   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12359     // Each iteration will OR 2 nodes and append the result until there is only
12360     // 1 node left, i.e. the final OR'd value of all vectors.
12361     SDValue LHS = VecIns[Slot];
12362     SDValue RHS = VecIns[Slot + 1];
12363     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12364   }
12365
12366   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12367                      VecIns.back(), VecIns.back());
12368 }
12369
12370 /// \brief return true if \c Op has a use that doesn't just read flags.
12371 static bool hasNonFlagsUse(SDValue Op) {
12372   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12373        ++UI) {
12374     SDNode *User = *UI;
12375     unsigned UOpNo = UI.getOperandNo();
12376     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12377       // Look pass truncate.
12378       UOpNo = User->use_begin().getOperandNo();
12379       User = *User->use_begin();
12380     }
12381
12382     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12383         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12384       return true;
12385   }
12386   return false;
12387 }
12388
12389 /// Emit nodes that will be selected as "test Op0,Op0", or something
12390 /// equivalent.
12391 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12392                                     SelectionDAG &DAG) const {
12393   if (Op.getValueType() == MVT::i1)
12394     // KORTEST instruction should be selected
12395     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12396                        DAG.getConstant(0, Op.getValueType()));
12397
12398   // CF and OF aren't always set the way we want. Determine which
12399   // of these we need.
12400   bool NeedCF = false;
12401   bool NeedOF = false;
12402   switch (X86CC) {
12403   default: break;
12404   case X86::COND_A: case X86::COND_AE:
12405   case X86::COND_B: case X86::COND_BE:
12406     NeedCF = true;
12407     break;
12408   case X86::COND_G: case X86::COND_GE:
12409   case X86::COND_L: case X86::COND_LE:
12410   case X86::COND_O: case X86::COND_NO: {
12411     // Check if we really need to set the
12412     // Overflow flag. If NoSignedWrap is present
12413     // that is not actually needed.
12414     switch (Op->getOpcode()) {
12415     case ISD::ADD:
12416     case ISD::SUB:
12417     case ISD::MUL:
12418     case ISD::SHL: {
12419       const BinaryWithFlagsSDNode *BinNode =
12420           cast<BinaryWithFlagsSDNode>(Op.getNode());
12421       if (BinNode->hasNoSignedWrap())
12422         break;
12423     }
12424     default:
12425       NeedOF = true;
12426       break;
12427     }
12428     break;
12429   }
12430   }
12431   // See if we can use the EFLAGS value from the operand instead of
12432   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12433   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12434   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12435     // Emit a CMP with 0, which is the TEST pattern.
12436     //if (Op.getValueType() == MVT::i1)
12437     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12438     //                     DAG.getConstant(0, MVT::i1));
12439     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12440                        DAG.getConstant(0, Op.getValueType()));
12441   }
12442   unsigned Opcode = 0;
12443   unsigned NumOperands = 0;
12444
12445   // Truncate operations may prevent the merge of the SETCC instruction
12446   // and the arithmetic instruction before it. Attempt to truncate the operands
12447   // of the arithmetic instruction and use a reduced bit-width instruction.
12448   bool NeedTruncation = false;
12449   SDValue ArithOp = Op;
12450   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12451     SDValue Arith = Op->getOperand(0);
12452     // Both the trunc and the arithmetic op need to have one user each.
12453     if (Arith->hasOneUse())
12454       switch (Arith.getOpcode()) {
12455         default: break;
12456         case ISD::ADD:
12457         case ISD::SUB:
12458         case ISD::AND:
12459         case ISD::OR:
12460         case ISD::XOR: {
12461           NeedTruncation = true;
12462           ArithOp = Arith;
12463         }
12464       }
12465   }
12466
12467   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12468   // which may be the result of a CAST.  We use the variable 'Op', which is the
12469   // non-casted variable when we check for possible users.
12470   switch (ArithOp.getOpcode()) {
12471   case ISD::ADD:
12472     // Due to an isel shortcoming, be conservative if this add is likely to be
12473     // selected as part of a load-modify-store instruction. When the root node
12474     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12475     // uses of other nodes in the match, such as the ADD in this case. This
12476     // leads to the ADD being left around and reselected, with the result being
12477     // two adds in the output.  Alas, even if none our users are stores, that
12478     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12479     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12480     // climbing the DAG back to the root, and it doesn't seem to be worth the
12481     // effort.
12482     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12483          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12484       if (UI->getOpcode() != ISD::CopyToReg &&
12485           UI->getOpcode() != ISD::SETCC &&
12486           UI->getOpcode() != ISD::STORE)
12487         goto default_case;
12488
12489     if (ConstantSDNode *C =
12490         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12491       // An add of one will be selected as an INC.
12492       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12493         Opcode = X86ISD::INC;
12494         NumOperands = 1;
12495         break;
12496       }
12497
12498       // An add of negative one (subtract of one) will be selected as a DEC.
12499       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12500         Opcode = X86ISD::DEC;
12501         NumOperands = 1;
12502         break;
12503       }
12504     }
12505
12506     // Otherwise use a regular EFLAGS-setting add.
12507     Opcode = X86ISD::ADD;
12508     NumOperands = 2;
12509     break;
12510   case ISD::SHL:
12511   case ISD::SRL:
12512     // If we have a constant logical shift that's only used in a comparison
12513     // against zero turn it into an equivalent AND. This allows turning it into
12514     // a TEST instruction later.
12515     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12516         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12517       EVT VT = Op.getValueType();
12518       unsigned BitWidth = VT.getSizeInBits();
12519       unsigned ShAmt = Op->getConstantOperandVal(1);
12520       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12521         break;
12522       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12523                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12524                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12525       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12526         break;
12527       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12528                                 DAG.getConstant(Mask, VT));
12529       DAG.ReplaceAllUsesWith(Op, New);
12530       Op = New;
12531     }
12532     break;
12533
12534   case ISD::AND:
12535     // If the primary and result isn't used, don't bother using X86ISD::AND,
12536     // because a TEST instruction will be better.
12537     if (!hasNonFlagsUse(Op))
12538       break;
12539     // FALL THROUGH
12540   case ISD::SUB:
12541   case ISD::OR:
12542   case ISD::XOR:
12543     // Due to the ISEL shortcoming noted above, be conservative if this op is
12544     // likely to be selected as part of a load-modify-store instruction.
12545     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12546            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12547       if (UI->getOpcode() == ISD::STORE)
12548         goto default_case;
12549
12550     // Otherwise use a regular EFLAGS-setting instruction.
12551     switch (ArithOp.getOpcode()) {
12552     default: llvm_unreachable("unexpected operator!");
12553     case ISD::SUB: Opcode = X86ISD::SUB; break;
12554     case ISD::XOR: Opcode = X86ISD::XOR; break;
12555     case ISD::AND: Opcode = X86ISD::AND; break;
12556     case ISD::OR: {
12557       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12558         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12559         if (EFLAGS.getNode())
12560           return EFLAGS;
12561       }
12562       Opcode = X86ISD::OR;
12563       break;
12564     }
12565     }
12566
12567     NumOperands = 2;
12568     break;
12569   case X86ISD::ADD:
12570   case X86ISD::SUB:
12571   case X86ISD::INC:
12572   case X86ISD::DEC:
12573   case X86ISD::OR:
12574   case X86ISD::XOR:
12575   case X86ISD::AND:
12576     return SDValue(Op.getNode(), 1);
12577   default:
12578   default_case:
12579     break;
12580   }
12581
12582   // If we found that truncation is beneficial, perform the truncation and
12583   // update 'Op'.
12584   if (NeedTruncation) {
12585     EVT VT = Op.getValueType();
12586     SDValue WideVal = Op->getOperand(0);
12587     EVT WideVT = WideVal.getValueType();
12588     unsigned ConvertedOp = 0;
12589     // Use a target machine opcode to prevent further DAGCombine
12590     // optimizations that may separate the arithmetic operations
12591     // from the setcc node.
12592     switch (WideVal.getOpcode()) {
12593       default: break;
12594       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12595       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12596       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12597       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12598       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12599     }
12600
12601     if (ConvertedOp) {
12602       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12603       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12604         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12605         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12606         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12607       }
12608     }
12609   }
12610
12611   if (Opcode == 0)
12612     // Emit a CMP with 0, which is the TEST pattern.
12613     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12614                        DAG.getConstant(0, Op.getValueType()));
12615
12616   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12617   SmallVector<SDValue, 4> Ops;
12618   for (unsigned i = 0; i != NumOperands; ++i)
12619     Ops.push_back(Op.getOperand(i));
12620
12621   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12622   DAG.ReplaceAllUsesWith(Op, New);
12623   return SDValue(New.getNode(), 1);
12624 }
12625
12626 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12627 /// equivalent.
12628 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12629                                    SDLoc dl, SelectionDAG &DAG) const {
12630   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12631     if (C->getAPIntValue() == 0)
12632       return EmitTest(Op0, X86CC, dl, DAG);
12633
12634      if (Op0.getValueType() == MVT::i1)
12635        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12636   }
12637  
12638   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12639        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12640     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12641     // This avoids subregister aliasing issues. Keep the smaller reference 
12642     // if we're optimizing for size, however, as that'll allow better folding 
12643     // of memory operations.
12644     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12645         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12646              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12647         !Subtarget->isAtom()) {
12648       unsigned ExtendOp =
12649           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12650       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12651       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12652     }
12653     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12654     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12655     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12656                               Op0, Op1);
12657     return SDValue(Sub.getNode(), 1);
12658   }
12659   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12660 }
12661
12662 /// Convert a comparison if required by the subtarget.
12663 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12664                                                  SelectionDAG &DAG) const {
12665   // If the subtarget does not support the FUCOMI instruction, floating-point
12666   // comparisons have to be converted.
12667   if (Subtarget->hasCMov() ||
12668       Cmp.getOpcode() != X86ISD::CMP ||
12669       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12670       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12671     return Cmp;
12672
12673   // The instruction selector will select an FUCOM instruction instead of
12674   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12675   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12676   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12677   SDLoc dl(Cmp);
12678   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12679   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12680   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12681                             DAG.getConstant(8, MVT::i8));
12682   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12683   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12684 }
12685
12686 static bool isAllOnes(SDValue V) {
12687   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12688   return C && C->isAllOnesValue();
12689 }
12690
12691 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12692 /// if it's possible.
12693 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12694                                      SDLoc dl, SelectionDAG &DAG) const {
12695   SDValue Op0 = And.getOperand(0);
12696   SDValue Op1 = And.getOperand(1);
12697   if (Op0.getOpcode() == ISD::TRUNCATE)
12698     Op0 = Op0.getOperand(0);
12699   if (Op1.getOpcode() == ISD::TRUNCATE)
12700     Op1 = Op1.getOperand(0);
12701
12702   SDValue LHS, RHS;
12703   if (Op1.getOpcode() == ISD::SHL)
12704     std::swap(Op0, Op1);
12705   if (Op0.getOpcode() == ISD::SHL) {
12706     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12707       if (And00C->getZExtValue() == 1) {
12708         // If we looked past a truncate, check that it's only truncating away
12709         // known zeros.
12710         unsigned BitWidth = Op0.getValueSizeInBits();
12711         unsigned AndBitWidth = And.getValueSizeInBits();
12712         if (BitWidth > AndBitWidth) {
12713           APInt Zeros, Ones;
12714           DAG.computeKnownBits(Op0, Zeros, Ones);
12715           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12716             return SDValue();
12717         }
12718         LHS = Op1;
12719         RHS = Op0.getOperand(1);
12720       }
12721   } else if (Op1.getOpcode() == ISD::Constant) {
12722     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12723     uint64_t AndRHSVal = AndRHS->getZExtValue();
12724     SDValue AndLHS = Op0;
12725
12726     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12727       LHS = AndLHS.getOperand(0);
12728       RHS = AndLHS.getOperand(1);
12729     }
12730
12731     // Use BT if the immediate can't be encoded in a TEST instruction.
12732     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12733       LHS = AndLHS;
12734       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12735     }
12736   }
12737
12738   if (LHS.getNode()) {
12739     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12740     // instruction.  Since the shift amount is in-range-or-undefined, we know
12741     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12742     // the encoding for the i16 version is larger than the i32 version.
12743     // Also promote i16 to i32 for performance / code size reason.
12744     if (LHS.getValueType() == MVT::i8 ||
12745         LHS.getValueType() == MVT::i16)
12746       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12747
12748     // If the operand types disagree, extend the shift amount to match.  Since
12749     // BT ignores high bits (like shifts) we can use anyextend.
12750     if (LHS.getValueType() != RHS.getValueType())
12751       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12752
12753     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12754     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12755     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12756                        DAG.getConstant(Cond, MVT::i8), BT);
12757   }
12758
12759   return SDValue();
12760 }
12761
12762 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12763 /// mask CMPs.
12764 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12765                               SDValue &Op1) {
12766   unsigned SSECC;
12767   bool Swap = false;
12768
12769   // SSE Condition code mapping:
12770   //  0 - EQ
12771   //  1 - LT
12772   //  2 - LE
12773   //  3 - UNORD
12774   //  4 - NEQ
12775   //  5 - NLT
12776   //  6 - NLE
12777   //  7 - ORD
12778   switch (SetCCOpcode) {
12779   default: llvm_unreachable("Unexpected SETCC condition");
12780   case ISD::SETOEQ:
12781   case ISD::SETEQ:  SSECC = 0; break;
12782   case ISD::SETOGT:
12783   case ISD::SETGT:  Swap = true; // Fallthrough
12784   case ISD::SETLT:
12785   case ISD::SETOLT: SSECC = 1; break;
12786   case ISD::SETOGE:
12787   case ISD::SETGE:  Swap = true; // Fallthrough
12788   case ISD::SETLE:
12789   case ISD::SETOLE: SSECC = 2; break;
12790   case ISD::SETUO:  SSECC = 3; break;
12791   case ISD::SETUNE:
12792   case ISD::SETNE:  SSECC = 4; break;
12793   case ISD::SETULE: Swap = true; // Fallthrough
12794   case ISD::SETUGE: SSECC = 5; break;
12795   case ISD::SETULT: Swap = true; // Fallthrough
12796   case ISD::SETUGT: SSECC = 6; break;
12797   case ISD::SETO:   SSECC = 7; break;
12798   case ISD::SETUEQ:
12799   case ISD::SETONE: SSECC = 8; break;
12800   }
12801   if (Swap)
12802     std::swap(Op0, Op1);
12803
12804   return SSECC;
12805 }
12806
12807 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12808 // ones, and then concatenate the result back.
12809 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12810   MVT VT = Op.getSimpleValueType();
12811
12812   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12813          "Unsupported value type for operation");
12814
12815   unsigned NumElems = VT.getVectorNumElements();
12816   SDLoc dl(Op);
12817   SDValue CC = Op.getOperand(2);
12818
12819   // Extract the LHS vectors
12820   SDValue LHS = Op.getOperand(0);
12821   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12822   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12823
12824   // Extract the RHS vectors
12825   SDValue RHS = Op.getOperand(1);
12826   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12827   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12828
12829   // Issue the operation on the smaller types and concatenate the result back
12830   MVT EltVT = VT.getVectorElementType();
12831   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12832   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12833                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12834                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12835 }
12836
12837 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12838                                      const X86Subtarget *Subtarget) {
12839   SDValue Op0 = Op.getOperand(0);
12840   SDValue Op1 = Op.getOperand(1);
12841   SDValue CC = Op.getOperand(2);
12842   MVT VT = Op.getSimpleValueType();
12843   SDLoc dl(Op);
12844
12845   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12846          Op.getValueType().getScalarType() == MVT::i1 &&
12847          "Cannot set masked compare for this operation");
12848
12849   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12850   unsigned  Opc = 0;
12851   bool Unsigned = false;
12852   bool Swap = false;
12853   unsigned SSECC;
12854   switch (SetCCOpcode) {
12855   default: llvm_unreachable("Unexpected SETCC condition");
12856   case ISD::SETNE:  SSECC = 4; break;
12857   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12858   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12859   case ISD::SETLT:  Swap = true; //fall-through
12860   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12861   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12862   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12863   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12864   case ISD::SETULE: Unsigned = true; //fall-through
12865   case ISD::SETLE:  SSECC = 2; break;
12866   }
12867
12868   if (Swap)
12869     std::swap(Op0, Op1);
12870   if (Opc)
12871     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12872   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12873   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12874                      DAG.getConstant(SSECC, MVT::i8));
12875 }
12876
12877 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12878 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12879 /// return an empty value.
12880 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12881 {
12882   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12883   if (!BV)
12884     return SDValue();
12885
12886   MVT VT = Op1.getSimpleValueType();
12887   MVT EVT = VT.getVectorElementType();
12888   unsigned n = VT.getVectorNumElements();
12889   SmallVector<SDValue, 8> ULTOp1;
12890
12891   for (unsigned i = 0; i < n; ++i) {
12892     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12893     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12894       return SDValue();
12895
12896     // Avoid underflow.
12897     APInt Val = Elt->getAPIntValue();
12898     if (Val == 0)
12899       return SDValue();
12900
12901     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12902   }
12903
12904   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12905 }
12906
12907 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12908                            SelectionDAG &DAG) {
12909   SDValue Op0 = Op.getOperand(0);
12910   SDValue Op1 = Op.getOperand(1);
12911   SDValue CC = Op.getOperand(2);
12912   MVT VT = Op.getSimpleValueType();
12913   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12914   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12915   SDLoc dl(Op);
12916
12917   if (isFP) {
12918 #ifndef NDEBUG
12919     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12920     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12921 #endif
12922
12923     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12924     unsigned Opc = X86ISD::CMPP;
12925     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12926       assert(VT.getVectorNumElements() <= 16);
12927       Opc = X86ISD::CMPM;
12928     }
12929     // In the two special cases we can't handle, emit two comparisons.
12930     if (SSECC == 8) {
12931       unsigned CC0, CC1;
12932       unsigned CombineOpc;
12933       if (SetCCOpcode == ISD::SETUEQ) {
12934         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12935       } else {
12936         assert(SetCCOpcode == ISD::SETONE);
12937         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12938       }
12939
12940       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12941                                  DAG.getConstant(CC0, MVT::i8));
12942       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12943                                  DAG.getConstant(CC1, MVT::i8));
12944       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12945     }
12946     // Handle all other FP comparisons here.
12947     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12948                        DAG.getConstant(SSECC, MVT::i8));
12949   }
12950
12951   // Break 256-bit integer vector compare into smaller ones.
12952   if (VT.is256BitVector() && !Subtarget->hasInt256())
12953     return Lower256IntVSETCC(Op, DAG);
12954
12955   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12956   EVT OpVT = Op1.getValueType();
12957   if (Subtarget->hasAVX512()) {
12958     if (Op1.getValueType().is512BitVector() ||
12959         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12960       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12961
12962     // In AVX-512 architecture setcc returns mask with i1 elements,
12963     // But there is no compare instruction for i8 and i16 elements.
12964     // We are not talking about 512-bit operands in this case, these
12965     // types are illegal.
12966     if (MaskResult &&
12967         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12968          OpVT.getVectorElementType().getSizeInBits() >= 8))
12969       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12970                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12971   }
12972
12973   // We are handling one of the integer comparisons here.  Since SSE only has
12974   // GT and EQ comparisons for integer, swapping operands and multiple
12975   // operations may be required for some comparisons.
12976   unsigned Opc;
12977   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12978   bool Subus = false;
12979
12980   switch (SetCCOpcode) {
12981   default: llvm_unreachable("Unexpected SETCC condition");
12982   case ISD::SETNE:  Invert = true;
12983   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12984   case ISD::SETLT:  Swap = true;
12985   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12986   case ISD::SETGE:  Swap = true;
12987   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12988                     Invert = true; break;
12989   case ISD::SETULT: Swap = true;
12990   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12991                     FlipSigns = true; break;
12992   case ISD::SETUGE: Swap = true;
12993   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12994                     FlipSigns = true; Invert = true; break;
12995   }
12996
12997   // Special case: Use min/max operations for SETULE/SETUGE
12998   MVT VET = VT.getVectorElementType();
12999   bool hasMinMax =
13000        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13001     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13002
13003   if (hasMinMax) {
13004     switch (SetCCOpcode) {
13005     default: break;
13006     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13007     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13008     }
13009
13010     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13011   }
13012
13013   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13014   if (!MinMax && hasSubus) {
13015     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13016     // Op0 u<= Op1:
13017     //   t = psubus Op0, Op1
13018     //   pcmpeq t, <0..0>
13019     switch (SetCCOpcode) {
13020     default: break;
13021     case ISD::SETULT: {
13022       // If the comparison is against a constant we can turn this into a
13023       // setule.  With psubus, setule does not require a swap.  This is
13024       // beneficial because the constant in the register is no longer
13025       // destructed as the destination so it can be hoisted out of a loop.
13026       // Only do this pre-AVX since vpcmp* is no longer destructive.
13027       if (Subtarget->hasAVX())
13028         break;
13029       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13030       if (ULEOp1.getNode()) {
13031         Op1 = ULEOp1;
13032         Subus = true; Invert = false; Swap = false;
13033       }
13034       break;
13035     }
13036     // Psubus is better than flip-sign because it requires no inversion.
13037     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13038     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13039     }
13040
13041     if (Subus) {
13042       Opc = X86ISD::SUBUS;
13043       FlipSigns = false;
13044     }
13045   }
13046
13047   if (Swap)
13048     std::swap(Op0, Op1);
13049
13050   // Check that the operation in question is available (most are plain SSE2,
13051   // but PCMPGTQ and PCMPEQQ have different requirements).
13052   if (VT == MVT::v2i64) {
13053     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13054       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13055
13056       // First cast everything to the right type.
13057       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13058       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13059
13060       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13061       // bits of the inputs before performing those operations. The lower
13062       // compare is always unsigned.
13063       SDValue SB;
13064       if (FlipSigns) {
13065         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13066       } else {
13067         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13068         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13069         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13070                          Sign, Zero, Sign, Zero);
13071       }
13072       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13073       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13074
13075       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13076       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13077       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13078
13079       // Create masks for only the low parts/high parts of the 64 bit integers.
13080       static const int MaskHi[] = { 1, 1, 3, 3 };
13081       static const int MaskLo[] = { 0, 0, 2, 2 };
13082       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13083       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13084       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13085
13086       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13087       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13088
13089       if (Invert)
13090         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13091
13092       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13093     }
13094
13095     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13096       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13097       // pcmpeqd + pshufd + pand.
13098       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13099
13100       // First cast everything to the right type.
13101       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13102       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13103
13104       // Do the compare.
13105       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13106
13107       // Make sure the lower and upper halves are both all-ones.
13108       static const int Mask[] = { 1, 0, 3, 2 };
13109       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13110       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13111
13112       if (Invert)
13113         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13114
13115       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13116     }
13117   }
13118
13119   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13120   // bits of the inputs before performing those operations.
13121   if (FlipSigns) {
13122     EVT EltVT = VT.getVectorElementType();
13123     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13124     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13125     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13126   }
13127
13128   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13129
13130   // If the logical-not of the result is required, perform that now.
13131   if (Invert)
13132     Result = DAG.getNOT(dl, Result, VT);
13133
13134   if (MinMax)
13135     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13136
13137   if (Subus)
13138     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13139                          getZeroVector(VT, Subtarget, DAG, dl));
13140
13141   return Result;
13142 }
13143
13144 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13145
13146   MVT VT = Op.getSimpleValueType();
13147
13148   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13149
13150   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13151          && "SetCC type must be 8-bit or 1-bit integer");
13152   SDValue Op0 = Op.getOperand(0);
13153   SDValue Op1 = Op.getOperand(1);
13154   SDLoc dl(Op);
13155   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13156
13157   // Optimize to BT if possible.
13158   // Lower (X & (1 << N)) == 0 to BT(X, N).
13159   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13160   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13161   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13162       Op1.getOpcode() == ISD::Constant &&
13163       cast<ConstantSDNode>(Op1)->isNullValue() &&
13164       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13165     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13166     if (NewSetCC.getNode())
13167       return NewSetCC;
13168   }
13169
13170   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13171   // these.
13172   if (Op1.getOpcode() == ISD::Constant &&
13173       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13174        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13175       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13176
13177     // If the input is a setcc, then reuse the input setcc or use a new one with
13178     // the inverted condition.
13179     if (Op0.getOpcode() == X86ISD::SETCC) {
13180       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13181       bool Invert = (CC == ISD::SETNE) ^
13182         cast<ConstantSDNode>(Op1)->isNullValue();
13183       if (!Invert)
13184         return Op0;
13185
13186       CCode = X86::GetOppositeBranchCondition(CCode);
13187       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13188                                   DAG.getConstant(CCode, MVT::i8),
13189                                   Op0.getOperand(1));
13190       if (VT == MVT::i1)
13191         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13192       return SetCC;
13193     }
13194   }
13195   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13196       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13197       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13198
13199     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13200     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13201   }
13202
13203   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13204   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13205   if (X86CC == X86::COND_INVALID)
13206     return SDValue();
13207
13208   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13209   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13210   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13211                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13212   if (VT == MVT::i1)
13213     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13214   return SetCC;
13215 }
13216
13217 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13218 static bool isX86LogicalCmp(SDValue Op) {
13219   unsigned Opc = Op.getNode()->getOpcode();
13220   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13221       Opc == X86ISD::SAHF)
13222     return true;
13223   if (Op.getResNo() == 1 &&
13224       (Opc == X86ISD::ADD ||
13225        Opc == X86ISD::SUB ||
13226        Opc == X86ISD::ADC ||
13227        Opc == X86ISD::SBB ||
13228        Opc == X86ISD::SMUL ||
13229        Opc == X86ISD::UMUL ||
13230        Opc == X86ISD::INC ||
13231        Opc == X86ISD::DEC ||
13232        Opc == X86ISD::OR ||
13233        Opc == X86ISD::XOR ||
13234        Opc == X86ISD::AND))
13235     return true;
13236
13237   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13238     return true;
13239
13240   return false;
13241 }
13242
13243 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13244   if (V.getOpcode() != ISD::TRUNCATE)
13245     return false;
13246
13247   SDValue VOp0 = V.getOperand(0);
13248   unsigned InBits = VOp0.getValueSizeInBits();
13249   unsigned Bits = V.getValueSizeInBits();
13250   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13251 }
13252
13253 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13254   bool addTest = true;
13255   SDValue Cond  = Op.getOperand(0);
13256   SDValue Op1 = Op.getOperand(1);
13257   SDValue Op2 = Op.getOperand(2);
13258   SDLoc DL(Op);
13259   EVT VT = Op1.getValueType();
13260   SDValue CC;
13261
13262   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13263   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13264   // sequence later on.
13265   if (Cond.getOpcode() == ISD::SETCC &&
13266       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13267        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13268       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13269     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13270     int SSECC = translateX86FSETCC(
13271         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13272
13273     if (SSECC != 8) {
13274       if (Subtarget->hasAVX512()) {
13275         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13276                                   DAG.getConstant(SSECC, MVT::i8));
13277         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13278       }
13279       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13280                                 DAG.getConstant(SSECC, MVT::i8));
13281       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13282       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13283       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13284     }
13285   }
13286
13287   if (Cond.getOpcode() == ISD::SETCC) {
13288     SDValue NewCond = LowerSETCC(Cond, DAG);
13289     if (NewCond.getNode())
13290       Cond = NewCond;
13291   }
13292
13293   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13294   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13295   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13296   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13297   if (Cond.getOpcode() == X86ISD::SETCC &&
13298       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13299       isZero(Cond.getOperand(1).getOperand(1))) {
13300     SDValue Cmp = Cond.getOperand(1);
13301
13302     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13303
13304     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13305         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13306       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13307
13308       SDValue CmpOp0 = Cmp.getOperand(0);
13309       // Apply further optimizations for special cases
13310       // (select (x != 0), -1, 0) -> neg & sbb
13311       // (select (x == 0), 0, -1) -> neg & sbb
13312       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13313         if (YC->isNullValue() &&
13314             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13315           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13316           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13317                                     DAG.getConstant(0, CmpOp0.getValueType()),
13318                                     CmpOp0);
13319           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13320                                     DAG.getConstant(X86::COND_B, MVT::i8),
13321                                     SDValue(Neg.getNode(), 1));
13322           return Res;
13323         }
13324
13325       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13326                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13327       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13328
13329       SDValue Res =   // Res = 0 or -1.
13330         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13331                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13332
13333       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13334         Res = DAG.getNOT(DL, Res, Res.getValueType());
13335
13336       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13337       if (!N2C || !N2C->isNullValue())
13338         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13339       return Res;
13340     }
13341   }
13342
13343   // Look past (and (setcc_carry (cmp ...)), 1).
13344   if (Cond.getOpcode() == ISD::AND &&
13345       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13346     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13347     if (C && C->getAPIntValue() == 1)
13348       Cond = Cond.getOperand(0);
13349   }
13350
13351   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13352   // setting operand in place of the X86ISD::SETCC.
13353   unsigned CondOpcode = Cond.getOpcode();
13354   if (CondOpcode == X86ISD::SETCC ||
13355       CondOpcode == X86ISD::SETCC_CARRY) {
13356     CC = Cond.getOperand(0);
13357
13358     SDValue Cmp = Cond.getOperand(1);
13359     unsigned Opc = Cmp.getOpcode();
13360     MVT VT = Op.getSimpleValueType();
13361
13362     bool IllegalFPCMov = false;
13363     if (VT.isFloatingPoint() && !VT.isVector() &&
13364         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13365       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13366
13367     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13368         Opc == X86ISD::BT) { // FIXME
13369       Cond = Cmp;
13370       addTest = false;
13371     }
13372   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13373              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13374              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13375               Cond.getOperand(0).getValueType() != MVT::i8)) {
13376     SDValue LHS = Cond.getOperand(0);
13377     SDValue RHS = Cond.getOperand(1);
13378     unsigned X86Opcode;
13379     unsigned X86Cond;
13380     SDVTList VTs;
13381     switch (CondOpcode) {
13382     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13383     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13384     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13385     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13386     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13387     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13388     default: llvm_unreachable("unexpected overflowing operator");
13389     }
13390     if (CondOpcode == ISD::UMULO)
13391       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13392                           MVT::i32);
13393     else
13394       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13395
13396     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13397
13398     if (CondOpcode == ISD::UMULO)
13399       Cond = X86Op.getValue(2);
13400     else
13401       Cond = X86Op.getValue(1);
13402
13403     CC = DAG.getConstant(X86Cond, MVT::i8);
13404     addTest = false;
13405   }
13406
13407   if (addTest) {
13408     // Look pass the truncate if the high bits are known zero.
13409     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13410         Cond = Cond.getOperand(0);
13411
13412     // We know the result of AND is compared against zero. Try to match
13413     // it to BT.
13414     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13415       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13416       if (NewSetCC.getNode()) {
13417         CC = NewSetCC.getOperand(0);
13418         Cond = NewSetCC.getOperand(1);
13419         addTest = false;
13420       }
13421     }
13422   }
13423
13424   if (addTest) {
13425     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13426     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13427   }
13428
13429   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13430   // a <  b ?  0 : -1 -> RES = setcc_carry
13431   // a >= b ? -1 :  0 -> RES = setcc_carry
13432   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13433   if (Cond.getOpcode() == X86ISD::SUB) {
13434     Cond = ConvertCmpIfNecessary(Cond, DAG);
13435     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13436
13437     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13438         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13439       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13440                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13441       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13442         return DAG.getNOT(DL, Res, Res.getValueType());
13443       return Res;
13444     }
13445   }
13446
13447   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13448   // widen the cmov and push the truncate through. This avoids introducing a new
13449   // branch during isel and doesn't add any extensions.
13450   if (Op.getValueType() == MVT::i8 &&
13451       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13452     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13453     if (T1.getValueType() == T2.getValueType() &&
13454         // Blacklist CopyFromReg to avoid partial register stalls.
13455         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13456       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13457       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13458       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13459     }
13460   }
13461
13462   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13463   // condition is true.
13464   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13465   SDValue Ops[] = { Op2, Op1, CC, Cond };
13466   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13467 }
13468
13469 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13470   MVT VT = Op->getSimpleValueType(0);
13471   SDValue In = Op->getOperand(0);
13472   MVT InVT = In.getSimpleValueType();
13473   SDLoc dl(Op);
13474
13475   unsigned int NumElts = VT.getVectorNumElements();
13476   if (NumElts != 8 && NumElts != 16)
13477     return SDValue();
13478
13479   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13480     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13481
13482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13483   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13484
13485   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13486   Constant *C = ConstantInt::get(*DAG.getContext(),
13487     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13488
13489   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13490   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13491   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13492                           MachinePointerInfo::getConstantPool(),
13493                           false, false, false, Alignment);
13494   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13495   if (VT.is512BitVector())
13496     return Brcst;
13497   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13498 }
13499
13500 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13501                                 SelectionDAG &DAG) {
13502   MVT VT = Op->getSimpleValueType(0);
13503   SDValue In = Op->getOperand(0);
13504   MVT InVT = In.getSimpleValueType();
13505   SDLoc dl(Op);
13506
13507   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13508     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13509
13510   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13511       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13512       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13513     return SDValue();
13514
13515   if (Subtarget->hasInt256())
13516     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13517
13518   // Optimize vectors in AVX mode
13519   // Sign extend  v8i16 to v8i32 and
13520   //              v4i32 to v4i64
13521   //
13522   // Divide input vector into two parts
13523   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13524   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13525   // concat the vectors to original VT
13526
13527   unsigned NumElems = InVT.getVectorNumElements();
13528   SDValue Undef = DAG.getUNDEF(InVT);
13529
13530   SmallVector<int,8> ShufMask1(NumElems, -1);
13531   for (unsigned i = 0; i != NumElems/2; ++i)
13532     ShufMask1[i] = i;
13533
13534   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13535
13536   SmallVector<int,8> ShufMask2(NumElems, -1);
13537   for (unsigned i = 0; i != NumElems/2; ++i)
13538     ShufMask2[i] = i + NumElems/2;
13539
13540   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13541
13542   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13543                                 VT.getVectorNumElements()/2);
13544
13545   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13546   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13547
13548   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13549 }
13550
13551 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13552 // may emit an illegal shuffle but the expansion is still better than scalar
13553 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13554 // we'll emit a shuffle and a arithmetic shift.
13555 // TODO: It is possible to support ZExt by zeroing the undef values during
13556 // the shuffle phase or after the shuffle.
13557 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13558                                  SelectionDAG &DAG) {
13559   MVT RegVT = Op.getSimpleValueType();
13560   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13561   assert(RegVT.isInteger() &&
13562          "We only custom lower integer vector sext loads.");
13563
13564   // Nothing useful we can do without SSE2 shuffles.
13565   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13566
13567   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13568   SDLoc dl(Ld);
13569   EVT MemVT = Ld->getMemoryVT();
13570   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13571   unsigned RegSz = RegVT.getSizeInBits();
13572
13573   ISD::LoadExtType Ext = Ld->getExtensionType();
13574
13575   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13576          && "Only anyext and sext are currently implemented.");
13577   assert(MemVT != RegVT && "Cannot extend to the same type");
13578   assert(MemVT.isVector() && "Must load a vector from memory");
13579
13580   unsigned NumElems = RegVT.getVectorNumElements();
13581   unsigned MemSz = MemVT.getSizeInBits();
13582   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13583
13584   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13585     // The only way in which we have a legal 256-bit vector result but not the
13586     // integer 256-bit operations needed to directly lower a sextload is if we
13587     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13588     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13589     // correctly legalized. We do this late to allow the canonical form of
13590     // sextload to persist throughout the rest of the DAG combiner -- it wants
13591     // to fold together any extensions it can, and so will fuse a sign_extend
13592     // of an sextload into a sextload targeting a wider value.
13593     SDValue Load;
13594     if (MemSz == 128) {
13595       // Just switch this to a normal load.
13596       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13597                                        "it must be a legal 128-bit vector "
13598                                        "type!");
13599       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13600                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13601                   Ld->isInvariant(), Ld->getAlignment());
13602     } else {
13603       assert(MemSz < 128 &&
13604              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13605       // Do an sext load to a 128-bit vector type. We want to use the same
13606       // number of elements, but elements half as wide. This will end up being
13607       // recursively lowered by this routine, but will succeed as we definitely
13608       // have all the necessary features if we're using AVX1.
13609       EVT HalfEltVT =
13610           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13611       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13612       Load =
13613           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13614                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13615                          Ld->isNonTemporal(), Ld->isInvariant(),
13616                          Ld->getAlignment());
13617     }
13618
13619     // Replace chain users with the new chain.
13620     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13621     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13622
13623     // Finally, do a normal sign-extend to the desired register.
13624     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13625   }
13626
13627   // All sizes must be a power of two.
13628   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13629          "Non-power-of-two elements are not custom lowered!");
13630
13631   // Attempt to load the original value using scalar loads.
13632   // Find the largest scalar type that divides the total loaded size.
13633   MVT SclrLoadTy = MVT::i8;
13634   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13635        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13636     MVT Tp = (MVT::SimpleValueType)tp;
13637     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13638       SclrLoadTy = Tp;
13639     }
13640   }
13641
13642   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13643   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13644       (64 <= MemSz))
13645     SclrLoadTy = MVT::f64;
13646
13647   // Calculate the number of scalar loads that we need to perform
13648   // in order to load our vector from memory.
13649   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13650
13651   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13652          "Can only lower sext loads with a single scalar load!");
13653
13654   unsigned loadRegZize = RegSz;
13655   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13656     loadRegZize /= 2;
13657
13658   // Represent our vector as a sequence of elements which are the
13659   // largest scalar that we can load.
13660   EVT LoadUnitVecVT = EVT::getVectorVT(
13661       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13662
13663   // Represent the data using the same element type that is stored in
13664   // memory. In practice, we ''widen'' MemVT.
13665   EVT WideVecVT =
13666       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13667                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13668
13669   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13670          "Invalid vector type");
13671
13672   // We can't shuffle using an illegal type.
13673   assert(TLI.isTypeLegal(WideVecVT) &&
13674          "We only lower types that form legal widened vector types");
13675
13676   SmallVector<SDValue, 8> Chains;
13677   SDValue Ptr = Ld->getBasePtr();
13678   SDValue Increment =
13679       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13680   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13681
13682   for (unsigned i = 0; i < NumLoads; ++i) {
13683     // Perform a single load.
13684     SDValue ScalarLoad =
13685         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13686                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13687                     Ld->getAlignment());
13688     Chains.push_back(ScalarLoad.getValue(1));
13689     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13690     // another round of DAGCombining.
13691     if (i == 0)
13692       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13693     else
13694       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13695                         ScalarLoad, DAG.getIntPtrConstant(i));
13696
13697     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13698   }
13699
13700   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13701
13702   // Bitcast the loaded value to a vector of the original element type, in
13703   // the size of the target vector type.
13704   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13705   unsigned SizeRatio = RegSz / MemSz;
13706
13707   if (Ext == ISD::SEXTLOAD) {
13708     // If we have SSE4.1, we can directly emit a VSEXT node.
13709     if (Subtarget->hasSSE41()) {
13710       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13711       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13712       return Sext;
13713     }
13714
13715     // Otherwise we'll shuffle the small elements in the high bits of the
13716     // larger type and perform an arithmetic shift. If the shift is not legal
13717     // it's better to scalarize.
13718     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13719            "We can't implement a sext load without an arithmetic right shift!");
13720
13721     // Redistribute the loaded elements into the different locations.
13722     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13723     for (unsigned i = 0; i != NumElems; ++i)
13724       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13725
13726     SDValue Shuff = DAG.getVectorShuffle(
13727         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13728
13729     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13730
13731     // Build the arithmetic shift.
13732     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13733                    MemVT.getVectorElementType().getSizeInBits();
13734     Shuff =
13735         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13736
13737     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13738     return Shuff;
13739   }
13740
13741   // Redistribute the loaded elements into the different locations.
13742   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13743   for (unsigned i = 0; i != NumElems; ++i)
13744     ShuffleVec[i * SizeRatio] = i;
13745
13746   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13747                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13748
13749   // Bitcast to the requested type.
13750   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13751   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13752   return Shuff;
13753 }
13754
13755 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13756 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13757 // from the AND / OR.
13758 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13759   Opc = Op.getOpcode();
13760   if (Opc != ISD::OR && Opc != ISD::AND)
13761     return false;
13762   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13763           Op.getOperand(0).hasOneUse() &&
13764           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13765           Op.getOperand(1).hasOneUse());
13766 }
13767
13768 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13769 // 1 and that the SETCC node has a single use.
13770 static bool isXor1OfSetCC(SDValue Op) {
13771   if (Op.getOpcode() != ISD::XOR)
13772     return false;
13773   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13774   if (N1C && N1C->getAPIntValue() == 1) {
13775     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13776       Op.getOperand(0).hasOneUse();
13777   }
13778   return false;
13779 }
13780
13781 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13782   bool addTest = true;
13783   SDValue Chain = Op.getOperand(0);
13784   SDValue Cond  = Op.getOperand(1);
13785   SDValue Dest  = Op.getOperand(2);
13786   SDLoc dl(Op);
13787   SDValue CC;
13788   bool Inverted = false;
13789
13790   if (Cond.getOpcode() == ISD::SETCC) {
13791     // Check for setcc([su]{add,sub,mul}o == 0).
13792     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13793         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13794         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13795         Cond.getOperand(0).getResNo() == 1 &&
13796         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13797          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13798          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13799          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13800          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13801          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13802       Inverted = true;
13803       Cond = Cond.getOperand(0);
13804     } else {
13805       SDValue NewCond = LowerSETCC(Cond, DAG);
13806       if (NewCond.getNode())
13807         Cond = NewCond;
13808     }
13809   }
13810 #if 0
13811   // FIXME: LowerXALUO doesn't handle these!!
13812   else if (Cond.getOpcode() == X86ISD::ADD  ||
13813            Cond.getOpcode() == X86ISD::SUB  ||
13814            Cond.getOpcode() == X86ISD::SMUL ||
13815            Cond.getOpcode() == X86ISD::UMUL)
13816     Cond = LowerXALUO(Cond, DAG);
13817 #endif
13818
13819   // Look pass (and (setcc_carry (cmp ...)), 1).
13820   if (Cond.getOpcode() == ISD::AND &&
13821       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13822     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13823     if (C && C->getAPIntValue() == 1)
13824       Cond = Cond.getOperand(0);
13825   }
13826
13827   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13828   // setting operand in place of the X86ISD::SETCC.
13829   unsigned CondOpcode = Cond.getOpcode();
13830   if (CondOpcode == X86ISD::SETCC ||
13831       CondOpcode == X86ISD::SETCC_CARRY) {
13832     CC = Cond.getOperand(0);
13833
13834     SDValue Cmp = Cond.getOperand(1);
13835     unsigned Opc = Cmp.getOpcode();
13836     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13837     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13838       Cond = Cmp;
13839       addTest = false;
13840     } else {
13841       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13842       default: break;
13843       case X86::COND_O:
13844       case X86::COND_B:
13845         // These can only come from an arithmetic instruction with overflow,
13846         // e.g. SADDO, UADDO.
13847         Cond = Cond.getNode()->getOperand(1);
13848         addTest = false;
13849         break;
13850       }
13851     }
13852   }
13853   CondOpcode = Cond.getOpcode();
13854   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13855       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13856       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13857        Cond.getOperand(0).getValueType() != MVT::i8)) {
13858     SDValue LHS = Cond.getOperand(0);
13859     SDValue RHS = Cond.getOperand(1);
13860     unsigned X86Opcode;
13861     unsigned X86Cond;
13862     SDVTList VTs;
13863     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13864     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13865     // X86ISD::INC).
13866     switch (CondOpcode) {
13867     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13868     case ISD::SADDO:
13869       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13870         if (C->isOne()) {
13871           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13872           break;
13873         }
13874       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13875     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13876     case ISD::SSUBO:
13877       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13878         if (C->isOne()) {
13879           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13880           break;
13881         }
13882       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13883     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13884     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13885     default: llvm_unreachable("unexpected overflowing operator");
13886     }
13887     if (Inverted)
13888       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13889     if (CondOpcode == ISD::UMULO)
13890       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13891                           MVT::i32);
13892     else
13893       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13894
13895     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13896
13897     if (CondOpcode == ISD::UMULO)
13898       Cond = X86Op.getValue(2);
13899     else
13900       Cond = X86Op.getValue(1);
13901
13902     CC = DAG.getConstant(X86Cond, MVT::i8);
13903     addTest = false;
13904   } else {
13905     unsigned CondOpc;
13906     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13907       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13908       if (CondOpc == ISD::OR) {
13909         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13910         // two branches instead of an explicit OR instruction with a
13911         // separate test.
13912         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13913             isX86LogicalCmp(Cmp)) {
13914           CC = Cond.getOperand(0).getOperand(0);
13915           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13916                               Chain, Dest, CC, Cmp);
13917           CC = Cond.getOperand(1).getOperand(0);
13918           Cond = Cmp;
13919           addTest = false;
13920         }
13921       } else { // ISD::AND
13922         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13923         // two branches instead of an explicit AND instruction with a
13924         // separate test. However, we only do this if this block doesn't
13925         // have a fall-through edge, because this requires an explicit
13926         // jmp when the condition is false.
13927         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13928             isX86LogicalCmp(Cmp) &&
13929             Op.getNode()->hasOneUse()) {
13930           X86::CondCode CCode =
13931             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13932           CCode = X86::GetOppositeBranchCondition(CCode);
13933           CC = DAG.getConstant(CCode, MVT::i8);
13934           SDNode *User = *Op.getNode()->use_begin();
13935           // Look for an unconditional branch following this conditional branch.
13936           // We need this because we need to reverse the successors in order
13937           // to implement FCMP_OEQ.
13938           if (User->getOpcode() == ISD::BR) {
13939             SDValue FalseBB = User->getOperand(1);
13940             SDNode *NewBR =
13941               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13942             assert(NewBR == User);
13943             (void)NewBR;
13944             Dest = FalseBB;
13945
13946             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13947                                 Chain, Dest, CC, Cmp);
13948             X86::CondCode CCode =
13949               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13950             CCode = X86::GetOppositeBranchCondition(CCode);
13951             CC = DAG.getConstant(CCode, MVT::i8);
13952             Cond = Cmp;
13953             addTest = false;
13954           }
13955         }
13956       }
13957     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13958       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13959       // It should be transformed during dag combiner except when the condition
13960       // is set by a arithmetics with overflow node.
13961       X86::CondCode CCode =
13962         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13963       CCode = X86::GetOppositeBranchCondition(CCode);
13964       CC = DAG.getConstant(CCode, MVT::i8);
13965       Cond = Cond.getOperand(0).getOperand(1);
13966       addTest = false;
13967     } else if (Cond.getOpcode() == ISD::SETCC &&
13968                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13969       // For FCMP_OEQ, we can emit
13970       // two branches instead of an explicit AND instruction with a
13971       // separate test. However, we only do this if this block doesn't
13972       // have a fall-through edge, because this requires an explicit
13973       // jmp when the condition is false.
13974       if (Op.getNode()->hasOneUse()) {
13975         SDNode *User = *Op.getNode()->use_begin();
13976         // Look for an unconditional branch following this conditional branch.
13977         // We need this because we need to reverse the successors in order
13978         // to implement FCMP_OEQ.
13979         if (User->getOpcode() == ISD::BR) {
13980           SDValue FalseBB = User->getOperand(1);
13981           SDNode *NewBR =
13982             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13983           assert(NewBR == User);
13984           (void)NewBR;
13985           Dest = FalseBB;
13986
13987           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13988                                     Cond.getOperand(0), Cond.getOperand(1));
13989           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13990           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13991           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13992                               Chain, Dest, CC, Cmp);
13993           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13994           Cond = Cmp;
13995           addTest = false;
13996         }
13997       }
13998     } else if (Cond.getOpcode() == ISD::SETCC &&
13999                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14000       // For FCMP_UNE, we can emit
14001       // two branches instead of an explicit AND instruction with a
14002       // separate test. However, we only do this if this block doesn't
14003       // have a fall-through edge, because this requires an explicit
14004       // jmp when the condition is false.
14005       if (Op.getNode()->hasOneUse()) {
14006         SDNode *User = *Op.getNode()->use_begin();
14007         // Look for an unconditional branch following this conditional branch.
14008         // We need this because we need to reverse the successors in order
14009         // to implement FCMP_UNE.
14010         if (User->getOpcode() == ISD::BR) {
14011           SDValue FalseBB = User->getOperand(1);
14012           SDNode *NewBR =
14013             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14014           assert(NewBR == User);
14015           (void)NewBR;
14016
14017           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14018                                     Cond.getOperand(0), Cond.getOperand(1));
14019           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14020           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14021           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14022                               Chain, Dest, CC, Cmp);
14023           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14024           Cond = Cmp;
14025           addTest = false;
14026           Dest = FalseBB;
14027         }
14028       }
14029     }
14030   }
14031
14032   if (addTest) {
14033     // Look pass the truncate if the high bits are known zero.
14034     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14035         Cond = Cond.getOperand(0);
14036
14037     // We know the result of AND is compared against zero. Try to match
14038     // it to BT.
14039     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14040       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14041       if (NewSetCC.getNode()) {
14042         CC = NewSetCC.getOperand(0);
14043         Cond = NewSetCC.getOperand(1);
14044         addTest = false;
14045       }
14046     }
14047   }
14048
14049   if (addTest) {
14050     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14051     CC = DAG.getConstant(X86Cond, MVT::i8);
14052     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14053   }
14054   Cond = ConvertCmpIfNecessary(Cond, DAG);
14055   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14056                      Chain, Dest, CC, Cond);
14057 }
14058
14059 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14060 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14061 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14062 // that the guard pages used by the OS virtual memory manager are allocated in
14063 // correct sequence.
14064 SDValue
14065 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14066                                            SelectionDAG &DAG) const {
14067   MachineFunction &MF = DAG.getMachineFunction();
14068   bool SplitStack = MF.shouldSplitStack();
14069   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14070                SplitStack;
14071   SDLoc dl(Op);
14072
14073   if (!Lower) {
14074     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14075     SDNode* Node = Op.getNode();
14076
14077     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14078     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14079         " not tell us which reg is the stack pointer!");
14080     EVT VT = Node->getValueType(0);
14081     SDValue Tmp1 = SDValue(Node, 0);
14082     SDValue Tmp2 = SDValue(Node, 1);
14083     SDValue Tmp3 = Node->getOperand(2);
14084     SDValue Chain = Tmp1.getOperand(0);
14085
14086     // Chain the dynamic stack allocation so that it doesn't modify the stack
14087     // pointer when other instructions are using the stack.
14088     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14089         SDLoc(Node));
14090
14091     SDValue Size = Tmp2.getOperand(1);
14092     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14093     Chain = SP.getValue(1);
14094     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14095     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14096     unsigned StackAlign = TFI.getStackAlignment();
14097     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14098     if (Align > StackAlign)
14099       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14100           DAG.getConstant(-(uint64_t)Align, VT));
14101     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14102
14103     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14104         DAG.getIntPtrConstant(0, true), SDValue(),
14105         SDLoc(Node));
14106
14107     SDValue Ops[2] = { Tmp1, Tmp2 };
14108     return DAG.getMergeValues(Ops, dl);
14109   }
14110
14111   // Get the inputs.
14112   SDValue Chain = Op.getOperand(0);
14113   SDValue Size  = Op.getOperand(1);
14114   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14115   EVT VT = Op.getNode()->getValueType(0);
14116
14117   bool Is64Bit = Subtarget->is64Bit();
14118   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14119
14120   if (SplitStack) {
14121     MachineRegisterInfo &MRI = MF.getRegInfo();
14122
14123     if (Is64Bit) {
14124       // The 64 bit implementation of segmented stacks needs to clobber both r10
14125       // r11. This makes it impossible to use it along with nested parameters.
14126       const Function *F = MF.getFunction();
14127
14128       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14129            I != E; ++I)
14130         if (I->hasNestAttr())
14131           report_fatal_error("Cannot use segmented stacks with functions that "
14132                              "have nested arguments.");
14133     }
14134
14135     const TargetRegisterClass *AddrRegClass =
14136       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14137     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14138     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14139     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14140                                 DAG.getRegister(Vreg, SPTy));
14141     SDValue Ops1[2] = { Value, Chain };
14142     return DAG.getMergeValues(Ops1, dl);
14143   } else {
14144     SDValue Flag;
14145     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14146
14147     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14148     Flag = Chain.getValue(1);
14149     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14150
14151     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14152
14153     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14154         DAG.getSubtarget().getRegisterInfo());
14155     unsigned SPReg = RegInfo->getStackRegister();
14156     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14157     Chain = SP.getValue(1);
14158
14159     if (Align) {
14160       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14161                        DAG.getConstant(-(uint64_t)Align, VT));
14162       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14163     }
14164
14165     SDValue Ops1[2] = { SP, Chain };
14166     return DAG.getMergeValues(Ops1, dl);
14167   }
14168 }
14169
14170 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14171   MachineFunction &MF = DAG.getMachineFunction();
14172   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14173
14174   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14175   SDLoc DL(Op);
14176
14177   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14178     // vastart just stores the address of the VarArgsFrameIndex slot into the
14179     // memory location argument.
14180     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14181                                    getPointerTy());
14182     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14183                         MachinePointerInfo(SV), false, false, 0);
14184   }
14185
14186   // __va_list_tag:
14187   //   gp_offset         (0 - 6 * 8)
14188   //   fp_offset         (48 - 48 + 8 * 16)
14189   //   overflow_arg_area (point to parameters coming in memory).
14190   //   reg_save_area
14191   SmallVector<SDValue, 8> MemOps;
14192   SDValue FIN = Op.getOperand(1);
14193   // Store gp_offset
14194   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14195                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14196                                                MVT::i32),
14197                                FIN, MachinePointerInfo(SV), false, false, 0);
14198   MemOps.push_back(Store);
14199
14200   // Store fp_offset
14201   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14202                     FIN, DAG.getIntPtrConstant(4));
14203   Store = DAG.getStore(Op.getOperand(0), DL,
14204                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14205                                        MVT::i32),
14206                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14207   MemOps.push_back(Store);
14208
14209   // Store ptr to overflow_arg_area
14210   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14211                     FIN, DAG.getIntPtrConstant(4));
14212   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14213                                     getPointerTy());
14214   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14215                        MachinePointerInfo(SV, 8),
14216                        false, false, 0);
14217   MemOps.push_back(Store);
14218
14219   // Store ptr to reg_save_area.
14220   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14221                     FIN, DAG.getIntPtrConstant(8));
14222   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14223                                     getPointerTy());
14224   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14225                        MachinePointerInfo(SV, 16), false, false, 0);
14226   MemOps.push_back(Store);
14227   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14228 }
14229
14230 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14231   assert(Subtarget->is64Bit() &&
14232          "LowerVAARG only handles 64-bit va_arg!");
14233   assert((Subtarget->isTargetLinux() ||
14234           Subtarget->isTargetDarwin()) &&
14235           "Unhandled target in LowerVAARG");
14236   assert(Op.getNode()->getNumOperands() == 4);
14237   SDValue Chain = Op.getOperand(0);
14238   SDValue SrcPtr = Op.getOperand(1);
14239   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14240   unsigned Align = Op.getConstantOperandVal(3);
14241   SDLoc dl(Op);
14242
14243   EVT ArgVT = Op.getNode()->getValueType(0);
14244   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14245   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14246   uint8_t ArgMode;
14247
14248   // Decide which area this value should be read from.
14249   // TODO: Implement the AMD64 ABI in its entirety. This simple
14250   // selection mechanism works only for the basic types.
14251   if (ArgVT == MVT::f80) {
14252     llvm_unreachable("va_arg for f80 not yet implemented");
14253   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14254     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14255   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14256     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14257   } else {
14258     llvm_unreachable("Unhandled argument type in LowerVAARG");
14259   }
14260
14261   if (ArgMode == 2) {
14262     // Sanity Check: Make sure using fp_offset makes sense.
14263     assert(!DAG.getTarget().Options.UseSoftFloat &&
14264            !(DAG.getMachineFunction()
14265                 .getFunction()->getAttributes()
14266                 .hasAttribute(AttributeSet::FunctionIndex,
14267                               Attribute::NoImplicitFloat)) &&
14268            Subtarget->hasSSE1());
14269   }
14270
14271   // Insert VAARG_64 node into the DAG
14272   // VAARG_64 returns two values: Variable Argument Address, Chain
14273   SmallVector<SDValue, 11> InstOps;
14274   InstOps.push_back(Chain);
14275   InstOps.push_back(SrcPtr);
14276   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14277   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14278   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14279   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14280   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14281                                           VTs, InstOps, MVT::i64,
14282                                           MachinePointerInfo(SV),
14283                                           /*Align=*/0,
14284                                           /*Volatile=*/false,
14285                                           /*ReadMem=*/true,
14286                                           /*WriteMem=*/true);
14287   Chain = VAARG.getValue(1);
14288
14289   // Load the next argument and return it
14290   return DAG.getLoad(ArgVT, dl,
14291                      Chain,
14292                      VAARG,
14293                      MachinePointerInfo(),
14294                      false, false, false, 0);
14295 }
14296
14297 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14298                            SelectionDAG &DAG) {
14299   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14300   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14301   SDValue Chain = Op.getOperand(0);
14302   SDValue DstPtr = Op.getOperand(1);
14303   SDValue SrcPtr = Op.getOperand(2);
14304   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14305   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14306   SDLoc DL(Op);
14307
14308   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14309                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14310                        false,
14311                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14312 }
14313
14314 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14315 // amount is a constant. Takes immediate version of shift as input.
14316 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14317                                           SDValue SrcOp, uint64_t ShiftAmt,
14318                                           SelectionDAG &DAG) {
14319   MVT ElementType = VT.getVectorElementType();
14320
14321   // Fold this packed shift into its first operand if ShiftAmt is 0.
14322   if (ShiftAmt == 0)
14323     return SrcOp;
14324
14325   // Check for ShiftAmt >= element width
14326   if (ShiftAmt >= ElementType.getSizeInBits()) {
14327     if (Opc == X86ISD::VSRAI)
14328       ShiftAmt = ElementType.getSizeInBits() - 1;
14329     else
14330       return DAG.getConstant(0, VT);
14331   }
14332
14333   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14334          && "Unknown target vector shift-by-constant node");
14335
14336   // Fold this packed vector shift into a build vector if SrcOp is a
14337   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14338   if (VT == SrcOp.getSimpleValueType() &&
14339       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14340     SmallVector<SDValue, 8> Elts;
14341     unsigned NumElts = SrcOp->getNumOperands();
14342     ConstantSDNode *ND;
14343
14344     switch(Opc) {
14345     default: llvm_unreachable(nullptr);
14346     case X86ISD::VSHLI:
14347       for (unsigned i=0; i!=NumElts; ++i) {
14348         SDValue CurrentOp = SrcOp->getOperand(i);
14349         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14350           Elts.push_back(CurrentOp);
14351           continue;
14352         }
14353         ND = cast<ConstantSDNode>(CurrentOp);
14354         const APInt &C = ND->getAPIntValue();
14355         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14356       }
14357       break;
14358     case X86ISD::VSRLI:
14359       for (unsigned i=0; i!=NumElts; ++i) {
14360         SDValue CurrentOp = SrcOp->getOperand(i);
14361         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14362           Elts.push_back(CurrentOp);
14363           continue;
14364         }
14365         ND = cast<ConstantSDNode>(CurrentOp);
14366         const APInt &C = ND->getAPIntValue();
14367         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14368       }
14369       break;
14370     case X86ISD::VSRAI:
14371       for (unsigned i=0; i!=NumElts; ++i) {
14372         SDValue CurrentOp = SrcOp->getOperand(i);
14373         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14374           Elts.push_back(CurrentOp);
14375           continue;
14376         }
14377         ND = cast<ConstantSDNode>(CurrentOp);
14378         const APInt &C = ND->getAPIntValue();
14379         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14380       }
14381       break;
14382     }
14383
14384     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14385   }
14386
14387   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14388 }
14389
14390 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14391 // may or may not be a constant. Takes immediate version of shift as input.
14392 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14393                                    SDValue SrcOp, SDValue ShAmt,
14394                                    SelectionDAG &DAG) {
14395   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14396
14397   // Catch shift-by-constant.
14398   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14399     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14400                                       CShAmt->getZExtValue(), DAG);
14401
14402   // Change opcode to non-immediate version
14403   switch (Opc) {
14404     default: llvm_unreachable("Unknown target vector shift node");
14405     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14406     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14407     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14408   }
14409
14410   // Need to build a vector containing shift amount
14411   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14412   SDValue ShOps[4];
14413   ShOps[0] = ShAmt;
14414   ShOps[1] = DAG.getConstant(0, MVT::i32);
14415   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14416   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14417
14418   // The return type has to be a 128-bit type with the same element
14419   // type as the input type.
14420   MVT EltVT = VT.getVectorElementType();
14421   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14422
14423   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14424   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14425 }
14426
14427 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14428 /// necessary casting for \p Mask when lowering masking intrinsics.
14429 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14430                                     SDValue PreservedSrc, SelectionDAG &DAG) {
14431     EVT VT = Op.getValueType();
14432     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14433                                   MVT::i1, VT.getVectorNumElements());
14434     SDLoc dl(Op);
14435
14436     assert(MaskVT.isSimple() && "invalid mask type");
14437     return DAG.getNode(ISD::VSELECT, dl, VT,
14438                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14439                        Op, PreservedSrc);
14440 }
14441
14442 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14443     switch (IntNo) {
14444     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14445     case Intrinsic::x86_fma_vfmadd_ps:
14446     case Intrinsic::x86_fma_vfmadd_pd:
14447     case Intrinsic::x86_fma_vfmadd_ps_256:
14448     case Intrinsic::x86_fma_vfmadd_pd_256:
14449     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14450     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14451       return X86ISD::FMADD;
14452     case Intrinsic::x86_fma_vfmsub_ps:
14453     case Intrinsic::x86_fma_vfmsub_pd:
14454     case Intrinsic::x86_fma_vfmsub_ps_256:
14455     case Intrinsic::x86_fma_vfmsub_pd_256:
14456     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14457     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14458       return X86ISD::FMSUB;
14459     case Intrinsic::x86_fma_vfnmadd_ps:
14460     case Intrinsic::x86_fma_vfnmadd_pd:
14461     case Intrinsic::x86_fma_vfnmadd_ps_256:
14462     case Intrinsic::x86_fma_vfnmadd_pd_256:
14463     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14464     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14465       return X86ISD::FNMADD;
14466     case Intrinsic::x86_fma_vfnmsub_ps:
14467     case Intrinsic::x86_fma_vfnmsub_pd:
14468     case Intrinsic::x86_fma_vfnmsub_ps_256:
14469     case Intrinsic::x86_fma_vfnmsub_pd_256:
14470     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14471     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14472       return X86ISD::FNMSUB;
14473     case Intrinsic::x86_fma_vfmaddsub_ps:
14474     case Intrinsic::x86_fma_vfmaddsub_pd:
14475     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14476     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14477     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14478     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14479       return X86ISD::FMADDSUB;
14480     case Intrinsic::x86_fma_vfmsubadd_ps:
14481     case Intrinsic::x86_fma_vfmsubadd_pd:
14482     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14483     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14484     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14485     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14486       return X86ISD::FMSUBADD;
14487     }
14488 }
14489
14490 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14491   SDLoc dl(Op);
14492   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14493   switch (IntNo) {
14494   default: return SDValue();    // Don't custom lower most intrinsics.
14495   // Comparison intrinsics.
14496   case Intrinsic::x86_sse_comieq_ss:
14497   case Intrinsic::x86_sse_comilt_ss:
14498   case Intrinsic::x86_sse_comile_ss:
14499   case Intrinsic::x86_sse_comigt_ss:
14500   case Intrinsic::x86_sse_comige_ss:
14501   case Intrinsic::x86_sse_comineq_ss:
14502   case Intrinsic::x86_sse_ucomieq_ss:
14503   case Intrinsic::x86_sse_ucomilt_ss:
14504   case Intrinsic::x86_sse_ucomile_ss:
14505   case Intrinsic::x86_sse_ucomigt_ss:
14506   case Intrinsic::x86_sse_ucomige_ss:
14507   case Intrinsic::x86_sse_ucomineq_ss:
14508   case Intrinsic::x86_sse2_comieq_sd:
14509   case Intrinsic::x86_sse2_comilt_sd:
14510   case Intrinsic::x86_sse2_comile_sd:
14511   case Intrinsic::x86_sse2_comigt_sd:
14512   case Intrinsic::x86_sse2_comige_sd:
14513   case Intrinsic::x86_sse2_comineq_sd:
14514   case Intrinsic::x86_sse2_ucomieq_sd:
14515   case Intrinsic::x86_sse2_ucomilt_sd:
14516   case Intrinsic::x86_sse2_ucomile_sd:
14517   case Intrinsic::x86_sse2_ucomigt_sd:
14518   case Intrinsic::x86_sse2_ucomige_sd:
14519   case Intrinsic::x86_sse2_ucomineq_sd: {
14520     unsigned Opc;
14521     ISD::CondCode CC;
14522     switch (IntNo) {
14523     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14524     case Intrinsic::x86_sse_comieq_ss:
14525     case Intrinsic::x86_sse2_comieq_sd:
14526       Opc = X86ISD::COMI;
14527       CC = ISD::SETEQ;
14528       break;
14529     case Intrinsic::x86_sse_comilt_ss:
14530     case Intrinsic::x86_sse2_comilt_sd:
14531       Opc = X86ISD::COMI;
14532       CC = ISD::SETLT;
14533       break;
14534     case Intrinsic::x86_sse_comile_ss:
14535     case Intrinsic::x86_sse2_comile_sd:
14536       Opc = X86ISD::COMI;
14537       CC = ISD::SETLE;
14538       break;
14539     case Intrinsic::x86_sse_comigt_ss:
14540     case Intrinsic::x86_sse2_comigt_sd:
14541       Opc = X86ISD::COMI;
14542       CC = ISD::SETGT;
14543       break;
14544     case Intrinsic::x86_sse_comige_ss:
14545     case Intrinsic::x86_sse2_comige_sd:
14546       Opc = X86ISD::COMI;
14547       CC = ISD::SETGE;
14548       break;
14549     case Intrinsic::x86_sse_comineq_ss:
14550     case Intrinsic::x86_sse2_comineq_sd:
14551       Opc = X86ISD::COMI;
14552       CC = ISD::SETNE;
14553       break;
14554     case Intrinsic::x86_sse_ucomieq_ss:
14555     case Intrinsic::x86_sse2_ucomieq_sd:
14556       Opc = X86ISD::UCOMI;
14557       CC = ISD::SETEQ;
14558       break;
14559     case Intrinsic::x86_sse_ucomilt_ss:
14560     case Intrinsic::x86_sse2_ucomilt_sd:
14561       Opc = X86ISD::UCOMI;
14562       CC = ISD::SETLT;
14563       break;
14564     case Intrinsic::x86_sse_ucomile_ss:
14565     case Intrinsic::x86_sse2_ucomile_sd:
14566       Opc = X86ISD::UCOMI;
14567       CC = ISD::SETLE;
14568       break;
14569     case Intrinsic::x86_sse_ucomigt_ss:
14570     case Intrinsic::x86_sse2_ucomigt_sd:
14571       Opc = X86ISD::UCOMI;
14572       CC = ISD::SETGT;
14573       break;
14574     case Intrinsic::x86_sse_ucomige_ss:
14575     case Intrinsic::x86_sse2_ucomige_sd:
14576       Opc = X86ISD::UCOMI;
14577       CC = ISD::SETGE;
14578       break;
14579     case Intrinsic::x86_sse_ucomineq_ss:
14580     case Intrinsic::x86_sse2_ucomineq_sd:
14581       Opc = X86ISD::UCOMI;
14582       CC = ISD::SETNE;
14583       break;
14584     }
14585
14586     SDValue LHS = Op.getOperand(1);
14587     SDValue RHS = Op.getOperand(2);
14588     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14589     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14590     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14591     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14592                                 DAG.getConstant(X86CC, MVT::i8), Cond);
14593     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14594   }
14595
14596   // Arithmetic intrinsics.
14597   case Intrinsic::x86_sse2_pmulu_dq:
14598   case Intrinsic::x86_avx2_pmulu_dq:
14599     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14600                        Op.getOperand(1), Op.getOperand(2));
14601
14602   case Intrinsic::x86_sse41_pmuldq:
14603   case Intrinsic::x86_avx2_pmul_dq:
14604     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14605                        Op.getOperand(1), Op.getOperand(2));
14606
14607   case Intrinsic::x86_sse2_pmulhu_w:
14608   case Intrinsic::x86_avx2_pmulhu_w:
14609     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14610                        Op.getOperand(1), Op.getOperand(2));
14611
14612   case Intrinsic::x86_sse2_pmulh_w:
14613   case Intrinsic::x86_avx2_pmulh_w:
14614     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14615                        Op.getOperand(1), Op.getOperand(2));
14616
14617   // SSE2/AVX2 sub with unsigned saturation intrinsics
14618   case Intrinsic::x86_sse2_psubus_b:
14619   case Intrinsic::x86_sse2_psubus_w:
14620   case Intrinsic::x86_avx2_psubus_b:
14621   case Intrinsic::x86_avx2_psubus_w:
14622     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14623                        Op.getOperand(1), Op.getOperand(2));
14624
14625   // SSE3/AVX horizontal add/sub intrinsics
14626   case Intrinsic::x86_sse3_hadd_ps:
14627   case Intrinsic::x86_sse3_hadd_pd:
14628   case Intrinsic::x86_avx_hadd_ps_256:
14629   case Intrinsic::x86_avx_hadd_pd_256:
14630   case Intrinsic::x86_sse3_hsub_ps:
14631   case Intrinsic::x86_sse3_hsub_pd:
14632   case Intrinsic::x86_avx_hsub_ps_256:
14633   case Intrinsic::x86_avx_hsub_pd_256:
14634   case Intrinsic::x86_ssse3_phadd_w_128:
14635   case Intrinsic::x86_ssse3_phadd_d_128:
14636   case Intrinsic::x86_avx2_phadd_w:
14637   case Intrinsic::x86_avx2_phadd_d:
14638   case Intrinsic::x86_ssse3_phsub_w_128:
14639   case Intrinsic::x86_ssse3_phsub_d_128:
14640   case Intrinsic::x86_avx2_phsub_w:
14641   case Intrinsic::x86_avx2_phsub_d: {
14642     unsigned Opcode;
14643     switch (IntNo) {
14644     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14645     case Intrinsic::x86_sse3_hadd_ps:
14646     case Intrinsic::x86_sse3_hadd_pd:
14647     case Intrinsic::x86_avx_hadd_ps_256:
14648     case Intrinsic::x86_avx_hadd_pd_256:
14649       Opcode = X86ISD::FHADD;
14650       break;
14651     case Intrinsic::x86_sse3_hsub_ps:
14652     case Intrinsic::x86_sse3_hsub_pd:
14653     case Intrinsic::x86_avx_hsub_ps_256:
14654     case Intrinsic::x86_avx_hsub_pd_256:
14655       Opcode = X86ISD::FHSUB;
14656       break;
14657     case Intrinsic::x86_ssse3_phadd_w_128:
14658     case Intrinsic::x86_ssse3_phadd_d_128:
14659     case Intrinsic::x86_avx2_phadd_w:
14660     case Intrinsic::x86_avx2_phadd_d:
14661       Opcode = X86ISD::HADD;
14662       break;
14663     case Intrinsic::x86_ssse3_phsub_w_128:
14664     case Intrinsic::x86_ssse3_phsub_d_128:
14665     case Intrinsic::x86_avx2_phsub_w:
14666     case Intrinsic::x86_avx2_phsub_d:
14667       Opcode = X86ISD::HSUB;
14668       break;
14669     }
14670     return DAG.getNode(Opcode, dl, Op.getValueType(),
14671                        Op.getOperand(1), Op.getOperand(2));
14672   }
14673
14674   // SSE2/SSE41/AVX2 integer max/min intrinsics.
14675   case Intrinsic::x86_sse2_pmaxu_b:
14676   case Intrinsic::x86_sse41_pmaxuw:
14677   case Intrinsic::x86_sse41_pmaxud:
14678   case Intrinsic::x86_avx2_pmaxu_b:
14679   case Intrinsic::x86_avx2_pmaxu_w:
14680   case Intrinsic::x86_avx2_pmaxu_d:
14681   case Intrinsic::x86_sse2_pminu_b:
14682   case Intrinsic::x86_sse41_pminuw:
14683   case Intrinsic::x86_sse41_pminud:
14684   case Intrinsic::x86_avx2_pminu_b:
14685   case Intrinsic::x86_avx2_pminu_w:
14686   case Intrinsic::x86_avx2_pminu_d:
14687   case Intrinsic::x86_sse41_pmaxsb:
14688   case Intrinsic::x86_sse2_pmaxs_w:
14689   case Intrinsic::x86_sse41_pmaxsd:
14690   case Intrinsic::x86_avx2_pmaxs_b:
14691   case Intrinsic::x86_avx2_pmaxs_w:
14692   case Intrinsic::x86_avx2_pmaxs_d:
14693   case Intrinsic::x86_sse41_pminsb:
14694   case Intrinsic::x86_sse2_pmins_w:
14695   case Intrinsic::x86_sse41_pminsd:
14696   case Intrinsic::x86_avx2_pmins_b:
14697   case Intrinsic::x86_avx2_pmins_w:
14698   case Intrinsic::x86_avx2_pmins_d: {
14699     unsigned Opcode;
14700     switch (IntNo) {
14701     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14702     case Intrinsic::x86_sse2_pmaxu_b:
14703     case Intrinsic::x86_sse41_pmaxuw:
14704     case Intrinsic::x86_sse41_pmaxud:
14705     case Intrinsic::x86_avx2_pmaxu_b:
14706     case Intrinsic::x86_avx2_pmaxu_w:
14707     case Intrinsic::x86_avx2_pmaxu_d:
14708       Opcode = X86ISD::UMAX;
14709       break;
14710     case Intrinsic::x86_sse2_pminu_b:
14711     case Intrinsic::x86_sse41_pminuw:
14712     case Intrinsic::x86_sse41_pminud:
14713     case Intrinsic::x86_avx2_pminu_b:
14714     case Intrinsic::x86_avx2_pminu_w:
14715     case Intrinsic::x86_avx2_pminu_d:
14716       Opcode = X86ISD::UMIN;
14717       break;
14718     case Intrinsic::x86_sse41_pmaxsb:
14719     case Intrinsic::x86_sse2_pmaxs_w:
14720     case Intrinsic::x86_sse41_pmaxsd:
14721     case Intrinsic::x86_avx2_pmaxs_b:
14722     case Intrinsic::x86_avx2_pmaxs_w:
14723     case Intrinsic::x86_avx2_pmaxs_d:
14724       Opcode = X86ISD::SMAX;
14725       break;
14726     case Intrinsic::x86_sse41_pminsb:
14727     case Intrinsic::x86_sse2_pmins_w:
14728     case Intrinsic::x86_sse41_pminsd:
14729     case Intrinsic::x86_avx2_pmins_b:
14730     case Intrinsic::x86_avx2_pmins_w:
14731     case Intrinsic::x86_avx2_pmins_d:
14732       Opcode = X86ISD::SMIN;
14733       break;
14734     }
14735     return DAG.getNode(Opcode, dl, Op.getValueType(),
14736                        Op.getOperand(1), Op.getOperand(2));
14737   }
14738
14739   // SSE/SSE2/AVX floating point max/min intrinsics.
14740   case Intrinsic::x86_sse_max_ps:
14741   case Intrinsic::x86_sse2_max_pd:
14742   case Intrinsic::x86_avx_max_ps_256:
14743   case Intrinsic::x86_avx_max_pd_256:
14744   case Intrinsic::x86_sse_min_ps:
14745   case Intrinsic::x86_sse2_min_pd:
14746   case Intrinsic::x86_avx_min_ps_256:
14747   case Intrinsic::x86_avx_min_pd_256: {
14748     unsigned Opcode;
14749     switch (IntNo) {
14750     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14751     case Intrinsic::x86_sse_max_ps:
14752     case Intrinsic::x86_sse2_max_pd:
14753     case Intrinsic::x86_avx_max_ps_256:
14754     case Intrinsic::x86_avx_max_pd_256:
14755       Opcode = X86ISD::FMAX;
14756       break;
14757     case Intrinsic::x86_sse_min_ps:
14758     case Intrinsic::x86_sse2_min_pd:
14759     case Intrinsic::x86_avx_min_ps_256:
14760     case Intrinsic::x86_avx_min_pd_256:
14761       Opcode = X86ISD::FMIN;
14762       break;
14763     }
14764     return DAG.getNode(Opcode, dl, Op.getValueType(),
14765                        Op.getOperand(1), Op.getOperand(2));
14766   }
14767
14768   // AVX2 variable shift intrinsics
14769   case Intrinsic::x86_avx2_psllv_d:
14770   case Intrinsic::x86_avx2_psllv_q:
14771   case Intrinsic::x86_avx2_psllv_d_256:
14772   case Intrinsic::x86_avx2_psllv_q_256:
14773   case Intrinsic::x86_avx2_psrlv_d:
14774   case Intrinsic::x86_avx2_psrlv_q:
14775   case Intrinsic::x86_avx2_psrlv_d_256:
14776   case Intrinsic::x86_avx2_psrlv_q_256:
14777   case Intrinsic::x86_avx2_psrav_d:
14778   case Intrinsic::x86_avx2_psrav_d_256: {
14779     unsigned Opcode;
14780     switch (IntNo) {
14781     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14782     case Intrinsic::x86_avx2_psllv_d:
14783     case Intrinsic::x86_avx2_psllv_q:
14784     case Intrinsic::x86_avx2_psllv_d_256:
14785     case Intrinsic::x86_avx2_psllv_q_256:
14786       Opcode = ISD::SHL;
14787       break;
14788     case Intrinsic::x86_avx2_psrlv_d:
14789     case Intrinsic::x86_avx2_psrlv_q:
14790     case Intrinsic::x86_avx2_psrlv_d_256:
14791     case Intrinsic::x86_avx2_psrlv_q_256:
14792       Opcode = ISD::SRL;
14793       break;
14794     case Intrinsic::x86_avx2_psrav_d:
14795     case Intrinsic::x86_avx2_psrav_d_256:
14796       Opcode = ISD::SRA;
14797       break;
14798     }
14799     return DAG.getNode(Opcode, dl, Op.getValueType(),
14800                        Op.getOperand(1), Op.getOperand(2));
14801   }
14802
14803   case Intrinsic::x86_sse2_packssdw_128:
14804   case Intrinsic::x86_sse2_packsswb_128:
14805   case Intrinsic::x86_avx2_packssdw:
14806   case Intrinsic::x86_avx2_packsswb:
14807     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14808                        Op.getOperand(1), Op.getOperand(2));
14809
14810   case Intrinsic::x86_sse2_packuswb_128:
14811   case Intrinsic::x86_sse41_packusdw:
14812   case Intrinsic::x86_avx2_packuswb:
14813   case Intrinsic::x86_avx2_packusdw:
14814     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14815                        Op.getOperand(1), Op.getOperand(2));
14816
14817   case Intrinsic::x86_ssse3_pshuf_b_128:
14818   case Intrinsic::x86_avx2_pshuf_b:
14819     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14820                        Op.getOperand(1), Op.getOperand(2));
14821
14822   case Intrinsic::x86_sse2_pshuf_d:
14823     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14824                        Op.getOperand(1), Op.getOperand(2));
14825
14826   case Intrinsic::x86_sse2_pshufl_w:
14827     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14828                        Op.getOperand(1), Op.getOperand(2));
14829
14830   case Intrinsic::x86_sse2_pshufh_w:
14831     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14832                        Op.getOperand(1), Op.getOperand(2));
14833
14834   case Intrinsic::x86_ssse3_psign_b_128:
14835   case Intrinsic::x86_ssse3_psign_w_128:
14836   case Intrinsic::x86_ssse3_psign_d_128:
14837   case Intrinsic::x86_avx2_psign_b:
14838   case Intrinsic::x86_avx2_psign_w:
14839   case Intrinsic::x86_avx2_psign_d:
14840     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14841                        Op.getOperand(1), Op.getOperand(2));
14842
14843   case Intrinsic::x86_sse41_insertps:
14844     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14845                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14846
14847   case Intrinsic::x86_avx_vperm2f128_ps_256:
14848   case Intrinsic::x86_avx_vperm2f128_pd_256:
14849   case Intrinsic::x86_avx_vperm2f128_si_256:
14850   case Intrinsic::x86_avx2_vperm2i128:
14851     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14852                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14853
14854   case Intrinsic::x86_avx2_permd:
14855   case Intrinsic::x86_avx2_permps:
14856     // Operands intentionally swapped. Mask is last operand to intrinsic,
14857     // but second operand for node/instruction.
14858     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14859                        Op.getOperand(2), Op.getOperand(1));
14860
14861   case Intrinsic::x86_sse_sqrt_ps:
14862   case Intrinsic::x86_sse2_sqrt_pd:
14863   case Intrinsic::x86_avx_sqrt_ps_256:
14864   case Intrinsic::x86_avx_sqrt_pd_256:
14865     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14866
14867   case Intrinsic::x86_avx512_mask_valign_q_512:
14868   case Intrinsic::x86_avx512_mask_valign_d_512:
14869     // Vector source operands are swapped.
14870     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14871                                             Op.getValueType(), Op.getOperand(2),
14872                                             Op.getOperand(1),
14873                                             Op.getOperand(3)),
14874                                 Op.getOperand(5), Op.getOperand(4), DAG);
14875
14876   // ptest and testp intrinsics. The intrinsic these come from are designed to
14877   // return an integer value, not just an instruction so lower it to the ptest
14878   // or testp pattern and a setcc for the result.
14879   case Intrinsic::x86_sse41_ptestz:
14880   case Intrinsic::x86_sse41_ptestc:
14881   case Intrinsic::x86_sse41_ptestnzc:
14882   case Intrinsic::x86_avx_ptestz_256:
14883   case Intrinsic::x86_avx_ptestc_256:
14884   case Intrinsic::x86_avx_ptestnzc_256:
14885   case Intrinsic::x86_avx_vtestz_ps:
14886   case Intrinsic::x86_avx_vtestc_ps:
14887   case Intrinsic::x86_avx_vtestnzc_ps:
14888   case Intrinsic::x86_avx_vtestz_pd:
14889   case Intrinsic::x86_avx_vtestc_pd:
14890   case Intrinsic::x86_avx_vtestnzc_pd:
14891   case Intrinsic::x86_avx_vtestz_ps_256:
14892   case Intrinsic::x86_avx_vtestc_ps_256:
14893   case Intrinsic::x86_avx_vtestnzc_ps_256:
14894   case Intrinsic::x86_avx_vtestz_pd_256:
14895   case Intrinsic::x86_avx_vtestc_pd_256:
14896   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14897     bool IsTestPacked = false;
14898     unsigned X86CC;
14899     switch (IntNo) {
14900     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14901     case Intrinsic::x86_avx_vtestz_ps:
14902     case Intrinsic::x86_avx_vtestz_pd:
14903     case Intrinsic::x86_avx_vtestz_ps_256:
14904     case Intrinsic::x86_avx_vtestz_pd_256:
14905       IsTestPacked = true; // Fallthrough
14906     case Intrinsic::x86_sse41_ptestz:
14907     case Intrinsic::x86_avx_ptestz_256:
14908       // ZF = 1
14909       X86CC = X86::COND_E;
14910       break;
14911     case Intrinsic::x86_avx_vtestc_ps:
14912     case Intrinsic::x86_avx_vtestc_pd:
14913     case Intrinsic::x86_avx_vtestc_ps_256:
14914     case Intrinsic::x86_avx_vtestc_pd_256:
14915       IsTestPacked = true; // Fallthrough
14916     case Intrinsic::x86_sse41_ptestc:
14917     case Intrinsic::x86_avx_ptestc_256:
14918       // CF = 1
14919       X86CC = X86::COND_B;
14920       break;
14921     case Intrinsic::x86_avx_vtestnzc_ps:
14922     case Intrinsic::x86_avx_vtestnzc_pd:
14923     case Intrinsic::x86_avx_vtestnzc_ps_256:
14924     case Intrinsic::x86_avx_vtestnzc_pd_256:
14925       IsTestPacked = true; // Fallthrough
14926     case Intrinsic::x86_sse41_ptestnzc:
14927     case Intrinsic::x86_avx_ptestnzc_256:
14928       // ZF and CF = 0
14929       X86CC = X86::COND_A;
14930       break;
14931     }
14932
14933     SDValue LHS = Op.getOperand(1);
14934     SDValue RHS = Op.getOperand(2);
14935     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14936     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14937     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14938     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14939     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14940   }
14941   case Intrinsic::x86_avx512_kortestz_w:
14942   case Intrinsic::x86_avx512_kortestc_w: {
14943     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14944     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14945     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14946     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14947     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14948     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14949     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14950   }
14951
14952   // SSE/AVX shift intrinsics
14953   case Intrinsic::x86_sse2_psll_w:
14954   case Intrinsic::x86_sse2_psll_d:
14955   case Intrinsic::x86_sse2_psll_q:
14956   case Intrinsic::x86_avx2_psll_w:
14957   case Intrinsic::x86_avx2_psll_d:
14958   case Intrinsic::x86_avx2_psll_q:
14959   case Intrinsic::x86_sse2_psrl_w:
14960   case Intrinsic::x86_sse2_psrl_d:
14961   case Intrinsic::x86_sse2_psrl_q:
14962   case Intrinsic::x86_avx2_psrl_w:
14963   case Intrinsic::x86_avx2_psrl_d:
14964   case Intrinsic::x86_avx2_psrl_q:
14965   case Intrinsic::x86_sse2_psra_w:
14966   case Intrinsic::x86_sse2_psra_d:
14967   case Intrinsic::x86_avx2_psra_w:
14968   case Intrinsic::x86_avx2_psra_d: {
14969     unsigned Opcode;
14970     switch (IntNo) {
14971     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14972     case Intrinsic::x86_sse2_psll_w:
14973     case Intrinsic::x86_sse2_psll_d:
14974     case Intrinsic::x86_sse2_psll_q:
14975     case Intrinsic::x86_avx2_psll_w:
14976     case Intrinsic::x86_avx2_psll_d:
14977     case Intrinsic::x86_avx2_psll_q:
14978       Opcode = X86ISD::VSHL;
14979       break;
14980     case Intrinsic::x86_sse2_psrl_w:
14981     case Intrinsic::x86_sse2_psrl_d:
14982     case Intrinsic::x86_sse2_psrl_q:
14983     case Intrinsic::x86_avx2_psrl_w:
14984     case Intrinsic::x86_avx2_psrl_d:
14985     case Intrinsic::x86_avx2_psrl_q:
14986       Opcode = X86ISD::VSRL;
14987       break;
14988     case Intrinsic::x86_sse2_psra_w:
14989     case Intrinsic::x86_sse2_psra_d:
14990     case Intrinsic::x86_avx2_psra_w:
14991     case Intrinsic::x86_avx2_psra_d:
14992       Opcode = X86ISD::VSRA;
14993       break;
14994     }
14995     return DAG.getNode(Opcode, dl, Op.getValueType(),
14996                        Op.getOperand(1), Op.getOperand(2));
14997   }
14998
14999   // SSE/AVX immediate shift intrinsics
15000   case Intrinsic::x86_sse2_pslli_w:
15001   case Intrinsic::x86_sse2_pslli_d:
15002   case Intrinsic::x86_sse2_pslli_q:
15003   case Intrinsic::x86_avx2_pslli_w:
15004   case Intrinsic::x86_avx2_pslli_d:
15005   case Intrinsic::x86_avx2_pslli_q:
15006   case Intrinsic::x86_sse2_psrli_w:
15007   case Intrinsic::x86_sse2_psrli_d:
15008   case Intrinsic::x86_sse2_psrli_q:
15009   case Intrinsic::x86_avx2_psrli_w:
15010   case Intrinsic::x86_avx2_psrli_d:
15011   case Intrinsic::x86_avx2_psrli_q:
15012   case Intrinsic::x86_sse2_psrai_w:
15013   case Intrinsic::x86_sse2_psrai_d:
15014   case Intrinsic::x86_avx2_psrai_w:
15015   case Intrinsic::x86_avx2_psrai_d: {
15016     unsigned Opcode;
15017     switch (IntNo) {
15018     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15019     case Intrinsic::x86_sse2_pslli_w:
15020     case Intrinsic::x86_sse2_pslli_d:
15021     case Intrinsic::x86_sse2_pslli_q:
15022     case Intrinsic::x86_avx2_pslli_w:
15023     case Intrinsic::x86_avx2_pslli_d:
15024     case Intrinsic::x86_avx2_pslli_q:
15025       Opcode = X86ISD::VSHLI;
15026       break;
15027     case Intrinsic::x86_sse2_psrli_w:
15028     case Intrinsic::x86_sse2_psrli_d:
15029     case Intrinsic::x86_sse2_psrli_q:
15030     case Intrinsic::x86_avx2_psrli_w:
15031     case Intrinsic::x86_avx2_psrli_d:
15032     case Intrinsic::x86_avx2_psrli_q:
15033       Opcode = X86ISD::VSRLI;
15034       break;
15035     case Intrinsic::x86_sse2_psrai_w:
15036     case Intrinsic::x86_sse2_psrai_d:
15037     case Intrinsic::x86_avx2_psrai_w:
15038     case Intrinsic::x86_avx2_psrai_d:
15039       Opcode = X86ISD::VSRAI;
15040       break;
15041     }
15042     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
15043                                Op.getOperand(1), Op.getOperand(2), DAG);
15044   }
15045
15046   case Intrinsic::x86_sse42_pcmpistria128:
15047   case Intrinsic::x86_sse42_pcmpestria128:
15048   case Intrinsic::x86_sse42_pcmpistric128:
15049   case Intrinsic::x86_sse42_pcmpestric128:
15050   case Intrinsic::x86_sse42_pcmpistrio128:
15051   case Intrinsic::x86_sse42_pcmpestrio128:
15052   case Intrinsic::x86_sse42_pcmpistris128:
15053   case Intrinsic::x86_sse42_pcmpestris128:
15054   case Intrinsic::x86_sse42_pcmpistriz128:
15055   case Intrinsic::x86_sse42_pcmpestriz128: {
15056     unsigned Opcode;
15057     unsigned X86CC;
15058     switch (IntNo) {
15059     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15060     case Intrinsic::x86_sse42_pcmpistria128:
15061       Opcode = X86ISD::PCMPISTRI;
15062       X86CC = X86::COND_A;
15063       break;
15064     case Intrinsic::x86_sse42_pcmpestria128:
15065       Opcode = X86ISD::PCMPESTRI;
15066       X86CC = X86::COND_A;
15067       break;
15068     case Intrinsic::x86_sse42_pcmpistric128:
15069       Opcode = X86ISD::PCMPISTRI;
15070       X86CC = X86::COND_B;
15071       break;
15072     case Intrinsic::x86_sse42_pcmpestric128:
15073       Opcode = X86ISD::PCMPESTRI;
15074       X86CC = X86::COND_B;
15075       break;
15076     case Intrinsic::x86_sse42_pcmpistrio128:
15077       Opcode = X86ISD::PCMPISTRI;
15078       X86CC = X86::COND_O;
15079       break;
15080     case Intrinsic::x86_sse42_pcmpestrio128:
15081       Opcode = X86ISD::PCMPESTRI;
15082       X86CC = X86::COND_O;
15083       break;
15084     case Intrinsic::x86_sse42_pcmpistris128:
15085       Opcode = X86ISD::PCMPISTRI;
15086       X86CC = X86::COND_S;
15087       break;
15088     case Intrinsic::x86_sse42_pcmpestris128:
15089       Opcode = X86ISD::PCMPESTRI;
15090       X86CC = X86::COND_S;
15091       break;
15092     case Intrinsic::x86_sse42_pcmpistriz128:
15093       Opcode = X86ISD::PCMPISTRI;
15094       X86CC = X86::COND_E;
15095       break;
15096     case Intrinsic::x86_sse42_pcmpestriz128:
15097       Opcode = X86ISD::PCMPESTRI;
15098       X86CC = X86::COND_E;
15099       break;
15100     }
15101     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15102     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15103     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15104     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15105                                 DAG.getConstant(X86CC, MVT::i8),
15106                                 SDValue(PCMP.getNode(), 1));
15107     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15108   }
15109
15110   case Intrinsic::x86_sse42_pcmpistri128:
15111   case Intrinsic::x86_sse42_pcmpestri128: {
15112     unsigned Opcode;
15113     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15114       Opcode = X86ISD::PCMPISTRI;
15115     else
15116       Opcode = X86ISD::PCMPESTRI;
15117
15118     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15119     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15120     return DAG.getNode(Opcode, dl, VTs, NewOps);
15121   }
15122
15123   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
15124   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
15125   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
15126   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
15127   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
15128   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
15129   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
15130   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
15131   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
15132   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
15133   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
15134   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
15135     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
15136     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
15137       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
15138                                               dl, Op.getValueType(),
15139                                               Op.getOperand(1),
15140                                               Op.getOperand(2),
15141                                               Op.getOperand(3)),
15142                                   Op.getOperand(4), Op.getOperand(1), DAG);
15143     else
15144       return SDValue();
15145   }
15146
15147   case Intrinsic::x86_fma_vfmadd_ps:
15148   case Intrinsic::x86_fma_vfmadd_pd:
15149   case Intrinsic::x86_fma_vfmsub_ps:
15150   case Intrinsic::x86_fma_vfmsub_pd:
15151   case Intrinsic::x86_fma_vfnmadd_ps:
15152   case Intrinsic::x86_fma_vfnmadd_pd:
15153   case Intrinsic::x86_fma_vfnmsub_ps:
15154   case Intrinsic::x86_fma_vfnmsub_pd:
15155   case Intrinsic::x86_fma_vfmaddsub_ps:
15156   case Intrinsic::x86_fma_vfmaddsub_pd:
15157   case Intrinsic::x86_fma_vfmsubadd_ps:
15158   case Intrinsic::x86_fma_vfmsubadd_pd:
15159   case Intrinsic::x86_fma_vfmadd_ps_256:
15160   case Intrinsic::x86_fma_vfmadd_pd_256:
15161   case Intrinsic::x86_fma_vfmsub_ps_256:
15162   case Intrinsic::x86_fma_vfmsub_pd_256:
15163   case Intrinsic::x86_fma_vfnmadd_ps_256:
15164   case Intrinsic::x86_fma_vfnmadd_pd_256:
15165   case Intrinsic::x86_fma_vfnmsub_ps_256:
15166   case Intrinsic::x86_fma_vfnmsub_pd_256:
15167   case Intrinsic::x86_fma_vfmaddsub_ps_256:
15168   case Intrinsic::x86_fma_vfmaddsub_pd_256:
15169   case Intrinsic::x86_fma_vfmsubadd_ps_256:
15170   case Intrinsic::x86_fma_vfmsubadd_pd_256:
15171     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
15172                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
15173   }
15174 }
15175
15176 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15177                               SDValue Src, SDValue Mask, SDValue Base,
15178                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15179                               const X86Subtarget * Subtarget) {
15180   SDLoc dl(Op);
15181   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15182   assert(C && "Invalid scale type");
15183   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15184   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15185                              Index.getSimpleValueType().getVectorNumElements());
15186   SDValue MaskInReg;
15187   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15188   if (MaskC)
15189     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15190   else
15191     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15192   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15193   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15194   SDValue Segment = DAG.getRegister(0, MVT::i32);
15195   if (Src.getOpcode() == ISD::UNDEF)
15196     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15197   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15198   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15199   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15200   return DAG.getMergeValues(RetOps, dl);
15201 }
15202
15203 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15204                                SDValue Src, SDValue Mask, SDValue Base,
15205                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15206   SDLoc dl(Op);
15207   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15208   assert(C && "Invalid scale type");
15209   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15210   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15211   SDValue Segment = DAG.getRegister(0, MVT::i32);
15212   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15213                              Index.getSimpleValueType().getVectorNumElements());
15214   SDValue MaskInReg;
15215   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15216   if (MaskC)
15217     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15218   else
15219     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15220   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15221   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15222   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15223   return SDValue(Res, 1);
15224 }
15225
15226 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15227                                SDValue Mask, SDValue Base, SDValue Index,
15228                                SDValue ScaleOp, SDValue Chain) {
15229   SDLoc dl(Op);
15230   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15231   assert(C && "Invalid scale type");
15232   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15233   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15234   SDValue Segment = DAG.getRegister(0, MVT::i32);
15235   EVT MaskVT =
15236     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15237   SDValue MaskInReg;
15238   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15239   if (MaskC)
15240     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15241   else
15242     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15243   //SDVTList VTs = DAG.getVTList(MVT::Other);
15244   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15245   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15246   return SDValue(Res, 0);
15247 }
15248
15249 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15250 // read performance monitor counters (x86_rdpmc).
15251 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15252                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15253                               SmallVectorImpl<SDValue> &Results) {
15254   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15255   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15256   SDValue LO, HI;
15257
15258   // The ECX register is used to select the index of the performance counter
15259   // to read.
15260   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15261                                    N->getOperand(2));
15262   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15263
15264   // Reads the content of a 64-bit performance counter and returns it in the
15265   // registers EDX:EAX.
15266   if (Subtarget->is64Bit()) {
15267     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15268     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15269                             LO.getValue(2));
15270   } else {
15271     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15272     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15273                             LO.getValue(2));
15274   }
15275   Chain = HI.getValue(1);
15276
15277   if (Subtarget->is64Bit()) {
15278     // The EAX register is loaded with the low-order 32 bits. The EDX register
15279     // is loaded with the supported high-order bits of the counter.
15280     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15281                               DAG.getConstant(32, MVT::i8));
15282     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15283     Results.push_back(Chain);
15284     return;
15285   }
15286
15287   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15288   SDValue Ops[] = { LO, HI };
15289   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15290   Results.push_back(Pair);
15291   Results.push_back(Chain);
15292 }
15293
15294 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15295 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15296 // also used to custom lower READCYCLECOUNTER nodes.
15297 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15298                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15299                               SmallVectorImpl<SDValue> &Results) {
15300   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15301   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15302   SDValue LO, HI;
15303
15304   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15305   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15306   // and the EAX register is loaded with the low-order 32 bits.
15307   if (Subtarget->is64Bit()) {
15308     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15309     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15310                             LO.getValue(2));
15311   } else {
15312     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15313     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15314                             LO.getValue(2));
15315   }
15316   SDValue Chain = HI.getValue(1);
15317
15318   if (Opcode == X86ISD::RDTSCP_DAG) {
15319     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15320
15321     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15322     // the ECX register. Add 'ecx' explicitly to the chain.
15323     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15324                                      HI.getValue(2));
15325     // Explicitly store the content of ECX at the location passed in input
15326     // to the 'rdtscp' intrinsic.
15327     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15328                          MachinePointerInfo(), false, false, 0);
15329   }
15330
15331   if (Subtarget->is64Bit()) {
15332     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15333     // the EAX register is loaded with the low-order 32 bits.
15334     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15335                               DAG.getConstant(32, MVT::i8));
15336     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15337     Results.push_back(Chain);
15338     return;
15339   }
15340
15341   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15342   SDValue Ops[] = { LO, HI };
15343   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15344   Results.push_back(Pair);
15345   Results.push_back(Chain);
15346 }
15347
15348 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15349                                      SelectionDAG &DAG) {
15350   SmallVector<SDValue, 2> Results;
15351   SDLoc DL(Op);
15352   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15353                           Results);
15354   return DAG.getMergeValues(Results, DL);
15355 }
15356
15357 enum IntrinsicType {
15358   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
15359 };
15360
15361 struct IntrinsicData {
15362   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
15363     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
15364   IntrinsicType Type;
15365   unsigned      Opc0;
15366   unsigned      Opc1;
15367 };
15368
15369 std::map < unsigned, IntrinsicData> IntrMap;
15370 static void InitIntinsicsMap() {
15371   static bool Initialized = false;
15372   if (Initialized) 
15373     return;
15374   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15375                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15376   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15377                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15378   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
15379                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
15380   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
15381                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
15382   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
15383                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
15384   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
15385                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
15386   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
15387                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
15388   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
15389                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
15390   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
15391                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
15392
15393   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
15394                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
15395   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
15396                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
15397   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
15398                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
15399   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
15400                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
15401   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
15402                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
15403   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
15404                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
15405   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
15406                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
15407   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
15408                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
15409    
15410   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
15411                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
15412                                                         X86::VGATHERPF1QPSm)));
15413   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
15414                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
15415                                                         X86::VGATHERPF1QPDm)));
15416   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
15417                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
15418                                                         X86::VGATHERPF1DPDm)));
15419   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
15420                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
15421                                                         X86::VGATHERPF1DPSm)));
15422   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
15423                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
15424                                                         X86::VSCATTERPF1QPSm)));
15425   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
15426                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
15427                                                         X86::VSCATTERPF1QPDm)));
15428   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
15429                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
15430                                                         X86::VSCATTERPF1DPDm)));
15431   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
15432                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
15433                                                         X86::VSCATTERPF1DPSm)));
15434   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
15435                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15436   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
15437                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15438   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
15439                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15440   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
15441                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15442   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
15443                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15444   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
15445                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15446   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
15447                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
15448   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
15449                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
15450   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
15451                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
15452   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
15453                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
15454   Initialized = true;
15455 }
15456
15457 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15458                                       SelectionDAG &DAG) {
15459   InitIntinsicsMap();
15460   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15461   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
15462   if (itr == IntrMap.end())
15463     return SDValue();
15464
15465   SDLoc dl(Op);
15466   IntrinsicData Intr = itr->second;
15467   switch(Intr.Type) {
15468   case RDSEED:
15469   case RDRAND: {
15470     // Emit the node with the right value type.
15471     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15472     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
15473
15474     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15475     // Otherwise return the value from Rand, which is always 0, casted to i32.
15476     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15477                       DAG.getConstant(1, Op->getValueType(1)),
15478                       DAG.getConstant(X86::COND_B, MVT::i32),
15479                       SDValue(Result.getNode(), 1) };
15480     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15481                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15482                                   Ops);
15483
15484     // Return { result, isValid, chain }.
15485     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15486                        SDValue(Result.getNode(), 2));
15487   }
15488   case GATHER: {
15489   //gather(v1, mask, index, base, scale);
15490     SDValue Chain = Op.getOperand(0);
15491     SDValue Src   = Op.getOperand(2);
15492     SDValue Base  = Op.getOperand(3);
15493     SDValue Index = Op.getOperand(4);
15494     SDValue Mask  = Op.getOperand(5);
15495     SDValue Scale = Op.getOperand(6);
15496     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15497                           Subtarget);
15498   }
15499   case SCATTER: {
15500   //scatter(base, mask, index, v1, scale);
15501     SDValue Chain = Op.getOperand(0);
15502     SDValue Base  = Op.getOperand(2);
15503     SDValue Mask  = Op.getOperand(3);
15504     SDValue Index = Op.getOperand(4);
15505     SDValue Src   = Op.getOperand(5);
15506     SDValue Scale = Op.getOperand(6);
15507     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15508   }
15509   case PREFETCH: {
15510     SDValue Hint = Op.getOperand(6);
15511     unsigned HintVal;
15512     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15513         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15514       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15515     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15516     SDValue Chain = Op.getOperand(0);
15517     SDValue Mask  = Op.getOperand(2);
15518     SDValue Index = Op.getOperand(3);
15519     SDValue Base  = Op.getOperand(4);
15520     SDValue Scale = Op.getOperand(5);
15521     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15522   }
15523   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15524   case RDTSC: {
15525     SmallVector<SDValue, 2> Results;
15526     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15527     return DAG.getMergeValues(Results, dl);
15528   }
15529   // Read Performance Monitoring Counters.
15530   case RDPMC: {
15531     SmallVector<SDValue, 2> Results;
15532     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15533     return DAG.getMergeValues(Results, dl);
15534   }
15535   // XTEST intrinsics.
15536   case XTEST: {
15537     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15538     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15539     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15540                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15541                                 InTrans);
15542     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15543     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15544                        Ret, SDValue(InTrans.getNode(), 1));
15545   }
15546   }
15547   llvm_unreachable("Unknown Intrinsic Type");
15548 }
15549
15550 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15551                                            SelectionDAG &DAG) const {
15552   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15553   MFI->setReturnAddressIsTaken(true);
15554
15555   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15556     return SDValue();
15557
15558   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15559   SDLoc dl(Op);
15560   EVT PtrVT = getPointerTy();
15561
15562   if (Depth > 0) {
15563     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15564     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15565         DAG.getSubtarget().getRegisterInfo());
15566     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15567     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15568                        DAG.getNode(ISD::ADD, dl, PtrVT,
15569                                    FrameAddr, Offset),
15570                        MachinePointerInfo(), false, false, false, 0);
15571   }
15572
15573   // Just load the return address.
15574   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15575   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15576                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15577 }
15578
15579 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15580   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15581   MFI->setFrameAddressIsTaken(true);
15582
15583   EVT VT = Op.getValueType();
15584   SDLoc dl(Op);  // FIXME probably not meaningful
15585   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15586   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15587       DAG.getSubtarget().getRegisterInfo());
15588   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15589   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15590           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15591          "Invalid Frame Register!");
15592   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15593   while (Depth--)
15594     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15595                             MachinePointerInfo(),
15596                             false, false, false, 0);
15597   return FrameAddr;
15598 }
15599
15600 // FIXME? Maybe this could be a TableGen attribute on some registers and
15601 // this table could be generated automatically from RegInfo.
15602 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15603                                               EVT VT) const {
15604   unsigned Reg = StringSwitch<unsigned>(RegName)
15605                        .Case("esp", X86::ESP)
15606                        .Case("rsp", X86::RSP)
15607                        .Default(0);
15608   if (Reg)
15609     return Reg;
15610   report_fatal_error("Invalid register name global variable");
15611 }
15612
15613 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15614                                                      SelectionDAG &DAG) const {
15615   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15616       DAG.getSubtarget().getRegisterInfo());
15617   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15618 }
15619
15620 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15621   SDValue Chain     = Op.getOperand(0);
15622   SDValue Offset    = Op.getOperand(1);
15623   SDValue Handler   = Op.getOperand(2);
15624   SDLoc dl      (Op);
15625
15626   EVT PtrVT = getPointerTy();
15627   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15628       DAG.getSubtarget().getRegisterInfo());
15629   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15630   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15631           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15632          "Invalid Frame Register!");
15633   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15634   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15635
15636   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15637                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15638   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15639   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15640                        false, false, 0);
15641   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15642
15643   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15644                      DAG.getRegister(StoreAddrReg, PtrVT));
15645 }
15646
15647 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15648                                                SelectionDAG &DAG) const {
15649   SDLoc DL(Op);
15650   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15651                      DAG.getVTList(MVT::i32, MVT::Other),
15652                      Op.getOperand(0), Op.getOperand(1));
15653 }
15654
15655 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15656                                                 SelectionDAG &DAG) const {
15657   SDLoc DL(Op);
15658   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15659                      Op.getOperand(0), Op.getOperand(1));
15660 }
15661
15662 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15663   return Op.getOperand(0);
15664 }
15665
15666 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15667                                                 SelectionDAG &DAG) const {
15668   SDValue Root = Op.getOperand(0);
15669   SDValue Trmp = Op.getOperand(1); // trampoline
15670   SDValue FPtr = Op.getOperand(2); // nested function
15671   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15672   SDLoc dl (Op);
15673
15674   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15675   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15676
15677   if (Subtarget->is64Bit()) {
15678     SDValue OutChains[6];
15679
15680     // Large code-model.
15681     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15682     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15683
15684     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15685     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15686
15687     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15688
15689     // Load the pointer to the nested function into R11.
15690     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15691     SDValue Addr = Trmp;
15692     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15693                                 Addr, MachinePointerInfo(TrmpAddr),
15694                                 false, false, 0);
15695
15696     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15697                        DAG.getConstant(2, MVT::i64));
15698     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15699                                 MachinePointerInfo(TrmpAddr, 2),
15700                                 false, false, 2);
15701
15702     // Load the 'nest' parameter value into R10.
15703     // R10 is specified in X86CallingConv.td
15704     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15705     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15706                        DAG.getConstant(10, MVT::i64));
15707     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15708                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15709                                 false, false, 0);
15710
15711     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15712                        DAG.getConstant(12, MVT::i64));
15713     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15714                                 MachinePointerInfo(TrmpAddr, 12),
15715                                 false, false, 2);
15716
15717     // Jump to the nested function.
15718     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15719     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15720                        DAG.getConstant(20, MVT::i64));
15721     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15722                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15723                                 false, false, 0);
15724
15725     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15726     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15727                        DAG.getConstant(22, MVT::i64));
15728     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15729                                 MachinePointerInfo(TrmpAddr, 22),
15730                                 false, false, 0);
15731
15732     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15733   } else {
15734     const Function *Func =
15735       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15736     CallingConv::ID CC = Func->getCallingConv();
15737     unsigned NestReg;
15738
15739     switch (CC) {
15740     default:
15741       llvm_unreachable("Unsupported calling convention");
15742     case CallingConv::C:
15743     case CallingConv::X86_StdCall: {
15744       // Pass 'nest' parameter in ECX.
15745       // Must be kept in sync with X86CallingConv.td
15746       NestReg = X86::ECX;
15747
15748       // Check that ECX wasn't needed by an 'inreg' parameter.
15749       FunctionType *FTy = Func->getFunctionType();
15750       const AttributeSet &Attrs = Func->getAttributes();
15751
15752       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15753         unsigned InRegCount = 0;
15754         unsigned Idx = 1;
15755
15756         for (FunctionType::param_iterator I = FTy->param_begin(),
15757              E = FTy->param_end(); I != E; ++I, ++Idx)
15758           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15759             // FIXME: should only count parameters that are lowered to integers.
15760             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15761
15762         if (InRegCount > 2) {
15763           report_fatal_error("Nest register in use - reduce number of inreg"
15764                              " parameters!");
15765         }
15766       }
15767       break;
15768     }
15769     case CallingConv::X86_FastCall:
15770     case CallingConv::X86_ThisCall:
15771     case CallingConv::Fast:
15772       // Pass 'nest' parameter in EAX.
15773       // Must be kept in sync with X86CallingConv.td
15774       NestReg = X86::EAX;
15775       break;
15776     }
15777
15778     SDValue OutChains[4];
15779     SDValue Addr, Disp;
15780
15781     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15782                        DAG.getConstant(10, MVT::i32));
15783     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15784
15785     // This is storing the opcode for MOV32ri.
15786     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15787     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15788     OutChains[0] = DAG.getStore(Root, dl,
15789                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15790                                 Trmp, MachinePointerInfo(TrmpAddr),
15791                                 false, false, 0);
15792
15793     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15794                        DAG.getConstant(1, MVT::i32));
15795     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15796                                 MachinePointerInfo(TrmpAddr, 1),
15797                                 false, false, 1);
15798
15799     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15800     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15801                        DAG.getConstant(5, MVT::i32));
15802     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15803                                 MachinePointerInfo(TrmpAddr, 5),
15804                                 false, false, 1);
15805
15806     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15807                        DAG.getConstant(6, MVT::i32));
15808     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15809                                 MachinePointerInfo(TrmpAddr, 6),
15810                                 false, false, 1);
15811
15812     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15813   }
15814 }
15815
15816 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15817                                             SelectionDAG &DAG) const {
15818   /*
15819    The rounding mode is in bits 11:10 of FPSR, and has the following
15820    settings:
15821      00 Round to nearest
15822      01 Round to -inf
15823      10 Round to +inf
15824      11 Round to 0
15825
15826   FLT_ROUNDS, on the other hand, expects the following:
15827     -1 Undefined
15828      0 Round to 0
15829      1 Round to nearest
15830      2 Round to +inf
15831      3 Round to -inf
15832
15833   To perform the conversion, we do:
15834     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15835   */
15836
15837   MachineFunction &MF = DAG.getMachineFunction();
15838   const TargetMachine &TM = MF.getTarget();
15839   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15840   unsigned StackAlignment = TFI.getStackAlignment();
15841   MVT VT = Op.getSimpleValueType();
15842   SDLoc DL(Op);
15843
15844   // Save FP Control Word to stack slot
15845   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15846   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15847
15848   MachineMemOperand *MMO =
15849    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15850                            MachineMemOperand::MOStore, 2, 2);
15851
15852   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15853   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15854                                           DAG.getVTList(MVT::Other),
15855                                           Ops, MVT::i16, MMO);
15856
15857   // Load FP Control Word from stack slot
15858   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15859                             MachinePointerInfo(), false, false, false, 0);
15860
15861   // Transform as necessary
15862   SDValue CWD1 =
15863     DAG.getNode(ISD::SRL, DL, MVT::i16,
15864                 DAG.getNode(ISD::AND, DL, MVT::i16,
15865                             CWD, DAG.getConstant(0x800, MVT::i16)),
15866                 DAG.getConstant(11, MVT::i8));
15867   SDValue CWD2 =
15868     DAG.getNode(ISD::SRL, DL, MVT::i16,
15869                 DAG.getNode(ISD::AND, DL, MVT::i16,
15870                             CWD, DAG.getConstant(0x400, MVT::i16)),
15871                 DAG.getConstant(9, MVT::i8));
15872
15873   SDValue RetVal =
15874     DAG.getNode(ISD::AND, DL, MVT::i16,
15875                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15876                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15877                             DAG.getConstant(1, MVT::i16)),
15878                 DAG.getConstant(3, MVT::i16));
15879
15880   return DAG.getNode((VT.getSizeInBits() < 16 ?
15881                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15882 }
15883
15884 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15885   MVT VT = Op.getSimpleValueType();
15886   EVT OpVT = VT;
15887   unsigned NumBits = VT.getSizeInBits();
15888   SDLoc dl(Op);
15889
15890   Op = Op.getOperand(0);
15891   if (VT == MVT::i8) {
15892     // Zero extend to i32 since there is not an i8 bsr.
15893     OpVT = MVT::i32;
15894     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15895   }
15896
15897   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15898   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15899   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15900
15901   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15902   SDValue Ops[] = {
15903     Op,
15904     DAG.getConstant(NumBits+NumBits-1, OpVT),
15905     DAG.getConstant(X86::COND_E, MVT::i8),
15906     Op.getValue(1)
15907   };
15908   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15909
15910   // Finally xor with NumBits-1.
15911   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15912
15913   if (VT == MVT::i8)
15914     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15915   return Op;
15916 }
15917
15918 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15919   MVT VT = Op.getSimpleValueType();
15920   EVT OpVT = VT;
15921   unsigned NumBits = VT.getSizeInBits();
15922   SDLoc dl(Op);
15923
15924   Op = Op.getOperand(0);
15925   if (VT == MVT::i8) {
15926     // Zero extend to i32 since there is not an i8 bsr.
15927     OpVT = MVT::i32;
15928     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15929   }
15930
15931   // Issue a bsr (scan bits in reverse).
15932   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15933   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15934
15935   // And xor with NumBits-1.
15936   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15937
15938   if (VT == MVT::i8)
15939     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15940   return Op;
15941 }
15942
15943 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15944   MVT VT = Op.getSimpleValueType();
15945   unsigned NumBits = VT.getSizeInBits();
15946   SDLoc dl(Op);
15947   Op = Op.getOperand(0);
15948
15949   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15950   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15951   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15952
15953   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15954   SDValue Ops[] = {
15955     Op,
15956     DAG.getConstant(NumBits, VT),
15957     DAG.getConstant(X86::COND_E, MVT::i8),
15958     Op.getValue(1)
15959   };
15960   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15961 }
15962
15963 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15964 // ones, and then concatenate the result back.
15965 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15966   MVT VT = Op.getSimpleValueType();
15967
15968   assert(VT.is256BitVector() && VT.isInteger() &&
15969          "Unsupported value type for operation");
15970
15971   unsigned NumElems = VT.getVectorNumElements();
15972   SDLoc dl(Op);
15973
15974   // Extract the LHS vectors
15975   SDValue LHS = Op.getOperand(0);
15976   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15977   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15978
15979   // Extract the RHS vectors
15980   SDValue RHS = Op.getOperand(1);
15981   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15982   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15983
15984   MVT EltVT = VT.getVectorElementType();
15985   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15986
15987   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15988                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15989                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15990 }
15991
15992 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15993   assert(Op.getSimpleValueType().is256BitVector() &&
15994          Op.getSimpleValueType().isInteger() &&
15995          "Only handle AVX 256-bit vector integer operation");
15996   return Lower256IntArith(Op, DAG);
15997 }
15998
15999 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16000   assert(Op.getSimpleValueType().is256BitVector() &&
16001          Op.getSimpleValueType().isInteger() &&
16002          "Only handle AVX 256-bit vector integer operation");
16003   return Lower256IntArith(Op, DAG);
16004 }
16005
16006 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16007                         SelectionDAG &DAG) {
16008   SDLoc dl(Op);
16009   MVT VT = Op.getSimpleValueType();
16010
16011   // Decompose 256-bit ops into smaller 128-bit ops.
16012   if (VT.is256BitVector() && !Subtarget->hasInt256())
16013     return Lower256IntArith(Op, DAG);
16014
16015   SDValue A = Op.getOperand(0);
16016   SDValue B = Op.getOperand(1);
16017
16018   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16019   if (VT == MVT::v4i32) {
16020     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16021            "Should not custom lower when pmuldq is available!");
16022
16023     // Extract the odd parts.
16024     static const int UnpackMask[] = { 1, -1, 3, -1 };
16025     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16026     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16027
16028     // Multiply the even parts.
16029     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16030     // Now multiply odd parts.
16031     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16032
16033     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16034     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16035
16036     // Merge the two vectors back together with a shuffle. This expands into 2
16037     // shuffles.
16038     static const int ShufMask[] = { 0, 4, 2, 6 };
16039     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16040   }
16041
16042   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16043          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16044
16045   //  Ahi = psrlqi(a, 32);
16046   //  Bhi = psrlqi(b, 32);
16047   //
16048   //  AloBlo = pmuludq(a, b);
16049   //  AloBhi = pmuludq(a, Bhi);
16050   //  AhiBlo = pmuludq(Ahi, b);
16051
16052   //  AloBhi = psllqi(AloBhi, 32);
16053   //  AhiBlo = psllqi(AhiBlo, 32);
16054   //  return AloBlo + AloBhi + AhiBlo;
16055
16056   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16057   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16058
16059   // Bit cast to 32-bit vectors for MULUDQ
16060   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16061                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16062   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16063   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16064   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16065   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16066
16067   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16068   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16069   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16070
16071   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16072   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16073
16074   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16075   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16076 }
16077
16078 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16079   assert(Subtarget->isTargetWin64() && "Unexpected target");
16080   EVT VT = Op.getValueType();
16081   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16082          "Unexpected return type for lowering");
16083
16084   RTLIB::Libcall LC;
16085   bool isSigned;
16086   switch (Op->getOpcode()) {
16087   default: llvm_unreachable("Unexpected request for libcall!");
16088   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16089   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16090   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16091   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16092   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16093   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16094   }
16095
16096   SDLoc dl(Op);
16097   SDValue InChain = DAG.getEntryNode();
16098
16099   TargetLowering::ArgListTy Args;
16100   TargetLowering::ArgListEntry Entry;
16101   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16102     EVT ArgVT = Op->getOperand(i).getValueType();
16103     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16104            "Unexpected argument type for lowering");
16105     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16106     Entry.Node = StackPtr;
16107     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16108                            false, false, 16);
16109     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16110     Entry.Ty = PointerType::get(ArgTy,0);
16111     Entry.isSExt = false;
16112     Entry.isZExt = false;
16113     Args.push_back(Entry);
16114   }
16115
16116   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16117                                          getPointerTy());
16118
16119   TargetLowering::CallLoweringInfo CLI(DAG);
16120   CLI.setDebugLoc(dl).setChain(InChain)
16121     .setCallee(getLibcallCallingConv(LC),
16122                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16123                Callee, std::move(Args), 0)
16124     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16125
16126   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16127   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16128 }
16129
16130 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16131                              SelectionDAG &DAG) {
16132   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16133   EVT VT = Op0.getValueType();
16134   SDLoc dl(Op);
16135
16136   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16137          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16138
16139   // PMULxD operations multiply each even value (starting at 0) of LHS with
16140   // the related value of RHS and produce a widen result.
16141   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16142   // => <2 x i64> <ae|cg>
16143   //
16144   // In other word, to have all the results, we need to perform two PMULxD:
16145   // 1. one with the even values.
16146   // 2. one with the odd values.
16147   // To achieve #2, with need to place the odd values at an even position.
16148   //
16149   // Place the odd value at an even position (basically, shift all values 1
16150   // step to the left):
16151   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16152   // <a|b|c|d> => <b|undef|d|undef>
16153   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16154   // <e|f|g|h> => <f|undef|h|undef>
16155   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16156
16157   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16158   // ints.
16159   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16160   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16161   unsigned Opcode =
16162       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16163   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16164   // => <2 x i64> <ae|cg>
16165   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16166                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16167   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16168   // => <2 x i64> <bf|dh>
16169   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16170                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16171
16172   // Shuffle it back into the right order.
16173   SDValue Highs, Lows;
16174   if (VT == MVT::v8i32) {
16175     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16176     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16177     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16178     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16179   } else {
16180     const int HighMask[] = {1, 5, 3, 7};
16181     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16182     const int LowMask[] = {0, 4, 2, 6};
16183     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16184   }
16185
16186   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16187   // unsigned multiply.
16188   if (IsSigned && !Subtarget->hasSSE41()) {
16189     SDValue ShAmt =
16190         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16191     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16192                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16193     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16194                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16195
16196     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16197     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16198   }
16199
16200   // The first result of MUL_LOHI is actually the low value, followed by the
16201   // high value.
16202   SDValue Ops[] = {Lows, Highs};
16203   return DAG.getMergeValues(Ops, dl);
16204 }
16205
16206 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16207                                          const X86Subtarget *Subtarget) {
16208   MVT VT = Op.getSimpleValueType();
16209   SDLoc dl(Op);
16210   SDValue R = Op.getOperand(0);
16211   SDValue Amt = Op.getOperand(1);
16212
16213   // Optimize shl/srl/sra with constant shift amount.
16214   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16215     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16216       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16217
16218       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16219           (Subtarget->hasInt256() &&
16220            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16221           (Subtarget->hasAVX512() &&
16222            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16223         if (Op.getOpcode() == ISD::SHL)
16224           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16225                                             DAG);
16226         if (Op.getOpcode() == ISD::SRL)
16227           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16228                                             DAG);
16229         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16230           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16231                                             DAG);
16232       }
16233
16234       if (VT == MVT::v16i8) {
16235         if (Op.getOpcode() == ISD::SHL) {
16236           // Make a large shift.
16237           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16238                                                    MVT::v8i16, R, ShiftAmt,
16239                                                    DAG);
16240           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16241           // Zero out the rightmost bits.
16242           SmallVector<SDValue, 16> V(16,
16243                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16244                                                      MVT::i8));
16245           return DAG.getNode(ISD::AND, dl, VT, SHL,
16246                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16247         }
16248         if (Op.getOpcode() == ISD::SRL) {
16249           // Make a large shift.
16250           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16251                                                    MVT::v8i16, R, ShiftAmt,
16252                                                    DAG);
16253           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16254           // Zero out the leftmost bits.
16255           SmallVector<SDValue, 16> V(16,
16256                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16257                                                      MVT::i8));
16258           return DAG.getNode(ISD::AND, dl, VT, SRL,
16259                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16260         }
16261         if (Op.getOpcode() == ISD::SRA) {
16262           if (ShiftAmt == 7) {
16263             // R s>> 7  ===  R s< 0
16264             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16265             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16266           }
16267
16268           // R s>> a === ((R u>> a) ^ m) - m
16269           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16270           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
16271                                                          MVT::i8));
16272           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16273           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16274           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16275           return Res;
16276         }
16277         llvm_unreachable("Unknown shift opcode.");
16278       }
16279
16280       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16281         if (Op.getOpcode() == ISD::SHL) {
16282           // Make a large shift.
16283           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16284                                                    MVT::v16i16, R, ShiftAmt,
16285                                                    DAG);
16286           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16287           // Zero out the rightmost bits.
16288           SmallVector<SDValue, 32> V(32,
16289                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16290                                                      MVT::i8));
16291           return DAG.getNode(ISD::AND, dl, VT, SHL,
16292                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16293         }
16294         if (Op.getOpcode() == ISD::SRL) {
16295           // Make a large shift.
16296           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16297                                                    MVT::v16i16, R, ShiftAmt,
16298                                                    DAG);
16299           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16300           // Zero out the leftmost bits.
16301           SmallVector<SDValue, 32> V(32,
16302                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16303                                                      MVT::i8));
16304           return DAG.getNode(ISD::AND, dl, VT, SRL,
16305                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16306         }
16307         if (Op.getOpcode() == ISD::SRA) {
16308           if (ShiftAmt == 7) {
16309             // R s>> 7  ===  R s< 0
16310             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16311             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16312           }
16313
16314           // R s>> a === ((R u>> a) ^ m) - m
16315           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16316           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16317                                                          MVT::i8));
16318           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16319           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16320           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16321           return Res;
16322         }
16323         llvm_unreachable("Unknown shift opcode.");
16324       }
16325     }
16326   }
16327
16328   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16329   if (!Subtarget->is64Bit() &&
16330       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16331       Amt.getOpcode() == ISD::BITCAST &&
16332       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16333     Amt = Amt.getOperand(0);
16334     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16335                      VT.getVectorNumElements();
16336     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16337     uint64_t ShiftAmt = 0;
16338     for (unsigned i = 0; i != Ratio; ++i) {
16339       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16340       if (!C)
16341         return SDValue();
16342       // 6 == Log2(64)
16343       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16344     }
16345     // Check remaining shift amounts.
16346     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16347       uint64_t ShAmt = 0;
16348       for (unsigned j = 0; j != Ratio; ++j) {
16349         ConstantSDNode *C =
16350           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16351         if (!C)
16352           return SDValue();
16353         // 6 == Log2(64)
16354         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16355       }
16356       if (ShAmt != ShiftAmt)
16357         return SDValue();
16358     }
16359     switch (Op.getOpcode()) {
16360     default:
16361       llvm_unreachable("Unknown shift opcode!");
16362     case ISD::SHL:
16363       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16364                                         DAG);
16365     case ISD::SRL:
16366       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16367                                         DAG);
16368     case ISD::SRA:
16369       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16370                                         DAG);
16371     }
16372   }
16373
16374   return SDValue();
16375 }
16376
16377 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16378                                         const X86Subtarget* Subtarget) {
16379   MVT VT = Op.getSimpleValueType();
16380   SDLoc dl(Op);
16381   SDValue R = Op.getOperand(0);
16382   SDValue Amt = Op.getOperand(1);
16383
16384   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16385       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16386       (Subtarget->hasInt256() &&
16387        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16388         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16389        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16390     SDValue BaseShAmt;
16391     EVT EltVT = VT.getVectorElementType();
16392
16393     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16394       unsigned NumElts = VT.getVectorNumElements();
16395       unsigned i, j;
16396       for (i = 0; i != NumElts; ++i) {
16397         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16398           continue;
16399         break;
16400       }
16401       for (j = i; j != NumElts; ++j) {
16402         SDValue Arg = Amt.getOperand(j);
16403         if (Arg.getOpcode() == ISD::UNDEF) continue;
16404         if (Arg != Amt.getOperand(i))
16405           break;
16406       }
16407       if (i != NumElts && j == NumElts)
16408         BaseShAmt = Amt.getOperand(i);
16409     } else {
16410       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16411         Amt = Amt.getOperand(0);
16412       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16413                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16414         SDValue InVec = Amt.getOperand(0);
16415         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16416           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16417           unsigned i = 0;
16418           for (; i != NumElts; ++i) {
16419             SDValue Arg = InVec.getOperand(i);
16420             if (Arg.getOpcode() == ISD::UNDEF) continue;
16421             BaseShAmt = Arg;
16422             break;
16423           }
16424         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16425            if (ConstantSDNode *C =
16426                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16427              unsigned SplatIdx =
16428                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16429              if (C->getZExtValue() == SplatIdx)
16430                BaseShAmt = InVec.getOperand(1);
16431            }
16432         }
16433         if (!BaseShAmt.getNode())
16434           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16435                                   DAG.getIntPtrConstant(0));
16436       }
16437     }
16438
16439     if (BaseShAmt.getNode()) {
16440       if (EltVT.bitsGT(MVT::i32))
16441         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16442       else if (EltVT.bitsLT(MVT::i32))
16443         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16444
16445       switch (Op.getOpcode()) {
16446       default:
16447         llvm_unreachable("Unknown shift opcode!");
16448       case ISD::SHL:
16449         switch (VT.SimpleTy) {
16450         default: return SDValue();
16451         case MVT::v2i64:
16452         case MVT::v4i32:
16453         case MVT::v8i16:
16454         case MVT::v4i64:
16455         case MVT::v8i32:
16456         case MVT::v16i16:
16457         case MVT::v16i32:
16458         case MVT::v8i64:
16459           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16460         }
16461       case ISD::SRA:
16462         switch (VT.SimpleTy) {
16463         default: return SDValue();
16464         case MVT::v4i32:
16465         case MVT::v8i16:
16466         case MVT::v8i32:
16467         case MVT::v16i16:
16468         case MVT::v16i32:
16469         case MVT::v8i64:
16470           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16471         }
16472       case ISD::SRL:
16473         switch (VT.SimpleTy) {
16474         default: return SDValue();
16475         case MVT::v2i64:
16476         case MVT::v4i32:
16477         case MVT::v8i16:
16478         case MVT::v4i64:
16479         case MVT::v8i32:
16480         case MVT::v16i16:
16481         case MVT::v16i32:
16482         case MVT::v8i64:
16483           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16484         }
16485       }
16486     }
16487   }
16488
16489   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16490   if (!Subtarget->is64Bit() &&
16491       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16492       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16493       Amt.getOpcode() == ISD::BITCAST &&
16494       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16495     Amt = Amt.getOperand(0);
16496     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16497                      VT.getVectorNumElements();
16498     std::vector<SDValue> Vals(Ratio);
16499     for (unsigned i = 0; i != Ratio; ++i)
16500       Vals[i] = Amt.getOperand(i);
16501     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16502       for (unsigned j = 0; j != Ratio; ++j)
16503         if (Vals[j] != Amt.getOperand(i + j))
16504           return SDValue();
16505     }
16506     switch (Op.getOpcode()) {
16507     default:
16508       llvm_unreachable("Unknown shift opcode!");
16509     case ISD::SHL:
16510       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16511     case ISD::SRL:
16512       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16513     case ISD::SRA:
16514       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16515     }
16516   }
16517
16518   return SDValue();
16519 }
16520
16521 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16522                           SelectionDAG &DAG) {
16523   MVT VT = Op.getSimpleValueType();
16524   SDLoc dl(Op);
16525   SDValue R = Op.getOperand(0);
16526   SDValue Amt = Op.getOperand(1);
16527   SDValue V;
16528
16529   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16530   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16531
16532   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16533   if (V.getNode())
16534     return V;
16535
16536   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16537   if (V.getNode())
16538       return V;
16539
16540   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16541     return Op;
16542   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16543   if (Subtarget->hasInt256()) {
16544     if (Op.getOpcode() == ISD::SRL &&
16545         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16546          VT == MVT::v4i64 || VT == MVT::v8i32))
16547       return Op;
16548     if (Op.getOpcode() == ISD::SHL &&
16549         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16550          VT == MVT::v4i64 || VT == MVT::v8i32))
16551       return Op;
16552     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16553       return Op;
16554   }
16555
16556   // If possible, lower this packed shift into a vector multiply instead of
16557   // expanding it into a sequence of scalar shifts.
16558   // Do this only if the vector shift count is a constant build_vector.
16559   if (Op.getOpcode() == ISD::SHL && 
16560       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16561        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16562       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16563     SmallVector<SDValue, 8> Elts;
16564     EVT SVT = VT.getScalarType();
16565     unsigned SVTBits = SVT.getSizeInBits();
16566     const APInt &One = APInt(SVTBits, 1);
16567     unsigned NumElems = VT.getVectorNumElements();
16568
16569     for (unsigned i=0; i !=NumElems; ++i) {
16570       SDValue Op = Amt->getOperand(i);
16571       if (Op->getOpcode() == ISD::UNDEF) {
16572         Elts.push_back(Op);
16573         continue;
16574       }
16575
16576       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16577       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16578       uint64_t ShAmt = C.getZExtValue();
16579       if (ShAmt >= SVTBits) {
16580         Elts.push_back(DAG.getUNDEF(SVT));
16581         continue;
16582       }
16583       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16584     }
16585     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16586     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16587   }
16588
16589   // Lower SHL with variable shift amount.
16590   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16591     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16592
16593     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16594     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16595     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16596     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16597   }
16598
16599   // If possible, lower this shift as a sequence of two shifts by
16600   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16601   // Example:
16602   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16603   //
16604   // Could be rewritten as:
16605   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16606   //
16607   // The advantage is that the two shifts from the example would be
16608   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16609   // the vector shift into four scalar shifts plus four pairs of vector
16610   // insert/extract.
16611   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16612       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16613     unsigned TargetOpcode = X86ISD::MOVSS;
16614     bool CanBeSimplified;
16615     // The splat value for the first packed shift (the 'X' from the example).
16616     SDValue Amt1 = Amt->getOperand(0);
16617     // The splat value for the second packed shift (the 'Y' from the example).
16618     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16619                                         Amt->getOperand(2);
16620
16621     // See if it is possible to replace this node with a sequence of
16622     // two shifts followed by a MOVSS/MOVSD
16623     if (VT == MVT::v4i32) {
16624       // Check if it is legal to use a MOVSS.
16625       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16626                         Amt2 == Amt->getOperand(3);
16627       if (!CanBeSimplified) {
16628         // Otherwise, check if we can still simplify this node using a MOVSD.
16629         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16630                           Amt->getOperand(2) == Amt->getOperand(3);
16631         TargetOpcode = X86ISD::MOVSD;
16632         Amt2 = Amt->getOperand(2);
16633       }
16634     } else {
16635       // Do similar checks for the case where the machine value type
16636       // is MVT::v8i16.
16637       CanBeSimplified = Amt1 == Amt->getOperand(1);
16638       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16639         CanBeSimplified = Amt2 == Amt->getOperand(i);
16640
16641       if (!CanBeSimplified) {
16642         TargetOpcode = X86ISD::MOVSD;
16643         CanBeSimplified = true;
16644         Amt2 = Amt->getOperand(4);
16645         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16646           CanBeSimplified = Amt1 == Amt->getOperand(i);
16647         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16648           CanBeSimplified = Amt2 == Amt->getOperand(j);
16649       }
16650     }
16651     
16652     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16653         isa<ConstantSDNode>(Amt2)) {
16654       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16655       EVT CastVT = MVT::v4i32;
16656       SDValue Splat1 = 
16657         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16658       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16659       SDValue Splat2 = 
16660         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16661       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16662       if (TargetOpcode == X86ISD::MOVSD)
16663         CastVT = MVT::v2i64;
16664       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16665       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16666       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16667                                             BitCast1, DAG);
16668       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16669     }
16670   }
16671
16672   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16673     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16674
16675     // a = a << 5;
16676     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16677     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16678
16679     // Turn 'a' into a mask suitable for VSELECT
16680     SDValue VSelM = DAG.getConstant(0x80, VT);
16681     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16682     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16683
16684     SDValue CM1 = DAG.getConstant(0x0f, VT);
16685     SDValue CM2 = DAG.getConstant(0x3f, VT);
16686
16687     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16688     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16689     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16690     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16691     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16692
16693     // a += a
16694     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16695     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16696     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16697
16698     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16699     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16700     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16701     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16702     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16703
16704     // a += a
16705     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16706     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16707     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16708
16709     // return VSELECT(r, r+r, a);
16710     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16711                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16712     return R;
16713   }
16714
16715   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16716   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16717   // solution better.
16718   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16719     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16720     unsigned ExtOpc =
16721         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16722     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16723     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16724     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16725                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16726     }
16727
16728   // Decompose 256-bit shifts into smaller 128-bit shifts.
16729   if (VT.is256BitVector()) {
16730     unsigned NumElems = VT.getVectorNumElements();
16731     MVT EltVT = VT.getVectorElementType();
16732     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16733
16734     // Extract the two vectors
16735     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16736     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16737
16738     // Recreate the shift amount vectors
16739     SDValue Amt1, Amt2;
16740     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16741       // Constant shift amount
16742       SmallVector<SDValue, 4> Amt1Csts;
16743       SmallVector<SDValue, 4> Amt2Csts;
16744       for (unsigned i = 0; i != NumElems/2; ++i)
16745         Amt1Csts.push_back(Amt->getOperand(i));
16746       for (unsigned i = NumElems/2; i != NumElems; ++i)
16747         Amt2Csts.push_back(Amt->getOperand(i));
16748
16749       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16750       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16751     } else {
16752       // Variable shift amount
16753       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16754       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16755     }
16756
16757     // Issue new vector shifts for the smaller types
16758     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16759     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16760
16761     // Concatenate the result back
16762     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16763   }
16764
16765   return SDValue();
16766 }
16767
16768 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16769   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16770   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16771   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16772   // has only one use.
16773   SDNode *N = Op.getNode();
16774   SDValue LHS = N->getOperand(0);
16775   SDValue RHS = N->getOperand(1);
16776   unsigned BaseOp = 0;
16777   unsigned Cond = 0;
16778   SDLoc DL(Op);
16779   switch (Op.getOpcode()) {
16780   default: llvm_unreachable("Unknown ovf instruction!");
16781   case ISD::SADDO:
16782     // A subtract of one will be selected as a INC. Note that INC doesn't
16783     // set CF, so we can't do this for UADDO.
16784     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16785       if (C->isOne()) {
16786         BaseOp = X86ISD::INC;
16787         Cond = X86::COND_O;
16788         break;
16789       }
16790     BaseOp = X86ISD::ADD;
16791     Cond = X86::COND_O;
16792     break;
16793   case ISD::UADDO:
16794     BaseOp = X86ISD::ADD;
16795     Cond = X86::COND_B;
16796     break;
16797   case ISD::SSUBO:
16798     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16799     // set CF, so we can't do this for USUBO.
16800     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16801       if (C->isOne()) {
16802         BaseOp = X86ISD::DEC;
16803         Cond = X86::COND_O;
16804         break;
16805       }
16806     BaseOp = X86ISD::SUB;
16807     Cond = X86::COND_O;
16808     break;
16809   case ISD::USUBO:
16810     BaseOp = X86ISD::SUB;
16811     Cond = X86::COND_B;
16812     break;
16813   case ISD::SMULO:
16814     BaseOp = X86ISD::SMUL;
16815     Cond = X86::COND_O;
16816     break;
16817   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16818     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16819                                  MVT::i32);
16820     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16821
16822     SDValue SetCC =
16823       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16824                   DAG.getConstant(X86::COND_O, MVT::i32),
16825                   SDValue(Sum.getNode(), 2));
16826
16827     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16828   }
16829   }
16830
16831   // Also sets EFLAGS.
16832   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16833   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16834
16835   SDValue SetCC =
16836     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16837                 DAG.getConstant(Cond, MVT::i32),
16838                 SDValue(Sum.getNode(), 1));
16839
16840   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16841 }
16842
16843 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16844                                                   SelectionDAG &DAG) const {
16845   SDLoc dl(Op);
16846   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16847   MVT VT = Op.getSimpleValueType();
16848
16849   if (!Subtarget->hasSSE2() || !VT.isVector())
16850     return SDValue();
16851
16852   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16853                       ExtraVT.getScalarType().getSizeInBits();
16854
16855   switch (VT.SimpleTy) {
16856     default: return SDValue();
16857     case MVT::v8i32:
16858     case MVT::v16i16:
16859       if (!Subtarget->hasFp256())
16860         return SDValue();
16861       if (!Subtarget->hasInt256()) {
16862         // needs to be split
16863         unsigned NumElems = VT.getVectorNumElements();
16864
16865         // Extract the LHS vectors
16866         SDValue LHS = Op.getOperand(0);
16867         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16868         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16869
16870         MVT EltVT = VT.getVectorElementType();
16871         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16872
16873         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16874         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16875         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16876                                    ExtraNumElems/2);
16877         SDValue Extra = DAG.getValueType(ExtraVT);
16878
16879         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16880         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16881
16882         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16883       }
16884       // fall through
16885     case MVT::v4i32:
16886     case MVT::v8i16: {
16887       SDValue Op0 = Op.getOperand(0);
16888       SDValue Op00 = Op0.getOperand(0);
16889       SDValue Tmp1;
16890       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16891       if (Op0.getOpcode() == ISD::BITCAST &&
16892           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16893         // (sext (vzext x)) -> (vsext x)
16894         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16895         if (Tmp1.getNode()) {
16896           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16897           // This folding is only valid when the in-reg type is a vector of i8,
16898           // i16, or i32.
16899           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16900               ExtraEltVT == MVT::i32) {
16901             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16902             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16903                    "This optimization is invalid without a VZEXT.");
16904             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16905           }
16906           Op0 = Tmp1;
16907         }
16908       }
16909
16910       // If the above didn't work, then just use Shift-Left + Shift-Right.
16911       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16912                                         DAG);
16913       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16914                                         DAG);
16915     }
16916   }
16917 }
16918
16919 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16920                                  SelectionDAG &DAG) {
16921   SDLoc dl(Op);
16922   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16923     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16924   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16925     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16926
16927   // The only fence that needs an instruction is a sequentially-consistent
16928   // cross-thread fence.
16929   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16930     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16931     // no-sse2). There isn't any reason to disable it if the target processor
16932     // supports it.
16933     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16934       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16935
16936     SDValue Chain = Op.getOperand(0);
16937     SDValue Zero = DAG.getConstant(0, MVT::i32);
16938     SDValue Ops[] = {
16939       DAG.getRegister(X86::ESP, MVT::i32), // Base
16940       DAG.getTargetConstant(1, MVT::i8),   // Scale
16941       DAG.getRegister(0, MVT::i32),        // Index
16942       DAG.getTargetConstant(0, MVT::i32),  // Disp
16943       DAG.getRegister(0, MVT::i32),        // Segment.
16944       Zero,
16945       Chain
16946     };
16947     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16948     return SDValue(Res, 0);
16949   }
16950
16951   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16952   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16953 }
16954
16955 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16956                              SelectionDAG &DAG) {
16957   MVT T = Op.getSimpleValueType();
16958   SDLoc DL(Op);
16959   unsigned Reg = 0;
16960   unsigned size = 0;
16961   switch(T.SimpleTy) {
16962   default: llvm_unreachable("Invalid value type!");
16963   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16964   case MVT::i16: Reg = X86::AX;  size = 2; break;
16965   case MVT::i32: Reg = X86::EAX; size = 4; break;
16966   case MVT::i64:
16967     assert(Subtarget->is64Bit() && "Node not type legal!");
16968     Reg = X86::RAX; size = 8;
16969     break;
16970   }
16971   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16972                                   Op.getOperand(2), SDValue());
16973   SDValue Ops[] = { cpIn.getValue(0),
16974                     Op.getOperand(1),
16975                     Op.getOperand(3),
16976                     DAG.getTargetConstant(size, MVT::i8),
16977                     cpIn.getValue(1) };
16978   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16979   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16980   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16981                                            Ops, T, MMO);
16982
16983   SDValue cpOut =
16984     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16985   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16986                                       MVT::i32, cpOut.getValue(2));
16987   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16988                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16989
16990   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16991   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16992   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16993   return SDValue();
16994 }
16995
16996 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16997                             SelectionDAG &DAG) {
16998   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16999   MVT DstVT = Op.getSimpleValueType();
17000
17001   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17002     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17003     if (DstVT != MVT::f64)
17004       // This conversion needs to be expanded.
17005       return SDValue();
17006
17007     SDValue InVec = Op->getOperand(0);
17008     SDLoc dl(Op);
17009     unsigned NumElts = SrcVT.getVectorNumElements();
17010     EVT SVT = SrcVT.getVectorElementType();
17011
17012     // Widen the vector in input in the case of MVT::v2i32.
17013     // Example: from MVT::v2i32 to MVT::v4i32.
17014     SmallVector<SDValue, 16> Elts;
17015     for (unsigned i = 0, e = NumElts; i != e; ++i)
17016       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17017                                  DAG.getIntPtrConstant(i)));
17018
17019     // Explicitly mark the extra elements as Undef.
17020     SDValue Undef = DAG.getUNDEF(SVT);
17021     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
17022       Elts.push_back(Undef);
17023
17024     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17025     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17026     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17027     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17028                        DAG.getIntPtrConstant(0));
17029   }
17030
17031   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17032          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17033   assert((DstVT == MVT::i64 ||
17034           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17035          "Unexpected custom BITCAST");
17036   // i64 <=> MMX conversions are Legal.
17037   if (SrcVT==MVT::i64 && DstVT.isVector())
17038     return Op;
17039   if (DstVT==MVT::i64 && SrcVT.isVector())
17040     return Op;
17041   // MMX <=> MMX conversions are Legal.
17042   if (SrcVT.isVector() && DstVT.isVector())
17043     return Op;
17044   // All other conversions need to be expanded.
17045   return SDValue();
17046 }
17047
17048 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17049   SDNode *Node = Op.getNode();
17050   SDLoc dl(Node);
17051   EVT T = Node->getValueType(0);
17052   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17053                               DAG.getConstant(0, T), Node->getOperand(2));
17054   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17055                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17056                        Node->getOperand(0),
17057                        Node->getOperand(1), negOp,
17058                        cast<AtomicSDNode>(Node)->getMemOperand(),
17059                        cast<AtomicSDNode>(Node)->getOrdering(),
17060                        cast<AtomicSDNode>(Node)->getSynchScope());
17061 }
17062
17063 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17064   SDNode *Node = Op.getNode();
17065   SDLoc dl(Node);
17066   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17067
17068   // Convert seq_cst store -> xchg
17069   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17070   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17071   //        (The only way to get a 16-byte store is cmpxchg16b)
17072   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17073   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17074       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17075     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17076                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17077                                  Node->getOperand(0),
17078                                  Node->getOperand(1), Node->getOperand(2),
17079                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17080                                  cast<AtomicSDNode>(Node)->getOrdering(),
17081                                  cast<AtomicSDNode>(Node)->getSynchScope());
17082     return Swap.getValue(1);
17083   }
17084   // Other atomic stores have a simple pattern.
17085   return Op;
17086 }
17087
17088 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17089   EVT VT = Op.getNode()->getSimpleValueType(0);
17090
17091   // Let legalize expand this if it isn't a legal type yet.
17092   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17093     return SDValue();
17094
17095   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17096
17097   unsigned Opc;
17098   bool ExtraOp = false;
17099   switch (Op.getOpcode()) {
17100   default: llvm_unreachable("Invalid code");
17101   case ISD::ADDC: Opc = X86ISD::ADD; break;
17102   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17103   case ISD::SUBC: Opc = X86ISD::SUB; break;
17104   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17105   }
17106
17107   if (!ExtraOp)
17108     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17109                        Op.getOperand(1));
17110   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17111                      Op.getOperand(1), Op.getOperand(2));
17112 }
17113
17114 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17115                             SelectionDAG &DAG) {
17116   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17117
17118   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17119   // which returns the values as { float, float } (in XMM0) or
17120   // { double, double } (which is returned in XMM0, XMM1).
17121   SDLoc dl(Op);
17122   SDValue Arg = Op.getOperand(0);
17123   EVT ArgVT = Arg.getValueType();
17124   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17125
17126   TargetLowering::ArgListTy Args;
17127   TargetLowering::ArgListEntry Entry;
17128
17129   Entry.Node = Arg;
17130   Entry.Ty = ArgTy;
17131   Entry.isSExt = false;
17132   Entry.isZExt = false;
17133   Args.push_back(Entry);
17134
17135   bool isF64 = ArgVT == MVT::f64;
17136   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17137   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17138   // the results are returned via SRet in memory.
17139   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17140   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17141   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17142
17143   Type *RetTy = isF64
17144     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
17145     : (Type*)VectorType::get(ArgTy, 4);
17146
17147   TargetLowering::CallLoweringInfo CLI(DAG);
17148   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17149     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17150
17151   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17152
17153   if (isF64)
17154     // Returned in xmm0 and xmm1.
17155     return CallResult.first;
17156
17157   // Returned in bits 0:31 and 32:64 xmm0.
17158   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17159                                CallResult.first, DAG.getIntPtrConstant(0));
17160   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17161                                CallResult.first, DAG.getIntPtrConstant(1));
17162   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17163   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17164 }
17165
17166 /// LowerOperation - Provide custom lowering hooks for some operations.
17167 ///
17168 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17169   switch (Op.getOpcode()) {
17170   default: llvm_unreachable("Should not custom lower this!");
17171   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
17172   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17173   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17174     return LowerCMP_SWAP(Op, Subtarget, DAG);
17175   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17176   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17177   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17178   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
17179   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
17180   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17181   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17182   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17183   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17184   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17185   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17186   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17187   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17188   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17189   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17190   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17191   case ISD::SHL_PARTS:
17192   case ISD::SRA_PARTS:
17193   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17194   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17195   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17196   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17197   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17198   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17199   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17200   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17201   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17202   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17203   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17204   case ISD::FABS:               return LowerFABS(Op, DAG);
17205   case ISD::FNEG:               return LowerFNEG(Op, DAG);
17206   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17207   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17208   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17209   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17210   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17211   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17212   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17213   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17214   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17215   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
17216   case ISD::INTRINSIC_VOID:
17217   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17218   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17219   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17220   case ISD::FRAME_TO_ARGS_OFFSET:
17221                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17222   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17223   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17224   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17225   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17226   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17227   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17228   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17229   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17230   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17231   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17232   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17233   case ISD::UMUL_LOHI:
17234   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17235   case ISD::SRA:
17236   case ISD::SRL:
17237   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17238   case ISD::SADDO:
17239   case ISD::UADDO:
17240   case ISD::SSUBO:
17241   case ISD::USUBO:
17242   case ISD::SMULO:
17243   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17244   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17245   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17246   case ISD::ADDC:
17247   case ISD::ADDE:
17248   case ISD::SUBC:
17249   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17250   case ISD::ADD:                return LowerADD(Op, DAG);
17251   case ISD::SUB:                return LowerSUB(Op, DAG);
17252   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17253   }
17254 }
17255
17256 static void ReplaceATOMIC_LOAD(SDNode *Node,
17257                                SmallVectorImpl<SDValue> &Results,
17258                                SelectionDAG &DAG) {
17259   SDLoc dl(Node);
17260   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17261
17262   // Convert wide load -> cmpxchg8b/cmpxchg16b
17263   // FIXME: On 32-bit, load -> fild or movq would be more efficient
17264   //        (The only way to get a 16-byte load is cmpxchg16b)
17265   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
17266   SDValue Zero = DAG.getConstant(0, VT);
17267   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
17268   SDValue Swap =
17269       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
17270                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
17271                            cast<AtomicSDNode>(Node)->getMemOperand(),
17272                            cast<AtomicSDNode>(Node)->getOrdering(),
17273                            cast<AtomicSDNode>(Node)->getOrdering(),
17274                            cast<AtomicSDNode>(Node)->getSynchScope());
17275   Results.push_back(Swap.getValue(0));
17276   Results.push_back(Swap.getValue(2));
17277 }
17278
17279 /// ReplaceNodeResults - Replace a node with an illegal result type
17280 /// with a new node built out of custom code.
17281 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17282                                            SmallVectorImpl<SDValue>&Results,
17283                                            SelectionDAG &DAG) const {
17284   SDLoc dl(N);
17285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17286   switch (N->getOpcode()) {
17287   default:
17288     llvm_unreachable("Do not know how to custom type legalize this operation!");
17289   case ISD::SIGN_EXTEND_INREG:
17290   case ISD::ADDC:
17291   case ISD::ADDE:
17292   case ISD::SUBC:
17293   case ISD::SUBE:
17294     // We don't want to expand or promote these.
17295     return;
17296   case ISD::SDIV:
17297   case ISD::UDIV:
17298   case ISD::SREM:
17299   case ISD::UREM:
17300   case ISD::SDIVREM:
17301   case ISD::UDIVREM: {
17302     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17303     Results.push_back(V);
17304     return;
17305   }
17306   case ISD::FP_TO_SINT:
17307   case ISD::FP_TO_UINT: {
17308     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17309
17310     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17311       return;
17312
17313     std::pair<SDValue,SDValue> Vals =
17314         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17315     SDValue FIST = Vals.first, StackSlot = Vals.second;
17316     if (FIST.getNode()) {
17317       EVT VT = N->getValueType(0);
17318       // Return a load from the stack slot.
17319       if (StackSlot.getNode())
17320         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17321                                       MachinePointerInfo(),
17322                                       false, false, false, 0));
17323       else
17324         Results.push_back(FIST);
17325     }
17326     return;
17327   }
17328   case ISD::UINT_TO_FP: {
17329     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17330     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17331         N->getValueType(0) != MVT::v2f32)
17332       return;
17333     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17334                                  N->getOperand(0));
17335     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17336                                      MVT::f64);
17337     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17338     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17339                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17340     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17341     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17342     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17343     return;
17344   }
17345   case ISD::FP_ROUND: {
17346     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17347         return;
17348     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17349     Results.push_back(V);
17350     return;
17351   }
17352   case ISD::INTRINSIC_W_CHAIN: {
17353     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17354     switch (IntNo) {
17355     default : llvm_unreachable("Do not know how to custom type "
17356                                "legalize this intrinsic operation!");
17357     case Intrinsic::x86_rdtsc:
17358       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17359                                      Results);
17360     case Intrinsic::x86_rdtscp:
17361       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17362                                      Results);
17363     case Intrinsic::x86_rdpmc:
17364       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17365     }
17366   }
17367   case ISD::READCYCLECOUNTER: {
17368     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17369                                    Results);
17370   }
17371   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17372     EVT T = N->getValueType(0);
17373     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17374     bool Regs64bit = T == MVT::i128;
17375     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17376     SDValue cpInL, cpInH;
17377     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17378                         DAG.getConstant(0, HalfT));
17379     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17380                         DAG.getConstant(1, HalfT));
17381     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17382                              Regs64bit ? X86::RAX : X86::EAX,
17383                              cpInL, SDValue());
17384     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17385                              Regs64bit ? X86::RDX : X86::EDX,
17386                              cpInH, cpInL.getValue(1));
17387     SDValue swapInL, swapInH;
17388     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17389                           DAG.getConstant(0, HalfT));
17390     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17391                           DAG.getConstant(1, HalfT));
17392     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17393                                Regs64bit ? X86::RBX : X86::EBX,
17394                                swapInL, cpInH.getValue(1));
17395     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17396                                Regs64bit ? X86::RCX : X86::ECX,
17397                                swapInH, swapInL.getValue(1));
17398     SDValue Ops[] = { swapInH.getValue(0),
17399                       N->getOperand(1),
17400                       swapInH.getValue(1) };
17401     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17402     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17403     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17404                                   X86ISD::LCMPXCHG8_DAG;
17405     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17406     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17407                                         Regs64bit ? X86::RAX : X86::EAX,
17408                                         HalfT, Result.getValue(1));
17409     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17410                                         Regs64bit ? X86::RDX : X86::EDX,
17411                                         HalfT, cpOutL.getValue(2));
17412     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17413
17414     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17415                                         MVT::i32, cpOutH.getValue(2));
17416     SDValue Success =
17417         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17418                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17419     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17420
17421     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17422     Results.push_back(Success);
17423     Results.push_back(EFLAGS.getValue(1));
17424     return;
17425   }
17426   case ISD::ATOMIC_SWAP:
17427   case ISD::ATOMIC_LOAD_ADD:
17428   case ISD::ATOMIC_LOAD_SUB:
17429   case ISD::ATOMIC_LOAD_AND:
17430   case ISD::ATOMIC_LOAD_OR:
17431   case ISD::ATOMIC_LOAD_XOR:
17432   case ISD::ATOMIC_LOAD_NAND:
17433   case ISD::ATOMIC_LOAD_MIN:
17434   case ISD::ATOMIC_LOAD_MAX:
17435   case ISD::ATOMIC_LOAD_UMIN:
17436   case ISD::ATOMIC_LOAD_UMAX:
17437     // Delegate to generic TypeLegalization. Situations we can really handle
17438     // should have already been dealt with by X86AtomicExpandPass.cpp.
17439     break;
17440   case ISD::ATOMIC_LOAD: {
17441     ReplaceATOMIC_LOAD(N, Results, DAG);
17442     return;
17443   }
17444   case ISD::BITCAST: {
17445     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17446     EVT DstVT = N->getValueType(0);
17447     EVT SrcVT = N->getOperand(0)->getValueType(0);
17448
17449     if (SrcVT != MVT::f64 ||
17450         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17451       return;
17452
17453     unsigned NumElts = DstVT.getVectorNumElements();
17454     EVT SVT = DstVT.getVectorElementType();
17455     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17456     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17457                                    MVT::v2f64, N->getOperand(0));
17458     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17459
17460     if (ExperimentalVectorWideningLegalization) {
17461       // If we are legalizing vectors by widening, we already have the desired
17462       // legal vector type, just return it.
17463       Results.push_back(ToVecInt);
17464       return;
17465     }
17466
17467     SmallVector<SDValue, 8> Elts;
17468     for (unsigned i = 0, e = NumElts; i != e; ++i)
17469       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17470                                    ToVecInt, DAG.getIntPtrConstant(i)));
17471
17472     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17473   }
17474   }
17475 }
17476
17477 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17478   switch (Opcode) {
17479   default: return nullptr;
17480   case X86ISD::BSF:                return "X86ISD::BSF";
17481   case X86ISD::BSR:                return "X86ISD::BSR";
17482   case X86ISD::SHLD:               return "X86ISD::SHLD";
17483   case X86ISD::SHRD:               return "X86ISD::SHRD";
17484   case X86ISD::FAND:               return "X86ISD::FAND";
17485   case X86ISD::FANDN:              return "X86ISD::FANDN";
17486   case X86ISD::FOR:                return "X86ISD::FOR";
17487   case X86ISD::FXOR:               return "X86ISD::FXOR";
17488   case X86ISD::FSRL:               return "X86ISD::FSRL";
17489   case X86ISD::FILD:               return "X86ISD::FILD";
17490   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17491   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17492   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17493   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17494   case X86ISD::FLD:                return "X86ISD::FLD";
17495   case X86ISD::FST:                return "X86ISD::FST";
17496   case X86ISD::CALL:               return "X86ISD::CALL";
17497   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17498   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17499   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17500   case X86ISD::BT:                 return "X86ISD::BT";
17501   case X86ISD::CMP:                return "X86ISD::CMP";
17502   case X86ISD::COMI:               return "X86ISD::COMI";
17503   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17504   case X86ISD::CMPM:               return "X86ISD::CMPM";
17505   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17506   case X86ISD::SETCC:              return "X86ISD::SETCC";
17507   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17508   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17509   case X86ISD::CMOV:               return "X86ISD::CMOV";
17510   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17511   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17512   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17513   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17514   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17515   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17516   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17517   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17518   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17519   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17520   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17521   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17522   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17523   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17524   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17525   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17526   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17527   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17528   case X86ISD::HADD:               return "X86ISD::HADD";
17529   case X86ISD::HSUB:               return "X86ISD::HSUB";
17530   case X86ISD::FHADD:              return "X86ISD::FHADD";
17531   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17532   case X86ISD::UMAX:               return "X86ISD::UMAX";
17533   case X86ISD::UMIN:               return "X86ISD::UMIN";
17534   case X86ISD::SMAX:               return "X86ISD::SMAX";
17535   case X86ISD::SMIN:               return "X86ISD::SMIN";
17536   case X86ISD::FMAX:               return "X86ISD::FMAX";
17537   case X86ISD::FMIN:               return "X86ISD::FMIN";
17538   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17539   case X86ISD::FMINC:              return "X86ISD::FMINC";
17540   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17541   case X86ISD::FRCP:               return "X86ISD::FRCP";
17542   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17543   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17544   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17545   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17546   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17547   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17548   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17549   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17550   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17551   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17552   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17553   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17554   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17555   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17556   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17557   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17558   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17559   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17560   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17561   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17562   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17563   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17564   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17565   case X86ISD::VSHL:               return "X86ISD::VSHL";
17566   case X86ISD::VSRL:               return "X86ISD::VSRL";
17567   case X86ISD::VSRA:               return "X86ISD::VSRA";
17568   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17569   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17570   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17571   case X86ISD::CMPP:               return "X86ISD::CMPP";
17572   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17573   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17574   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17575   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17576   case X86ISD::ADD:                return "X86ISD::ADD";
17577   case X86ISD::SUB:                return "X86ISD::SUB";
17578   case X86ISD::ADC:                return "X86ISD::ADC";
17579   case X86ISD::SBB:                return "X86ISD::SBB";
17580   case X86ISD::SMUL:               return "X86ISD::SMUL";
17581   case X86ISD::UMUL:               return "X86ISD::UMUL";
17582   case X86ISD::INC:                return "X86ISD::INC";
17583   case X86ISD::DEC:                return "X86ISD::DEC";
17584   case X86ISD::OR:                 return "X86ISD::OR";
17585   case X86ISD::XOR:                return "X86ISD::XOR";
17586   case X86ISD::AND:                return "X86ISD::AND";
17587   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17588   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17589   case X86ISD::PTEST:              return "X86ISD::PTEST";
17590   case X86ISD::TESTP:              return "X86ISD::TESTP";
17591   case X86ISD::TESTM:              return "X86ISD::TESTM";
17592   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17593   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17594   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17595   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17596   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17597   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17598   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17599   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17600   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17601   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17602   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17603   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17604   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17605   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17606   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17607   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17608   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17609   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17610   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17611   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17612   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17613   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17614   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17615   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17616   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17617   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17618   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17619   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17620   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17621   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17622   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17623   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17624   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17625   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17626   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17627   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17628   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17629   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17630   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17631   case X86ISD::SAHF:               return "X86ISD::SAHF";
17632   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17633   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17634   case X86ISD::FMADD:              return "X86ISD::FMADD";
17635   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17636   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17637   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17638   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17639   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17640   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17641   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17642   case X86ISD::XTEST:              return "X86ISD::XTEST";
17643   }
17644 }
17645
17646 // isLegalAddressingMode - Return true if the addressing mode represented
17647 // by AM is legal for this target, for a load/store of the specified type.
17648 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17649                                               Type *Ty) const {
17650   // X86 supports extremely general addressing modes.
17651   CodeModel::Model M = getTargetMachine().getCodeModel();
17652   Reloc::Model R = getTargetMachine().getRelocationModel();
17653
17654   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17655   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17656     return false;
17657
17658   if (AM.BaseGV) {
17659     unsigned GVFlags =
17660       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17661
17662     // If a reference to this global requires an extra load, we can't fold it.
17663     if (isGlobalStubReference(GVFlags))
17664       return false;
17665
17666     // If BaseGV requires a register for the PIC base, we cannot also have a
17667     // BaseReg specified.
17668     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17669       return false;
17670
17671     // If lower 4G is not available, then we must use rip-relative addressing.
17672     if ((M != CodeModel::Small || R != Reloc::Static) &&
17673         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17674       return false;
17675   }
17676
17677   switch (AM.Scale) {
17678   case 0:
17679   case 1:
17680   case 2:
17681   case 4:
17682   case 8:
17683     // These scales always work.
17684     break;
17685   case 3:
17686   case 5:
17687   case 9:
17688     // These scales are formed with basereg+scalereg.  Only accept if there is
17689     // no basereg yet.
17690     if (AM.HasBaseReg)
17691       return false;
17692     break;
17693   default:  // Other stuff never works.
17694     return false;
17695   }
17696
17697   return true;
17698 }
17699
17700 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17701   unsigned Bits = Ty->getScalarSizeInBits();
17702
17703   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17704   // particularly cheaper than those without.
17705   if (Bits == 8)
17706     return false;
17707
17708   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17709   // variable shifts just as cheap as scalar ones.
17710   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17711     return false;
17712
17713   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17714   // fully general vector.
17715   return true;
17716 }
17717
17718 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17719   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17720     return false;
17721   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17722   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17723   return NumBits1 > NumBits2;
17724 }
17725
17726 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17727   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17728     return false;
17729
17730   if (!isTypeLegal(EVT::getEVT(Ty1)))
17731     return false;
17732
17733   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17734
17735   // Assuming the caller doesn't have a zeroext or signext return parameter,
17736   // truncation all the way down to i1 is valid.
17737   return true;
17738 }
17739
17740 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17741   return isInt<32>(Imm);
17742 }
17743
17744 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17745   // Can also use sub to handle negated immediates.
17746   return isInt<32>(Imm);
17747 }
17748
17749 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17750   if (!VT1.isInteger() || !VT2.isInteger())
17751     return false;
17752   unsigned NumBits1 = VT1.getSizeInBits();
17753   unsigned NumBits2 = VT2.getSizeInBits();
17754   return NumBits1 > NumBits2;
17755 }
17756
17757 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17758   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17759   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17760 }
17761
17762 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17763   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17764   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17765 }
17766
17767 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17768   EVT VT1 = Val.getValueType();
17769   if (isZExtFree(VT1, VT2))
17770     return true;
17771
17772   if (Val.getOpcode() != ISD::LOAD)
17773     return false;
17774
17775   if (!VT1.isSimple() || !VT1.isInteger() ||
17776       !VT2.isSimple() || !VT2.isInteger())
17777     return false;
17778
17779   switch (VT1.getSimpleVT().SimpleTy) {
17780   default: break;
17781   case MVT::i8:
17782   case MVT::i16:
17783   case MVT::i32:
17784     // X86 has 8, 16, and 32-bit zero-extending loads.
17785     return true;
17786   }
17787
17788   return false;
17789 }
17790
17791 bool
17792 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17793   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17794     return false;
17795
17796   VT = VT.getScalarType();
17797
17798   if (!VT.isSimple())
17799     return false;
17800
17801   switch (VT.getSimpleVT().SimpleTy) {
17802   case MVT::f32:
17803   case MVT::f64:
17804     return true;
17805   default:
17806     break;
17807   }
17808
17809   return false;
17810 }
17811
17812 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17813   // i16 instructions are longer (0x66 prefix) and potentially slower.
17814   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17815 }
17816
17817 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17818 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17819 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17820 /// are assumed to be legal.
17821 bool
17822 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17823                                       EVT VT) const {
17824   if (!VT.isSimple())
17825     return false;
17826
17827   MVT SVT = VT.getSimpleVT();
17828
17829   // Very little shuffling can be done for 64-bit vectors right now.
17830   if (VT.getSizeInBits() == 64)
17831     return false;
17832
17833   // If this is a single-input shuffle with no 128 bit lane crossings we can
17834   // lower it into pshufb.
17835   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17836       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17837     bool isLegal = true;
17838     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17839       if (M[I] >= (int)SVT.getVectorNumElements() ||
17840           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17841         isLegal = false;
17842         break;
17843       }
17844     }
17845     if (isLegal)
17846       return true;
17847   }
17848
17849   // FIXME: blends, shifts.
17850   return (SVT.getVectorNumElements() == 2 ||
17851           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17852           isMOVLMask(M, SVT) ||
17853           isMOVHLPSMask(M, SVT) ||
17854           isSHUFPMask(M, SVT) ||
17855           isPSHUFDMask(M, SVT) ||
17856           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17857           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17858           isPALIGNRMask(M, SVT, Subtarget) ||
17859           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17860           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17861           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17862           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17863           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17864 }
17865
17866 bool
17867 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17868                                           EVT VT) const {
17869   if (!VT.isSimple())
17870     return false;
17871
17872   MVT SVT = VT.getSimpleVT();
17873   unsigned NumElts = SVT.getVectorNumElements();
17874   // FIXME: This collection of masks seems suspect.
17875   if (NumElts == 2)
17876     return true;
17877   if (NumElts == 4 && SVT.is128BitVector()) {
17878     return (isMOVLMask(Mask, SVT)  ||
17879             isCommutedMOVLMask(Mask, SVT, true) ||
17880             isSHUFPMask(Mask, SVT) ||
17881             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17882   }
17883   return false;
17884 }
17885
17886 //===----------------------------------------------------------------------===//
17887 //                           X86 Scheduler Hooks
17888 //===----------------------------------------------------------------------===//
17889
17890 /// Utility function to emit xbegin specifying the start of an RTM region.
17891 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17892                                      const TargetInstrInfo *TII) {
17893   DebugLoc DL = MI->getDebugLoc();
17894
17895   const BasicBlock *BB = MBB->getBasicBlock();
17896   MachineFunction::iterator I = MBB;
17897   ++I;
17898
17899   // For the v = xbegin(), we generate
17900   //
17901   // thisMBB:
17902   //  xbegin sinkMBB
17903   //
17904   // mainMBB:
17905   //  eax = -1
17906   //
17907   // sinkMBB:
17908   //  v = eax
17909
17910   MachineBasicBlock *thisMBB = MBB;
17911   MachineFunction *MF = MBB->getParent();
17912   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17913   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17914   MF->insert(I, mainMBB);
17915   MF->insert(I, sinkMBB);
17916
17917   // Transfer the remainder of BB and its successor edges to sinkMBB.
17918   sinkMBB->splice(sinkMBB->begin(), MBB,
17919                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17920   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17921
17922   // thisMBB:
17923   //  xbegin sinkMBB
17924   //  # fallthrough to mainMBB
17925   //  # abortion to sinkMBB
17926   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17927   thisMBB->addSuccessor(mainMBB);
17928   thisMBB->addSuccessor(sinkMBB);
17929
17930   // mainMBB:
17931   //  EAX = -1
17932   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17933   mainMBB->addSuccessor(sinkMBB);
17934
17935   // sinkMBB:
17936   // EAX is live into the sinkMBB
17937   sinkMBB->addLiveIn(X86::EAX);
17938   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17939           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17940     .addReg(X86::EAX);
17941
17942   MI->eraseFromParent();
17943   return sinkMBB;
17944 }
17945
17946 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17947 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17948 // in the .td file.
17949 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17950                                        const TargetInstrInfo *TII) {
17951   unsigned Opc;
17952   switch (MI->getOpcode()) {
17953   default: llvm_unreachable("illegal opcode!");
17954   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17955   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17956   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17957   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17958   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17959   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17960   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17961   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17962   }
17963
17964   DebugLoc dl = MI->getDebugLoc();
17965   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17966
17967   unsigned NumArgs = MI->getNumOperands();
17968   for (unsigned i = 1; i < NumArgs; ++i) {
17969     MachineOperand &Op = MI->getOperand(i);
17970     if (!(Op.isReg() && Op.isImplicit()))
17971       MIB.addOperand(Op);
17972   }
17973   if (MI->hasOneMemOperand())
17974     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17975
17976   BuildMI(*BB, MI, dl,
17977     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17978     .addReg(X86::XMM0);
17979
17980   MI->eraseFromParent();
17981   return BB;
17982 }
17983
17984 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17985 // defs in an instruction pattern
17986 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17987                                        const TargetInstrInfo *TII) {
17988   unsigned Opc;
17989   switch (MI->getOpcode()) {
17990   default: llvm_unreachable("illegal opcode!");
17991   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17992   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17993   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17994   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17995   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17996   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17997   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17998   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17999   }
18000
18001   DebugLoc dl = MI->getDebugLoc();
18002   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18003
18004   unsigned NumArgs = MI->getNumOperands(); // remove the results
18005   for (unsigned i = 1; i < NumArgs; ++i) {
18006     MachineOperand &Op = MI->getOperand(i);
18007     if (!(Op.isReg() && Op.isImplicit()))
18008       MIB.addOperand(Op);
18009   }
18010   if (MI->hasOneMemOperand())
18011     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18012
18013   BuildMI(*BB, MI, dl,
18014     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18015     .addReg(X86::ECX);
18016
18017   MI->eraseFromParent();
18018   return BB;
18019 }
18020
18021 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18022                                        const TargetInstrInfo *TII,
18023                                        const X86Subtarget* Subtarget) {
18024   DebugLoc dl = MI->getDebugLoc();
18025
18026   // Address into RAX/EAX, other two args into ECX, EDX.
18027   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18028   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18029   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18030   for (int i = 0; i < X86::AddrNumOperands; ++i)
18031     MIB.addOperand(MI->getOperand(i));
18032
18033   unsigned ValOps = X86::AddrNumOperands;
18034   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18035     .addReg(MI->getOperand(ValOps).getReg());
18036   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18037     .addReg(MI->getOperand(ValOps+1).getReg());
18038
18039   // The instruction doesn't actually take any operands though.
18040   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18041
18042   MI->eraseFromParent(); // The pseudo is gone now.
18043   return BB;
18044 }
18045
18046 MachineBasicBlock *
18047 X86TargetLowering::EmitVAARG64WithCustomInserter(
18048                    MachineInstr *MI,
18049                    MachineBasicBlock *MBB) const {
18050   // Emit va_arg instruction on X86-64.
18051
18052   // Operands to this pseudo-instruction:
18053   // 0  ) Output        : destination address (reg)
18054   // 1-5) Input         : va_list address (addr, i64mem)
18055   // 6  ) ArgSize       : Size (in bytes) of vararg type
18056   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18057   // 8  ) Align         : Alignment of type
18058   // 9  ) EFLAGS (implicit-def)
18059
18060   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18061   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
18062
18063   unsigned DestReg = MI->getOperand(0).getReg();
18064   MachineOperand &Base = MI->getOperand(1);
18065   MachineOperand &Scale = MI->getOperand(2);
18066   MachineOperand &Index = MI->getOperand(3);
18067   MachineOperand &Disp = MI->getOperand(4);
18068   MachineOperand &Segment = MI->getOperand(5);
18069   unsigned ArgSize = MI->getOperand(6).getImm();
18070   unsigned ArgMode = MI->getOperand(7).getImm();
18071   unsigned Align = MI->getOperand(8).getImm();
18072
18073   // Memory Reference
18074   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18075   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18076   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18077
18078   // Machine Information
18079   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18080   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18081   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18082   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18083   DebugLoc DL = MI->getDebugLoc();
18084
18085   // struct va_list {
18086   //   i32   gp_offset
18087   //   i32   fp_offset
18088   //   i64   overflow_area (address)
18089   //   i64   reg_save_area (address)
18090   // }
18091   // sizeof(va_list) = 24
18092   // alignment(va_list) = 8
18093
18094   unsigned TotalNumIntRegs = 6;
18095   unsigned TotalNumXMMRegs = 8;
18096   bool UseGPOffset = (ArgMode == 1);
18097   bool UseFPOffset = (ArgMode == 2);
18098   unsigned MaxOffset = TotalNumIntRegs * 8 +
18099                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18100
18101   /* Align ArgSize to a multiple of 8 */
18102   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18103   bool NeedsAlign = (Align > 8);
18104
18105   MachineBasicBlock *thisMBB = MBB;
18106   MachineBasicBlock *overflowMBB;
18107   MachineBasicBlock *offsetMBB;
18108   MachineBasicBlock *endMBB;
18109
18110   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18111   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18112   unsigned OffsetReg = 0;
18113
18114   if (!UseGPOffset && !UseFPOffset) {
18115     // If we only pull from the overflow region, we don't create a branch.
18116     // We don't need to alter control flow.
18117     OffsetDestReg = 0; // unused
18118     OverflowDestReg = DestReg;
18119
18120     offsetMBB = nullptr;
18121     overflowMBB = thisMBB;
18122     endMBB = thisMBB;
18123   } else {
18124     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18125     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18126     // If not, pull from overflow_area. (branch to overflowMBB)
18127     //
18128     //       thisMBB
18129     //         |     .
18130     //         |        .
18131     //     offsetMBB   overflowMBB
18132     //         |        .
18133     //         |     .
18134     //        endMBB
18135
18136     // Registers for the PHI in endMBB
18137     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18138     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18139
18140     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18141     MachineFunction *MF = MBB->getParent();
18142     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18143     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18144     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18145
18146     MachineFunction::iterator MBBIter = MBB;
18147     ++MBBIter;
18148
18149     // Insert the new basic blocks
18150     MF->insert(MBBIter, offsetMBB);
18151     MF->insert(MBBIter, overflowMBB);
18152     MF->insert(MBBIter, endMBB);
18153
18154     // Transfer the remainder of MBB and its successor edges to endMBB.
18155     endMBB->splice(endMBB->begin(), thisMBB,
18156                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18157     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18158
18159     // Make offsetMBB and overflowMBB successors of thisMBB
18160     thisMBB->addSuccessor(offsetMBB);
18161     thisMBB->addSuccessor(overflowMBB);
18162
18163     // endMBB is a successor of both offsetMBB and overflowMBB
18164     offsetMBB->addSuccessor(endMBB);
18165     overflowMBB->addSuccessor(endMBB);
18166
18167     // Load the offset value into a register
18168     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18169     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18170       .addOperand(Base)
18171       .addOperand(Scale)
18172       .addOperand(Index)
18173       .addDisp(Disp, UseFPOffset ? 4 : 0)
18174       .addOperand(Segment)
18175       .setMemRefs(MMOBegin, MMOEnd);
18176
18177     // Check if there is enough room left to pull this argument.
18178     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18179       .addReg(OffsetReg)
18180       .addImm(MaxOffset + 8 - ArgSizeA8);
18181
18182     // Branch to "overflowMBB" if offset >= max
18183     // Fall through to "offsetMBB" otherwise
18184     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18185       .addMBB(overflowMBB);
18186   }
18187
18188   // In offsetMBB, emit code to use the reg_save_area.
18189   if (offsetMBB) {
18190     assert(OffsetReg != 0);
18191
18192     // Read the reg_save_area address.
18193     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18194     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18195       .addOperand(Base)
18196       .addOperand(Scale)
18197       .addOperand(Index)
18198       .addDisp(Disp, 16)
18199       .addOperand(Segment)
18200       .setMemRefs(MMOBegin, MMOEnd);
18201
18202     // Zero-extend the offset
18203     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18204       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18205         .addImm(0)
18206         .addReg(OffsetReg)
18207         .addImm(X86::sub_32bit);
18208
18209     // Add the offset to the reg_save_area to get the final address.
18210     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18211       .addReg(OffsetReg64)
18212       .addReg(RegSaveReg);
18213
18214     // Compute the offset for the next argument
18215     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18216     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18217       .addReg(OffsetReg)
18218       .addImm(UseFPOffset ? 16 : 8);
18219
18220     // Store it back into the va_list.
18221     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18222       .addOperand(Base)
18223       .addOperand(Scale)
18224       .addOperand(Index)
18225       .addDisp(Disp, UseFPOffset ? 4 : 0)
18226       .addOperand(Segment)
18227       .addReg(NextOffsetReg)
18228       .setMemRefs(MMOBegin, MMOEnd);
18229
18230     // Jump to endMBB
18231     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
18232       .addMBB(endMBB);
18233   }
18234
18235   //
18236   // Emit code to use overflow area
18237   //
18238
18239   // Load the overflow_area address into a register.
18240   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18241   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18242     .addOperand(Base)
18243     .addOperand(Scale)
18244     .addOperand(Index)
18245     .addDisp(Disp, 8)
18246     .addOperand(Segment)
18247     .setMemRefs(MMOBegin, MMOEnd);
18248
18249   // If we need to align it, do so. Otherwise, just copy the address
18250   // to OverflowDestReg.
18251   if (NeedsAlign) {
18252     // Align the overflow address
18253     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18254     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18255
18256     // aligned_addr = (addr + (align-1)) & ~(align-1)
18257     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18258       .addReg(OverflowAddrReg)
18259       .addImm(Align-1);
18260
18261     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18262       .addReg(TmpReg)
18263       .addImm(~(uint64_t)(Align-1));
18264   } else {
18265     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18266       .addReg(OverflowAddrReg);
18267   }
18268
18269   // Compute the next overflow address after this argument.
18270   // (the overflow address should be kept 8-byte aligned)
18271   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18272   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18273     .addReg(OverflowDestReg)
18274     .addImm(ArgSizeA8);
18275
18276   // Store the new overflow address.
18277   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18278     .addOperand(Base)
18279     .addOperand(Scale)
18280     .addOperand(Index)
18281     .addDisp(Disp, 8)
18282     .addOperand(Segment)
18283     .addReg(NextAddrReg)
18284     .setMemRefs(MMOBegin, MMOEnd);
18285
18286   // If we branched, emit the PHI to the front of endMBB.
18287   if (offsetMBB) {
18288     BuildMI(*endMBB, endMBB->begin(), DL,
18289             TII->get(X86::PHI), DestReg)
18290       .addReg(OffsetDestReg).addMBB(offsetMBB)
18291       .addReg(OverflowDestReg).addMBB(overflowMBB);
18292   }
18293
18294   // Erase the pseudo instruction
18295   MI->eraseFromParent();
18296
18297   return endMBB;
18298 }
18299
18300 MachineBasicBlock *
18301 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18302                                                  MachineInstr *MI,
18303                                                  MachineBasicBlock *MBB) const {
18304   // Emit code to save XMM registers to the stack. The ABI says that the
18305   // number of registers to save is given in %al, so it's theoretically
18306   // possible to do an indirect jump trick to avoid saving all of them,
18307   // however this code takes a simpler approach and just executes all
18308   // of the stores if %al is non-zero. It's less code, and it's probably
18309   // easier on the hardware branch predictor, and stores aren't all that
18310   // expensive anyway.
18311
18312   // Create the new basic blocks. One block contains all the XMM stores,
18313   // and one block is the final destination regardless of whether any
18314   // stores were performed.
18315   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18316   MachineFunction *F = MBB->getParent();
18317   MachineFunction::iterator MBBIter = MBB;
18318   ++MBBIter;
18319   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18320   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18321   F->insert(MBBIter, XMMSaveMBB);
18322   F->insert(MBBIter, EndMBB);
18323
18324   // Transfer the remainder of MBB and its successor edges to EndMBB.
18325   EndMBB->splice(EndMBB->begin(), MBB,
18326                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18327   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18328
18329   // The original block will now fall through to the XMM save block.
18330   MBB->addSuccessor(XMMSaveMBB);
18331   // The XMMSaveMBB will fall through to the end block.
18332   XMMSaveMBB->addSuccessor(EndMBB);
18333
18334   // Now add the instructions.
18335   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18336   DebugLoc DL = MI->getDebugLoc();
18337
18338   unsigned CountReg = MI->getOperand(0).getReg();
18339   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18340   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18341
18342   if (!Subtarget->isTargetWin64()) {
18343     // If %al is 0, branch around the XMM save block.
18344     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18345     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18346     MBB->addSuccessor(EndMBB);
18347   }
18348
18349   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18350   // that was just emitted, but clearly shouldn't be "saved".
18351   assert((MI->getNumOperands() <= 3 ||
18352           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18353           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18354          && "Expected last argument to be EFLAGS");
18355   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18356   // In the XMM save block, save all the XMM argument registers.
18357   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18358     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18359     MachineMemOperand *MMO =
18360       F->getMachineMemOperand(
18361           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18362         MachineMemOperand::MOStore,
18363         /*Size=*/16, /*Align=*/16);
18364     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18365       .addFrameIndex(RegSaveFrameIndex)
18366       .addImm(/*Scale=*/1)
18367       .addReg(/*IndexReg=*/0)
18368       .addImm(/*Disp=*/Offset)
18369       .addReg(/*Segment=*/0)
18370       .addReg(MI->getOperand(i).getReg())
18371       .addMemOperand(MMO);
18372   }
18373
18374   MI->eraseFromParent();   // The pseudo instruction is gone now.
18375
18376   return EndMBB;
18377 }
18378
18379 // The EFLAGS operand of SelectItr might be missing a kill marker
18380 // because there were multiple uses of EFLAGS, and ISel didn't know
18381 // which to mark. Figure out whether SelectItr should have had a
18382 // kill marker, and set it if it should. Returns the correct kill
18383 // marker value.
18384 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18385                                      MachineBasicBlock* BB,
18386                                      const TargetRegisterInfo* TRI) {
18387   // Scan forward through BB for a use/def of EFLAGS.
18388   MachineBasicBlock::iterator miI(std::next(SelectItr));
18389   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18390     const MachineInstr& mi = *miI;
18391     if (mi.readsRegister(X86::EFLAGS))
18392       return false;
18393     if (mi.definesRegister(X86::EFLAGS))
18394       break; // Should have kill-flag - update below.
18395   }
18396
18397   // If we hit the end of the block, check whether EFLAGS is live into a
18398   // successor.
18399   if (miI == BB->end()) {
18400     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18401                                           sEnd = BB->succ_end();
18402          sItr != sEnd; ++sItr) {
18403       MachineBasicBlock* succ = *sItr;
18404       if (succ->isLiveIn(X86::EFLAGS))
18405         return false;
18406     }
18407   }
18408
18409   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18410   // out. SelectMI should have a kill flag on EFLAGS.
18411   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18412   return true;
18413 }
18414
18415 MachineBasicBlock *
18416 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18417                                      MachineBasicBlock *BB) const {
18418   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18419   DebugLoc DL = MI->getDebugLoc();
18420
18421   // To "insert" a SELECT_CC instruction, we actually have to insert the
18422   // diamond control-flow pattern.  The incoming instruction knows the
18423   // destination vreg to set, the condition code register to branch on, the
18424   // true/false values to select between, and a branch opcode to use.
18425   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18426   MachineFunction::iterator It = BB;
18427   ++It;
18428
18429   //  thisMBB:
18430   //  ...
18431   //   TrueVal = ...
18432   //   cmpTY ccX, r1, r2
18433   //   bCC copy1MBB
18434   //   fallthrough --> copy0MBB
18435   MachineBasicBlock *thisMBB = BB;
18436   MachineFunction *F = BB->getParent();
18437   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18438   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18439   F->insert(It, copy0MBB);
18440   F->insert(It, sinkMBB);
18441
18442   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18443   // live into the sink and copy blocks.
18444   const TargetRegisterInfo *TRI =
18445       BB->getParent()->getSubtarget().getRegisterInfo();
18446   if (!MI->killsRegister(X86::EFLAGS) &&
18447       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18448     copy0MBB->addLiveIn(X86::EFLAGS);
18449     sinkMBB->addLiveIn(X86::EFLAGS);
18450   }
18451
18452   // Transfer the remainder of BB and its successor edges to sinkMBB.
18453   sinkMBB->splice(sinkMBB->begin(), BB,
18454                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18455   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18456
18457   // Add the true and fallthrough blocks as its successors.
18458   BB->addSuccessor(copy0MBB);
18459   BB->addSuccessor(sinkMBB);
18460
18461   // Create the conditional branch instruction.
18462   unsigned Opc =
18463     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18464   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18465
18466   //  copy0MBB:
18467   //   %FalseValue = ...
18468   //   # fallthrough to sinkMBB
18469   copy0MBB->addSuccessor(sinkMBB);
18470
18471   //  sinkMBB:
18472   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18473   //  ...
18474   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18475           TII->get(X86::PHI), MI->getOperand(0).getReg())
18476     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18477     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18478
18479   MI->eraseFromParent();   // The pseudo instruction is gone now.
18480   return sinkMBB;
18481 }
18482
18483 MachineBasicBlock *
18484 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18485                                         bool Is64Bit) const {
18486   MachineFunction *MF = BB->getParent();
18487   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18488   DebugLoc DL = MI->getDebugLoc();
18489   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18490
18491   assert(MF->shouldSplitStack());
18492
18493   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18494   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18495
18496   // BB:
18497   //  ... [Till the alloca]
18498   // If stacklet is not large enough, jump to mallocMBB
18499   //
18500   // bumpMBB:
18501   //  Allocate by subtracting from RSP
18502   //  Jump to continueMBB
18503   //
18504   // mallocMBB:
18505   //  Allocate by call to runtime
18506   //
18507   // continueMBB:
18508   //  ...
18509   //  [rest of original BB]
18510   //
18511
18512   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18513   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18514   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18515
18516   MachineRegisterInfo &MRI = MF->getRegInfo();
18517   const TargetRegisterClass *AddrRegClass =
18518     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18519
18520   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18521     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18522     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18523     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18524     sizeVReg = MI->getOperand(1).getReg(),
18525     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18526
18527   MachineFunction::iterator MBBIter = BB;
18528   ++MBBIter;
18529
18530   MF->insert(MBBIter, bumpMBB);
18531   MF->insert(MBBIter, mallocMBB);
18532   MF->insert(MBBIter, continueMBB);
18533
18534   continueMBB->splice(continueMBB->begin(), BB,
18535                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18536   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18537
18538   // Add code to the main basic block to check if the stack limit has been hit,
18539   // and if so, jump to mallocMBB otherwise to bumpMBB.
18540   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18541   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18542     .addReg(tmpSPVReg).addReg(sizeVReg);
18543   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18544     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18545     .addReg(SPLimitVReg);
18546   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18547
18548   // bumpMBB simply decreases the stack pointer, since we know the current
18549   // stacklet has enough space.
18550   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18551     .addReg(SPLimitVReg);
18552   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18553     .addReg(SPLimitVReg);
18554   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18555
18556   // Calls into a routine in libgcc to allocate more space from the heap.
18557   const uint32_t *RegMask = MF->getTarget()
18558                                 .getSubtargetImpl()
18559                                 ->getRegisterInfo()
18560                                 ->getCallPreservedMask(CallingConv::C);
18561   if (Is64Bit) {
18562     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18563       .addReg(sizeVReg);
18564     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18565       .addExternalSymbol("__morestack_allocate_stack_space")
18566       .addRegMask(RegMask)
18567       .addReg(X86::RDI, RegState::Implicit)
18568       .addReg(X86::RAX, RegState::ImplicitDefine);
18569   } else {
18570     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18571       .addImm(12);
18572     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18573     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18574       .addExternalSymbol("__morestack_allocate_stack_space")
18575       .addRegMask(RegMask)
18576       .addReg(X86::EAX, RegState::ImplicitDefine);
18577   }
18578
18579   if (!Is64Bit)
18580     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18581       .addImm(16);
18582
18583   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18584     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18585   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18586
18587   // Set up the CFG correctly.
18588   BB->addSuccessor(bumpMBB);
18589   BB->addSuccessor(mallocMBB);
18590   mallocMBB->addSuccessor(continueMBB);
18591   bumpMBB->addSuccessor(continueMBB);
18592
18593   // Take care of the PHI nodes.
18594   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18595           MI->getOperand(0).getReg())
18596     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18597     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18598
18599   // Delete the original pseudo instruction.
18600   MI->eraseFromParent();
18601
18602   // And we're done.
18603   return continueMBB;
18604 }
18605
18606 MachineBasicBlock *
18607 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18608                                         MachineBasicBlock *BB) const {
18609   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18610   DebugLoc DL = MI->getDebugLoc();
18611
18612   assert(!Subtarget->isTargetMacho());
18613
18614   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18615   // non-trivial part is impdef of ESP.
18616
18617   if (Subtarget->isTargetWin64()) {
18618     if (Subtarget->isTargetCygMing()) {
18619       // ___chkstk(Mingw64):
18620       // Clobbers R10, R11, RAX and EFLAGS.
18621       // Updates RSP.
18622       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18623         .addExternalSymbol("___chkstk")
18624         .addReg(X86::RAX, RegState::Implicit)
18625         .addReg(X86::RSP, RegState::Implicit)
18626         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18627         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18628         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18629     } else {
18630       // __chkstk(MSVCRT): does not update stack pointer.
18631       // Clobbers R10, R11 and EFLAGS.
18632       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18633         .addExternalSymbol("__chkstk")
18634         .addReg(X86::RAX, RegState::Implicit)
18635         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18636       // RAX has the offset to be subtracted from RSP.
18637       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18638         .addReg(X86::RSP)
18639         .addReg(X86::RAX);
18640     }
18641   } else {
18642     const char *StackProbeSymbol =
18643       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18644
18645     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18646       .addExternalSymbol(StackProbeSymbol)
18647       .addReg(X86::EAX, RegState::Implicit)
18648       .addReg(X86::ESP, RegState::Implicit)
18649       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18650       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18651       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18652   }
18653
18654   MI->eraseFromParent();   // The pseudo instruction is gone now.
18655   return BB;
18656 }
18657
18658 MachineBasicBlock *
18659 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18660                                       MachineBasicBlock *BB) const {
18661   // This is pretty easy.  We're taking the value that we received from
18662   // our load from the relocation, sticking it in either RDI (x86-64)
18663   // or EAX and doing an indirect call.  The return value will then
18664   // be in the normal return register.
18665   MachineFunction *F = BB->getParent();
18666   const X86InstrInfo *TII =
18667       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18668   DebugLoc DL = MI->getDebugLoc();
18669
18670   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18671   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18672
18673   // Get a register mask for the lowered call.
18674   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18675   // proper register mask.
18676   const uint32_t *RegMask = F->getTarget()
18677                                 .getSubtargetImpl()
18678                                 ->getRegisterInfo()
18679                                 ->getCallPreservedMask(CallingConv::C);
18680   if (Subtarget->is64Bit()) {
18681     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18682                                       TII->get(X86::MOV64rm), X86::RDI)
18683     .addReg(X86::RIP)
18684     .addImm(0).addReg(0)
18685     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18686                       MI->getOperand(3).getTargetFlags())
18687     .addReg(0);
18688     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18689     addDirectMem(MIB, X86::RDI);
18690     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18691   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18692     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18693                                       TII->get(X86::MOV32rm), X86::EAX)
18694     .addReg(0)
18695     .addImm(0).addReg(0)
18696     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18697                       MI->getOperand(3).getTargetFlags())
18698     .addReg(0);
18699     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18700     addDirectMem(MIB, X86::EAX);
18701     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18702   } else {
18703     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18704                                       TII->get(X86::MOV32rm), X86::EAX)
18705     .addReg(TII->getGlobalBaseReg(F))
18706     .addImm(0).addReg(0)
18707     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18708                       MI->getOperand(3).getTargetFlags())
18709     .addReg(0);
18710     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18711     addDirectMem(MIB, X86::EAX);
18712     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18713   }
18714
18715   MI->eraseFromParent(); // The pseudo instruction is gone now.
18716   return BB;
18717 }
18718
18719 MachineBasicBlock *
18720 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18721                                     MachineBasicBlock *MBB) const {
18722   DebugLoc DL = MI->getDebugLoc();
18723   MachineFunction *MF = MBB->getParent();
18724   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18725   MachineRegisterInfo &MRI = MF->getRegInfo();
18726
18727   const BasicBlock *BB = MBB->getBasicBlock();
18728   MachineFunction::iterator I = MBB;
18729   ++I;
18730
18731   // Memory Reference
18732   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18733   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18734
18735   unsigned DstReg;
18736   unsigned MemOpndSlot = 0;
18737
18738   unsigned CurOp = 0;
18739
18740   DstReg = MI->getOperand(CurOp++).getReg();
18741   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18742   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18743   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18744   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18745
18746   MemOpndSlot = CurOp;
18747
18748   MVT PVT = getPointerTy();
18749   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18750          "Invalid Pointer Size!");
18751
18752   // For v = setjmp(buf), we generate
18753   //
18754   // thisMBB:
18755   //  buf[LabelOffset] = restoreMBB
18756   //  SjLjSetup restoreMBB
18757   //
18758   // mainMBB:
18759   //  v_main = 0
18760   //
18761   // sinkMBB:
18762   //  v = phi(main, restore)
18763   //
18764   // restoreMBB:
18765   //  v_restore = 1
18766
18767   MachineBasicBlock *thisMBB = MBB;
18768   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18769   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18770   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18771   MF->insert(I, mainMBB);
18772   MF->insert(I, sinkMBB);
18773   MF->push_back(restoreMBB);
18774
18775   MachineInstrBuilder MIB;
18776
18777   // Transfer the remainder of BB and its successor edges to sinkMBB.
18778   sinkMBB->splice(sinkMBB->begin(), MBB,
18779                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18780   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18781
18782   // thisMBB:
18783   unsigned PtrStoreOpc = 0;
18784   unsigned LabelReg = 0;
18785   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18786   Reloc::Model RM = MF->getTarget().getRelocationModel();
18787   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18788                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18789
18790   // Prepare IP either in reg or imm.
18791   if (!UseImmLabel) {
18792     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18793     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18794     LabelReg = MRI.createVirtualRegister(PtrRC);
18795     if (Subtarget->is64Bit()) {
18796       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18797               .addReg(X86::RIP)
18798               .addImm(0)
18799               .addReg(0)
18800               .addMBB(restoreMBB)
18801               .addReg(0);
18802     } else {
18803       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18804       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18805               .addReg(XII->getGlobalBaseReg(MF))
18806               .addImm(0)
18807               .addReg(0)
18808               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18809               .addReg(0);
18810     }
18811   } else
18812     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18813   // Store IP
18814   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18815   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18816     if (i == X86::AddrDisp)
18817       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18818     else
18819       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18820   }
18821   if (!UseImmLabel)
18822     MIB.addReg(LabelReg);
18823   else
18824     MIB.addMBB(restoreMBB);
18825   MIB.setMemRefs(MMOBegin, MMOEnd);
18826   // Setup
18827   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18828           .addMBB(restoreMBB);
18829
18830   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18831       MF->getSubtarget().getRegisterInfo());
18832   MIB.addRegMask(RegInfo->getNoPreservedMask());
18833   thisMBB->addSuccessor(mainMBB);
18834   thisMBB->addSuccessor(restoreMBB);
18835
18836   // mainMBB:
18837   //  EAX = 0
18838   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18839   mainMBB->addSuccessor(sinkMBB);
18840
18841   // sinkMBB:
18842   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18843           TII->get(X86::PHI), DstReg)
18844     .addReg(mainDstReg).addMBB(mainMBB)
18845     .addReg(restoreDstReg).addMBB(restoreMBB);
18846
18847   // restoreMBB:
18848   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18849   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18850   restoreMBB->addSuccessor(sinkMBB);
18851
18852   MI->eraseFromParent();
18853   return sinkMBB;
18854 }
18855
18856 MachineBasicBlock *
18857 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18858                                      MachineBasicBlock *MBB) const {
18859   DebugLoc DL = MI->getDebugLoc();
18860   MachineFunction *MF = MBB->getParent();
18861   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18862   MachineRegisterInfo &MRI = MF->getRegInfo();
18863
18864   // Memory Reference
18865   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18866   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18867
18868   MVT PVT = getPointerTy();
18869   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18870          "Invalid Pointer Size!");
18871
18872   const TargetRegisterClass *RC =
18873     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18874   unsigned Tmp = MRI.createVirtualRegister(RC);
18875   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18876   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18877       MF->getSubtarget().getRegisterInfo());
18878   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18879   unsigned SP = RegInfo->getStackRegister();
18880
18881   MachineInstrBuilder MIB;
18882
18883   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18884   const int64_t SPOffset = 2 * PVT.getStoreSize();
18885
18886   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18887   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18888
18889   // Reload FP
18890   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18891   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18892     MIB.addOperand(MI->getOperand(i));
18893   MIB.setMemRefs(MMOBegin, MMOEnd);
18894   // Reload IP
18895   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18896   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18897     if (i == X86::AddrDisp)
18898       MIB.addDisp(MI->getOperand(i), LabelOffset);
18899     else
18900       MIB.addOperand(MI->getOperand(i));
18901   }
18902   MIB.setMemRefs(MMOBegin, MMOEnd);
18903   // Reload SP
18904   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18905   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18906     if (i == X86::AddrDisp)
18907       MIB.addDisp(MI->getOperand(i), SPOffset);
18908     else
18909       MIB.addOperand(MI->getOperand(i));
18910   }
18911   MIB.setMemRefs(MMOBegin, MMOEnd);
18912   // Jump
18913   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18914
18915   MI->eraseFromParent();
18916   return MBB;
18917 }
18918
18919 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18920 // accumulator loops. Writing back to the accumulator allows the coalescer
18921 // to remove extra copies in the loop.   
18922 MachineBasicBlock *
18923 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18924                                  MachineBasicBlock *MBB) const {
18925   MachineOperand &AddendOp = MI->getOperand(3);
18926
18927   // Bail out early if the addend isn't a register - we can't switch these.
18928   if (!AddendOp.isReg())
18929     return MBB;
18930
18931   MachineFunction &MF = *MBB->getParent();
18932   MachineRegisterInfo &MRI = MF.getRegInfo();
18933
18934   // Check whether the addend is defined by a PHI:
18935   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18936   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18937   if (!AddendDef.isPHI())
18938     return MBB;
18939
18940   // Look for the following pattern:
18941   // loop:
18942   //   %addend = phi [%entry, 0], [%loop, %result]
18943   //   ...
18944   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18945
18946   // Replace with:
18947   //   loop:
18948   //   %addend = phi [%entry, 0], [%loop, %result]
18949   //   ...
18950   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18951
18952   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18953     assert(AddendDef.getOperand(i).isReg());
18954     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18955     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18956     if (&PHISrcInst == MI) {
18957       // Found a matching instruction.
18958       unsigned NewFMAOpc = 0;
18959       switch (MI->getOpcode()) {
18960         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18961         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18962         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18963         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18964         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18965         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18966         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18967         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18968         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18969         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18970         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18971         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18972         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18973         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18974         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18975         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18976         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18977         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18978         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18979         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18980         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18981         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18982         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18983         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18984         default: llvm_unreachable("Unrecognized FMA variant.");
18985       }
18986
18987       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18988       MachineInstrBuilder MIB =
18989         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18990         .addOperand(MI->getOperand(0))
18991         .addOperand(MI->getOperand(3))
18992         .addOperand(MI->getOperand(2))
18993         .addOperand(MI->getOperand(1));
18994       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18995       MI->eraseFromParent();
18996     }
18997   }
18998
18999   return MBB;
19000 }
19001
19002 MachineBasicBlock *
19003 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19004                                                MachineBasicBlock *BB) const {
19005   switch (MI->getOpcode()) {
19006   default: llvm_unreachable("Unexpected instr type to insert");
19007   case X86::TAILJMPd64:
19008   case X86::TAILJMPr64:
19009   case X86::TAILJMPm64:
19010     llvm_unreachable("TAILJMP64 would not be touched here.");
19011   case X86::TCRETURNdi64:
19012   case X86::TCRETURNri64:
19013   case X86::TCRETURNmi64:
19014     return BB;
19015   case X86::WIN_ALLOCA:
19016     return EmitLoweredWinAlloca(MI, BB);
19017   case X86::SEG_ALLOCA_32:
19018     return EmitLoweredSegAlloca(MI, BB, false);
19019   case X86::SEG_ALLOCA_64:
19020     return EmitLoweredSegAlloca(MI, BB, true);
19021   case X86::TLSCall_32:
19022   case X86::TLSCall_64:
19023     return EmitLoweredTLSCall(MI, BB);
19024   case X86::CMOV_GR8:
19025   case X86::CMOV_FR32:
19026   case X86::CMOV_FR64:
19027   case X86::CMOV_V4F32:
19028   case X86::CMOV_V2F64:
19029   case X86::CMOV_V2I64:
19030   case X86::CMOV_V8F32:
19031   case X86::CMOV_V4F64:
19032   case X86::CMOV_V4I64:
19033   case X86::CMOV_V16F32:
19034   case X86::CMOV_V8F64:
19035   case X86::CMOV_V8I64:
19036   case X86::CMOV_GR16:
19037   case X86::CMOV_GR32:
19038   case X86::CMOV_RFP32:
19039   case X86::CMOV_RFP64:
19040   case X86::CMOV_RFP80:
19041     return EmitLoweredSelect(MI, BB);
19042
19043   case X86::FP32_TO_INT16_IN_MEM:
19044   case X86::FP32_TO_INT32_IN_MEM:
19045   case X86::FP32_TO_INT64_IN_MEM:
19046   case X86::FP64_TO_INT16_IN_MEM:
19047   case X86::FP64_TO_INT32_IN_MEM:
19048   case X86::FP64_TO_INT64_IN_MEM:
19049   case X86::FP80_TO_INT16_IN_MEM:
19050   case X86::FP80_TO_INT32_IN_MEM:
19051   case X86::FP80_TO_INT64_IN_MEM: {
19052     MachineFunction *F = BB->getParent();
19053     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
19054     DebugLoc DL = MI->getDebugLoc();
19055
19056     // Change the floating point control register to use "round towards zero"
19057     // mode when truncating to an integer value.
19058     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19059     addFrameReference(BuildMI(*BB, MI, DL,
19060                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19061
19062     // Load the old value of the high byte of the control word...
19063     unsigned OldCW =
19064       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19065     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19066                       CWFrameIdx);
19067
19068     // Set the high part to be round to zero...
19069     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19070       .addImm(0xC7F);
19071
19072     // Reload the modified control word now...
19073     addFrameReference(BuildMI(*BB, MI, DL,
19074                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19075
19076     // Restore the memory image of control word to original value
19077     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19078       .addReg(OldCW);
19079
19080     // Get the X86 opcode to use.
19081     unsigned Opc;
19082     switch (MI->getOpcode()) {
19083     default: llvm_unreachable("illegal opcode!");
19084     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19085     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19086     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19087     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19088     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19089     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19090     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19091     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19092     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19093     }
19094
19095     X86AddressMode AM;
19096     MachineOperand &Op = MI->getOperand(0);
19097     if (Op.isReg()) {
19098       AM.BaseType = X86AddressMode::RegBase;
19099       AM.Base.Reg = Op.getReg();
19100     } else {
19101       AM.BaseType = X86AddressMode::FrameIndexBase;
19102       AM.Base.FrameIndex = Op.getIndex();
19103     }
19104     Op = MI->getOperand(1);
19105     if (Op.isImm())
19106       AM.Scale = Op.getImm();
19107     Op = MI->getOperand(2);
19108     if (Op.isImm())
19109       AM.IndexReg = Op.getImm();
19110     Op = MI->getOperand(3);
19111     if (Op.isGlobal()) {
19112       AM.GV = Op.getGlobal();
19113     } else {
19114       AM.Disp = Op.getImm();
19115     }
19116     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19117                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19118
19119     // Reload the original control word now.
19120     addFrameReference(BuildMI(*BB, MI, DL,
19121                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19122
19123     MI->eraseFromParent();   // The pseudo instruction is gone now.
19124     return BB;
19125   }
19126     // String/text processing lowering.
19127   case X86::PCMPISTRM128REG:
19128   case X86::VPCMPISTRM128REG:
19129   case X86::PCMPISTRM128MEM:
19130   case X86::VPCMPISTRM128MEM:
19131   case X86::PCMPESTRM128REG:
19132   case X86::VPCMPESTRM128REG:
19133   case X86::PCMPESTRM128MEM:
19134   case X86::VPCMPESTRM128MEM:
19135     assert(Subtarget->hasSSE42() &&
19136            "Target must have SSE4.2 or AVX features enabled");
19137     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19138
19139   // String/text processing lowering.
19140   case X86::PCMPISTRIREG:
19141   case X86::VPCMPISTRIREG:
19142   case X86::PCMPISTRIMEM:
19143   case X86::VPCMPISTRIMEM:
19144   case X86::PCMPESTRIREG:
19145   case X86::VPCMPESTRIREG:
19146   case X86::PCMPESTRIMEM:
19147   case X86::VPCMPESTRIMEM:
19148     assert(Subtarget->hasSSE42() &&
19149            "Target must have SSE4.2 or AVX features enabled");
19150     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19151
19152   // Thread synchronization.
19153   case X86::MONITOR:
19154     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
19155                        Subtarget);
19156
19157   // xbegin
19158   case X86::XBEGIN:
19159     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19160
19161   case X86::VASTART_SAVE_XMM_REGS:
19162     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19163
19164   case X86::VAARG_64:
19165     return EmitVAARG64WithCustomInserter(MI, BB);
19166
19167   case X86::EH_SjLj_SetJmp32:
19168   case X86::EH_SjLj_SetJmp64:
19169     return emitEHSjLjSetJmp(MI, BB);
19170
19171   case X86::EH_SjLj_LongJmp32:
19172   case X86::EH_SjLj_LongJmp64:
19173     return emitEHSjLjLongJmp(MI, BB);
19174
19175   case TargetOpcode::STACKMAP:
19176   case TargetOpcode::PATCHPOINT:
19177     return emitPatchPoint(MI, BB);
19178
19179   case X86::VFMADDPDr213r:
19180   case X86::VFMADDPSr213r:
19181   case X86::VFMADDSDr213r:
19182   case X86::VFMADDSSr213r:
19183   case X86::VFMSUBPDr213r:
19184   case X86::VFMSUBPSr213r:
19185   case X86::VFMSUBSDr213r:
19186   case X86::VFMSUBSSr213r:
19187   case X86::VFNMADDPDr213r:
19188   case X86::VFNMADDPSr213r:
19189   case X86::VFNMADDSDr213r:
19190   case X86::VFNMADDSSr213r:
19191   case X86::VFNMSUBPDr213r:
19192   case X86::VFNMSUBPSr213r:
19193   case X86::VFNMSUBSDr213r:
19194   case X86::VFNMSUBSSr213r:
19195   case X86::VFMADDPDr213rY:
19196   case X86::VFMADDPSr213rY:
19197   case X86::VFMSUBPDr213rY:
19198   case X86::VFMSUBPSr213rY:
19199   case X86::VFNMADDPDr213rY:
19200   case X86::VFNMADDPSr213rY:
19201   case X86::VFNMSUBPDr213rY:
19202   case X86::VFNMSUBPSr213rY:
19203     return emitFMA3Instr(MI, BB);
19204   }
19205 }
19206
19207 //===----------------------------------------------------------------------===//
19208 //                           X86 Optimization Hooks
19209 //===----------------------------------------------------------------------===//
19210
19211 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19212                                                       APInt &KnownZero,
19213                                                       APInt &KnownOne,
19214                                                       const SelectionDAG &DAG,
19215                                                       unsigned Depth) const {
19216   unsigned BitWidth = KnownZero.getBitWidth();
19217   unsigned Opc = Op.getOpcode();
19218   assert((Opc >= ISD::BUILTIN_OP_END ||
19219           Opc == ISD::INTRINSIC_WO_CHAIN ||
19220           Opc == ISD::INTRINSIC_W_CHAIN ||
19221           Opc == ISD::INTRINSIC_VOID) &&
19222          "Should use MaskedValueIsZero if you don't know whether Op"
19223          " is a target node!");
19224
19225   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19226   switch (Opc) {
19227   default: break;
19228   case X86ISD::ADD:
19229   case X86ISD::SUB:
19230   case X86ISD::ADC:
19231   case X86ISD::SBB:
19232   case X86ISD::SMUL:
19233   case X86ISD::UMUL:
19234   case X86ISD::INC:
19235   case X86ISD::DEC:
19236   case X86ISD::OR:
19237   case X86ISD::XOR:
19238   case X86ISD::AND:
19239     // These nodes' second result is a boolean.
19240     if (Op.getResNo() == 0)
19241       break;
19242     // Fallthrough
19243   case X86ISD::SETCC:
19244     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19245     break;
19246   case ISD::INTRINSIC_WO_CHAIN: {
19247     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19248     unsigned NumLoBits = 0;
19249     switch (IntId) {
19250     default: break;
19251     case Intrinsic::x86_sse_movmsk_ps:
19252     case Intrinsic::x86_avx_movmsk_ps_256:
19253     case Intrinsic::x86_sse2_movmsk_pd:
19254     case Intrinsic::x86_avx_movmsk_pd_256:
19255     case Intrinsic::x86_mmx_pmovmskb:
19256     case Intrinsic::x86_sse2_pmovmskb_128:
19257     case Intrinsic::x86_avx2_pmovmskb: {
19258       // High bits of movmskp{s|d}, pmovmskb are known zero.
19259       switch (IntId) {
19260         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19261         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19262         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19263         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19264         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19265         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19266         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19267         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19268       }
19269       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19270       break;
19271     }
19272     }
19273     break;
19274   }
19275   }
19276 }
19277
19278 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19279   SDValue Op,
19280   const SelectionDAG &,
19281   unsigned Depth) const {
19282   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19283   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19284     return Op.getValueType().getScalarType().getSizeInBits();
19285
19286   // Fallback case.
19287   return 1;
19288 }
19289
19290 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19291 /// node is a GlobalAddress + offset.
19292 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19293                                        const GlobalValue* &GA,
19294                                        int64_t &Offset) const {
19295   if (N->getOpcode() == X86ISD::Wrapper) {
19296     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19297       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19298       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19299       return true;
19300     }
19301   }
19302   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19303 }
19304
19305 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19306 /// same as extracting the high 128-bit part of 256-bit vector and then
19307 /// inserting the result into the low part of a new 256-bit vector
19308 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19309   EVT VT = SVOp->getValueType(0);
19310   unsigned NumElems = VT.getVectorNumElements();
19311
19312   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19313   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19314     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19315         SVOp->getMaskElt(j) >= 0)
19316       return false;
19317
19318   return true;
19319 }
19320
19321 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19322 /// same as extracting the low 128-bit part of 256-bit vector and then
19323 /// inserting the result into the high part of a new 256-bit vector
19324 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19325   EVT VT = SVOp->getValueType(0);
19326   unsigned NumElems = VT.getVectorNumElements();
19327
19328   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19329   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19330     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19331         SVOp->getMaskElt(j) >= 0)
19332       return false;
19333
19334   return true;
19335 }
19336
19337 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19338 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19339                                         TargetLowering::DAGCombinerInfo &DCI,
19340                                         const X86Subtarget* Subtarget) {
19341   SDLoc dl(N);
19342   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19343   SDValue V1 = SVOp->getOperand(0);
19344   SDValue V2 = SVOp->getOperand(1);
19345   EVT VT = SVOp->getValueType(0);
19346   unsigned NumElems = VT.getVectorNumElements();
19347
19348   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19349       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19350     //
19351     //                   0,0,0,...
19352     //                      |
19353     //    V      UNDEF    BUILD_VECTOR    UNDEF
19354     //     \      /           \           /
19355     //  CONCAT_VECTOR         CONCAT_VECTOR
19356     //         \                  /
19357     //          \                /
19358     //          RESULT: V + zero extended
19359     //
19360     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19361         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19362         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19363       return SDValue();
19364
19365     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19366       return SDValue();
19367
19368     // To match the shuffle mask, the first half of the mask should
19369     // be exactly the first vector, and all the rest a splat with the
19370     // first element of the second one.
19371     for (unsigned i = 0; i != NumElems/2; ++i)
19372       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19373           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19374         return SDValue();
19375
19376     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19377     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19378       if (Ld->hasNUsesOfValue(1, 0)) {
19379         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19380         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19381         SDValue ResNode =
19382           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19383                                   Ld->getMemoryVT(),
19384                                   Ld->getPointerInfo(),
19385                                   Ld->getAlignment(),
19386                                   false/*isVolatile*/, true/*ReadMem*/,
19387                                   false/*WriteMem*/);
19388
19389         // Make sure the newly-created LOAD is in the same position as Ld in
19390         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19391         // and update uses of Ld's output chain to use the TokenFactor.
19392         if (Ld->hasAnyUseOfValue(1)) {
19393           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19394                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19395           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19396           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19397                                  SDValue(ResNode.getNode(), 1));
19398         }
19399
19400         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19401       }
19402     }
19403
19404     // Emit a zeroed vector and insert the desired subvector on its
19405     // first half.
19406     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19407     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19408     return DCI.CombineTo(N, InsV);
19409   }
19410
19411   //===--------------------------------------------------------------------===//
19412   // Combine some shuffles into subvector extracts and inserts:
19413   //
19414
19415   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19416   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19417     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19418     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19419     return DCI.CombineTo(N, InsV);
19420   }
19421
19422   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19423   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19424     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19425     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19426     return DCI.CombineTo(N, InsV);
19427   }
19428
19429   return SDValue();
19430 }
19431
19432 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19433 /// possible.
19434 ///
19435 /// This is the leaf of the recursive combinine below. When we have found some
19436 /// chain of single-use x86 shuffle instructions and accumulated the combined
19437 /// shuffle mask represented by them, this will try to pattern match that mask
19438 /// into either a single instruction if there is a special purpose instruction
19439 /// for this operation, or into a PSHUFB instruction which is a fully general
19440 /// instruction but should only be used to replace chains over a certain depth.
19441 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19442                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19443                                    TargetLowering::DAGCombinerInfo &DCI,
19444                                    const X86Subtarget *Subtarget) {
19445   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19446
19447   // Find the operand that enters the chain. Note that multiple uses are OK
19448   // here, we're not going to remove the operand we find.
19449   SDValue Input = Op.getOperand(0);
19450   while (Input.getOpcode() == ISD::BITCAST)
19451     Input = Input.getOperand(0);
19452
19453   MVT VT = Input.getSimpleValueType();
19454   MVT RootVT = Root.getSimpleValueType();
19455   SDLoc DL(Root);
19456
19457   // Just remove no-op shuffle masks.
19458   if (Mask.size() == 1) {
19459     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19460                   /*AddTo*/ true);
19461     return true;
19462   }
19463
19464   // Use the float domain if the operand type is a floating point type.
19465   bool FloatDomain = VT.isFloatingPoint();
19466
19467   // If we don't have access to VEX encodings, the generic PSHUF instructions
19468   // are preferable to some of the specialized forms despite requiring one more
19469   // byte to encode because they can implicitly copy.
19470   //
19471   // IF we *do* have VEX encodings, than we can use shorter, more specific
19472   // shuffle instructions freely as they can copy due to the extra register
19473   // operand.
19474   if (Subtarget->hasAVX()) {
19475     // We have both floating point and integer variants of shuffles that dup
19476     // either the low or high half of the vector.
19477     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19478       bool Lo = Mask.equals(0, 0);
19479       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19480                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19481       if (Depth == 1 && Root->getOpcode() == Shuffle)
19482         return false; // Nothing to do!
19483       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19484       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19485       DCI.AddToWorklist(Op.getNode());
19486       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19487       DCI.AddToWorklist(Op.getNode());
19488       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19489                     /*AddTo*/ true);
19490       return true;
19491     }
19492
19493     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19494
19495     // For the integer domain we have specialized instructions for duplicating
19496     // any element size from the low or high half.
19497     if (!FloatDomain &&
19498         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19499          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19500          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19501          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19502          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19503                      15))) {
19504       bool Lo = Mask[0] == 0;
19505       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19506       if (Depth == 1 && Root->getOpcode() == Shuffle)
19507         return false; // Nothing to do!
19508       MVT ShuffleVT;
19509       switch (Mask.size()) {
19510       case 4: ShuffleVT = MVT::v4i32; break;
19511       case 8: ShuffleVT = MVT::v8i16; break;
19512       case 16: ShuffleVT = MVT::v16i8; break;
19513       };
19514       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19515       DCI.AddToWorklist(Op.getNode());
19516       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19517       DCI.AddToWorklist(Op.getNode());
19518       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19519                     /*AddTo*/ true);
19520       return true;
19521     }
19522   }
19523
19524   // Don't try to re-form single instruction chains under any circumstances now
19525   // that we've done encoding canonicalization for them.
19526   if (Depth < 2)
19527     return false;
19528
19529   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19530   // can replace them with a single PSHUFB instruction profitably. Intel's
19531   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19532   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19533   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19534     SmallVector<SDValue, 16> PSHUFBMask;
19535     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19536     int Ratio = 16 / Mask.size();
19537     for (unsigned i = 0; i < 16; ++i) {
19538       int M = Mask[i / Ratio] != SM_SentinelZero
19539                   ? Ratio * Mask[i / Ratio] + i % Ratio
19540                   : 255;
19541       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19542     }
19543     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19544     DCI.AddToWorklist(Op.getNode());
19545     SDValue PSHUFBMaskOp =
19546         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19547     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19548     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19549     DCI.AddToWorklist(Op.getNode());
19550     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19551                   /*AddTo*/ true);
19552     return true;
19553   }
19554
19555   // Failed to find any combines.
19556   return false;
19557 }
19558
19559 /// \brief Fully generic combining of x86 shuffle instructions.
19560 ///
19561 /// This should be the last combine run over the x86 shuffle instructions. Once
19562 /// they have been fully optimized, this will recursively consider all chains
19563 /// of single-use shuffle instructions, build a generic model of the cumulative
19564 /// shuffle operation, and check for simpler instructions which implement this
19565 /// operation. We use this primarily for two purposes:
19566 ///
19567 /// 1) Collapse generic shuffles to specialized single instructions when
19568 ///    equivalent. In most cases, this is just an encoding size win, but
19569 ///    sometimes we will collapse multiple generic shuffles into a single
19570 ///    special-purpose shuffle.
19571 /// 2) Look for sequences of shuffle instructions with 3 or more total
19572 ///    instructions, and replace them with the slightly more expensive SSSE3
19573 ///    PSHUFB instruction if available. We do this as the last combining step
19574 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19575 ///    a suitable short sequence of other instructions. The PHUFB will either
19576 ///    use a register or have to read from memory and so is slightly (but only
19577 ///    slightly) more expensive than the other shuffle instructions.
19578 ///
19579 /// Because this is inherently a quadratic operation (for each shuffle in
19580 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19581 /// This should never be an issue in practice as the shuffle lowering doesn't
19582 /// produce sequences of more than 8 instructions.
19583 ///
19584 /// FIXME: We will currently miss some cases where the redundant shuffling
19585 /// would simplify under the threshold for PSHUFB formation because of
19586 /// combine-ordering. To fix this, we should do the redundant instruction
19587 /// combining in this recursive walk.
19588 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19589                                           ArrayRef<int> RootMask,
19590                                           int Depth, bool HasPSHUFB,
19591                                           SelectionDAG &DAG,
19592                                           TargetLowering::DAGCombinerInfo &DCI,
19593                                           const X86Subtarget *Subtarget) {
19594   // Bound the depth of our recursive combine because this is ultimately
19595   // quadratic in nature.
19596   if (Depth > 8)
19597     return false;
19598
19599   // Directly rip through bitcasts to find the underlying operand.
19600   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19601     Op = Op.getOperand(0);
19602
19603   MVT VT = Op.getSimpleValueType();
19604   if (!VT.isVector())
19605     return false; // Bail if we hit a non-vector.
19606   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19607   // version should be added.
19608   if (VT.getSizeInBits() != 128)
19609     return false;
19610
19611   assert(Root.getSimpleValueType().isVector() &&
19612          "Shuffles operate on vector types!");
19613   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19614          "Can only combine shuffles of the same vector register size.");
19615
19616   if (!isTargetShuffle(Op.getOpcode()))
19617     return false;
19618   SmallVector<int, 16> OpMask;
19619   bool IsUnary;
19620   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19621   // We only can combine unary shuffles which we can decode the mask for.
19622   if (!HaveMask || !IsUnary)
19623     return false;
19624
19625   assert(VT.getVectorNumElements() == OpMask.size() &&
19626          "Different mask size from vector size!");
19627   assert(((RootMask.size() > OpMask.size() &&
19628            RootMask.size() % OpMask.size() == 0) ||
19629           (OpMask.size() > RootMask.size() &&
19630            OpMask.size() % RootMask.size() == 0) ||
19631           OpMask.size() == RootMask.size()) &&
19632          "The smaller number of elements must divide the larger.");
19633   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19634   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19635   assert(((RootRatio == 1 && OpRatio == 1) ||
19636           (RootRatio == 1) != (OpRatio == 1)) &&
19637          "Must not have a ratio for both incoming and op masks!");
19638
19639   SmallVector<int, 16> Mask;
19640   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19641
19642   // Merge this shuffle operation's mask into our accumulated mask. Note that
19643   // this shuffle's mask will be the first applied to the input, followed by the
19644   // root mask to get us all the way to the root value arrangement. The reason
19645   // for this order is that we are recursing up the operation chain.
19646   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19647     int RootIdx = i / RootRatio;
19648     if (RootMask[RootIdx] == SM_SentinelZero) {
19649       // This is a zero-ed lane, we're done.
19650       Mask.push_back(SM_SentinelZero);
19651       continue;
19652     }
19653
19654     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19655     int OpIdx = RootMaskedIdx / OpRatio;
19656     if (OpMask[OpIdx] == SM_SentinelZero) {
19657       // The incoming lanes are zero, it doesn't matter which ones we are using.
19658       Mask.push_back(SM_SentinelZero);
19659       continue;
19660     }
19661
19662     // Ok, we have non-zero lanes, map them through.
19663     Mask.push_back(OpMask[OpIdx] * OpRatio +
19664                    RootMaskedIdx % OpRatio);
19665   }
19666
19667   // See if we can recurse into the operand to combine more things.
19668   switch (Op.getOpcode()) {
19669     case X86ISD::PSHUFB:
19670       HasPSHUFB = true;
19671     case X86ISD::PSHUFD:
19672     case X86ISD::PSHUFHW:
19673     case X86ISD::PSHUFLW:
19674       if (Op.getOperand(0).hasOneUse() &&
19675           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19676                                         HasPSHUFB, DAG, DCI, Subtarget))
19677         return true;
19678       break;
19679
19680     case X86ISD::UNPCKL:
19681     case X86ISD::UNPCKH:
19682       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19683       // We can't check for single use, we have to check that this shuffle is the only user.
19684       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19685           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19686                                         HasPSHUFB, DAG, DCI, Subtarget))
19687           return true;
19688       break;
19689   }
19690
19691   // Minor canonicalization of the accumulated shuffle mask to make it easier
19692   // to match below. All this does is detect masks with squential pairs of
19693   // elements, and shrink them to the half-width mask. It does this in a loop
19694   // so it will reduce the size of the mask to the minimal width mask which
19695   // performs an equivalent shuffle.
19696   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19697     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19698       Mask[i] = Mask[2 * i] / 2;
19699     Mask.resize(Mask.size() / 2);
19700   }
19701
19702   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19703                                 Subtarget);
19704 }
19705
19706 /// \brief Get the PSHUF-style mask from PSHUF node.
19707 ///
19708 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19709 /// PSHUF-style masks that can be reused with such instructions.
19710 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19711   SmallVector<int, 4> Mask;
19712   bool IsUnary;
19713   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19714   (void)HaveMask;
19715   assert(HaveMask);
19716
19717   switch (N.getOpcode()) {
19718   case X86ISD::PSHUFD:
19719     return Mask;
19720   case X86ISD::PSHUFLW:
19721     Mask.resize(4);
19722     return Mask;
19723   case X86ISD::PSHUFHW:
19724     Mask.erase(Mask.begin(), Mask.begin() + 4);
19725     for (int &M : Mask)
19726       M -= 4;
19727     return Mask;
19728   default:
19729     llvm_unreachable("No valid shuffle instruction found!");
19730   }
19731 }
19732
19733 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19734 ///
19735 /// We walk up the chain and look for a combinable shuffle, skipping over
19736 /// shuffles that we could hoist this shuffle's transformation past without
19737 /// altering anything.
19738 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19739                                          SelectionDAG &DAG,
19740                                          TargetLowering::DAGCombinerInfo &DCI) {
19741   assert(N.getOpcode() == X86ISD::PSHUFD &&
19742          "Called with something other than an x86 128-bit half shuffle!");
19743   SDLoc DL(N);
19744
19745   // Walk up a single-use chain looking for a combinable shuffle.
19746   SDValue V = N.getOperand(0);
19747   for (; V.hasOneUse(); V = V.getOperand(0)) {
19748     switch (V.getOpcode()) {
19749     default:
19750       return false; // Nothing combined!
19751
19752     case ISD::BITCAST:
19753       // Skip bitcasts as we always know the type for the target specific
19754       // instructions.
19755       continue;
19756
19757     case X86ISD::PSHUFD:
19758       // Found another dword shuffle.
19759       break;
19760
19761     case X86ISD::PSHUFLW:
19762       // Check that the low words (being shuffled) are the identity in the
19763       // dword shuffle, and the high words are self-contained.
19764       if (Mask[0] != 0 || Mask[1] != 1 ||
19765           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19766         return false;
19767
19768       continue;
19769
19770     case X86ISD::PSHUFHW:
19771       // Check that the high words (being shuffled) are the identity in the
19772       // dword shuffle, and the low words are self-contained.
19773       if (Mask[2] != 2 || Mask[3] != 3 ||
19774           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19775         return false;
19776
19777       continue;
19778
19779     case X86ISD::UNPCKL:
19780     case X86ISD::UNPCKH:
19781       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19782       // shuffle into a preceding word shuffle.
19783       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19784         return false;
19785
19786       // Search for a half-shuffle which we can combine with.
19787       unsigned CombineOp =
19788           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19789       if (V.getOperand(0) != V.getOperand(1) ||
19790           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19791         return false;
19792       V = V.getOperand(0);
19793       do {
19794         switch (V.getOpcode()) {
19795         default:
19796           return false; // Nothing to combine.
19797
19798         case X86ISD::PSHUFLW:
19799         case X86ISD::PSHUFHW:
19800           if (V.getOpcode() == CombineOp)
19801             break;
19802
19803           // Fallthrough!
19804         case ISD::BITCAST:
19805           V = V.getOperand(0);
19806           continue;
19807         }
19808         break;
19809       } while (V.hasOneUse());
19810       break;
19811     }
19812     // Break out of the loop if we break out of the switch.
19813     break;
19814   }
19815
19816   if (!V.hasOneUse())
19817     // We fell out of the loop without finding a viable combining instruction.
19818     return false;
19819
19820   // Record the old value to use in RAUW-ing.
19821   SDValue Old = V;
19822
19823   // Merge this node's mask and our incoming mask.
19824   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19825   for (int &M : Mask)
19826     M = VMask[M];
19827   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19828                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19829
19830   // It is possible that one of the combinable shuffles was completely absorbed
19831   // by the other, just replace it and revisit all users in that case.
19832   if (Old.getNode() == V.getNode()) {
19833     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19834     return true;
19835   }
19836
19837   // Replace N with its operand as we're going to combine that shuffle away.
19838   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19839
19840   // Replace the combinable shuffle with the combined one, updating all users
19841   // so that we re-evaluate the chain here.
19842   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19843   return true;
19844 }
19845
19846 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19847 ///
19848 /// We walk up the chain, skipping shuffles of the other half and looking
19849 /// through shuffles which switch halves trying to find a shuffle of the same
19850 /// pair of dwords.
19851 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19852                                         SelectionDAG &DAG,
19853                                         TargetLowering::DAGCombinerInfo &DCI) {
19854   assert(
19855       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19856       "Called with something other than an x86 128-bit half shuffle!");
19857   SDLoc DL(N);
19858   unsigned CombineOpcode = N.getOpcode();
19859
19860   // Walk up a single-use chain looking for a combinable shuffle.
19861   SDValue V = N.getOperand(0);
19862   for (; V.hasOneUse(); V = V.getOperand(0)) {
19863     switch (V.getOpcode()) {
19864     default:
19865       return false; // Nothing combined!
19866
19867     case ISD::BITCAST:
19868       // Skip bitcasts as we always know the type for the target specific
19869       // instructions.
19870       continue;
19871
19872     case X86ISD::PSHUFLW:
19873     case X86ISD::PSHUFHW:
19874       if (V.getOpcode() == CombineOpcode)
19875         break;
19876
19877       // Other-half shuffles are no-ops.
19878       continue;
19879     }
19880     // Break out of the loop if we break out of the switch.
19881     break;
19882   }
19883
19884   if (!V.hasOneUse())
19885     // We fell out of the loop without finding a viable combining instruction.
19886     return false;
19887
19888   // Combine away the bottom node as its shuffle will be accumulated into
19889   // a preceding shuffle.
19890   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19891
19892   // Record the old value.
19893   SDValue Old = V;
19894
19895   // Merge this node's mask and our incoming mask (adjusted to account for all
19896   // the pshufd instructions encountered).
19897   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19898   for (int &M : Mask)
19899     M = VMask[M];
19900   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19901                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19902
19903   // Check that the shuffles didn't cancel each other out. If not, we need to
19904   // combine to the new one.
19905   if (Old != V)
19906     // Replace the combinable shuffle with the combined one, updating all users
19907     // so that we re-evaluate the chain here.
19908     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19909
19910   return true;
19911 }
19912
19913 /// \brief Try to combine x86 target specific shuffles.
19914 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19915                                            TargetLowering::DAGCombinerInfo &DCI,
19916                                            const X86Subtarget *Subtarget) {
19917   SDLoc DL(N);
19918   MVT VT = N.getSimpleValueType();
19919   SmallVector<int, 4> Mask;
19920
19921   switch (N.getOpcode()) {
19922   case X86ISD::PSHUFD:
19923   case X86ISD::PSHUFLW:
19924   case X86ISD::PSHUFHW:
19925     Mask = getPSHUFShuffleMask(N);
19926     assert(Mask.size() == 4);
19927     break;
19928   default:
19929     return SDValue();
19930   }
19931
19932   // Nuke no-op shuffles that show up after combining.
19933   if (isNoopShuffleMask(Mask))
19934     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19935
19936   // Look for simplifications involving one or two shuffle instructions.
19937   SDValue V = N.getOperand(0);
19938   switch (N.getOpcode()) {
19939   default:
19940     break;
19941   case X86ISD::PSHUFLW:
19942   case X86ISD::PSHUFHW:
19943     assert(VT == MVT::v8i16);
19944     (void)VT;
19945
19946     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19947       return SDValue(); // We combined away this shuffle, so we're done.
19948
19949     // See if this reduces to a PSHUFD which is no more expensive and can
19950     // combine with more operations.
19951     if (canWidenShuffleElements(Mask)) {
19952       int DMask[] = {-1, -1, -1, -1};
19953       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19954       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19955       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19956       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19957       DCI.AddToWorklist(V.getNode());
19958       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19959                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19960       DCI.AddToWorklist(V.getNode());
19961       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19962     }
19963
19964     // Look for shuffle patterns which can be implemented as a single unpack.
19965     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19966     // only works when we have a PSHUFD followed by two half-shuffles.
19967     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19968         (V.getOpcode() == X86ISD::PSHUFLW ||
19969          V.getOpcode() == X86ISD::PSHUFHW) &&
19970         V.getOpcode() != N.getOpcode() &&
19971         V.hasOneUse()) {
19972       SDValue D = V.getOperand(0);
19973       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19974         D = D.getOperand(0);
19975       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19976         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19977         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19978         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19979         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19980         int WordMask[8];
19981         for (int i = 0; i < 4; ++i) {
19982           WordMask[i + NOffset] = Mask[i] + NOffset;
19983           WordMask[i + VOffset] = VMask[i] + VOffset;
19984         }
19985         // Map the word mask through the DWord mask.
19986         int MappedMask[8];
19987         for (int i = 0; i < 8; ++i)
19988           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19989         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19990         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19991         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19992                        std::begin(UnpackLoMask)) ||
19993             std::equal(std::begin(MappedMask), std::end(MappedMask),
19994                        std::begin(UnpackHiMask))) {
19995           // We can replace all three shuffles with an unpack.
19996           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19997           DCI.AddToWorklist(V.getNode());
19998           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19999                                                 : X86ISD::UNPCKH,
20000                              DL, MVT::v8i16, V, V);
20001         }
20002       }
20003     }
20004
20005     break;
20006
20007   case X86ISD::PSHUFD:
20008     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20009       return SDValue(); // We combined away this shuffle.
20010
20011     break;
20012   }
20013
20014   return SDValue();
20015 }
20016
20017 /// PerformShuffleCombine - Performs several different shuffle combines.
20018 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20019                                      TargetLowering::DAGCombinerInfo &DCI,
20020                                      const X86Subtarget *Subtarget) {
20021   SDLoc dl(N);
20022   SDValue N0 = N->getOperand(0);
20023   SDValue N1 = N->getOperand(1);
20024   EVT VT = N->getValueType(0);
20025
20026   // Don't create instructions with illegal types after legalize types has run.
20027   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20028   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20029     return SDValue();
20030
20031   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20032   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20033       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20034     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20035
20036   // During Type Legalization, when promoting illegal vector types,
20037   // the backend might introduce new shuffle dag nodes and bitcasts.
20038   //
20039   // This code performs the following transformation:
20040   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20041   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20042   //
20043   // We do this only if both the bitcast and the BINOP dag nodes have
20044   // one use. Also, perform this transformation only if the new binary
20045   // operation is legal. This is to avoid introducing dag nodes that
20046   // potentially need to be further expanded (or custom lowered) into a
20047   // less optimal sequence of dag nodes.
20048   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20049       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20050       N0.getOpcode() == ISD::BITCAST) {
20051     SDValue BC0 = N0.getOperand(0);
20052     EVT SVT = BC0.getValueType();
20053     unsigned Opcode = BC0.getOpcode();
20054     unsigned NumElts = VT.getVectorNumElements();
20055     
20056     if (BC0.hasOneUse() && SVT.isVector() &&
20057         SVT.getVectorNumElements() * 2 == NumElts &&
20058         TLI.isOperationLegal(Opcode, VT)) {
20059       bool CanFold = false;
20060       switch (Opcode) {
20061       default : break;
20062       case ISD::ADD :
20063       case ISD::FADD :
20064       case ISD::SUB :
20065       case ISD::FSUB :
20066       case ISD::MUL :
20067       case ISD::FMUL :
20068         CanFold = true;
20069       }
20070
20071       unsigned SVTNumElts = SVT.getVectorNumElements();
20072       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20073       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20074         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20075       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20076         CanFold = SVOp->getMaskElt(i) < 0;
20077
20078       if (CanFold) {
20079         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20080         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20081         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20082         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20083       }
20084     }
20085   }
20086
20087   // Only handle 128 wide vector from here on.
20088   if (!VT.is128BitVector())
20089     return SDValue();
20090
20091   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20092   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20093   // consecutive, non-overlapping, and in the right order.
20094   SmallVector<SDValue, 16> Elts;
20095   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20096     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20097
20098   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20099   if (LD.getNode())
20100     return LD;
20101
20102   if (isTargetShuffle(N->getOpcode())) {
20103     SDValue Shuffle =
20104         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20105     if (Shuffle.getNode())
20106       return Shuffle;
20107
20108     // Try recursively combining arbitrary sequences of x86 shuffle
20109     // instructions into higher-order shuffles. We do this after combining
20110     // specific PSHUF instruction sequences into their minimal form so that we
20111     // can evaluate how many specialized shuffle instructions are involved in
20112     // a particular chain.
20113     SmallVector<int, 1> NonceMask; // Just a placeholder.
20114     NonceMask.push_back(0);
20115     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20116                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20117                                       DCI, Subtarget))
20118       return SDValue(); // This routine will use CombineTo to replace N.
20119   }
20120
20121   return SDValue();
20122 }
20123
20124 /// PerformTruncateCombine - Converts truncate operation to
20125 /// a sequence of vector shuffle operations.
20126 /// It is possible when we truncate 256-bit vector to 128-bit vector
20127 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20128                                       TargetLowering::DAGCombinerInfo &DCI,
20129                                       const X86Subtarget *Subtarget)  {
20130   return SDValue();
20131 }
20132
20133 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20134 /// specific shuffle of a load can be folded into a single element load.
20135 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20136 /// shuffles have been customed lowered so we need to handle those here.
20137 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20138                                          TargetLowering::DAGCombinerInfo &DCI) {
20139   if (DCI.isBeforeLegalizeOps())
20140     return SDValue();
20141
20142   SDValue InVec = N->getOperand(0);
20143   SDValue EltNo = N->getOperand(1);
20144
20145   if (!isa<ConstantSDNode>(EltNo))
20146     return SDValue();
20147
20148   EVT VT = InVec.getValueType();
20149
20150   bool HasShuffleIntoBitcast = false;
20151   if (InVec.getOpcode() == ISD::BITCAST) {
20152     // Don't duplicate a load with other uses.
20153     if (!InVec.hasOneUse())
20154       return SDValue();
20155     EVT BCVT = InVec.getOperand(0).getValueType();
20156     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
20157       return SDValue();
20158     InVec = InVec.getOperand(0);
20159     HasShuffleIntoBitcast = true;
20160   }
20161
20162   if (!isTargetShuffle(InVec.getOpcode()))
20163     return SDValue();
20164
20165   // Don't duplicate a load with other uses.
20166   if (!InVec.hasOneUse())
20167     return SDValue();
20168
20169   SmallVector<int, 16> ShuffleMask;
20170   bool UnaryShuffle;
20171   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
20172                             UnaryShuffle))
20173     return SDValue();
20174
20175   // Select the input vector, guarding against out of range extract vector.
20176   unsigned NumElems = VT.getVectorNumElements();
20177   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20178   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20179   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20180                                          : InVec.getOperand(1);
20181
20182   // If inputs to shuffle are the same for both ops, then allow 2 uses
20183   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20184
20185   if (LdNode.getOpcode() == ISD::BITCAST) {
20186     // Don't duplicate a load with other uses.
20187     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20188       return SDValue();
20189
20190     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20191     LdNode = LdNode.getOperand(0);
20192   }
20193
20194   if (!ISD::isNormalLoad(LdNode.getNode()))
20195     return SDValue();
20196
20197   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20198
20199   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20200     return SDValue();
20201
20202   if (HasShuffleIntoBitcast) {
20203     // If there's a bitcast before the shuffle, check if the load type and
20204     // alignment is valid.
20205     unsigned Align = LN0->getAlignment();
20206     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20207     unsigned NewAlign = TLI.getDataLayout()->
20208       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
20209
20210     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
20211       return SDValue();
20212   }
20213
20214   // All checks match so transform back to vector_shuffle so that DAG combiner
20215   // can finish the job
20216   SDLoc dl(N);
20217
20218   // Create shuffle node taking into account the case that its a unary shuffle
20219   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
20220   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
20221                                  InVec.getOperand(0), Shuffle,
20222                                  &ShuffleMask[0]);
20223   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
20224   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20225                      EltNo);
20226 }
20227
20228 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20229 /// generation and convert it from being a bunch of shuffles and extracts
20230 /// to a simple store and scalar loads to extract the elements.
20231 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20232                                          TargetLowering::DAGCombinerInfo &DCI) {
20233   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20234   if (NewOp.getNode())
20235     return NewOp;
20236
20237   SDValue InputVector = N->getOperand(0);
20238
20239   // Detect whether we are trying to convert from mmx to i32 and the bitcast
20240   // from mmx to v2i32 has a single usage.
20241   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
20242       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
20243       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
20244     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20245                        N->getValueType(0),
20246                        InputVector.getNode()->getOperand(0));
20247
20248   // Only operate on vectors of 4 elements, where the alternative shuffling
20249   // gets to be more expensive.
20250   if (InputVector.getValueType() != MVT::v4i32)
20251     return SDValue();
20252
20253   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20254   // single use which is a sign-extend or zero-extend, and all elements are
20255   // used.
20256   SmallVector<SDNode *, 4> Uses;
20257   unsigned ExtractedElements = 0;
20258   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20259        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20260     if (UI.getUse().getResNo() != InputVector.getResNo())
20261       return SDValue();
20262
20263     SDNode *Extract = *UI;
20264     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20265       return SDValue();
20266
20267     if (Extract->getValueType(0) != MVT::i32)
20268       return SDValue();
20269     if (!Extract->hasOneUse())
20270       return SDValue();
20271     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20272         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20273       return SDValue();
20274     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20275       return SDValue();
20276
20277     // Record which element was extracted.
20278     ExtractedElements |=
20279       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20280
20281     Uses.push_back(Extract);
20282   }
20283
20284   // If not all the elements were used, this may not be worthwhile.
20285   if (ExtractedElements != 15)
20286     return SDValue();
20287
20288   // Ok, we've now decided to do the transformation.
20289   SDLoc dl(InputVector);
20290
20291   // Store the value to a temporary stack slot.
20292   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20293   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20294                             MachinePointerInfo(), false, false, 0);
20295
20296   // Replace each use (extract) with a load of the appropriate element.
20297   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20298        UE = Uses.end(); UI != UE; ++UI) {
20299     SDNode *Extract = *UI;
20300
20301     // cOMpute the element's address.
20302     SDValue Idx = Extract->getOperand(1);
20303     unsigned EltSize =
20304         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
20305     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
20306     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20307     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20308
20309     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20310                                      StackPtr, OffsetVal);
20311
20312     // Load the scalar.
20313     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
20314                                      ScalarAddr, MachinePointerInfo(),
20315                                      false, false, false, 0);
20316
20317     // Replace the exact with the load.
20318     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20319   }
20320
20321   // The replacement was made in place; don't return anything.
20322   return SDValue();
20323 }
20324
20325 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20326 static std::pair<unsigned, bool>
20327 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20328                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20329   if (!VT.isVector())
20330     return std::make_pair(0, false);
20331
20332   bool NeedSplit = false;
20333   switch (VT.getSimpleVT().SimpleTy) {
20334   default: return std::make_pair(0, false);
20335   case MVT::v32i8:
20336   case MVT::v16i16:
20337   case MVT::v8i32:
20338     if (!Subtarget->hasAVX2())
20339       NeedSplit = true;
20340     if (!Subtarget->hasAVX())
20341       return std::make_pair(0, false);
20342     break;
20343   case MVT::v16i8:
20344   case MVT::v8i16:
20345   case MVT::v4i32:
20346     if (!Subtarget->hasSSE2())
20347       return std::make_pair(0, false);
20348   }
20349
20350   // SSE2 has only a small subset of the operations.
20351   bool hasUnsigned = Subtarget->hasSSE41() ||
20352                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20353   bool hasSigned = Subtarget->hasSSE41() ||
20354                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20355
20356   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20357
20358   unsigned Opc = 0;
20359   // Check for x CC y ? x : y.
20360   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20361       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20362     switch (CC) {
20363     default: break;
20364     case ISD::SETULT:
20365     case ISD::SETULE:
20366       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20367     case ISD::SETUGT:
20368     case ISD::SETUGE:
20369       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20370     case ISD::SETLT:
20371     case ISD::SETLE:
20372       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20373     case ISD::SETGT:
20374     case ISD::SETGE:
20375       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20376     }
20377   // Check for x CC y ? y : x -- a min/max with reversed arms.
20378   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20379              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20380     switch (CC) {
20381     default: break;
20382     case ISD::SETULT:
20383     case ISD::SETULE:
20384       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20385     case ISD::SETUGT:
20386     case ISD::SETUGE:
20387       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20388     case ISD::SETLT:
20389     case ISD::SETLE:
20390       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20391     case ISD::SETGT:
20392     case ISD::SETGE:
20393       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20394     }
20395   }
20396
20397   return std::make_pair(Opc, NeedSplit);
20398 }
20399
20400 static SDValue
20401 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20402                                       const X86Subtarget *Subtarget) {
20403   SDLoc dl(N);
20404   SDValue Cond = N->getOperand(0);
20405   SDValue LHS = N->getOperand(1);
20406   SDValue RHS = N->getOperand(2);
20407
20408   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20409     SDValue CondSrc = Cond->getOperand(0);
20410     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20411       Cond = CondSrc->getOperand(0);
20412   }
20413
20414   MVT VT = N->getSimpleValueType(0);
20415   MVT EltVT = VT.getVectorElementType();
20416   unsigned NumElems = VT.getVectorNumElements();
20417   // There is no blend with immediate in AVX-512.
20418   if (VT.is512BitVector())
20419     return SDValue();
20420
20421   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20422     return SDValue();
20423   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20424     return SDValue();
20425
20426   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20427     return SDValue();
20428
20429   // A vselect where all conditions and data are constants can be optimized into
20430   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20431   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20432       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20433     return SDValue();
20434
20435   unsigned MaskValue = 0;
20436   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20437     return SDValue();
20438
20439   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20440   for (unsigned i = 0; i < NumElems; ++i) {
20441     // Be sure we emit undef where we can.
20442     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20443       ShuffleMask[i] = -1;
20444     else
20445       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20446   }
20447
20448   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20449 }
20450
20451 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20452 /// nodes.
20453 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20454                                     TargetLowering::DAGCombinerInfo &DCI,
20455                                     const X86Subtarget *Subtarget) {
20456   SDLoc DL(N);
20457   SDValue Cond = N->getOperand(0);
20458   // Get the LHS/RHS of the select.
20459   SDValue LHS = N->getOperand(1);
20460   SDValue RHS = N->getOperand(2);
20461   EVT VT = LHS.getValueType();
20462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20463
20464   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20465   // instructions match the semantics of the common C idiom x<y?x:y but not
20466   // x<=y?x:y, because of how they handle negative zero (which can be
20467   // ignored in unsafe-math mode).
20468   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20469       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20470       (Subtarget->hasSSE2() ||
20471        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20472     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20473
20474     unsigned Opcode = 0;
20475     // Check for x CC y ? x : y.
20476     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20477         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20478       switch (CC) {
20479       default: break;
20480       case ISD::SETULT:
20481         // Converting this to a min would handle NaNs incorrectly, and swapping
20482         // the operands would cause it to handle comparisons between positive
20483         // and negative zero incorrectly.
20484         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20485           if (!DAG.getTarget().Options.UnsafeFPMath &&
20486               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20487             break;
20488           std::swap(LHS, RHS);
20489         }
20490         Opcode = X86ISD::FMIN;
20491         break;
20492       case ISD::SETOLE:
20493         // Converting this to a min would handle comparisons between positive
20494         // and negative zero incorrectly.
20495         if (!DAG.getTarget().Options.UnsafeFPMath &&
20496             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20497           break;
20498         Opcode = X86ISD::FMIN;
20499         break;
20500       case ISD::SETULE:
20501         // Converting this to a min would handle both negative zeros and NaNs
20502         // incorrectly, but we can swap the operands to fix both.
20503         std::swap(LHS, RHS);
20504       case ISD::SETOLT:
20505       case ISD::SETLT:
20506       case ISD::SETLE:
20507         Opcode = X86ISD::FMIN;
20508         break;
20509
20510       case ISD::SETOGE:
20511         // Converting this to a max would handle comparisons between positive
20512         // and negative zero incorrectly.
20513         if (!DAG.getTarget().Options.UnsafeFPMath &&
20514             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20515           break;
20516         Opcode = X86ISD::FMAX;
20517         break;
20518       case ISD::SETUGT:
20519         // Converting this to a max would handle NaNs incorrectly, and swapping
20520         // the operands would cause it to handle comparisons between positive
20521         // and negative zero incorrectly.
20522         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20523           if (!DAG.getTarget().Options.UnsafeFPMath &&
20524               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20525             break;
20526           std::swap(LHS, RHS);
20527         }
20528         Opcode = X86ISD::FMAX;
20529         break;
20530       case ISD::SETUGE:
20531         // Converting this to a max would handle both negative zeros and NaNs
20532         // incorrectly, but we can swap the operands to fix both.
20533         std::swap(LHS, RHS);
20534       case ISD::SETOGT:
20535       case ISD::SETGT:
20536       case ISD::SETGE:
20537         Opcode = X86ISD::FMAX;
20538         break;
20539       }
20540     // Check for x CC y ? y : x -- a min/max with reversed arms.
20541     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20542                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20543       switch (CC) {
20544       default: break;
20545       case ISD::SETOGE:
20546         // Converting this to a min would handle comparisons between positive
20547         // and negative zero incorrectly, and swapping the operands would
20548         // cause it to handle NaNs incorrectly.
20549         if (!DAG.getTarget().Options.UnsafeFPMath &&
20550             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20551           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20552             break;
20553           std::swap(LHS, RHS);
20554         }
20555         Opcode = X86ISD::FMIN;
20556         break;
20557       case ISD::SETUGT:
20558         // Converting this to a min would handle NaNs incorrectly.
20559         if (!DAG.getTarget().Options.UnsafeFPMath &&
20560             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20561           break;
20562         Opcode = X86ISD::FMIN;
20563         break;
20564       case ISD::SETUGE:
20565         // Converting this to a min would handle both negative zeros and NaNs
20566         // incorrectly, but we can swap the operands to fix both.
20567         std::swap(LHS, RHS);
20568       case ISD::SETOGT:
20569       case ISD::SETGT:
20570       case ISD::SETGE:
20571         Opcode = X86ISD::FMIN;
20572         break;
20573
20574       case ISD::SETULT:
20575         // Converting this to a max would handle NaNs incorrectly.
20576         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20577           break;
20578         Opcode = X86ISD::FMAX;
20579         break;
20580       case ISD::SETOLE:
20581         // Converting this to a max would handle comparisons between positive
20582         // and negative zero incorrectly, and swapping the operands would
20583         // cause it to handle NaNs incorrectly.
20584         if (!DAG.getTarget().Options.UnsafeFPMath &&
20585             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20586           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20587             break;
20588           std::swap(LHS, RHS);
20589         }
20590         Opcode = X86ISD::FMAX;
20591         break;
20592       case ISD::SETULE:
20593         // Converting this to a max would handle both negative zeros and NaNs
20594         // incorrectly, but we can swap the operands to fix both.
20595         std::swap(LHS, RHS);
20596       case ISD::SETOLT:
20597       case ISD::SETLT:
20598       case ISD::SETLE:
20599         Opcode = X86ISD::FMAX;
20600         break;
20601       }
20602     }
20603
20604     if (Opcode)
20605       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20606   }
20607
20608   EVT CondVT = Cond.getValueType();
20609   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20610       CondVT.getVectorElementType() == MVT::i1) {
20611     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20612     // lowering on AVX-512. In this case we convert it to
20613     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20614     // The same situation for all 128 and 256-bit vectors of i8 and i16
20615     EVT OpVT = LHS.getValueType();
20616     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20617         (OpVT.getVectorElementType() == MVT::i8 ||
20618          OpVT.getVectorElementType() == MVT::i16)) {
20619       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20620       DCI.AddToWorklist(Cond.getNode());
20621       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20622     }
20623   }
20624   // If this is a select between two integer constants, try to do some
20625   // optimizations.
20626   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20627     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20628       // Don't do this for crazy integer types.
20629       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20630         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20631         // so that TrueC (the true value) is larger than FalseC.
20632         bool NeedsCondInvert = false;
20633
20634         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20635             // Efficiently invertible.
20636             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20637              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20638               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20639           NeedsCondInvert = true;
20640           std::swap(TrueC, FalseC);
20641         }
20642
20643         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20644         if (FalseC->getAPIntValue() == 0 &&
20645             TrueC->getAPIntValue().isPowerOf2()) {
20646           if (NeedsCondInvert) // Invert the condition if needed.
20647             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20648                                DAG.getConstant(1, Cond.getValueType()));
20649
20650           // Zero extend the condition if needed.
20651           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20652
20653           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20654           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20655                              DAG.getConstant(ShAmt, MVT::i8));
20656         }
20657
20658         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20659         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20660           if (NeedsCondInvert) // Invert the condition if needed.
20661             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20662                                DAG.getConstant(1, Cond.getValueType()));
20663
20664           // Zero extend the condition if needed.
20665           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20666                              FalseC->getValueType(0), Cond);
20667           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20668                              SDValue(FalseC, 0));
20669         }
20670
20671         // Optimize cases that will turn into an LEA instruction.  This requires
20672         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20673         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20674           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20675           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20676
20677           bool isFastMultiplier = false;
20678           if (Diff < 10) {
20679             switch ((unsigned char)Diff) {
20680               default: break;
20681               case 1:  // result = add base, cond
20682               case 2:  // result = lea base(    , cond*2)
20683               case 3:  // result = lea base(cond, cond*2)
20684               case 4:  // result = lea base(    , cond*4)
20685               case 5:  // result = lea base(cond, cond*4)
20686               case 8:  // result = lea base(    , cond*8)
20687               case 9:  // result = lea base(cond, cond*8)
20688                 isFastMultiplier = true;
20689                 break;
20690             }
20691           }
20692
20693           if (isFastMultiplier) {
20694             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20695             if (NeedsCondInvert) // Invert the condition if needed.
20696               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20697                                  DAG.getConstant(1, Cond.getValueType()));
20698
20699             // Zero extend the condition if needed.
20700             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20701                                Cond);
20702             // Scale the condition by the difference.
20703             if (Diff != 1)
20704               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20705                                  DAG.getConstant(Diff, Cond.getValueType()));
20706
20707             // Add the base if non-zero.
20708             if (FalseC->getAPIntValue() != 0)
20709               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20710                                  SDValue(FalseC, 0));
20711             return Cond;
20712           }
20713         }
20714       }
20715   }
20716
20717   // Canonicalize max and min:
20718   // (x > y) ? x : y -> (x >= y) ? x : y
20719   // (x < y) ? x : y -> (x <= y) ? x : y
20720   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20721   // the need for an extra compare
20722   // against zero. e.g.
20723   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20724   // subl   %esi, %edi
20725   // testl  %edi, %edi
20726   // movl   $0, %eax
20727   // cmovgl %edi, %eax
20728   // =>
20729   // xorl   %eax, %eax
20730   // subl   %esi, $edi
20731   // cmovsl %eax, %edi
20732   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20733       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20734       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20735     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20736     switch (CC) {
20737     default: break;
20738     case ISD::SETLT:
20739     case ISD::SETGT: {
20740       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20741       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20742                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20743       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20744     }
20745     }
20746   }
20747
20748   // Early exit check
20749   if (!TLI.isTypeLegal(VT))
20750     return SDValue();
20751
20752   // Match VSELECTs into subs with unsigned saturation.
20753   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20754       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20755       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20756        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20757     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20758
20759     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20760     // left side invert the predicate to simplify logic below.
20761     SDValue Other;
20762     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20763       Other = RHS;
20764       CC = ISD::getSetCCInverse(CC, true);
20765     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20766       Other = LHS;
20767     }
20768
20769     if (Other.getNode() && Other->getNumOperands() == 2 &&
20770         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20771       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20772       SDValue CondRHS = Cond->getOperand(1);
20773
20774       // Look for a general sub with unsigned saturation first.
20775       // x >= y ? x-y : 0 --> subus x, y
20776       // x >  y ? x-y : 0 --> subus x, y
20777       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20778           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20779         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20780
20781       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20782         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20783           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20784             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20785               // If the RHS is a constant we have to reverse the const
20786               // canonicalization.
20787               // x > C-1 ? x+-C : 0 --> subus x, C
20788               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20789                   CondRHSConst->getAPIntValue() ==
20790                       (-OpRHSConst->getAPIntValue() - 1))
20791                 return DAG.getNode(
20792                     X86ISD::SUBUS, DL, VT, OpLHS,
20793                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20794
20795           // Another special case: If C was a sign bit, the sub has been
20796           // canonicalized into a xor.
20797           // FIXME: Would it be better to use computeKnownBits to determine
20798           //        whether it's safe to decanonicalize the xor?
20799           // x s< 0 ? x^C : 0 --> subus x, C
20800           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20801               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20802               OpRHSConst->getAPIntValue().isSignBit())
20803             // Note that we have to rebuild the RHS constant here to ensure we
20804             // don't rely on particular values of undef lanes.
20805             return DAG.getNode(
20806                 X86ISD::SUBUS, DL, VT, OpLHS,
20807                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20808         }
20809     }
20810   }
20811
20812   // Try to match a min/max vector operation.
20813   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20814     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20815     unsigned Opc = ret.first;
20816     bool NeedSplit = ret.second;
20817
20818     if (Opc && NeedSplit) {
20819       unsigned NumElems = VT.getVectorNumElements();
20820       // Extract the LHS vectors
20821       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20822       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20823
20824       // Extract the RHS vectors
20825       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20826       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20827
20828       // Create min/max for each subvector
20829       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20830       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20831
20832       // Merge the result
20833       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20834     } else if (Opc)
20835       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20836   }
20837
20838   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20839   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20840       // Check if SETCC has already been promoted
20841       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20842       // Check that condition value type matches vselect operand type
20843       CondVT == VT) { 
20844
20845     assert(Cond.getValueType().isVector() &&
20846            "vector select expects a vector selector!");
20847
20848     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20849     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20850
20851     if (!TValIsAllOnes && !FValIsAllZeros) {
20852       // Try invert the condition if true value is not all 1s and false value
20853       // is not all 0s.
20854       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20855       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20856
20857       if (TValIsAllZeros || FValIsAllOnes) {
20858         SDValue CC = Cond.getOperand(2);
20859         ISD::CondCode NewCC =
20860           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20861                                Cond.getOperand(0).getValueType().isInteger());
20862         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20863         std::swap(LHS, RHS);
20864         TValIsAllOnes = FValIsAllOnes;
20865         FValIsAllZeros = TValIsAllZeros;
20866       }
20867     }
20868
20869     if (TValIsAllOnes || FValIsAllZeros) {
20870       SDValue Ret;
20871
20872       if (TValIsAllOnes && FValIsAllZeros)
20873         Ret = Cond;
20874       else if (TValIsAllOnes)
20875         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20876                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20877       else if (FValIsAllZeros)
20878         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20879                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20880
20881       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20882     }
20883   }
20884
20885   // Try to fold this VSELECT into a MOVSS/MOVSD
20886   if (N->getOpcode() == ISD::VSELECT &&
20887       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20888     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20889         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20890       bool CanFold = false;
20891       unsigned NumElems = Cond.getNumOperands();
20892       SDValue A = LHS;
20893       SDValue B = RHS;
20894       
20895       if (isZero(Cond.getOperand(0))) {
20896         CanFold = true;
20897
20898         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20899         // fold (vselect <0,-1> -> (movsd A, B)
20900         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20901           CanFold = isAllOnes(Cond.getOperand(i));
20902       } else if (isAllOnes(Cond.getOperand(0))) {
20903         CanFold = true;
20904         std::swap(A, B);
20905
20906         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20907         // fold (vselect <-1,0> -> (movsd B, A)
20908         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20909           CanFold = isZero(Cond.getOperand(i));
20910       }
20911
20912       if (CanFold) {
20913         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20914           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20915         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20916       }
20917
20918       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20919         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20920         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20921         //                             (v2i64 (bitcast B)))))
20922         //
20923         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20924         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20925         //                             (v2f64 (bitcast B)))))
20926         //
20927         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20928         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20929         //                             (v2i64 (bitcast A)))))
20930         //
20931         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20932         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20933         //                             (v2f64 (bitcast A)))))
20934
20935         CanFold = (isZero(Cond.getOperand(0)) &&
20936                    isZero(Cond.getOperand(1)) &&
20937                    isAllOnes(Cond.getOperand(2)) &&
20938                    isAllOnes(Cond.getOperand(3)));
20939
20940         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20941             isAllOnes(Cond.getOperand(1)) &&
20942             isZero(Cond.getOperand(2)) &&
20943             isZero(Cond.getOperand(3))) {
20944           CanFold = true;
20945           std::swap(LHS, RHS);
20946         }
20947
20948         if (CanFold) {
20949           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20950           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20951           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20952           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20953                                                 NewB, DAG);
20954           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20955         }
20956       }
20957     }
20958   }
20959
20960   // If we know that this node is legal then we know that it is going to be
20961   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20962   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20963   // to simplify previous instructions.
20964   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20965       !DCI.isBeforeLegalize() &&
20966       // We explicitly check against v8i16 and v16i16 because, although
20967       // they're marked as Custom, they might only be legal when Cond is a
20968       // build_vector of constants. This will be taken care in a later
20969       // condition.
20970       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20971        VT != MVT::v8i16)) {
20972     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20973
20974     // Don't optimize vector selects that map to mask-registers.
20975     if (BitWidth == 1)
20976       return SDValue();
20977
20978     // Check all uses of that condition operand to check whether it will be
20979     // consumed by non-BLEND instructions, which may depend on all bits are set
20980     // properly.
20981     for (SDNode::use_iterator I = Cond->use_begin(),
20982                               E = Cond->use_end(); I != E; ++I)
20983       if (I->getOpcode() != ISD::VSELECT)
20984         // TODO: Add other opcodes eventually lowered into BLEND.
20985         return SDValue();
20986
20987     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20988     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20989
20990     APInt KnownZero, KnownOne;
20991     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20992                                           DCI.isBeforeLegalizeOps());
20993     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20994         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20995       DCI.CommitTargetLoweringOpt(TLO);
20996   }
20997
20998   // We should generate an X86ISD::BLENDI from a vselect if its argument
20999   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21000   // constants. This specific pattern gets generated when we split a
21001   // selector for a 512 bit vector in a machine without AVX512 (but with
21002   // 256-bit vectors), during legalization:
21003   //
21004   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21005   //
21006   // Iff we find this pattern and the build_vectors are built from
21007   // constants, we translate the vselect into a shuffle_vector that we
21008   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21009   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
21010     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21011     if (Shuffle.getNode())
21012       return Shuffle;
21013   }
21014
21015   return SDValue();
21016 }
21017
21018 // Check whether a boolean test is testing a boolean value generated by
21019 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21020 // code.
21021 //
21022 // Simplify the following patterns:
21023 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21024 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21025 // to (Op EFLAGS Cond)
21026 //
21027 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21028 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21029 // to (Op EFLAGS !Cond)
21030 //
21031 // where Op could be BRCOND or CMOV.
21032 //
21033 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21034   // Quit if not CMP and SUB with its value result used.
21035   if (Cmp.getOpcode() != X86ISD::CMP &&
21036       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21037       return SDValue();
21038
21039   // Quit if not used as a boolean value.
21040   if (CC != X86::COND_E && CC != X86::COND_NE)
21041     return SDValue();
21042
21043   // Check CMP operands. One of them should be 0 or 1 and the other should be
21044   // an SetCC or extended from it.
21045   SDValue Op1 = Cmp.getOperand(0);
21046   SDValue Op2 = Cmp.getOperand(1);
21047
21048   SDValue SetCC;
21049   const ConstantSDNode* C = nullptr;
21050   bool needOppositeCond = (CC == X86::COND_E);
21051   bool checkAgainstTrue = false; // Is it a comparison against 1?
21052
21053   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21054     SetCC = Op2;
21055   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21056     SetCC = Op1;
21057   else // Quit if all operands are not constants.
21058     return SDValue();
21059
21060   if (C->getZExtValue() == 1) {
21061     needOppositeCond = !needOppositeCond;
21062     checkAgainstTrue = true;
21063   } else if (C->getZExtValue() != 0)
21064     // Quit if the constant is neither 0 or 1.
21065     return SDValue();
21066
21067   bool truncatedToBoolWithAnd = false;
21068   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21069   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21070          SetCC.getOpcode() == ISD::TRUNCATE ||
21071          SetCC.getOpcode() == ISD::AND) {
21072     if (SetCC.getOpcode() == ISD::AND) {
21073       int OpIdx = -1;
21074       ConstantSDNode *CS;
21075       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21076           CS->getZExtValue() == 1)
21077         OpIdx = 1;
21078       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21079           CS->getZExtValue() == 1)
21080         OpIdx = 0;
21081       if (OpIdx == -1)
21082         break;
21083       SetCC = SetCC.getOperand(OpIdx);
21084       truncatedToBoolWithAnd = true;
21085     } else
21086       SetCC = SetCC.getOperand(0);
21087   }
21088
21089   switch (SetCC.getOpcode()) {
21090   case X86ISD::SETCC_CARRY:
21091     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21092     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21093     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21094     // truncated to i1 using 'and'.
21095     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21096       break;
21097     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21098            "Invalid use of SETCC_CARRY!");
21099     // FALL THROUGH
21100   case X86ISD::SETCC:
21101     // Set the condition code or opposite one if necessary.
21102     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21103     if (needOppositeCond)
21104       CC = X86::GetOppositeBranchCondition(CC);
21105     return SetCC.getOperand(1);
21106   case X86ISD::CMOV: {
21107     // Check whether false/true value has canonical one, i.e. 0 or 1.
21108     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21109     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21110     // Quit if true value is not a constant.
21111     if (!TVal)
21112       return SDValue();
21113     // Quit if false value is not a constant.
21114     if (!FVal) {
21115       SDValue Op = SetCC.getOperand(0);
21116       // Skip 'zext' or 'trunc' node.
21117       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21118           Op.getOpcode() == ISD::TRUNCATE)
21119         Op = Op.getOperand(0);
21120       // A special case for rdrand/rdseed, where 0 is set if false cond is
21121       // found.
21122       if ((Op.getOpcode() != X86ISD::RDRAND &&
21123            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21124         return SDValue();
21125     }
21126     // Quit if false value is not the constant 0 or 1.
21127     bool FValIsFalse = true;
21128     if (FVal && FVal->getZExtValue() != 0) {
21129       if (FVal->getZExtValue() != 1)
21130         return SDValue();
21131       // If FVal is 1, opposite cond is needed.
21132       needOppositeCond = !needOppositeCond;
21133       FValIsFalse = false;
21134     }
21135     // Quit if TVal is not the constant opposite of FVal.
21136     if (FValIsFalse && TVal->getZExtValue() != 1)
21137       return SDValue();
21138     if (!FValIsFalse && TVal->getZExtValue() != 0)
21139       return SDValue();
21140     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21141     if (needOppositeCond)
21142       CC = X86::GetOppositeBranchCondition(CC);
21143     return SetCC.getOperand(3);
21144   }
21145   }
21146
21147   return SDValue();
21148 }
21149
21150 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21151 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21152                                   TargetLowering::DAGCombinerInfo &DCI,
21153                                   const X86Subtarget *Subtarget) {
21154   SDLoc DL(N);
21155
21156   // If the flag operand isn't dead, don't touch this CMOV.
21157   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21158     return SDValue();
21159
21160   SDValue FalseOp = N->getOperand(0);
21161   SDValue TrueOp = N->getOperand(1);
21162   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21163   SDValue Cond = N->getOperand(3);
21164
21165   if (CC == X86::COND_E || CC == X86::COND_NE) {
21166     switch (Cond.getOpcode()) {
21167     default: break;
21168     case X86ISD::BSR:
21169     case X86ISD::BSF:
21170       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21171       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21172         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21173     }
21174   }
21175
21176   SDValue Flags;
21177
21178   Flags = checkBoolTestSetCCCombine(Cond, CC);
21179   if (Flags.getNode() &&
21180       // Extra check as FCMOV only supports a subset of X86 cond.
21181       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21182     SDValue Ops[] = { FalseOp, TrueOp,
21183                       DAG.getConstant(CC, MVT::i8), Flags };
21184     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21185   }
21186
21187   // If this is a select between two integer constants, try to do some
21188   // optimizations.  Note that the operands are ordered the opposite of SELECT
21189   // operands.
21190   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21191     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21192       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21193       // larger than FalseC (the false value).
21194       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21195         CC = X86::GetOppositeBranchCondition(CC);
21196         std::swap(TrueC, FalseC);
21197         std::swap(TrueOp, FalseOp);
21198       }
21199
21200       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21201       // This is efficient for any integer data type (including i8/i16) and
21202       // shift amount.
21203       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21204         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21205                            DAG.getConstant(CC, MVT::i8), Cond);
21206
21207         // Zero extend the condition if needed.
21208         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21209
21210         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21211         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21212                            DAG.getConstant(ShAmt, MVT::i8));
21213         if (N->getNumValues() == 2)  // Dead flag value?
21214           return DCI.CombineTo(N, Cond, SDValue());
21215         return Cond;
21216       }
21217
21218       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21219       // for any integer data type, including i8/i16.
21220       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21221         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21222                            DAG.getConstant(CC, MVT::i8), Cond);
21223
21224         // Zero extend the condition if needed.
21225         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21226                            FalseC->getValueType(0), Cond);
21227         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21228                            SDValue(FalseC, 0));
21229
21230         if (N->getNumValues() == 2)  // Dead flag value?
21231           return DCI.CombineTo(N, Cond, SDValue());
21232         return Cond;
21233       }
21234
21235       // Optimize cases that will turn into an LEA instruction.  This requires
21236       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21237       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21238         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21239         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21240
21241         bool isFastMultiplier = false;
21242         if (Diff < 10) {
21243           switch ((unsigned char)Diff) {
21244           default: break;
21245           case 1:  // result = add base, cond
21246           case 2:  // result = lea base(    , cond*2)
21247           case 3:  // result = lea base(cond, cond*2)
21248           case 4:  // result = lea base(    , cond*4)
21249           case 5:  // result = lea base(cond, cond*4)
21250           case 8:  // result = lea base(    , cond*8)
21251           case 9:  // result = lea base(cond, cond*8)
21252             isFastMultiplier = true;
21253             break;
21254           }
21255         }
21256
21257         if (isFastMultiplier) {
21258           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21259           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21260                              DAG.getConstant(CC, MVT::i8), Cond);
21261           // Zero extend the condition if needed.
21262           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21263                              Cond);
21264           // Scale the condition by the difference.
21265           if (Diff != 1)
21266             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21267                                DAG.getConstant(Diff, Cond.getValueType()));
21268
21269           // Add the base if non-zero.
21270           if (FalseC->getAPIntValue() != 0)
21271             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21272                                SDValue(FalseC, 0));
21273           if (N->getNumValues() == 2)  // Dead flag value?
21274             return DCI.CombineTo(N, Cond, SDValue());
21275           return Cond;
21276         }
21277       }
21278     }
21279   }
21280
21281   // Handle these cases:
21282   //   (select (x != c), e, c) -> select (x != c), e, x),
21283   //   (select (x == c), c, e) -> select (x == c), x, e)
21284   // where the c is an integer constant, and the "select" is the combination
21285   // of CMOV and CMP.
21286   //
21287   // The rationale for this change is that the conditional-move from a constant
21288   // needs two instructions, however, conditional-move from a register needs
21289   // only one instruction.
21290   //
21291   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21292   //  some instruction-combining opportunities. This opt needs to be
21293   //  postponed as late as possible.
21294   //
21295   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21296     // the DCI.xxxx conditions are provided to postpone the optimization as
21297     // late as possible.
21298
21299     ConstantSDNode *CmpAgainst = nullptr;
21300     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21301         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21302         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21303
21304       if (CC == X86::COND_NE &&
21305           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21306         CC = X86::GetOppositeBranchCondition(CC);
21307         std::swap(TrueOp, FalseOp);
21308       }
21309
21310       if (CC == X86::COND_E &&
21311           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21312         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21313                           DAG.getConstant(CC, MVT::i8), Cond };
21314         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21315       }
21316     }
21317   }
21318
21319   return SDValue();
21320 }
21321
21322 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21323                                                 const X86Subtarget *Subtarget) {
21324   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21325   switch (IntNo) {
21326   default: return SDValue();
21327   // SSE/AVX/AVX2 blend intrinsics.
21328   case Intrinsic::x86_avx2_pblendvb:
21329   case Intrinsic::x86_avx2_pblendw:
21330   case Intrinsic::x86_avx2_pblendd_128:
21331   case Intrinsic::x86_avx2_pblendd_256:
21332     // Don't try to simplify this intrinsic if we don't have AVX2.
21333     if (!Subtarget->hasAVX2())
21334       return SDValue();
21335     // FALL-THROUGH
21336   case Intrinsic::x86_avx_blend_pd_256:
21337   case Intrinsic::x86_avx_blend_ps_256:
21338   case Intrinsic::x86_avx_blendv_pd_256:
21339   case Intrinsic::x86_avx_blendv_ps_256:
21340     // Don't try to simplify this intrinsic if we don't have AVX.
21341     if (!Subtarget->hasAVX())
21342       return SDValue();
21343     // FALL-THROUGH
21344   case Intrinsic::x86_sse41_pblendw:
21345   case Intrinsic::x86_sse41_blendpd:
21346   case Intrinsic::x86_sse41_blendps:
21347   case Intrinsic::x86_sse41_blendvps:
21348   case Intrinsic::x86_sse41_blendvpd:
21349   case Intrinsic::x86_sse41_pblendvb: {
21350     SDValue Op0 = N->getOperand(1);
21351     SDValue Op1 = N->getOperand(2);
21352     SDValue Mask = N->getOperand(3);
21353
21354     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21355     if (!Subtarget->hasSSE41())
21356       return SDValue();
21357
21358     // fold (blend A, A, Mask) -> A
21359     if (Op0 == Op1)
21360       return Op0;
21361     // fold (blend A, B, allZeros) -> A
21362     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21363       return Op0;
21364     // fold (blend A, B, allOnes) -> B
21365     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21366       return Op1;
21367     
21368     // Simplify the case where the mask is a constant i32 value.
21369     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21370       if (C->isNullValue())
21371         return Op0;
21372       if (C->isAllOnesValue())
21373         return Op1;
21374     }
21375
21376     return SDValue();
21377   }
21378
21379   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21380   case Intrinsic::x86_sse2_psrai_w:
21381   case Intrinsic::x86_sse2_psrai_d:
21382   case Intrinsic::x86_avx2_psrai_w:
21383   case Intrinsic::x86_avx2_psrai_d:
21384   case Intrinsic::x86_sse2_psra_w:
21385   case Intrinsic::x86_sse2_psra_d:
21386   case Intrinsic::x86_avx2_psra_w:
21387   case Intrinsic::x86_avx2_psra_d: {
21388     SDValue Op0 = N->getOperand(1);
21389     SDValue Op1 = N->getOperand(2);
21390     EVT VT = Op0.getValueType();
21391     assert(VT.isVector() && "Expected a vector type!");
21392
21393     if (isa<BuildVectorSDNode>(Op1))
21394       Op1 = Op1.getOperand(0);
21395
21396     if (!isa<ConstantSDNode>(Op1))
21397       return SDValue();
21398
21399     EVT SVT = VT.getVectorElementType();
21400     unsigned SVTBits = SVT.getSizeInBits();
21401
21402     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21403     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21404     uint64_t ShAmt = C.getZExtValue();
21405
21406     // Don't try to convert this shift into a ISD::SRA if the shift
21407     // count is bigger than or equal to the element size.
21408     if (ShAmt >= SVTBits)
21409       return SDValue();
21410
21411     // Trivial case: if the shift count is zero, then fold this
21412     // into the first operand.
21413     if (ShAmt == 0)
21414       return Op0;
21415
21416     // Replace this packed shift intrinsic with a target independent
21417     // shift dag node.
21418     SDValue Splat = DAG.getConstant(C, VT);
21419     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21420   }
21421   }
21422 }
21423
21424 /// PerformMulCombine - Optimize a single multiply with constant into two
21425 /// in order to implement it with two cheaper instructions, e.g.
21426 /// LEA + SHL, LEA + LEA.
21427 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21428                                  TargetLowering::DAGCombinerInfo &DCI) {
21429   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21430     return SDValue();
21431
21432   EVT VT = N->getValueType(0);
21433   if (VT != MVT::i64)
21434     return SDValue();
21435
21436   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21437   if (!C)
21438     return SDValue();
21439   uint64_t MulAmt = C->getZExtValue();
21440   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21441     return SDValue();
21442
21443   uint64_t MulAmt1 = 0;
21444   uint64_t MulAmt2 = 0;
21445   if ((MulAmt % 9) == 0) {
21446     MulAmt1 = 9;
21447     MulAmt2 = MulAmt / 9;
21448   } else if ((MulAmt % 5) == 0) {
21449     MulAmt1 = 5;
21450     MulAmt2 = MulAmt / 5;
21451   } else if ((MulAmt % 3) == 0) {
21452     MulAmt1 = 3;
21453     MulAmt2 = MulAmt / 3;
21454   }
21455   if (MulAmt2 &&
21456       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21457     SDLoc DL(N);
21458
21459     if (isPowerOf2_64(MulAmt2) &&
21460         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21461       // If second multiplifer is pow2, issue it first. We want the multiply by
21462       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21463       // is an add.
21464       std::swap(MulAmt1, MulAmt2);
21465
21466     SDValue NewMul;
21467     if (isPowerOf2_64(MulAmt1))
21468       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21469                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21470     else
21471       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21472                            DAG.getConstant(MulAmt1, VT));
21473
21474     if (isPowerOf2_64(MulAmt2))
21475       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21476                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21477     else
21478       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21479                            DAG.getConstant(MulAmt2, VT));
21480
21481     // Do not add new nodes to DAG combiner worklist.
21482     DCI.CombineTo(N, NewMul, false);
21483   }
21484   return SDValue();
21485 }
21486
21487 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21488   SDValue N0 = N->getOperand(0);
21489   SDValue N1 = N->getOperand(1);
21490   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21491   EVT VT = N0.getValueType();
21492
21493   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21494   // since the result of setcc_c is all zero's or all ones.
21495   if (VT.isInteger() && !VT.isVector() &&
21496       N1C && N0.getOpcode() == ISD::AND &&
21497       N0.getOperand(1).getOpcode() == ISD::Constant) {
21498     SDValue N00 = N0.getOperand(0);
21499     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21500         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21501           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21502          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21503       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21504       APInt ShAmt = N1C->getAPIntValue();
21505       Mask = Mask.shl(ShAmt);
21506       if (Mask != 0)
21507         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21508                            N00, DAG.getConstant(Mask, VT));
21509     }
21510   }
21511
21512   // Hardware support for vector shifts is sparse which makes us scalarize the
21513   // vector operations in many cases. Also, on sandybridge ADD is faster than
21514   // shl.
21515   // (shl V, 1) -> add V,V
21516   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21517     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21518       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21519       // We shift all of the values by one. In many cases we do not have
21520       // hardware support for this operation. This is better expressed as an ADD
21521       // of two values.
21522       if (N1SplatC->getZExtValue() == 1)
21523         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21524     }
21525
21526   return SDValue();
21527 }
21528
21529 /// \brief Returns a vector of 0s if the node in input is a vector logical
21530 /// shift by a constant amount which is known to be bigger than or equal
21531 /// to the vector element size in bits.
21532 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21533                                       const X86Subtarget *Subtarget) {
21534   EVT VT = N->getValueType(0);
21535
21536   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21537       (!Subtarget->hasInt256() ||
21538        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21539     return SDValue();
21540
21541   SDValue Amt = N->getOperand(1);
21542   SDLoc DL(N);
21543   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21544     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21545       APInt ShiftAmt = AmtSplat->getAPIntValue();
21546       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21547
21548       // SSE2/AVX2 logical shifts always return a vector of 0s
21549       // if the shift amount is bigger than or equal to
21550       // the element size. The constant shift amount will be
21551       // encoded as a 8-bit immediate.
21552       if (ShiftAmt.trunc(8).uge(MaxAmount))
21553         return getZeroVector(VT, Subtarget, DAG, DL);
21554     }
21555
21556   return SDValue();
21557 }
21558
21559 /// PerformShiftCombine - Combine shifts.
21560 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21561                                    TargetLowering::DAGCombinerInfo &DCI,
21562                                    const X86Subtarget *Subtarget) {
21563   if (N->getOpcode() == ISD::SHL) {
21564     SDValue V = PerformSHLCombine(N, DAG);
21565     if (V.getNode()) return V;
21566   }
21567
21568   if (N->getOpcode() != ISD::SRA) {
21569     // Try to fold this logical shift into a zero vector.
21570     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21571     if (V.getNode()) return V;
21572   }
21573
21574   return SDValue();
21575 }
21576
21577 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21578 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21579 // and friends.  Likewise for OR -> CMPNEQSS.
21580 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21581                             TargetLowering::DAGCombinerInfo &DCI,
21582                             const X86Subtarget *Subtarget) {
21583   unsigned opcode;
21584
21585   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21586   // we're requiring SSE2 for both.
21587   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21588     SDValue N0 = N->getOperand(0);
21589     SDValue N1 = N->getOperand(1);
21590     SDValue CMP0 = N0->getOperand(1);
21591     SDValue CMP1 = N1->getOperand(1);
21592     SDLoc DL(N);
21593
21594     // The SETCCs should both refer to the same CMP.
21595     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21596       return SDValue();
21597
21598     SDValue CMP00 = CMP0->getOperand(0);
21599     SDValue CMP01 = CMP0->getOperand(1);
21600     EVT     VT    = CMP00.getValueType();
21601
21602     if (VT == MVT::f32 || VT == MVT::f64) {
21603       bool ExpectingFlags = false;
21604       // Check for any users that want flags:
21605       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21606            !ExpectingFlags && UI != UE; ++UI)
21607         switch (UI->getOpcode()) {
21608         default:
21609         case ISD::BR_CC:
21610         case ISD::BRCOND:
21611         case ISD::SELECT:
21612           ExpectingFlags = true;
21613           break;
21614         case ISD::CopyToReg:
21615         case ISD::SIGN_EXTEND:
21616         case ISD::ZERO_EXTEND:
21617         case ISD::ANY_EXTEND:
21618           break;
21619         }
21620
21621       if (!ExpectingFlags) {
21622         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21623         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21624
21625         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21626           X86::CondCode tmp = cc0;
21627           cc0 = cc1;
21628           cc1 = tmp;
21629         }
21630
21631         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21632             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21633           // FIXME: need symbolic constants for these magic numbers.
21634           // See X86ATTInstPrinter.cpp:printSSECC().
21635           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21636           if (Subtarget->hasAVX512()) {
21637             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21638                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21639             if (N->getValueType(0) != MVT::i1)
21640               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21641                                  FSetCC);
21642             return FSetCC;
21643           }
21644           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21645                                               CMP00.getValueType(), CMP00, CMP01,
21646                                               DAG.getConstant(x86cc, MVT::i8));
21647
21648           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21649           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21650
21651           if (is64BitFP && !Subtarget->is64Bit()) {
21652             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21653             // 64-bit integer, since that's not a legal type. Since
21654             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21655             // bits, but can do this little dance to extract the lowest 32 bits
21656             // and work with those going forward.
21657             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21658                                            OnesOrZeroesF);
21659             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21660                                            Vector64);
21661             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21662                                         Vector32, DAG.getIntPtrConstant(0));
21663             IntVT = MVT::i32;
21664           }
21665
21666           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21667           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21668                                       DAG.getConstant(1, IntVT));
21669           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21670           return OneBitOfTruth;
21671         }
21672       }
21673     }
21674   }
21675   return SDValue();
21676 }
21677
21678 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21679 /// so it can be folded inside ANDNP.
21680 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21681   EVT VT = N->getValueType(0);
21682
21683   // Match direct AllOnes for 128 and 256-bit vectors
21684   if (ISD::isBuildVectorAllOnes(N))
21685     return true;
21686
21687   // Look through a bit convert.
21688   if (N->getOpcode() == ISD::BITCAST)
21689     N = N->getOperand(0).getNode();
21690
21691   // Sometimes the operand may come from a insert_subvector building a 256-bit
21692   // allones vector
21693   if (VT.is256BitVector() &&
21694       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21695     SDValue V1 = N->getOperand(0);
21696     SDValue V2 = N->getOperand(1);
21697
21698     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21699         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21700         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21701         ISD::isBuildVectorAllOnes(V2.getNode()))
21702       return true;
21703   }
21704
21705   return false;
21706 }
21707
21708 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21709 // register. In most cases we actually compare or select YMM-sized registers
21710 // and mixing the two types creates horrible code. This method optimizes
21711 // some of the transition sequences.
21712 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21713                                  TargetLowering::DAGCombinerInfo &DCI,
21714                                  const X86Subtarget *Subtarget) {
21715   EVT VT = N->getValueType(0);
21716   if (!VT.is256BitVector())
21717     return SDValue();
21718
21719   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21720           N->getOpcode() == ISD::ZERO_EXTEND ||
21721           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21722
21723   SDValue Narrow = N->getOperand(0);
21724   EVT NarrowVT = Narrow->getValueType(0);
21725   if (!NarrowVT.is128BitVector())
21726     return SDValue();
21727
21728   if (Narrow->getOpcode() != ISD::XOR &&
21729       Narrow->getOpcode() != ISD::AND &&
21730       Narrow->getOpcode() != ISD::OR)
21731     return SDValue();
21732
21733   SDValue N0  = Narrow->getOperand(0);
21734   SDValue N1  = Narrow->getOperand(1);
21735   SDLoc DL(Narrow);
21736
21737   // The Left side has to be a trunc.
21738   if (N0.getOpcode() != ISD::TRUNCATE)
21739     return SDValue();
21740
21741   // The type of the truncated inputs.
21742   EVT WideVT = N0->getOperand(0)->getValueType(0);
21743   if (WideVT != VT)
21744     return SDValue();
21745
21746   // The right side has to be a 'trunc' or a constant vector.
21747   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21748   ConstantSDNode *RHSConstSplat = nullptr;
21749   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21750     RHSConstSplat = RHSBV->getConstantSplatNode();
21751   if (!RHSTrunc && !RHSConstSplat)
21752     return SDValue();
21753
21754   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21755
21756   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21757     return SDValue();
21758
21759   // Set N0 and N1 to hold the inputs to the new wide operation.
21760   N0 = N0->getOperand(0);
21761   if (RHSConstSplat) {
21762     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21763                      SDValue(RHSConstSplat, 0));
21764     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21765     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21766   } else if (RHSTrunc) {
21767     N1 = N1->getOperand(0);
21768   }
21769
21770   // Generate the wide operation.
21771   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21772   unsigned Opcode = N->getOpcode();
21773   switch (Opcode) {
21774   case ISD::ANY_EXTEND:
21775     return Op;
21776   case ISD::ZERO_EXTEND: {
21777     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21778     APInt Mask = APInt::getAllOnesValue(InBits);
21779     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21780     return DAG.getNode(ISD::AND, DL, VT,
21781                        Op, DAG.getConstant(Mask, VT));
21782   }
21783   case ISD::SIGN_EXTEND:
21784     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21785                        Op, DAG.getValueType(NarrowVT));
21786   default:
21787     llvm_unreachable("Unexpected opcode");
21788   }
21789 }
21790
21791 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21792                                  TargetLowering::DAGCombinerInfo &DCI,
21793                                  const X86Subtarget *Subtarget) {
21794   EVT VT = N->getValueType(0);
21795   if (DCI.isBeforeLegalizeOps())
21796     return SDValue();
21797
21798   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21799   if (R.getNode())
21800     return R;
21801
21802   // Create BEXTR instructions
21803   // BEXTR is ((X >> imm) & (2**size-1))
21804   if (VT == MVT::i32 || VT == MVT::i64) {
21805     SDValue N0 = N->getOperand(0);
21806     SDValue N1 = N->getOperand(1);
21807     SDLoc DL(N);
21808
21809     // Check for BEXTR.
21810     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21811         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21812       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21813       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21814       if (MaskNode && ShiftNode) {
21815         uint64_t Mask = MaskNode->getZExtValue();
21816         uint64_t Shift = ShiftNode->getZExtValue();
21817         if (isMask_64(Mask)) {
21818           uint64_t MaskSize = CountPopulation_64(Mask);
21819           if (Shift + MaskSize <= VT.getSizeInBits())
21820             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21821                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21822         }
21823       }
21824     } // BEXTR
21825
21826     return SDValue();
21827   }
21828
21829   // Want to form ANDNP nodes:
21830   // 1) In the hopes of then easily combining them with OR and AND nodes
21831   //    to form PBLEND/PSIGN.
21832   // 2) To match ANDN packed intrinsics
21833   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21834     return SDValue();
21835
21836   SDValue N0 = N->getOperand(0);
21837   SDValue N1 = N->getOperand(1);
21838   SDLoc DL(N);
21839
21840   // Check LHS for vnot
21841   if (N0.getOpcode() == ISD::XOR &&
21842       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21843       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21844     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21845
21846   // Check RHS for vnot
21847   if (N1.getOpcode() == ISD::XOR &&
21848       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21849       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21850     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21851
21852   return SDValue();
21853 }
21854
21855 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21856                                 TargetLowering::DAGCombinerInfo &DCI,
21857                                 const X86Subtarget *Subtarget) {
21858   if (DCI.isBeforeLegalizeOps())
21859     return SDValue();
21860
21861   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21862   if (R.getNode())
21863     return R;
21864
21865   SDValue N0 = N->getOperand(0);
21866   SDValue N1 = N->getOperand(1);
21867   EVT VT = N->getValueType(0);
21868
21869   // look for psign/blend
21870   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21871     if (!Subtarget->hasSSSE3() ||
21872         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21873       return SDValue();
21874
21875     // Canonicalize pandn to RHS
21876     if (N0.getOpcode() == X86ISD::ANDNP)
21877       std::swap(N0, N1);
21878     // or (and (m, y), (pandn m, x))
21879     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21880       SDValue Mask = N1.getOperand(0);
21881       SDValue X    = N1.getOperand(1);
21882       SDValue Y;
21883       if (N0.getOperand(0) == Mask)
21884         Y = N0.getOperand(1);
21885       if (N0.getOperand(1) == Mask)
21886         Y = N0.getOperand(0);
21887
21888       // Check to see if the mask appeared in both the AND and ANDNP and
21889       if (!Y.getNode())
21890         return SDValue();
21891
21892       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21893       // Look through mask bitcast.
21894       if (Mask.getOpcode() == ISD::BITCAST)
21895         Mask = Mask.getOperand(0);
21896       if (X.getOpcode() == ISD::BITCAST)
21897         X = X.getOperand(0);
21898       if (Y.getOpcode() == ISD::BITCAST)
21899         Y = Y.getOperand(0);
21900
21901       EVT MaskVT = Mask.getValueType();
21902
21903       // Validate that the Mask operand is a vector sra node.
21904       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21905       // there is no psrai.b
21906       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21907       unsigned SraAmt = ~0;
21908       if (Mask.getOpcode() == ISD::SRA) {
21909         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21910           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21911             SraAmt = AmtConst->getZExtValue();
21912       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21913         SDValue SraC = Mask.getOperand(1);
21914         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21915       }
21916       if ((SraAmt + 1) != EltBits)
21917         return SDValue();
21918
21919       SDLoc DL(N);
21920
21921       // Now we know we at least have a plendvb with the mask val.  See if
21922       // we can form a psignb/w/d.
21923       // psign = x.type == y.type == mask.type && y = sub(0, x);
21924       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21925           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21926           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21927         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21928                "Unsupported VT for PSIGN");
21929         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21930         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21931       }
21932       // PBLENDVB only available on SSE 4.1
21933       if (!Subtarget->hasSSE41())
21934         return SDValue();
21935
21936       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21937
21938       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21939       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21940       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21941       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21942       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21943     }
21944   }
21945
21946   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21947     return SDValue();
21948
21949   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21950   MachineFunction &MF = DAG.getMachineFunction();
21951   bool OptForSize = MF.getFunction()->getAttributes().
21952     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21953
21954   // SHLD/SHRD instructions have lower register pressure, but on some
21955   // platforms they have higher latency than the equivalent
21956   // series of shifts/or that would otherwise be generated.
21957   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21958   // have higher latencies and we are not optimizing for size.
21959   if (!OptForSize && Subtarget->isSHLDSlow())
21960     return SDValue();
21961
21962   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21963     std::swap(N0, N1);
21964   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21965     return SDValue();
21966   if (!N0.hasOneUse() || !N1.hasOneUse())
21967     return SDValue();
21968
21969   SDValue ShAmt0 = N0.getOperand(1);
21970   if (ShAmt0.getValueType() != MVT::i8)
21971     return SDValue();
21972   SDValue ShAmt1 = N1.getOperand(1);
21973   if (ShAmt1.getValueType() != MVT::i8)
21974     return SDValue();
21975   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21976     ShAmt0 = ShAmt0.getOperand(0);
21977   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21978     ShAmt1 = ShAmt1.getOperand(0);
21979
21980   SDLoc DL(N);
21981   unsigned Opc = X86ISD::SHLD;
21982   SDValue Op0 = N0.getOperand(0);
21983   SDValue Op1 = N1.getOperand(0);
21984   if (ShAmt0.getOpcode() == ISD::SUB) {
21985     Opc = X86ISD::SHRD;
21986     std::swap(Op0, Op1);
21987     std::swap(ShAmt0, ShAmt1);
21988   }
21989
21990   unsigned Bits = VT.getSizeInBits();
21991   if (ShAmt1.getOpcode() == ISD::SUB) {
21992     SDValue Sum = ShAmt1.getOperand(0);
21993     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21994       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21995       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21996         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21997       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21998         return DAG.getNode(Opc, DL, VT,
21999                            Op0, Op1,
22000                            DAG.getNode(ISD::TRUNCATE, DL,
22001                                        MVT::i8, ShAmt0));
22002     }
22003   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22004     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22005     if (ShAmt0C &&
22006         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22007       return DAG.getNode(Opc, DL, VT,
22008                          N0.getOperand(0), N1.getOperand(0),
22009                          DAG.getNode(ISD::TRUNCATE, DL,
22010                                        MVT::i8, ShAmt0));
22011   }
22012
22013   return SDValue();
22014 }
22015
22016 // Generate NEG and CMOV for integer abs.
22017 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22018   EVT VT = N->getValueType(0);
22019
22020   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22021   // 8-bit integer abs to NEG and CMOV.
22022   if (VT.isInteger() && VT.getSizeInBits() == 8)
22023     return SDValue();
22024
22025   SDValue N0 = N->getOperand(0);
22026   SDValue N1 = N->getOperand(1);
22027   SDLoc DL(N);
22028
22029   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22030   // and change it to SUB and CMOV.
22031   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22032       N0.getOpcode() == ISD::ADD &&
22033       N0.getOperand(1) == N1 &&
22034       N1.getOpcode() == ISD::SRA &&
22035       N1.getOperand(0) == N0.getOperand(0))
22036     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22037       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22038         // Generate SUB & CMOV.
22039         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22040                                   DAG.getConstant(0, VT), N0.getOperand(0));
22041
22042         SDValue Ops[] = { N0.getOperand(0), Neg,
22043                           DAG.getConstant(X86::COND_GE, MVT::i8),
22044                           SDValue(Neg.getNode(), 1) };
22045         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22046       }
22047   return SDValue();
22048 }
22049
22050 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22051 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22052                                  TargetLowering::DAGCombinerInfo &DCI,
22053                                  const X86Subtarget *Subtarget) {
22054   if (DCI.isBeforeLegalizeOps())
22055     return SDValue();
22056
22057   if (Subtarget->hasCMov()) {
22058     SDValue RV = performIntegerAbsCombine(N, DAG);
22059     if (RV.getNode())
22060       return RV;
22061   }
22062
22063   return SDValue();
22064 }
22065
22066 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22067 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22068                                   TargetLowering::DAGCombinerInfo &DCI,
22069                                   const X86Subtarget *Subtarget) {
22070   LoadSDNode *Ld = cast<LoadSDNode>(N);
22071   EVT RegVT = Ld->getValueType(0);
22072   EVT MemVT = Ld->getMemoryVT();
22073   SDLoc dl(Ld);
22074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22075
22076   // On Sandybridge unaligned 256bit loads are inefficient.
22077   ISD::LoadExtType Ext = Ld->getExtensionType();
22078   unsigned Alignment = Ld->getAlignment();
22079   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22080   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
22081       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22082     unsigned NumElems = RegVT.getVectorNumElements();
22083     if (NumElems < 2)
22084       return SDValue();
22085
22086     SDValue Ptr = Ld->getBasePtr();
22087     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22088
22089     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22090                                   NumElems/2);
22091     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22092                                 Ld->getPointerInfo(), Ld->isVolatile(),
22093                                 Ld->isNonTemporal(), Ld->isInvariant(),
22094                                 Alignment);
22095     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22096     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22097                                 Ld->getPointerInfo(), Ld->isVolatile(),
22098                                 Ld->isNonTemporal(), Ld->isInvariant(),
22099                                 std::min(16U, Alignment));
22100     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22101                              Load1.getValue(1),
22102                              Load2.getValue(1));
22103
22104     SDValue NewVec = DAG.getUNDEF(RegVT);
22105     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22106     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22107     return DCI.CombineTo(N, NewVec, TF, true);
22108   }
22109
22110   return SDValue();
22111 }
22112
22113 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22114 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22115                                    const X86Subtarget *Subtarget) {
22116   StoreSDNode *St = cast<StoreSDNode>(N);
22117   EVT VT = St->getValue().getValueType();
22118   EVT StVT = St->getMemoryVT();
22119   SDLoc dl(St);
22120   SDValue StoredVal = St->getOperand(1);
22121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22122
22123   // If we are saving a concatenation of two XMM registers, perform two stores.
22124   // On Sandy Bridge, 256-bit memory operations are executed by two
22125   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
22126   // memory  operation.
22127   unsigned Alignment = St->getAlignment();
22128   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22129   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
22130       StVT == VT && !IsAligned) {
22131     unsigned NumElems = VT.getVectorNumElements();
22132     if (NumElems < 2)
22133       return SDValue();
22134
22135     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22136     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22137
22138     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22139     SDValue Ptr0 = St->getBasePtr();
22140     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22141
22142     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22143                                 St->getPointerInfo(), St->isVolatile(),
22144                                 St->isNonTemporal(), Alignment);
22145     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22146                                 St->getPointerInfo(), St->isVolatile(),
22147                                 St->isNonTemporal(),
22148                                 std::min(16U, Alignment));
22149     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22150   }
22151
22152   // Optimize trunc store (of multiple scalars) to shuffle and store.
22153   // First, pack all of the elements in one place. Next, store to memory
22154   // in fewer chunks.
22155   if (St->isTruncatingStore() && VT.isVector()) {
22156     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22157     unsigned NumElems = VT.getVectorNumElements();
22158     assert(StVT != VT && "Cannot truncate to the same type");
22159     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22160     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22161
22162     // From, To sizes and ElemCount must be pow of two
22163     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22164     // We are going to use the original vector elt for storing.
22165     // Accumulated smaller vector elements must be a multiple of the store size.
22166     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22167
22168     unsigned SizeRatio  = FromSz / ToSz;
22169
22170     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22171
22172     // Create a type on which we perform the shuffle
22173     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22174             StVT.getScalarType(), NumElems*SizeRatio);
22175
22176     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22177
22178     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22179     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22180     for (unsigned i = 0; i != NumElems; ++i)
22181       ShuffleVec[i] = i * SizeRatio;
22182
22183     // Can't shuffle using an illegal type.
22184     if (!TLI.isTypeLegal(WideVecVT))
22185       return SDValue();
22186
22187     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22188                                          DAG.getUNDEF(WideVecVT),
22189                                          &ShuffleVec[0]);
22190     // At this point all of the data is stored at the bottom of the
22191     // register. We now need to save it to mem.
22192
22193     // Find the largest store unit
22194     MVT StoreType = MVT::i8;
22195     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
22196          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
22197       MVT Tp = (MVT::SimpleValueType)tp;
22198       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22199         StoreType = Tp;
22200     }
22201
22202     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22203     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22204         (64 <= NumElems * ToSz))
22205       StoreType = MVT::f64;
22206
22207     // Bitcast the original vector into a vector of store-size units
22208     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22209             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22210     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22211     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22212     SmallVector<SDValue, 8> Chains;
22213     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22214                                         TLI.getPointerTy());
22215     SDValue Ptr = St->getBasePtr();
22216
22217     // Perform one or more big stores into memory.
22218     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22219       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22220                                    StoreType, ShuffWide,
22221                                    DAG.getIntPtrConstant(i));
22222       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22223                                 St->getPointerInfo(), St->isVolatile(),
22224                                 St->isNonTemporal(), St->getAlignment());
22225       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22226       Chains.push_back(Ch);
22227     }
22228
22229     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22230   }
22231
22232   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22233   // the FP state in cases where an emms may be missing.
22234   // A preferable solution to the general problem is to figure out the right
22235   // places to insert EMMS.  This qualifies as a quick hack.
22236
22237   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22238   if (VT.getSizeInBits() != 64)
22239     return SDValue();
22240
22241   const Function *F = DAG.getMachineFunction().getFunction();
22242   bool NoImplicitFloatOps = F->getAttributes().
22243     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
22244   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22245                      && Subtarget->hasSSE2();
22246   if ((VT.isVector() ||
22247        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22248       isa<LoadSDNode>(St->getValue()) &&
22249       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22250       St->getChain().hasOneUse() && !St->isVolatile()) {
22251     SDNode* LdVal = St->getValue().getNode();
22252     LoadSDNode *Ld = nullptr;
22253     int TokenFactorIndex = -1;
22254     SmallVector<SDValue, 8> Ops;
22255     SDNode* ChainVal = St->getChain().getNode();
22256     // Must be a store of a load.  We currently handle two cases:  the load
22257     // is a direct child, and it's under an intervening TokenFactor.  It is
22258     // possible to dig deeper under nested TokenFactors.
22259     if (ChainVal == LdVal)
22260       Ld = cast<LoadSDNode>(St->getChain());
22261     else if (St->getValue().hasOneUse() &&
22262              ChainVal->getOpcode() == ISD::TokenFactor) {
22263       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22264         if (ChainVal->getOperand(i).getNode() == LdVal) {
22265           TokenFactorIndex = i;
22266           Ld = cast<LoadSDNode>(St->getValue());
22267         } else
22268           Ops.push_back(ChainVal->getOperand(i));
22269       }
22270     }
22271
22272     if (!Ld || !ISD::isNormalLoad(Ld))
22273       return SDValue();
22274
22275     // If this is not the MMX case, i.e. we are just turning i64 load/store
22276     // into f64 load/store, avoid the transformation if there are multiple
22277     // uses of the loaded value.
22278     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22279       return SDValue();
22280
22281     SDLoc LdDL(Ld);
22282     SDLoc StDL(N);
22283     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22284     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22285     // pair instead.
22286     if (Subtarget->is64Bit() || F64IsLegal) {
22287       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22288       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22289                                   Ld->getPointerInfo(), Ld->isVolatile(),
22290                                   Ld->isNonTemporal(), Ld->isInvariant(),
22291                                   Ld->getAlignment());
22292       SDValue NewChain = NewLd.getValue(1);
22293       if (TokenFactorIndex != -1) {
22294         Ops.push_back(NewChain);
22295         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22296       }
22297       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22298                           St->getPointerInfo(),
22299                           St->isVolatile(), St->isNonTemporal(),
22300                           St->getAlignment());
22301     }
22302
22303     // Otherwise, lower to two pairs of 32-bit loads / stores.
22304     SDValue LoAddr = Ld->getBasePtr();
22305     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22306                                  DAG.getConstant(4, MVT::i32));
22307
22308     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22309                                Ld->getPointerInfo(),
22310                                Ld->isVolatile(), Ld->isNonTemporal(),
22311                                Ld->isInvariant(), Ld->getAlignment());
22312     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22313                                Ld->getPointerInfo().getWithOffset(4),
22314                                Ld->isVolatile(), Ld->isNonTemporal(),
22315                                Ld->isInvariant(),
22316                                MinAlign(Ld->getAlignment(), 4));
22317
22318     SDValue NewChain = LoLd.getValue(1);
22319     if (TokenFactorIndex != -1) {
22320       Ops.push_back(LoLd);
22321       Ops.push_back(HiLd);
22322       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22323     }
22324
22325     LoAddr = St->getBasePtr();
22326     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22327                          DAG.getConstant(4, MVT::i32));
22328
22329     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22330                                 St->getPointerInfo(),
22331                                 St->isVolatile(), St->isNonTemporal(),
22332                                 St->getAlignment());
22333     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22334                                 St->getPointerInfo().getWithOffset(4),
22335                                 St->isVolatile(),
22336                                 St->isNonTemporal(),
22337                                 MinAlign(St->getAlignment(), 4));
22338     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22339   }
22340   return SDValue();
22341 }
22342
22343 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22344 /// and return the operands for the horizontal operation in LHS and RHS.  A
22345 /// horizontal operation performs the binary operation on successive elements
22346 /// of its first operand, then on successive elements of its second operand,
22347 /// returning the resulting values in a vector.  For example, if
22348 ///   A = < float a0, float a1, float a2, float a3 >
22349 /// and
22350 ///   B = < float b0, float b1, float b2, float b3 >
22351 /// then the result of doing a horizontal operation on A and B is
22352 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22353 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22354 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22355 /// set to A, RHS to B, and the routine returns 'true'.
22356 /// Note that the binary operation should have the property that if one of the
22357 /// operands is UNDEF then the result is UNDEF.
22358 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22359   // Look for the following pattern: if
22360   //   A = < float a0, float a1, float a2, float a3 >
22361   //   B = < float b0, float b1, float b2, float b3 >
22362   // and
22363   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22364   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22365   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22366   // which is A horizontal-op B.
22367
22368   // At least one of the operands should be a vector shuffle.
22369   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22370       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22371     return false;
22372
22373   MVT VT = LHS.getSimpleValueType();
22374
22375   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22376          "Unsupported vector type for horizontal add/sub");
22377
22378   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22379   // operate independently on 128-bit lanes.
22380   unsigned NumElts = VT.getVectorNumElements();
22381   unsigned NumLanes = VT.getSizeInBits()/128;
22382   unsigned NumLaneElts = NumElts / NumLanes;
22383   assert((NumLaneElts % 2 == 0) &&
22384          "Vector type should have an even number of elements in each lane");
22385   unsigned HalfLaneElts = NumLaneElts/2;
22386
22387   // View LHS in the form
22388   //   LHS = VECTOR_SHUFFLE A, B, LMask
22389   // If LHS is not a shuffle then pretend it is the shuffle
22390   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22391   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22392   // type VT.
22393   SDValue A, B;
22394   SmallVector<int, 16> LMask(NumElts);
22395   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22396     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22397       A = LHS.getOperand(0);
22398     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22399       B = LHS.getOperand(1);
22400     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22401     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22402   } else {
22403     if (LHS.getOpcode() != ISD::UNDEF)
22404       A = LHS;
22405     for (unsigned i = 0; i != NumElts; ++i)
22406       LMask[i] = i;
22407   }
22408
22409   // Likewise, view RHS in the form
22410   //   RHS = VECTOR_SHUFFLE C, D, RMask
22411   SDValue C, D;
22412   SmallVector<int, 16> RMask(NumElts);
22413   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22414     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22415       C = RHS.getOperand(0);
22416     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22417       D = RHS.getOperand(1);
22418     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22419     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22420   } else {
22421     if (RHS.getOpcode() != ISD::UNDEF)
22422       C = RHS;
22423     for (unsigned i = 0; i != NumElts; ++i)
22424       RMask[i] = i;
22425   }
22426
22427   // Check that the shuffles are both shuffling the same vectors.
22428   if (!(A == C && B == D) && !(A == D && B == C))
22429     return false;
22430
22431   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22432   if (!A.getNode() && !B.getNode())
22433     return false;
22434
22435   // If A and B occur in reverse order in RHS, then "swap" them (which means
22436   // rewriting the mask).
22437   if (A != C)
22438     CommuteVectorShuffleMask(RMask, NumElts);
22439
22440   // At this point LHS and RHS are equivalent to
22441   //   LHS = VECTOR_SHUFFLE A, B, LMask
22442   //   RHS = VECTOR_SHUFFLE A, B, RMask
22443   // Check that the masks correspond to performing a horizontal operation.
22444   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22445     for (unsigned i = 0; i != NumLaneElts; ++i) {
22446       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22447
22448       // Ignore any UNDEF components.
22449       if (LIdx < 0 || RIdx < 0 ||
22450           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22451           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22452         continue;
22453
22454       // Check that successive elements are being operated on.  If not, this is
22455       // not a horizontal operation.
22456       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22457       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22458       if (!(LIdx == Index && RIdx == Index + 1) &&
22459           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22460         return false;
22461     }
22462   }
22463
22464   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22465   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22466   return true;
22467 }
22468
22469 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22470 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22471                                   const X86Subtarget *Subtarget) {
22472   EVT VT = N->getValueType(0);
22473   SDValue LHS = N->getOperand(0);
22474   SDValue RHS = N->getOperand(1);
22475
22476   // Try to synthesize horizontal adds from adds of shuffles.
22477   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22478        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22479       isHorizontalBinOp(LHS, RHS, true))
22480     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22481   return SDValue();
22482 }
22483
22484 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22485 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22486                                   const X86Subtarget *Subtarget) {
22487   EVT VT = N->getValueType(0);
22488   SDValue LHS = N->getOperand(0);
22489   SDValue RHS = N->getOperand(1);
22490
22491   // Try to synthesize horizontal subs from subs of shuffles.
22492   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22493        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22494       isHorizontalBinOp(LHS, RHS, false))
22495     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22496   return SDValue();
22497 }
22498
22499 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22500 /// X86ISD::FXOR nodes.
22501 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22502   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22503   // F[X]OR(0.0, x) -> x
22504   // F[X]OR(x, 0.0) -> x
22505   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22506     if (C->getValueAPF().isPosZero())
22507       return N->getOperand(1);
22508   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22509     if (C->getValueAPF().isPosZero())
22510       return N->getOperand(0);
22511   return SDValue();
22512 }
22513
22514 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22515 /// X86ISD::FMAX nodes.
22516 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22517   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22518
22519   // Only perform optimizations if UnsafeMath is used.
22520   if (!DAG.getTarget().Options.UnsafeFPMath)
22521     return SDValue();
22522
22523   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22524   // into FMINC and FMAXC, which are Commutative operations.
22525   unsigned NewOp = 0;
22526   switch (N->getOpcode()) {
22527     default: llvm_unreachable("unknown opcode");
22528     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22529     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22530   }
22531
22532   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22533                      N->getOperand(0), N->getOperand(1));
22534 }
22535
22536 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22537 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22538   // FAND(0.0, x) -> 0.0
22539   // FAND(x, 0.0) -> 0.0
22540   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22541     if (C->getValueAPF().isPosZero())
22542       return N->getOperand(0);
22543   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22544     if (C->getValueAPF().isPosZero())
22545       return N->getOperand(1);
22546   return SDValue();
22547 }
22548
22549 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22550 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22551   // FANDN(x, 0.0) -> 0.0
22552   // FANDN(0.0, x) -> x
22553   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22554     if (C->getValueAPF().isPosZero())
22555       return N->getOperand(1);
22556   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22557     if (C->getValueAPF().isPosZero())
22558       return N->getOperand(1);
22559   return SDValue();
22560 }
22561
22562 static SDValue PerformBTCombine(SDNode *N,
22563                                 SelectionDAG &DAG,
22564                                 TargetLowering::DAGCombinerInfo &DCI) {
22565   // BT ignores high bits in the bit index operand.
22566   SDValue Op1 = N->getOperand(1);
22567   if (Op1.hasOneUse()) {
22568     unsigned BitWidth = Op1.getValueSizeInBits();
22569     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22570     APInt KnownZero, KnownOne;
22571     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22572                                           !DCI.isBeforeLegalizeOps());
22573     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22574     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22575         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22576       DCI.CommitTargetLoweringOpt(TLO);
22577   }
22578   return SDValue();
22579 }
22580
22581 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22582   SDValue Op = N->getOperand(0);
22583   if (Op.getOpcode() == ISD::BITCAST)
22584     Op = Op.getOperand(0);
22585   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22586   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22587       VT.getVectorElementType().getSizeInBits() ==
22588       OpVT.getVectorElementType().getSizeInBits()) {
22589     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22590   }
22591   return SDValue();
22592 }
22593
22594 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22595                                                const X86Subtarget *Subtarget) {
22596   EVT VT = N->getValueType(0);
22597   if (!VT.isVector())
22598     return SDValue();
22599
22600   SDValue N0 = N->getOperand(0);
22601   SDValue N1 = N->getOperand(1);
22602   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22603   SDLoc dl(N);
22604
22605   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22606   // both SSE and AVX2 since there is no sign-extended shift right
22607   // operation on a vector with 64-bit elements.
22608   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22609   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22610   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22611       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22612     SDValue N00 = N0.getOperand(0);
22613
22614     // EXTLOAD has a better solution on AVX2,
22615     // it may be replaced with X86ISD::VSEXT node.
22616     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22617       if (!ISD::isNormalLoad(N00.getNode()))
22618         return SDValue();
22619
22620     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22621         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22622                                   N00, N1);
22623       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22624     }
22625   }
22626   return SDValue();
22627 }
22628
22629 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22630                                   TargetLowering::DAGCombinerInfo &DCI,
22631                                   const X86Subtarget *Subtarget) {
22632   if (!DCI.isBeforeLegalizeOps())
22633     return SDValue();
22634
22635   if (!Subtarget->hasFp256())
22636     return SDValue();
22637
22638   EVT VT = N->getValueType(0);
22639   if (VT.isVector() && VT.getSizeInBits() == 256) {
22640     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22641     if (R.getNode())
22642       return R;
22643   }
22644
22645   return SDValue();
22646 }
22647
22648 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22649                                  const X86Subtarget* Subtarget) {
22650   SDLoc dl(N);
22651   EVT VT = N->getValueType(0);
22652
22653   // Let legalize expand this if it isn't a legal type yet.
22654   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22655     return SDValue();
22656
22657   EVT ScalarVT = VT.getScalarType();
22658   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22659       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22660     return SDValue();
22661
22662   SDValue A = N->getOperand(0);
22663   SDValue B = N->getOperand(1);
22664   SDValue C = N->getOperand(2);
22665
22666   bool NegA = (A.getOpcode() == ISD::FNEG);
22667   bool NegB = (B.getOpcode() == ISD::FNEG);
22668   bool NegC = (C.getOpcode() == ISD::FNEG);
22669
22670   // Negative multiplication when NegA xor NegB
22671   bool NegMul = (NegA != NegB);
22672   if (NegA)
22673     A = A.getOperand(0);
22674   if (NegB)
22675     B = B.getOperand(0);
22676   if (NegC)
22677     C = C.getOperand(0);
22678
22679   unsigned Opcode;
22680   if (!NegMul)
22681     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22682   else
22683     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22684
22685   return DAG.getNode(Opcode, dl, VT, A, B, C);
22686 }
22687
22688 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22689                                   TargetLowering::DAGCombinerInfo &DCI,
22690                                   const X86Subtarget *Subtarget) {
22691   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22692   //           (and (i32 x86isd::setcc_carry), 1)
22693   // This eliminates the zext. This transformation is necessary because
22694   // ISD::SETCC is always legalized to i8.
22695   SDLoc dl(N);
22696   SDValue N0 = N->getOperand(0);
22697   EVT VT = N->getValueType(0);
22698
22699   if (N0.getOpcode() == ISD::AND &&
22700       N0.hasOneUse() &&
22701       N0.getOperand(0).hasOneUse()) {
22702     SDValue N00 = N0.getOperand(0);
22703     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22704       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22705       if (!C || C->getZExtValue() != 1)
22706         return SDValue();
22707       return DAG.getNode(ISD::AND, dl, VT,
22708                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22709                                      N00.getOperand(0), N00.getOperand(1)),
22710                          DAG.getConstant(1, VT));
22711     }
22712   }
22713
22714   if (N0.getOpcode() == ISD::TRUNCATE &&
22715       N0.hasOneUse() &&
22716       N0.getOperand(0).hasOneUse()) {
22717     SDValue N00 = N0.getOperand(0);
22718     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22719       return DAG.getNode(ISD::AND, dl, VT,
22720                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22721                                      N00.getOperand(0), N00.getOperand(1)),
22722                          DAG.getConstant(1, VT));
22723     }
22724   }
22725   if (VT.is256BitVector()) {
22726     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22727     if (R.getNode())
22728       return R;
22729   }
22730
22731   return SDValue();
22732 }
22733
22734 // Optimize x == -y --> x+y == 0
22735 //          x != -y --> x+y != 0
22736 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22737                                       const X86Subtarget* Subtarget) {
22738   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22739   SDValue LHS = N->getOperand(0);
22740   SDValue RHS = N->getOperand(1);
22741   EVT VT = N->getValueType(0);
22742   SDLoc DL(N);
22743
22744   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22745     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22746       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22747         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22748                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22749         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22750                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22751       }
22752   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22753     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22754       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22755         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22756                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22757         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22758                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22759       }
22760
22761   if (VT.getScalarType() == MVT::i1) {
22762     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22763       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22764     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22765     if (!IsSEXT0 && !IsVZero0)
22766       return SDValue();
22767     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22768       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22769     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22770
22771     if (!IsSEXT1 && !IsVZero1)
22772       return SDValue();
22773
22774     if (IsSEXT0 && IsVZero1) {
22775       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22776       if (CC == ISD::SETEQ)
22777         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22778       return LHS.getOperand(0);
22779     }
22780     if (IsSEXT1 && IsVZero0) {
22781       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22782       if (CC == ISD::SETEQ)
22783         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22784       return RHS.getOperand(0);
22785     }
22786   }
22787
22788   return SDValue();
22789 }
22790
22791 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22792                                       const X86Subtarget *Subtarget) {
22793   SDLoc dl(N);
22794   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22795   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22796          "X86insertps is only defined for v4x32");
22797
22798   SDValue Ld = N->getOperand(1);
22799   if (MayFoldLoad(Ld)) {
22800     // Extract the countS bits from the immediate so we can get the proper
22801     // address when narrowing the vector load to a specific element.
22802     // When the second source op is a memory address, interps doesn't use
22803     // countS and just gets an f32 from that address.
22804     unsigned DestIndex =
22805         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22806     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22807   } else
22808     return SDValue();
22809
22810   // Create this as a scalar to vector to match the instruction pattern.
22811   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22812   // countS bits are ignored when loading from memory on insertps, which
22813   // means we don't need to explicitly set them to 0.
22814   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22815                      LoadScalarToVector, N->getOperand(2));
22816 }
22817
22818 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22819 // as "sbb reg,reg", since it can be extended without zext and produces
22820 // an all-ones bit which is more useful than 0/1 in some cases.
22821 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22822                                MVT VT) {
22823   if (VT == MVT::i8)
22824     return DAG.getNode(ISD::AND, DL, VT,
22825                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22826                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22827                        DAG.getConstant(1, VT));
22828   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22829   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22830                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22831                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22832 }
22833
22834 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22835 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22836                                    TargetLowering::DAGCombinerInfo &DCI,
22837                                    const X86Subtarget *Subtarget) {
22838   SDLoc DL(N);
22839   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22840   SDValue EFLAGS = N->getOperand(1);
22841
22842   if (CC == X86::COND_A) {
22843     // Try to convert COND_A into COND_B in an attempt to facilitate
22844     // materializing "setb reg".
22845     //
22846     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22847     // cannot take an immediate as its first operand.
22848     //
22849     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22850         EFLAGS.getValueType().isInteger() &&
22851         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22852       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22853                                    EFLAGS.getNode()->getVTList(),
22854                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22855       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22856       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22857     }
22858   }
22859
22860   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22861   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22862   // cases.
22863   if (CC == X86::COND_B)
22864     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22865
22866   SDValue Flags;
22867
22868   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22869   if (Flags.getNode()) {
22870     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22871     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22872   }
22873
22874   return SDValue();
22875 }
22876
22877 // Optimize branch condition evaluation.
22878 //
22879 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22880                                     TargetLowering::DAGCombinerInfo &DCI,
22881                                     const X86Subtarget *Subtarget) {
22882   SDLoc DL(N);
22883   SDValue Chain = N->getOperand(0);
22884   SDValue Dest = N->getOperand(1);
22885   SDValue EFLAGS = N->getOperand(3);
22886   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22887
22888   SDValue Flags;
22889
22890   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22891   if (Flags.getNode()) {
22892     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22893     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22894                        Flags);
22895   }
22896
22897   return SDValue();
22898 }
22899
22900 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22901                                                          SelectionDAG &DAG) {
22902   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22903   // optimize away operation when it's from a constant.
22904   //
22905   // The general transformation is:
22906   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22907   //       AND(VECTOR_CMP(x,y), constant2)
22908   //    constant2 = UNARYOP(constant)
22909
22910   // Early exit if this isn't a vector operation, the operand of the
22911   // unary operation isn't a bitwise AND, or if the sizes of the operations
22912   // aren't the same.
22913   EVT VT = N->getValueType(0);
22914   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22915       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22916       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22917     return SDValue();
22918
22919   // Now check that the other operand of the AND is a constant. We could
22920   // make the transformation for non-constant splats as well, but it's unclear
22921   // that would be a benefit as it would not eliminate any operations, just
22922   // perform one more step in scalar code before moving to the vector unit.
22923   if (BuildVectorSDNode *BV =
22924           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22925     // Bail out if the vector isn't a constant.
22926     if (!BV->isConstant())
22927       return SDValue();
22928
22929     // Everything checks out. Build up the new and improved node.
22930     SDLoc DL(N);
22931     EVT IntVT = BV->getValueType(0);
22932     // Create a new constant of the appropriate type for the transformed
22933     // DAG.
22934     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22935     // The AND node needs bitcasts to/from an integer vector type around it.
22936     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22937     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22938                                  N->getOperand(0)->getOperand(0), MaskConst);
22939     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22940     return Res;
22941   }
22942
22943   return SDValue();
22944 }
22945
22946 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22947                                         const X86TargetLowering *XTLI) {
22948   // First try to optimize away the conversion entirely when it's
22949   // conditionally from a constant. Vectors only.
22950   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22951   if (Res != SDValue())
22952     return Res;
22953
22954   // Now move on to more general possibilities.
22955   SDValue Op0 = N->getOperand(0);
22956   EVT InVT = Op0->getValueType(0);
22957
22958   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22959   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22960     SDLoc dl(N);
22961     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22962     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22963     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22964   }
22965
22966   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22967   // a 32-bit target where SSE doesn't support i64->FP operations.
22968   if (Op0.getOpcode() == ISD::LOAD) {
22969     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22970     EVT VT = Ld->getValueType(0);
22971     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22972         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22973         !XTLI->getSubtarget()->is64Bit() &&
22974         VT == MVT::i64) {
22975       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22976                                           Ld->getChain(), Op0, DAG);
22977       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22978       return FILDChain;
22979     }
22980   }
22981   return SDValue();
22982 }
22983
22984 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22985 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22986                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22987   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22988   // the result is either zero or one (depending on the input carry bit).
22989   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22990   if (X86::isZeroNode(N->getOperand(0)) &&
22991       X86::isZeroNode(N->getOperand(1)) &&
22992       // We don't have a good way to replace an EFLAGS use, so only do this when
22993       // dead right now.
22994       SDValue(N, 1).use_empty()) {
22995     SDLoc DL(N);
22996     EVT VT = N->getValueType(0);
22997     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22998     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22999                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23000                                            DAG.getConstant(X86::COND_B,MVT::i8),
23001                                            N->getOperand(2)),
23002                                DAG.getConstant(1, VT));
23003     return DCI.CombineTo(N, Res1, CarryOut);
23004   }
23005
23006   return SDValue();
23007 }
23008
23009 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23010 //      (add Y, (setne X, 0)) -> sbb -1, Y
23011 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23012 //      (sub (setne X, 0), Y) -> adc -1, Y
23013 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23014   SDLoc DL(N);
23015
23016   // Look through ZExts.
23017   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23018   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23019     return SDValue();
23020
23021   SDValue SetCC = Ext.getOperand(0);
23022   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23023     return SDValue();
23024
23025   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23026   if (CC != X86::COND_E && CC != X86::COND_NE)
23027     return SDValue();
23028
23029   SDValue Cmp = SetCC.getOperand(1);
23030   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23031       !X86::isZeroNode(Cmp.getOperand(1)) ||
23032       !Cmp.getOperand(0).getValueType().isInteger())
23033     return SDValue();
23034
23035   SDValue CmpOp0 = Cmp.getOperand(0);
23036   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23037                                DAG.getConstant(1, CmpOp0.getValueType()));
23038
23039   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23040   if (CC == X86::COND_NE)
23041     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23042                        DL, OtherVal.getValueType(), OtherVal,
23043                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23044   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23045                      DL, OtherVal.getValueType(), OtherVal,
23046                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23047 }
23048
23049 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23050 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23051                                  const X86Subtarget *Subtarget) {
23052   EVT VT = N->getValueType(0);
23053   SDValue Op0 = N->getOperand(0);
23054   SDValue Op1 = N->getOperand(1);
23055
23056   // Try to synthesize horizontal adds from adds of shuffles.
23057   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23058        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23059       isHorizontalBinOp(Op0, Op1, true))
23060     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23061
23062   return OptimizeConditionalInDecrement(N, DAG);
23063 }
23064
23065 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23066                                  const X86Subtarget *Subtarget) {
23067   SDValue Op0 = N->getOperand(0);
23068   SDValue Op1 = N->getOperand(1);
23069
23070   // X86 can't encode an immediate LHS of a sub. See if we can push the
23071   // negation into a preceding instruction.
23072   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23073     // If the RHS of the sub is a XOR with one use and a constant, invert the
23074     // immediate. Then add one to the LHS of the sub so we can turn
23075     // X-Y -> X+~Y+1, saving one register.
23076     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23077         isa<ConstantSDNode>(Op1.getOperand(1))) {
23078       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23079       EVT VT = Op0.getValueType();
23080       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23081                                    Op1.getOperand(0),
23082                                    DAG.getConstant(~XorC, VT));
23083       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23084                          DAG.getConstant(C->getAPIntValue()+1, VT));
23085     }
23086   }
23087
23088   // Try to synthesize horizontal adds from adds of shuffles.
23089   EVT VT = N->getValueType(0);
23090   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23091        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23092       isHorizontalBinOp(Op0, Op1, true))
23093     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23094
23095   return OptimizeConditionalInDecrement(N, DAG);
23096 }
23097
23098 /// performVZEXTCombine - Performs build vector combines
23099 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23100                                         TargetLowering::DAGCombinerInfo &DCI,
23101                                         const X86Subtarget *Subtarget) {
23102   // (vzext (bitcast (vzext (x)) -> (vzext x)
23103   SDValue In = N->getOperand(0);
23104   while (In.getOpcode() == ISD::BITCAST)
23105     In = In.getOperand(0);
23106
23107   if (In.getOpcode() != X86ISD::VZEXT)
23108     return SDValue();
23109
23110   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
23111                      In.getOperand(0));
23112 }
23113
23114 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23115                                              DAGCombinerInfo &DCI) const {
23116   SelectionDAG &DAG = DCI.DAG;
23117   switch (N->getOpcode()) {
23118   default: break;
23119   case ISD::EXTRACT_VECTOR_ELT:
23120     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23121   case ISD::VSELECT:
23122   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23123   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23124   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23125   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23126   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23127   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23128   case ISD::SHL:
23129   case ISD::SRA:
23130   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23131   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23132   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23133   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23134   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23135   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23136   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
23137   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23138   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23139   case X86ISD::FXOR:
23140   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23141   case X86ISD::FMIN:
23142   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23143   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23144   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23145   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23146   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23147   case ISD::ANY_EXTEND:
23148   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23149   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23150   case ISD::SIGN_EXTEND_INREG:
23151     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23152   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23153   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23154   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23155   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23156   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23157   case X86ISD::SHUFP:       // Handle all target specific shuffles
23158   case X86ISD::PALIGNR:
23159   case X86ISD::UNPCKH:
23160   case X86ISD::UNPCKL:
23161   case X86ISD::MOVHLPS:
23162   case X86ISD::MOVLHPS:
23163   case X86ISD::PSHUFB:
23164   case X86ISD::PSHUFD:
23165   case X86ISD::PSHUFHW:
23166   case X86ISD::PSHUFLW:
23167   case X86ISD::MOVSS:
23168   case X86ISD::MOVSD:
23169   case X86ISD::VPERMILP:
23170   case X86ISD::VPERM2X128:
23171   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23172   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23173   case ISD::INTRINSIC_WO_CHAIN:
23174     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23175   case X86ISD::INSERTPS:
23176     return PerformINSERTPSCombine(N, DAG, Subtarget);
23177   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23178   }
23179
23180   return SDValue();
23181 }
23182
23183 /// isTypeDesirableForOp - Return true if the target has native support for
23184 /// the specified value type and it is 'desirable' to use the type for the
23185 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23186 /// instruction encodings are longer and some i16 instructions are slow.
23187 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23188   if (!isTypeLegal(VT))
23189     return false;
23190   if (VT != MVT::i16)
23191     return true;
23192
23193   switch (Opc) {
23194   default:
23195     return true;
23196   case ISD::LOAD:
23197   case ISD::SIGN_EXTEND:
23198   case ISD::ZERO_EXTEND:
23199   case ISD::ANY_EXTEND:
23200   case ISD::SHL:
23201   case ISD::SRL:
23202   case ISD::SUB:
23203   case ISD::ADD:
23204   case ISD::MUL:
23205   case ISD::AND:
23206   case ISD::OR:
23207   case ISD::XOR:
23208     return false;
23209   }
23210 }
23211
23212 /// IsDesirableToPromoteOp - This method query the target whether it is
23213 /// beneficial for dag combiner to promote the specified node. If true, it
23214 /// should return the desired promotion type by reference.
23215 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23216   EVT VT = Op.getValueType();
23217   if (VT != MVT::i16)
23218     return false;
23219
23220   bool Promote = false;
23221   bool Commute = false;
23222   switch (Op.getOpcode()) {
23223   default: break;
23224   case ISD::LOAD: {
23225     LoadSDNode *LD = cast<LoadSDNode>(Op);
23226     // If the non-extending load has a single use and it's not live out, then it
23227     // might be folded.
23228     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23229                                                      Op.hasOneUse()*/) {
23230       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23231              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23232         // The only case where we'd want to promote LOAD (rather then it being
23233         // promoted as an operand is when it's only use is liveout.
23234         if (UI->getOpcode() != ISD::CopyToReg)
23235           return false;
23236       }
23237     }
23238     Promote = true;
23239     break;
23240   }
23241   case ISD::SIGN_EXTEND:
23242   case ISD::ZERO_EXTEND:
23243   case ISD::ANY_EXTEND:
23244     Promote = true;
23245     break;
23246   case ISD::SHL:
23247   case ISD::SRL: {
23248     SDValue N0 = Op.getOperand(0);
23249     // Look out for (store (shl (load), x)).
23250     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23251       return false;
23252     Promote = true;
23253     break;
23254   }
23255   case ISD::ADD:
23256   case ISD::MUL:
23257   case ISD::AND:
23258   case ISD::OR:
23259   case ISD::XOR:
23260     Commute = true;
23261     // fallthrough
23262   case ISD::SUB: {
23263     SDValue N0 = Op.getOperand(0);
23264     SDValue N1 = Op.getOperand(1);
23265     if (!Commute && MayFoldLoad(N1))
23266       return false;
23267     // Avoid disabling potential load folding opportunities.
23268     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23269       return false;
23270     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23271       return false;
23272     Promote = true;
23273   }
23274   }
23275
23276   PVT = MVT::i32;
23277   return Promote;
23278 }
23279
23280 //===----------------------------------------------------------------------===//
23281 //                           X86 Inline Assembly Support
23282 //===----------------------------------------------------------------------===//
23283
23284 namespace {
23285   // Helper to match a string separated by whitespace.
23286   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23287     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23288
23289     for (unsigned i = 0, e = args.size(); i != e; ++i) {
23290       StringRef piece(*args[i]);
23291       if (!s.startswith(piece)) // Check if the piece matches.
23292         return false;
23293
23294       s = s.substr(piece.size());
23295       StringRef::size_type pos = s.find_first_not_of(" \t");
23296       if (pos == 0) // We matched a prefix.
23297         return false;
23298
23299       s = s.substr(pos);
23300     }
23301
23302     return s.empty();
23303   }
23304   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23305 }
23306
23307 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23308
23309   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23310     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23311         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23312         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23313
23314       if (AsmPieces.size() == 3)
23315         return true;
23316       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23317         return true;
23318     }
23319   }
23320   return false;
23321 }
23322
23323 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23324   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23325
23326   std::string AsmStr = IA->getAsmString();
23327
23328   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23329   if (!Ty || Ty->getBitWidth() % 16 != 0)
23330     return false;
23331
23332   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23333   SmallVector<StringRef, 4> AsmPieces;
23334   SplitString(AsmStr, AsmPieces, ";\n");
23335
23336   switch (AsmPieces.size()) {
23337   default: return false;
23338   case 1:
23339     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23340     // we will turn this bswap into something that will be lowered to logical
23341     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23342     // lower so don't worry about this.
23343     // bswap $0
23344     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23345         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23346         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23347         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23348         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23349         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23350       // No need to check constraints, nothing other than the equivalent of
23351       // "=r,0" would be valid here.
23352       return IntrinsicLowering::LowerToByteSwap(CI);
23353     }
23354
23355     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23356     if (CI->getType()->isIntegerTy(16) &&
23357         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23358         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23359          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23360       AsmPieces.clear();
23361       const std::string &ConstraintsStr = IA->getConstraintString();
23362       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23363       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23364       if (clobbersFlagRegisters(AsmPieces))
23365         return IntrinsicLowering::LowerToByteSwap(CI);
23366     }
23367     break;
23368   case 3:
23369     if (CI->getType()->isIntegerTy(32) &&
23370         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23371         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23372         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23373         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23374       AsmPieces.clear();
23375       const std::string &ConstraintsStr = IA->getConstraintString();
23376       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23377       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23378       if (clobbersFlagRegisters(AsmPieces))
23379         return IntrinsicLowering::LowerToByteSwap(CI);
23380     }
23381
23382     if (CI->getType()->isIntegerTy(64)) {
23383       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23384       if (Constraints.size() >= 2 &&
23385           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23386           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23387         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23388         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23389             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23390             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23391           return IntrinsicLowering::LowerToByteSwap(CI);
23392       }
23393     }
23394     break;
23395   }
23396   return false;
23397 }
23398
23399 /// getConstraintType - Given a constraint letter, return the type of
23400 /// constraint it is for this target.
23401 X86TargetLowering::ConstraintType
23402 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23403   if (Constraint.size() == 1) {
23404     switch (Constraint[0]) {
23405     case 'R':
23406     case 'q':
23407     case 'Q':
23408     case 'f':
23409     case 't':
23410     case 'u':
23411     case 'y':
23412     case 'x':
23413     case 'Y':
23414     case 'l':
23415       return C_RegisterClass;
23416     case 'a':
23417     case 'b':
23418     case 'c':
23419     case 'd':
23420     case 'S':
23421     case 'D':
23422     case 'A':
23423       return C_Register;
23424     case 'I':
23425     case 'J':
23426     case 'K':
23427     case 'L':
23428     case 'M':
23429     case 'N':
23430     case 'G':
23431     case 'C':
23432     case 'e':
23433     case 'Z':
23434       return C_Other;
23435     default:
23436       break;
23437     }
23438   }
23439   return TargetLowering::getConstraintType(Constraint);
23440 }
23441
23442 /// Examine constraint type and operand type and determine a weight value.
23443 /// This object must already have been set up with the operand type
23444 /// and the current alternative constraint selected.
23445 TargetLowering::ConstraintWeight
23446   X86TargetLowering::getSingleConstraintMatchWeight(
23447     AsmOperandInfo &info, const char *constraint) const {
23448   ConstraintWeight weight = CW_Invalid;
23449   Value *CallOperandVal = info.CallOperandVal;
23450     // If we don't have a value, we can't do a match,
23451     // but allow it at the lowest weight.
23452   if (!CallOperandVal)
23453     return CW_Default;
23454   Type *type = CallOperandVal->getType();
23455   // Look at the constraint type.
23456   switch (*constraint) {
23457   default:
23458     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23459   case 'R':
23460   case 'q':
23461   case 'Q':
23462   case 'a':
23463   case 'b':
23464   case 'c':
23465   case 'd':
23466   case 'S':
23467   case 'D':
23468   case 'A':
23469     if (CallOperandVal->getType()->isIntegerTy())
23470       weight = CW_SpecificReg;
23471     break;
23472   case 'f':
23473   case 't':
23474   case 'u':
23475     if (type->isFloatingPointTy())
23476       weight = CW_SpecificReg;
23477     break;
23478   case 'y':
23479     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23480       weight = CW_SpecificReg;
23481     break;
23482   case 'x':
23483   case 'Y':
23484     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23485         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23486       weight = CW_Register;
23487     break;
23488   case 'I':
23489     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23490       if (C->getZExtValue() <= 31)
23491         weight = CW_Constant;
23492     }
23493     break;
23494   case 'J':
23495     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23496       if (C->getZExtValue() <= 63)
23497         weight = CW_Constant;
23498     }
23499     break;
23500   case 'K':
23501     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23502       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23503         weight = CW_Constant;
23504     }
23505     break;
23506   case 'L':
23507     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23508       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23509         weight = CW_Constant;
23510     }
23511     break;
23512   case 'M':
23513     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23514       if (C->getZExtValue() <= 3)
23515         weight = CW_Constant;
23516     }
23517     break;
23518   case 'N':
23519     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23520       if (C->getZExtValue() <= 0xff)
23521         weight = CW_Constant;
23522     }
23523     break;
23524   case 'G':
23525   case 'C':
23526     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23527       weight = CW_Constant;
23528     }
23529     break;
23530   case 'e':
23531     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23532       if ((C->getSExtValue() >= -0x80000000LL) &&
23533           (C->getSExtValue() <= 0x7fffffffLL))
23534         weight = CW_Constant;
23535     }
23536     break;
23537   case 'Z':
23538     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23539       if (C->getZExtValue() <= 0xffffffff)
23540         weight = CW_Constant;
23541     }
23542     break;
23543   }
23544   return weight;
23545 }
23546
23547 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23548 /// with another that has more specific requirements based on the type of the
23549 /// corresponding operand.
23550 const char *X86TargetLowering::
23551 LowerXConstraint(EVT ConstraintVT) const {
23552   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23553   // 'f' like normal targets.
23554   if (ConstraintVT.isFloatingPoint()) {
23555     if (Subtarget->hasSSE2())
23556       return "Y";
23557     if (Subtarget->hasSSE1())
23558       return "x";
23559   }
23560
23561   return TargetLowering::LowerXConstraint(ConstraintVT);
23562 }
23563
23564 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23565 /// vector.  If it is invalid, don't add anything to Ops.
23566 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23567                                                      std::string &Constraint,
23568                                                      std::vector<SDValue>&Ops,
23569                                                      SelectionDAG &DAG) const {
23570   SDValue Result;
23571
23572   // Only support length 1 constraints for now.
23573   if (Constraint.length() > 1) return;
23574
23575   char ConstraintLetter = Constraint[0];
23576   switch (ConstraintLetter) {
23577   default: break;
23578   case 'I':
23579     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23580       if (C->getZExtValue() <= 31) {
23581         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23582         break;
23583       }
23584     }
23585     return;
23586   case 'J':
23587     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23588       if (C->getZExtValue() <= 63) {
23589         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23590         break;
23591       }
23592     }
23593     return;
23594   case 'K':
23595     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23596       if (isInt<8>(C->getSExtValue())) {
23597         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23598         break;
23599       }
23600     }
23601     return;
23602   case 'N':
23603     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23604       if (C->getZExtValue() <= 255) {
23605         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23606         break;
23607       }
23608     }
23609     return;
23610   case 'e': {
23611     // 32-bit signed value
23612     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23613       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23614                                            C->getSExtValue())) {
23615         // Widen to 64 bits here to get it sign extended.
23616         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23617         break;
23618       }
23619     // FIXME gcc accepts some relocatable values here too, but only in certain
23620     // memory models; it's complicated.
23621     }
23622     return;
23623   }
23624   case 'Z': {
23625     // 32-bit unsigned value
23626     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23627       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23628                                            C->getZExtValue())) {
23629         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23630         break;
23631       }
23632     }
23633     // FIXME gcc accepts some relocatable values here too, but only in certain
23634     // memory models; it's complicated.
23635     return;
23636   }
23637   case 'i': {
23638     // Literal immediates are always ok.
23639     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23640       // Widen to 64 bits here to get it sign extended.
23641       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23642       break;
23643     }
23644
23645     // In any sort of PIC mode addresses need to be computed at runtime by
23646     // adding in a register or some sort of table lookup.  These can't
23647     // be used as immediates.
23648     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23649       return;
23650
23651     // If we are in non-pic codegen mode, we allow the address of a global (with
23652     // an optional displacement) to be used with 'i'.
23653     GlobalAddressSDNode *GA = nullptr;
23654     int64_t Offset = 0;
23655
23656     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23657     while (1) {
23658       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23659         Offset += GA->getOffset();
23660         break;
23661       } else if (Op.getOpcode() == ISD::ADD) {
23662         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23663           Offset += C->getZExtValue();
23664           Op = Op.getOperand(0);
23665           continue;
23666         }
23667       } else if (Op.getOpcode() == ISD::SUB) {
23668         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23669           Offset += -C->getZExtValue();
23670           Op = Op.getOperand(0);
23671           continue;
23672         }
23673       }
23674
23675       // Otherwise, this isn't something we can handle, reject it.
23676       return;
23677     }
23678
23679     const GlobalValue *GV = GA->getGlobal();
23680     // If we require an extra load to get this address, as in PIC mode, we
23681     // can't accept it.
23682     if (isGlobalStubReference(
23683             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23684       return;
23685
23686     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23687                                         GA->getValueType(0), Offset);
23688     break;
23689   }
23690   }
23691
23692   if (Result.getNode()) {
23693     Ops.push_back(Result);
23694     return;
23695   }
23696   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23697 }
23698
23699 std::pair<unsigned, const TargetRegisterClass*>
23700 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23701                                                 MVT VT) const {
23702   // First, see if this is a constraint that directly corresponds to an LLVM
23703   // register class.
23704   if (Constraint.size() == 1) {
23705     // GCC Constraint Letters
23706     switch (Constraint[0]) {
23707     default: break;
23708       // TODO: Slight differences here in allocation order and leaving
23709       // RIP in the class. Do they matter any more here than they do
23710       // in the normal allocation?
23711     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23712       if (Subtarget->is64Bit()) {
23713         if (VT == MVT::i32 || VT == MVT::f32)
23714           return std::make_pair(0U, &X86::GR32RegClass);
23715         if (VT == MVT::i16)
23716           return std::make_pair(0U, &X86::GR16RegClass);
23717         if (VT == MVT::i8 || VT == MVT::i1)
23718           return std::make_pair(0U, &X86::GR8RegClass);
23719         if (VT == MVT::i64 || VT == MVT::f64)
23720           return std::make_pair(0U, &X86::GR64RegClass);
23721         break;
23722       }
23723       // 32-bit fallthrough
23724     case 'Q':   // Q_REGS
23725       if (VT == MVT::i32 || VT == MVT::f32)
23726         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23727       if (VT == MVT::i16)
23728         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23729       if (VT == MVT::i8 || VT == MVT::i1)
23730         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23731       if (VT == MVT::i64)
23732         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23733       break;
23734     case 'r':   // GENERAL_REGS
23735     case 'l':   // INDEX_REGS
23736       if (VT == MVT::i8 || VT == MVT::i1)
23737         return std::make_pair(0U, &X86::GR8RegClass);
23738       if (VT == MVT::i16)
23739         return std::make_pair(0U, &X86::GR16RegClass);
23740       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23741         return std::make_pair(0U, &X86::GR32RegClass);
23742       return std::make_pair(0U, &X86::GR64RegClass);
23743     case 'R':   // LEGACY_REGS
23744       if (VT == MVT::i8 || VT == MVT::i1)
23745         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23746       if (VT == MVT::i16)
23747         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23748       if (VT == MVT::i32 || !Subtarget->is64Bit())
23749         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23750       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23751     case 'f':  // FP Stack registers.
23752       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23753       // value to the correct fpstack register class.
23754       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23755         return std::make_pair(0U, &X86::RFP32RegClass);
23756       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23757         return std::make_pair(0U, &X86::RFP64RegClass);
23758       return std::make_pair(0U, &X86::RFP80RegClass);
23759     case 'y':   // MMX_REGS if MMX allowed.
23760       if (!Subtarget->hasMMX()) break;
23761       return std::make_pair(0U, &X86::VR64RegClass);
23762     case 'Y':   // SSE_REGS if SSE2 allowed
23763       if (!Subtarget->hasSSE2()) break;
23764       // FALL THROUGH.
23765     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23766       if (!Subtarget->hasSSE1()) break;
23767
23768       switch (VT.SimpleTy) {
23769       default: break;
23770       // Scalar SSE types.
23771       case MVT::f32:
23772       case MVT::i32:
23773         return std::make_pair(0U, &X86::FR32RegClass);
23774       case MVT::f64:
23775       case MVT::i64:
23776         return std::make_pair(0U, &X86::FR64RegClass);
23777       // Vector types.
23778       case MVT::v16i8:
23779       case MVT::v8i16:
23780       case MVT::v4i32:
23781       case MVT::v2i64:
23782       case MVT::v4f32:
23783       case MVT::v2f64:
23784         return std::make_pair(0U, &X86::VR128RegClass);
23785       // AVX types.
23786       case MVT::v32i8:
23787       case MVT::v16i16:
23788       case MVT::v8i32:
23789       case MVT::v4i64:
23790       case MVT::v8f32:
23791       case MVT::v4f64:
23792         return std::make_pair(0U, &X86::VR256RegClass);
23793       case MVT::v8f64:
23794       case MVT::v16f32:
23795       case MVT::v16i32:
23796       case MVT::v8i64:
23797         return std::make_pair(0U, &X86::VR512RegClass);
23798       }
23799       break;
23800     }
23801   }
23802
23803   // Use the default implementation in TargetLowering to convert the register
23804   // constraint into a member of a register class.
23805   std::pair<unsigned, const TargetRegisterClass*> Res;
23806   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23807
23808   // Not found as a standard register?
23809   if (!Res.second) {
23810     // Map st(0) -> st(7) -> ST0
23811     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23812         tolower(Constraint[1]) == 's' &&
23813         tolower(Constraint[2]) == 't' &&
23814         Constraint[3] == '(' &&
23815         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23816         Constraint[5] == ')' &&
23817         Constraint[6] == '}') {
23818
23819       Res.first = X86::FP0+Constraint[4]-'0';
23820       Res.second = &X86::RFP80RegClass;
23821       return Res;
23822     }
23823
23824     // GCC allows "st(0)" to be called just plain "st".
23825     if (StringRef("{st}").equals_lower(Constraint)) {
23826       Res.first = X86::FP0;
23827       Res.second = &X86::RFP80RegClass;
23828       return Res;
23829     }
23830
23831     // flags -> EFLAGS
23832     if (StringRef("{flags}").equals_lower(Constraint)) {
23833       Res.first = X86::EFLAGS;
23834       Res.second = &X86::CCRRegClass;
23835       return Res;
23836     }
23837
23838     // 'A' means EAX + EDX.
23839     if (Constraint == "A") {
23840       Res.first = X86::EAX;
23841       Res.second = &X86::GR32_ADRegClass;
23842       return Res;
23843     }
23844     return Res;
23845   }
23846
23847   // Otherwise, check to see if this is a register class of the wrong value
23848   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23849   // turn into {ax},{dx}.
23850   if (Res.second->hasType(VT))
23851     return Res;   // Correct type already, nothing to do.
23852
23853   // All of the single-register GCC register classes map their values onto
23854   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23855   // really want an 8-bit or 32-bit register, map to the appropriate register
23856   // class and return the appropriate register.
23857   if (Res.second == &X86::GR16RegClass) {
23858     if (VT == MVT::i8 || VT == MVT::i1) {
23859       unsigned DestReg = 0;
23860       switch (Res.first) {
23861       default: break;
23862       case X86::AX: DestReg = X86::AL; break;
23863       case X86::DX: DestReg = X86::DL; break;
23864       case X86::CX: DestReg = X86::CL; break;
23865       case X86::BX: DestReg = X86::BL; break;
23866       }
23867       if (DestReg) {
23868         Res.first = DestReg;
23869         Res.second = &X86::GR8RegClass;
23870       }
23871     } else if (VT == MVT::i32 || VT == MVT::f32) {
23872       unsigned DestReg = 0;
23873       switch (Res.first) {
23874       default: break;
23875       case X86::AX: DestReg = X86::EAX; break;
23876       case X86::DX: DestReg = X86::EDX; break;
23877       case X86::CX: DestReg = X86::ECX; break;
23878       case X86::BX: DestReg = X86::EBX; break;
23879       case X86::SI: DestReg = X86::ESI; break;
23880       case X86::DI: DestReg = X86::EDI; break;
23881       case X86::BP: DestReg = X86::EBP; break;
23882       case X86::SP: DestReg = X86::ESP; break;
23883       }
23884       if (DestReg) {
23885         Res.first = DestReg;
23886         Res.second = &X86::GR32RegClass;
23887       }
23888     } else if (VT == MVT::i64 || VT == MVT::f64) {
23889       unsigned DestReg = 0;
23890       switch (Res.first) {
23891       default: break;
23892       case X86::AX: DestReg = X86::RAX; break;
23893       case X86::DX: DestReg = X86::RDX; break;
23894       case X86::CX: DestReg = X86::RCX; break;
23895       case X86::BX: DestReg = X86::RBX; break;
23896       case X86::SI: DestReg = X86::RSI; break;
23897       case X86::DI: DestReg = X86::RDI; break;
23898       case X86::BP: DestReg = X86::RBP; break;
23899       case X86::SP: DestReg = X86::RSP; break;
23900       }
23901       if (DestReg) {
23902         Res.first = DestReg;
23903         Res.second = &X86::GR64RegClass;
23904       }
23905     }
23906   } else if (Res.second == &X86::FR32RegClass ||
23907              Res.second == &X86::FR64RegClass ||
23908              Res.second == &X86::VR128RegClass ||
23909              Res.second == &X86::VR256RegClass ||
23910              Res.second == &X86::FR32XRegClass ||
23911              Res.second == &X86::FR64XRegClass ||
23912              Res.second == &X86::VR128XRegClass ||
23913              Res.second == &X86::VR256XRegClass ||
23914              Res.second == &X86::VR512RegClass) {
23915     // Handle references to XMM physical registers that got mapped into the
23916     // wrong class.  This can happen with constraints like {xmm0} where the
23917     // target independent register mapper will just pick the first match it can
23918     // find, ignoring the required type.
23919
23920     if (VT == MVT::f32 || VT == MVT::i32)
23921       Res.second = &X86::FR32RegClass;
23922     else if (VT == MVT::f64 || VT == MVT::i64)
23923       Res.second = &X86::FR64RegClass;
23924     else if (X86::VR128RegClass.hasType(VT))
23925       Res.second = &X86::VR128RegClass;
23926     else if (X86::VR256RegClass.hasType(VT))
23927       Res.second = &X86::VR256RegClass;
23928     else if (X86::VR512RegClass.hasType(VT))
23929       Res.second = &X86::VR512RegClass;
23930   }
23931
23932   return Res;
23933 }
23934
23935 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23936                                             Type *Ty) const {
23937   // Scaling factors are not free at all.
23938   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23939   // will take 2 allocations in the out of order engine instead of 1
23940   // for plain addressing mode, i.e. inst (reg1).
23941   // E.g.,
23942   // vaddps (%rsi,%drx), %ymm0, %ymm1
23943   // Requires two allocations (one for the load, one for the computation)
23944   // whereas:
23945   // vaddps (%rsi), %ymm0, %ymm1
23946   // Requires just 1 allocation, i.e., freeing allocations for other operations
23947   // and having less micro operations to execute.
23948   //
23949   // For some X86 architectures, this is even worse because for instance for
23950   // stores, the complex addressing mode forces the instruction to use the
23951   // "load" ports instead of the dedicated "store" port.
23952   // E.g., on Haswell:
23953   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23954   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23955   if (isLegalAddressingMode(AM, Ty))
23956     // Scale represents reg2 * scale, thus account for 1
23957     // as soon as we use a second register.
23958     return AM.Scale != 0;
23959   return -1;
23960 }
23961
23962 bool X86TargetLowering::isTargetFTOL() const {
23963   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23964 }