[X86] Simplify X87 stackifier pass.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     // We support custom legalizing of sext and anyext loads for specific
1015     // memory vector types which we can load as a scalar (or sequence of
1016     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017     // loads these must work with a single scalar load.
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019     if (Subtarget->is64Bit()) {
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1022     }
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1034     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036
1037     if (Subtarget->is64Bit()) {
1038       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1039       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040     }
1041
1042     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044       MVT VT = (MVT::SimpleValueType)i;
1045
1046       // Do not attempt to promote non-128-bit vectors
1047       if (!VT.is128BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    VT, Promote);
1051       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1052       setOperationAction(ISD::OR,     VT, Promote);
1053       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1054       setOperationAction(ISD::XOR,    VT, Promote);
1055       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1056       setOperationAction(ISD::LOAD,   VT, Promote);
1057       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1058       setOperationAction(ISD::SELECT, VT, Promote);
1059       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060     }
1061
1062     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1063
1064     // Custom lower v2i64 and v2f64 selects.
1065     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1066     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1067     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1068     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1069
1070     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1072
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1075     // As there is no 64-bit GPR available, we need build a special custom
1076     // sequence to convert from v2i32 to v2f32.
1077     if (!Subtarget->is64Bit())
1078       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1079
1080     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1082
1083     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1084
1085     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1087     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1088   }
1089
1090   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1094     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1099     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1101
1102     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1105     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1106     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1107     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1110     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1111     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1112
1113     // FIXME: Do we need to handle scalar-to-vector here?
1114     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1115
1116     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1120     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1121     // There is no BLENDI for byte vectors. We don't need to custom lower
1122     // some vselects for now.
1123     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1124
1125     // SSE41 brings specific instructions for doing vector sign extend even in
1126     // cases where we don't have SRA.
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1130
1131     // i8 and i16 vectors are custom , because the source register and source
1132     // source memory operand types are not the same width.  f32 vectors are
1133     // custom since the immediate controlling the insert encodes additional
1134     // information.
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1139
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1144
1145     // FIXME: these should be Legal but thats only for the case where
1146     // the index is constant.  For now custom expand to deal with that.
1147     if (Subtarget->is64Bit()) {
1148       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1150     }
1151   }
1152
1153   if (Subtarget->hasSSE2()) {
1154     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1155     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1156
1157     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1158     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1159
1160     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1161     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1162
1163     // In the customized shift lowering, the legal cases in AVX2 will be
1164     // recognized.
1165     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1172   }
1173
1174   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1181
1182     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1184     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1185
1186     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1194     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1196     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1197     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1198
1199     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1207     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1209     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1210     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1211
1212     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213     // even though v8i16 is a legal type.
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1216     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1217
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1219     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1220     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1221
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1223     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1224
1225     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1226
1227     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1228     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1229
1230     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1231     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1232
1233     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1234     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1235
1236     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1239     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1240
1241     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1243     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1244
1245     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1248     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1249
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1252     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1255     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1258     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1261     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1262
1263     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1269       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1270     }
1271
1272     if (Subtarget->hasInt256()) {
1273       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1276       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1277
1278       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1281       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1282
1283       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1284       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1285       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1286       // Don't lower v32i8 because there is no 128-bit byte mul
1287
1288       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1290       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1291       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1292
1293       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1294       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1295     } else {
1296       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1299       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1300
1301       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1304       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1305
1306       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1309       // Don't lower v32i8 because there is no 128-bit byte mul
1310     }
1311
1312     // In the customized shift lowering, the legal cases in AVX2 will be
1313     // recognized.
1314     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1315     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1316
1317     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1318     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1319
1320     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1321
1322     // Custom lower several nodes for 256-bit types.
1323     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Extract subvector is special because the value type
1328       // (result) is 128-bit but the source is 256-bit wide.
1329       if (VT.is128BitVector())
1330         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1331
1332       // Do not attempt to custom lower other non-256-bit vectors
1333       if (!VT.is256BitVector())
1334         continue;
1335
1336       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1337       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1338       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1339       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1341       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1342       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1343     }
1344
1345     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347       MVT VT = (MVT::SimpleValueType)i;
1348
1349       // Do not attempt to promote non-256-bit vectors
1350       if (!VT.is256BitVector())
1351         continue;
1352
1353       setOperationAction(ISD::AND,    VT, Promote);
1354       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1355       setOperationAction(ISD::OR,     VT, Promote);
1356       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1357       setOperationAction(ISD::XOR,    VT, Promote);
1358       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1359       setOperationAction(ISD::LOAD,   VT, Promote);
1360       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1361       setOperationAction(ISD::SELECT, VT, Promote);
1362       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1363     }
1364   }
1365
1366   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1370     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1371
1372     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1373     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1374     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1375
1376     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1377     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1378     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1379     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1380     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1381     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1386     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1392     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1393     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1394
1395     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1399     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1400     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1401     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1402     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1403
1404     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1406     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1407     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1408     if (Subtarget->is64Bit()) {
1409       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1411       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1412       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1413     }
1414     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1422     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1423     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1424
1425     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460
1461     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1470     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1471
1472     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1473     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1474
1475     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1476     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1477
1478     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1480     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1482     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1483     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1484
1485     if (Subtarget->hasCDI()) {
1486       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1487       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1488     }
1489
1490     // Custom lower several nodes.
1491     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493       MVT VT = (MVT::SimpleValueType)i;
1494
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       // Extract subvector is special because the value type
1497       // (result) is 256/128-bit but the source is 512-bit wide.
1498       if (VT.is128BitVector() || VT.is256BitVector())
1499         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1500
1501       if (VT.getVectorElementType() == MVT::i1)
1502         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1503
1504       // Do not attempt to custom lower other non-512-bit vectors
1505       if (!VT.is512BitVector())
1506         continue;
1507
1508       if ( EltSize >= 32) {
1509         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1510         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1511         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1512         setOperationAction(ISD::VSELECT,             VT, Legal);
1513         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1514         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1515         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1516       }
1517     }
1518     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519       MVT VT = (MVT::SimpleValueType)i;
1520
1521       // Do not attempt to promote non-256-bit vectors
1522       if (!VT.is512BitVector())
1523         continue;
1524
1525       setOperationAction(ISD::SELECT, VT, Promote);
1526       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1527     }
1528   }// has  AVX-512
1529
1530   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1532     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1533   }
1534
1535   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536   // of this type with custom code.
1537   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1540                        Custom);
1541   }
1542
1543   // We want to custom lower some of our intrinsics.
1544   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547   if (!Subtarget->is64Bit())
1548     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1549
1550   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551   // handle type legalization for these operations here.
1552   //
1553   // FIXME: We really should do custom legalization for addition and
1554   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1555   // than generic legalization for 64-bit multiplication-with-overflow, though.
1556   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557     // Add/Sub/Mul with overflow operations are custom lowered.
1558     MVT VT = IntVTs[i];
1559     setOperationAction(ISD::SADDO, VT, Custom);
1560     setOperationAction(ISD::UADDO, VT, Custom);
1561     setOperationAction(ISD::SSUBO, VT, Custom);
1562     setOperationAction(ISD::USUBO, VT, Custom);
1563     setOperationAction(ISD::SMULO, VT, Custom);
1564     setOperationAction(ISD::UMULO, VT, Custom);
1565   }
1566
1567   // There are no 8-bit 3-address imul/mul instructions
1568   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1570
1571   if (!Subtarget->is64Bit()) {
1572     // These libcalls are not available in 32-bit.
1573     setLibcallName(RTLIB::SHL_I128, nullptr);
1574     setLibcallName(RTLIB::SRL_I128, nullptr);
1575     setLibcallName(RTLIB::SRA_I128, nullptr);
1576   }
1577
1578   // Combine sin / cos into one node or libcall if possible.
1579   if (Subtarget->hasSinCos()) {
1580     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582     if (Subtarget->isTargetDarwin()) {
1583       // For MacOSX, we don't want to the normal expansion of a libcall to
1584       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1585       // traffic.
1586       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1588     }
1589   }
1590
1591   if (Subtarget->isTargetWin64()) {
1592     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::SREM, MVT::i128, Custom);
1595     setOperationAction(ISD::UREM, MVT::i128, Custom);
1596     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1598   }
1599
1600   // We have target-specific dag combine patterns for the following nodes:
1601   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603   setTargetDAGCombine(ISD::VSELECT);
1604   setTargetDAGCombine(ISD::SELECT);
1605   setTargetDAGCombine(ISD::SHL);
1606   setTargetDAGCombine(ISD::SRA);
1607   setTargetDAGCombine(ISD::SRL);
1608   setTargetDAGCombine(ISD::OR);
1609   setTargetDAGCombine(ISD::AND);
1610   setTargetDAGCombine(ISD::ADD);
1611   setTargetDAGCombine(ISD::FADD);
1612   setTargetDAGCombine(ISD::FSUB);
1613   setTargetDAGCombine(ISD::FMA);
1614   setTargetDAGCombine(ISD::SUB);
1615   setTargetDAGCombine(ISD::LOAD);
1616   setTargetDAGCombine(ISD::STORE);
1617   setTargetDAGCombine(ISD::ZERO_EXTEND);
1618   setTargetDAGCombine(ISD::ANY_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND);
1620   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621   setTargetDAGCombine(ISD::TRUNCATE);
1622   setTargetDAGCombine(ISD::SINT_TO_FP);
1623   setTargetDAGCombine(ISD::SETCC);
1624   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625   setTargetDAGCombine(ISD::BUILD_VECTOR);
1626   if (Subtarget->is64Bit())
1627     setTargetDAGCombine(ISD::MUL);
1628   setTargetDAGCombine(ISD::XOR);
1629
1630   computeRegisterProperties();
1631
1632   // On Darwin, -Os means optimize for size without hurting performance,
1633   // do not reduce the limit.
1634   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   setPrefLoopAlignment(4); // 2^4 bytes.
1641
1642   // Predictable cmov don't hurt on atom because it's in-order.
1643   PredictableSelectIsExpensive = !Subtarget->isAtom();
1644
1645   setPrefFunctionAlignment(4); // 2^4 bytes.
1646 }
1647
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651          Subtarget->is64Bit();
1652 }
1653
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656   if (ExperimentalVectorWideningLegalization &&
1657       VT.getVectorNumElements() != 1 &&
1658       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659     return TypeWidenVector;
1660
1661   return TargetLoweringBase::getPreferredVectorAction(VT);
1662 }
1663
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1665   if (!VT.isVector())
1666     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1667
1668   if (Subtarget->hasAVX512())
1669     switch(VT.getVectorNumElements()) {
1670     case  8: return MVT::v8i1;
1671     case 16: return MVT::v16i1;
1672   }
1673
1674   return VT.changeVectorElementTypeToInteger();
1675 }
1676
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1680   if (MaxAlign == 16)
1681     return;
1682   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683     if (VTy->getBitWidth() == 128)
1684       MaxAlign = 16;
1685   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686     unsigned EltAlign = 0;
1687     getMaxByValAlign(ATy->getElementType(), EltAlign);
1688     if (EltAlign > MaxAlign)
1689       MaxAlign = EltAlign;
1690   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692       unsigned EltAlign = 0;
1693       getMaxByValAlign(STy->getElementType(i), EltAlign);
1694       if (EltAlign > MaxAlign)
1695         MaxAlign = EltAlign;
1696       if (MaxAlign == 16)
1697         break;
1698     }
1699   }
1700 }
1701
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707   if (Subtarget->is64Bit()) {
1708     // Max of 8 and alignment of type.
1709     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1710     if (TyAlign > 8)
1711       return TyAlign;
1712     return 8;
1713   }
1714
1715   unsigned Align = 4;
1716   if (Subtarget->hasSSE1())
1717     getMaxByValAlign(Ty, Align);
1718   return Align;
1719 }
1720
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1732 EVT
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734                                        unsigned DstAlign, unsigned SrcAlign,
1735                                        bool IsMemset, bool ZeroMemset,
1736                                        bool MemcpyStrSrc,
1737                                        MachineFunction &MF) const {
1738   const Function *F = MF.getFunction();
1739   if ((!IsMemset || ZeroMemset) &&
1740       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741                                        Attribute::NoImplicitFloat)) {
1742     if (Size >= 16 &&
1743         (Subtarget->isUnalignedMemAccessFast() ||
1744          ((DstAlign == 0 || DstAlign >= 16) &&
1745           (SrcAlign == 0 || SrcAlign >= 16)))) {
1746       if (Size >= 32) {
1747         if (Subtarget->hasInt256())
1748           return MVT::v8i32;
1749         if (Subtarget->hasFp256())
1750           return MVT::v8f32;
1751       }
1752       if (Subtarget->hasSSE2())
1753         return MVT::v4i32;
1754       if (Subtarget->hasSSE1())
1755         return MVT::v4f32;
1756     } else if (!MemcpyStrSrc && Size >= 8 &&
1757                !Subtarget->is64Bit() &&
1758                Subtarget->hasSSE2()) {
1759       // Do not use f64 to lower memcpy if source is string constant. It's
1760       // better to use i32 to avoid the loads.
1761       return MVT::f64;
1762     }
1763   }
1764   if (Subtarget->is64Bit() && Size >= 8)
1765     return MVT::i64;
1766   return MVT::i32;
1767 }
1768
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1770   if (VT == MVT::f32)
1771     return X86ScalarSSEf32;
1772   else if (VT == MVT::f64)
1773     return X86ScalarSSEf64;
1774   return true;
1775 }
1776
1777 bool
1778 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1779                                                   unsigned,
1780                                                   unsigned,
1781                                                   bool *Fast) const {
1782   if (Fast)
1783     *Fast = Subtarget->isUnalignedMemAccessFast();
1784   return true;
1785 }
1786
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function.  The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1792   // symbol.
1793   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794       Subtarget->isPICStyleGOT())
1795     return MachineJumpTableInfo::EK_Custom32;
1796
1797   // Otherwise, use the normal jump table encoding heuristics.
1798   return TargetLowering::getJumpTableEncoding();
1799 }
1800
1801 const MCExpr *
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803                                              const MachineBasicBlock *MBB,
1804                                              unsigned uid,MCContext &Ctx) const{
1805   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806          Subtarget->isPICStyleGOT());
1807   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1808   // entries.
1809   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1811 }
1812
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1814 /// jumptable.
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816                                                     SelectionDAG &DAG) const {
1817   if (!Subtarget->is64Bit())
1818     // This doesn't have SDLoc associated with it, but is not really the
1819     // same as a Register.
1820     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1821   return Table;
1822 }
1823
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1826 /// MCExpr.
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829                              MCContext &Ctx) const {
1830   // X86-64 uses RIP relative addressing based on the jump table label.
1831   if (Subtarget->isPICStyleRIPRel())
1832     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833
1834   // Otherwise, the reference is relative to the PIC base.
1835   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1836 }
1837
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841   const TargetRegisterClass *RRC = nullptr;
1842   uint8_t Cost = 1;
1843   switch (VT.SimpleTy) {
1844   default:
1845     return TargetLowering::findRepresentativeClass(VT);
1846   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847     RRC = Subtarget->is64Bit() ?
1848       (const TargetRegisterClass*)&X86::GR64RegClass :
1849       (const TargetRegisterClass*)&X86::GR32RegClass;
1850     break;
1851   case MVT::x86mmx:
1852     RRC = &X86::VR64RegClass;
1853     break;
1854   case MVT::f32: case MVT::f64:
1855   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856   case MVT::v4f32: case MVT::v2f64:
1857   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1858   case MVT::v4f64:
1859     RRC = &X86::VR128RegClass;
1860     break;
1861   }
1862   return std::make_pair(RRC, Cost);
1863 }
1864
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866                                                unsigned &Offset) const {
1867   if (!Subtarget->isTargetLinux())
1868     return false;
1869
1870   if (Subtarget->is64Bit()) {
1871     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1872     Offset = 0x28;
1873     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1874       AddressSpace = 256;
1875     else
1876       AddressSpace = 257;
1877   } else {
1878     // %gs:0x14 on i386
1879     Offset = 0x14;
1880     AddressSpace = 256;
1881   }
1882   return true;
1883 }
1884
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886                                             unsigned DestAS) const {
1887   assert(SrcAS != DestAS && "Expected different address spaces!");
1888
1889   return SrcAS < 256 && DestAS < 256;
1890 }
1891
1892 //===----------------------------------------------------------------------===//
1893 //               Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1895
1896 #include "X86GenCallingConv.inc"
1897
1898 bool
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900                                   MachineFunction &MF, bool isVarArg,
1901                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1902                         LLVMContext &Context) const {
1903   SmallVector<CCValAssign, 16> RVLocs;
1904   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1905                  RVLocs, Context);
1906   return CCInfo.CheckReturn(Outs, RetCC_X86);
1907 }
1908
1909 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1910   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1911   return ScratchRegs;
1912 }
1913
1914 SDValue
1915 X86TargetLowering::LowerReturn(SDValue Chain,
1916                                CallingConv::ID CallConv, bool isVarArg,
1917                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1918                                const SmallVectorImpl<SDValue> &OutVals,
1919                                SDLoc dl, SelectionDAG &DAG) const {
1920   MachineFunction &MF = DAG.getMachineFunction();
1921   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1922
1923   SmallVector<CCValAssign, 16> RVLocs;
1924   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1925                  RVLocs, *DAG.getContext());
1926   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1927
1928   SDValue Flag;
1929   SmallVector<SDValue, 6> RetOps;
1930   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1931   // Operand #1 = Bytes To Pop
1932   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1933                    MVT::i16));
1934
1935   // Copy the result values into the output registers.
1936   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1937     CCValAssign &VA = RVLocs[i];
1938     assert(VA.isRegLoc() && "Can only return in registers!");
1939     SDValue ValToCopy = OutVals[i];
1940     EVT ValVT = ValToCopy.getValueType();
1941
1942     // Promote values to the appropriate types
1943     if (VA.getLocInfo() == CCValAssign::SExt)
1944       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945     else if (VA.getLocInfo() == CCValAssign::ZExt)
1946       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::AExt)
1948       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949     else if (VA.getLocInfo() == CCValAssign::BCvt)
1950       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1951
1952     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953            "Unexpected FP-extend for return value.");  
1954
1955     // If this is x86-64, and we disabled SSE, we can't return FP values,
1956     // or SSE or MMX vectors.
1957     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960       report_fatal_error("SSE register return with SSE disabled");
1961     }
1962     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1963     // llvm-gcc has never done it right and no one has noticed, so this
1964     // should be OK for now.
1965     if (ValVT == MVT::f64 &&
1966         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967       report_fatal_error("SSE2 register return with SSE2 disabled");
1968
1969     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970     // the RET instruction and handled by the FP Stackifier.
1971     if (VA.getLocReg() == X86::FP0 ||
1972         VA.getLocReg() == X86::FP1) {
1973       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974       // change the value to the FP stack register class.
1975       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977       RetOps.push_back(ValToCopy);
1978       // Don't emit a copytoreg.
1979       continue;
1980     }
1981
1982     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983     // which is returned in RAX / RDX.
1984     if (Subtarget->is64Bit()) {
1985       if (ValVT == MVT::x86mmx) {
1986         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1989                                   ValToCopy);
1990           // If we don't have SSE2 available, convert to v4f32 so the generated
1991           // register is legal.
1992           if (!Subtarget->hasSSE2())
1993             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1994         }
1995       }
1996     }
1997
1998     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999     Flag = Chain.getValue(1);
2000     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2001   }
2002
2003   // The x86-64 ABIs require that for returning structs by value we copy
2004   // the sret argument into %rax/%eax (depending on ABI) for the return.
2005   // Win32 requires us to put the sret argument to %eax as well.
2006   // We saved the argument into a virtual register in the entry block,
2007   // so now we copy the value out and into %rax/%eax.
2008   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2009       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2010     MachineFunction &MF = DAG.getMachineFunction();
2011     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2012     unsigned Reg = FuncInfo->getSRetReturnReg();
2013     assert(Reg &&
2014            "SRetReturnReg should have been set in LowerFormalArguments().");
2015     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2016
2017     unsigned RetValReg
2018         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019           X86::RAX : X86::EAX;
2020     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021     Flag = Chain.getValue(1);
2022
2023     // RAX/EAX now acts like a return value.
2024     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2025   }
2026
2027   RetOps[0] = Chain;  // Update chain.
2028
2029   // Add the flag if we have it.
2030   if (Flag.getNode())
2031     RetOps.push_back(Flag);
2032
2033   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2034 }
2035
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037   if (N->getNumValues() != 1)
2038     return false;
2039   if (!N->hasNUsesOfValue(1, 0))
2040     return false;
2041
2042   SDValue TCChain = Chain;
2043   SDNode *Copy = *N->use_begin();
2044   if (Copy->getOpcode() == ISD::CopyToReg) {
2045     // If the copy has a glue operand, we conservatively assume it isn't safe to
2046     // perform a tail call.
2047     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2048       return false;
2049     TCChain = Copy->getOperand(0);
2050   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2051     return false;
2052
2053   bool HasRet = false;
2054   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2055        UI != UE; ++UI) {
2056     if (UI->getOpcode() != X86ISD::RET_FLAG)
2057       return false;
2058     HasRet = true;
2059   }
2060
2061   if (!HasRet)
2062     return false;
2063
2064   Chain = TCChain;
2065   return true;
2066 }
2067
2068 MVT
2069 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2070                                             ISD::NodeType ExtendKind) const {
2071   MVT ReturnMVT;
2072   // TODO: Is this also valid on 32-bit?
2073   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2074     ReturnMVT = MVT::i8;
2075   else
2076     ReturnMVT = MVT::i32;
2077
2078   MVT MinVT = getRegisterType(ReturnMVT);
2079   return VT.bitsLT(MinVT) ? MinVT : VT;
2080 }
2081
2082 /// LowerCallResult - Lower the result values of a call into the
2083 /// appropriate copies out of appropriate physical registers.
2084 ///
2085 SDValue
2086 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2087                                    CallingConv::ID CallConv, bool isVarArg,
2088                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2089                                    SDLoc dl, SelectionDAG &DAG,
2090                                    SmallVectorImpl<SDValue> &InVals) const {
2091
2092   // Assign locations to each value returned by this call.
2093   SmallVector<CCValAssign, 16> RVLocs;
2094   bool Is64Bit = Subtarget->is64Bit();
2095   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2096                  DAG.getTarget(), RVLocs, *DAG.getContext());
2097   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2098
2099   // Copy all of the result registers out of their specified physreg.
2100   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2101     CCValAssign &VA = RVLocs[i];
2102     EVT CopyVT = VA.getValVT();
2103
2104     // If this is x86-64, and we disabled SSE, we can't return FP values
2105     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2106         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2107       report_fatal_error("SSE register return with SSE disabled");
2108     }
2109
2110     // If we prefer to use the value in xmm registers, copy it out as f80 and
2111     // use a truncate to move it from fp stack reg to xmm reg.
2112     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2113         isScalarFPTypeInSSEReg(VA.getValVT()))
2114       CopyVT = MVT::f80;
2115
2116     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2117                                CopyVT, InFlag).getValue(1);
2118     SDValue Val = Chain.getValue(0);
2119
2120     if (CopyVT != VA.getValVT())
2121       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2122                         // This truncation won't change the value.
2123                         DAG.getIntPtrConstant(1));
2124
2125     InFlag = Chain.getValue(2);
2126     InVals.push_back(Val);
2127   }
2128
2129   return Chain;
2130 }
2131
2132 //===----------------------------------------------------------------------===//
2133 //                C & StdCall & Fast Calling Convention implementation
2134 //===----------------------------------------------------------------------===//
2135 //  StdCall calling convention seems to be standard for many Windows' API
2136 //  routines and around. It differs from C calling convention just a little:
2137 //  callee should clean up the stack, not caller. Symbols should be also
2138 //  decorated in some fancy way :) It doesn't support any vector arguments.
2139 //  For info on fast calling convention see Fast Calling Convention (tail call)
2140 //  implementation LowerX86_32FastCCCallTo.
2141
2142 /// CallIsStructReturn - Determines whether a call uses struct return
2143 /// semantics.
2144 enum StructReturnType {
2145   NotStructReturn,
2146   RegStructReturn,
2147   StackStructReturn
2148 };
2149 static StructReturnType
2150 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2151   if (Outs.empty())
2152     return NotStructReturn;
2153
2154   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2155   if (!Flags.isSRet())
2156     return NotStructReturn;
2157   if (Flags.isInReg())
2158     return RegStructReturn;
2159   return StackStructReturn;
2160 }
2161
2162 /// ArgsAreStructReturn - Determines whether a function uses struct
2163 /// return semantics.
2164 static StructReturnType
2165 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2166   if (Ins.empty())
2167     return NotStructReturn;
2168
2169   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2170   if (!Flags.isSRet())
2171     return NotStructReturn;
2172   if (Flags.isInReg())
2173     return RegStructReturn;
2174   return StackStructReturn;
2175 }
2176
2177 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2178 /// by "Src" to address "Dst" with size and alignment information specified by
2179 /// the specific parameter attribute. The copy will be passed as a byval
2180 /// function parameter.
2181 static SDValue
2182 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2183                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2184                           SDLoc dl) {
2185   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2186
2187   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2188                        /*isVolatile*/false, /*AlwaysInline=*/true,
2189                        MachinePointerInfo(), MachinePointerInfo());
2190 }
2191
2192 /// IsTailCallConvention - Return true if the calling convention is one that
2193 /// supports tail call optimization.
2194 static bool IsTailCallConvention(CallingConv::ID CC) {
2195   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2196           CC == CallingConv::HiPE);
2197 }
2198
2199 /// \brief Return true if the calling convention is a C calling convention.
2200 static bool IsCCallConvention(CallingConv::ID CC) {
2201   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2202           CC == CallingConv::X86_64_SysV);
2203 }
2204
2205 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2206   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2207     return false;
2208
2209   CallSite CS(CI);
2210   CallingConv::ID CalleeCC = CS.getCallingConv();
2211   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2212     return false;
2213
2214   return true;
2215 }
2216
2217 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2218 /// a tailcall target by changing its ABI.
2219 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2220                                    bool GuaranteedTailCallOpt) {
2221   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2222 }
2223
2224 SDValue
2225 X86TargetLowering::LowerMemArgument(SDValue Chain,
2226                                     CallingConv::ID CallConv,
2227                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2228                                     SDLoc dl, SelectionDAG &DAG,
2229                                     const CCValAssign &VA,
2230                                     MachineFrameInfo *MFI,
2231                                     unsigned i) const {
2232   // Create the nodes corresponding to a load from this parameter slot.
2233   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2234   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2235       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2236   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2237   EVT ValVT;
2238
2239   // If value is passed by pointer we have address passed instead of the value
2240   // itself.
2241   if (VA.getLocInfo() == CCValAssign::Indirect)
2242     ValVT = VA.getLocVT();
2243   else
2244     ValVT = VA.getValVT();
2245
2246   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2247   // changed with more analysis.
2248   // In case of tail call optimization mark all arguments mutable. Since they
2249   // could be overwritten by lowering of arguments in case of a tail call.
2250   if (Flags.isByVal()) {
2251     unsigned Bytes = Flags.getByValSize();
2252     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2253     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2254     return DAG.getFrameIndex(FI, getPointerTy());
2255   } else {
2256     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2257                                     VA.getLocMemOffset(), isImmutable);
2258     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2259     return DAG.getLoad(ValVT, dl, Chain, FIN,
2260                        MachinePointerInfo::getFixedStack(FI),
2261                        false, false, false, 0);
2262   }
2263 }
2264
2265 SDValue
2266 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2267                                         CallingConv::ID CallConv,
2268                                         bool isVarArg,
2269                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2270                                         SDLoc dl,
2271                                         SelectionDAG &DAG,
2272                                         SmallVectorImpl<SDValue> &InVals)
2273                                           const {
2274   MachineFunction &MF = DAG.getMachineFunction();
2275   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2276
2277   const Function* Fn = MF.getFunction();
2278   if (Fn->hasExternalLinkage() &&
2279       Subtarget->isTargetCygMing() &&
2280       Fn->getName() == "main")
2281     FuncInfo->setForceFramePointer(true);
2282
2283   MachineFrameInfo *MFI = MF.getFrameInfo();
2284   bool Is64Bit = Subtarget->is64Bit();
2285   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2286
2287   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2288          "Var args not supported with calling convention fastcc, ghc or hipe");
2289
2290   // Assign locations to all of the incoming arguments.
2291   SmallVector<CCValAssign, 16> ArgLocs;
2292   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2293                  ArgLocs, *DAG.getContext());
2294
2295   // Allocate shadow area for Win64
2296   if (IsWin64)
2297     CCInfo.AllocateStack(32, 8);
2298
2299   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2300
2301   unsigned LastVal = ~0U;
2302   SDValue ArgValue;
2303   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2304     CCValAssign &VA = ArgLocs[i];
2305     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2306     // places.
2307     assert(VA.getValNo() != LastVal &&
2308            "Don't support value assigned to multiple locs yet");
2309     (void)LastVal;
2310     LastVal = VA.getValNo();
2311
2312     if (VA.isRegLoc()) {
2313       EVT RegVT = VA.getLocVT();
2314       const TargetRegisterClass *RC;
2315       if (RegVT == MVT::i32)
2316         RC = &X86::GR32RegClass;
2317       else if (Is64Bit && RegVT == MVT::i64)
2318         RC = &X86::GR64RegClass;
2319       else if (RegVT == MVT::f32)
2320         RC = &X86::FR32RegClass;
2321       else if (RegVT == MVT::f64)
2322         RC = &X86::FR64RegClass;
2323       else if (RegVT.is512BitVector())
2324         RC = &X86::VR512RegClass;
2325       else if (RegVT.is256BitVector())
2326         RC = &X86::VR256RegClass;
2327       else if (RegVT.is128BitVector())
2328         RC = &X86::VR128RegClass;
2329       else if (RegVT == MVT::x86mmx)
2330         RC = &X86::VR64RegClass;
2331       else if (RegVT == MVT::i1)
2332         RC = &X86::VK1RegClass;
2333       else if (RegVT == MVT::v8i1)
2334         RC = &X86::VK8RegClass;
2335       else if (RegVT == MVT::v16i1)
2336         RC = &X86::VK16RegClass;
2337       else if (RegVT == MVT::v32i1)
2338         RC = &X86::VK32RegClass;
2339       else if (RegVT == MVT::v64i1)
2340         RC = &X86::VK64RegClass;
2341       else
2342         llvm_unreachable("Unknown argument type!");
2343
2344       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2345       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2346
2347       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2348       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2349       // right size.
2350       if (VA.getLocInfo() == CCValAssign::SExt)
2351         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2352                                DAG.getValueType(VA.getValVT()));
2353       else if (VA.getLocInfo() == CCValAssign::ZExt)
2354         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2355                                DAG.getValueType(VA.getValVT()));
2356       else if (VA.getLocInfo() == CCValAssign::BCvt)
2357         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2358
2359       if (VA.isExtInLoc()) {
2360         // Handle MMX values passed in XMM regs.
2361         if (RegVT.isVector())
2362           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2363         else
2364           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2365       }
2366     } else {
2367       assert(VA.isMemLoc());
2368       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2369     }
2370
2371     // If value is passed via pointer - do a load.
2372     if (VA.getLocInfo() == CCValAssign::Indirect)
2373       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2374                              MachinePointerInfo(), false, false, false, 0);
2375
2376     InVals.push_back(ArgValue);
2377   }
2378
2379   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2380     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381       // The x86-64 ABIs require that for returning structs by value we copy
2382       // the sret argument into %rax/%eax (depending on ABI) for the return.
2383       // Win32 requires us to put the sret argument to %eax as well.
2384       // Save the argument into a virtual register so that we can access it
2385       // from the return points.
2386       if (Ins[i].Flags.isSRet()) {
2387         unsigned Reg = FuncInfo->getSRetReturnReg();
2388         if (!Reg) {
2389           MVT PtrTy = getPointerTy();
2390           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2391           FuncInfo->setSRetReturnReg(Reg);
2392         }
2393         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2394         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2395         break;
2396       }
2397     }
2398   }
2399
2400   unsigned StackSize = CCInfo.getNextStackOffset();
2401   // Align stack specially for tail calls.
2402   if (FuncIsMadeTailCallSafe(CallConv,
2403                              MF.getTarget().Options.GuaranteedTailCallOpt))
2404     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2405
2406   // If the function takes variable number of arguments, make a frame index for
2407   // the start of the first vararg value... for expansion of llvm.va_start.
2408   if (isVarArg) {
2409     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2410                     CallConv != CallingConv::X86_ThisCall)) {
2411       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2412     }
2413     if (Is64Bit) {
2414       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2415
2416       // FIXME: We should really autogenerate these arrays
2417       static const MCPhysReg GPR64ArgRegsWin64[] = {
2418         X86::RCX, X86::RDX, X86::R8,  X86::R9
2419       };
2420       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2421         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2422       };
2423       static const MCPhysReg XMMArgRegs64Bit[] = {
2424         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2425         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2426       };
2427       const MCPhysReg *GPR64ArgRegs;
2428       unsigned NumXMMRegs = 0;
2429
2430       if (IsWin64) {
2431         // The XMM registers which might contain var arg parameters are shadowed
2432         // in their paired GPR.  So we only need to save the GPR to their home
2433         // slots.
2434         TotalNumIntRegs = 4;
2435         GPR64ArgRegs = GPR64ArgRegsWin64;
2436       } else {
2437         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2438         GPR64ArgRegs = GPR64ArgRegs64Bit;
2439
2440         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2441                                                 TotalNumXMMRegs);
2442       }
2443       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2444                                                        TotalNumIntRegs);
2445
2446       bool NoImplicitFloatOps = Fn->getAttributes().
2447         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2448       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2449              "SSE register cannot be used when SSE is disabled!");
2450       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2451                NoImplicitFloatOps) &&
2452              "SSE register cannot be used when SSE is disabled!");
2453       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2454           !Subtarget->hasSSE1())
2455         // Kernel mode asks for SSE to be disabled, so don't push them
2456         // on the stack.
2457         TotalNumXMMRegs = 0;
2458
2459       if (IsWin64) {
2460         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2461         // Get to the caller-allocated home save location.  Add 8 to account
2462         // for the return address.
2463         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2464         FuncInfo->setRegSaveFrameIndex(
2465           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2466         // Fixup to set vararg frame on shadow area (4 x i64).
2467         if (NumIntRegs < 4)
2468           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2469       } else {
2470         // For X86-64, if there are vararg parameters that are passed via
2471         // registers, then we must store them to their spots on the stack so
2472         // they may be loaded by deferencing the result of va_next.
2473         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2474         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2475         FuncInfo->setRegSaveFrameIndex(
2476           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2477                                false));
2478       }
2479
2480       // Store the integer parameter registers.
2481       SmallVector<SDValue, 8> MemOps;
2482       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2483                                         getPointerTy());
2484       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2485       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2486         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2487                                   DAG.getIntPtrConstant(Offset));
2488         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2489                                      &X86::GR64RegClass);
2490         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2491         SDValue Store =
2492           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2493                        MachinePointerInfo::getFixedStack(
2494                          FuncInfo->getRegSaveFrameIndex(), Offset),
2495                        false, false, 0);
2496         MemOps.push_back(Store);
2497         Offset += 8;
2498       }
2499
2500       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2501         // Now store the XMM (fp + vector) parameter registers.
2502         SmallVector<SDValue, 11> SaveXMMOps;
2503         SaveXMMOps.push_back(Chain);
2504
2505         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2506         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2507         SaveXMMOps.push_back(ALVal);
2508
2509         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2510                                FuncInfo->getRegSaveFrameIndex()));
2511         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2512                                FuncInfo->getVarArgsFPOffset()));
2513
2514         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2515           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2516                                        &X86::VR128RegClass);
2517           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2518           SaveXMMOps.push_back(Val);
2519         }
2520         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2521                                      MVT::Other, SaveXMMOps));
2522       }
2523
2524       if (!MemOps.empty())
2525         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2526     }
2527   }
2528
2529   // Some CCs need callee pop.
2530   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2531                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2532     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2533   } else {
2534     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2535     // If this is an sret function, the return should pop the hidden pointer.
2536     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2537         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2538         argsAreStructReturn(Ins) == StackStructReturn)
2539       FuncInfo->setBytesToPopOnReturn(4);
2540   }
2541
2542   if (!Is64Bit) {
2543     // RegSaveFrameIndex is X86-64 only.
2544     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2545     if (CallConv == CallingConv::X86_FastCall ||
2546         CallConv == CallingConv::X86_ThisCall)
2547       // fastcc functions can't have varargs.
2548       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2549   }
2550
2551   FuncInfo->setArgumentStackSize(StackSize);
2552
2553   return Chain;
2554 }
2555
2556 SDValue
2557 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2558                                     SDValue StackPtr, SDValue Arg,
2559                                     SDLoc dl, SelectionDAG &DAG,
2560                                     const CCValAssign &VA,
2561                                     ISD::ArgFlagsTy Flags) const {
2562   unsigned LocMemOffset = VA.getLocMemOffset();
2563   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2564   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2565   if (Flags.isByVal())
2566     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2567
2568   return DAG.getStore(Chain, dl, Arg, PtrOff,
2569                       MachinePointerInfo::getStack(LocMemOffset),
2570                       false, false, 0);
2571 }
2572
2573 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2574 /// optimization is performed and it is required.
2575 SDValue
2576 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2577                                            SDValue &OutRetAddr, SDValue Chain,
2578                                            bool IsTailCall, bool Is64Bit,
2579                                            int FPDiff, SDLoc dl) const {
2580   // Adjust the Return address stack slot.
2581   EVT VT = getPointerTy();
2582   OutRetAddr = getReturnAddressFrameIndex(DAG);
2583
2584   // Load the "old" Return address.
2585   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2586                            false, false, false, 0);
2587   return SDValue(OutRetAddr.getNode(), 1);
2588 }
2589
2590 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2591 /// optimization is performed and it is required (FPDiff!=0).
2592 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2593                                         SDValue Chain, SDValue RetAddrFrIdx,
2594                                         EVT PtrVT, unsigned SlotSize,
2595                                         int FPDiff, SDLoc dl) {
2596   // Store the return address to the appropriate stack slot.
2597   if (!FPDiff) return Chain;
2598   // Calculate the new stack slot for the return address.
2599   int NewReturnAddrFI =
2600     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2601                                          false);
2602   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2603   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2604                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2605                        false, false, 0);
2606   return Chain;
2607 }
2608
2609 SDValue
2610 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2611                              SmallVectorImpl<SDValue> &InVals) const {
2612   SelectionDAG &DAG                     = CLI.DAG;
2613   SDLoc &dl                             = CLI.DL;
2614   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2615   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2616   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2617   SDValue Chain                         = CLI.Chain;
2618   SDValue Callee                        = CLI.Callee;
2619   CallingConv::ID CallConv              = CLI.CallConv;
2620   bool &isTailCall                      = CLI.IsTailCall;
2621   bool isVarArg                         = CLI.IsVarArg;
2622
2623   MachineFunction &MF = DAG.getMachineFunction();
2624   bool Is64Bit        = Subtarget->is64Bit();
2625   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2626   StructReturnType SR = callIsStructReturn(Outs);
2627   bool IsSibcall      = false;
2628
2629   if (MF.getTarget().Options.DisableTailCalls)
2630     isTailCall = false;
2631
2632   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2633   if (IsMustTail) {
2634     // Force this to be a tail call.  The verifier rules are enough to ensure
2635     // that we can lower this successfully without moving the return address
2636     // around.
2637     isTailCall = true;
2638   } else if (isTailCall) {
2639     // Check if it's really possible to do a tail call.
2640     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2641                     isVarArg, SR != NotStructReturn,
2642                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2643                     Outs, OutVals, Ins, DAG);
2644
2645     // Sibcalls are automatically detected tailcalls which do not require
2646     // ABI changes.
2647     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2648       IsSibcall = true;
2649
2650     if (isTailCall)
2651       ++NumTailCalls;
2652   }
2653
2654   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2655          "Var args not supported with calling convention fastcc, ghc or hipe");
2656
2657   // Analyze operands of the call, assigning locations to each operand.
2658   SmallVector<CCValAssign, 16> ArgLocs;
2659   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2660                  ArgLocs, *DAG.getContext());
2661
2662   // Allocate shadow area for Win64
2663   if (IsWin64)
2664     CCInfo.AllocateStack(32, 8);
2665
2666   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2667
2668   // Get a count of how many bytes are to be pushed on the stack.
2669   unsigned NumBytes = CCInfo.getNextStackOffset();
2670   if (IsSibcall)
2671     // This is a sibcall. The memory operands are available in caller's
2672     // own caller's stack.
2673     NumBytes = 0;
2674   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2675            IsTailCallConvention(CallConv))
2676     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2677
2678   int FPDiff = 0;
2679   if (isTailCall && !IsSibcall && !IsMustTail) {
2680     // Lower arguments at fp - stackoffset + fpdiff.
2681     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2682     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2683
2684     FPDiff = NumBytesCallerPushed - NumBytes;
2685
2686     // Set the delta of movement of the returnaddr stackslot.
2687     // But only set if delta is greater than previous delta.
2688     if (FPDiff < X86Info->getTCReturnAddrDelta())
2689       X86Info->setTCReturnAddrDelta(FPDiff);
2690   }
2691
2692   unsigned NumBytesToPush = NumBytes;
2693   unsigned NumBytesToPop = NumBytes;
2694
2695   // If we have an inalloca argument, all stack space has already been allocated
2696   // for us and be right at the top of the stack.  We don't support multiple
2697   // arguments passed in memory when using inalloca.
2698   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2699     NumBytesToPush = 0;
2700     if (!ArgLocs.back().isMemLoc())
2701       report_fatal_error("cannot use inalloca attribute on a register "
2702                          "parameter");
2703     if (ArgLocs.back().getLocMemOffset() != 0)
2704       report_fatal_error("any parameter with the inalloca attribute must be "
2705                          "the only memory argument");
2706   }
2707
2708   if (!IsSibcall)
2709     Chain = DAG.getCALLSEQ_START(
2710         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2711
2712   SDValue RetAddrFrIdx;
2713   // Load return address for tail calls.
2714   if (isTailCall && FPDiff)
2715     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2716                                     Is64Bit, FPDiff, dl);
2717
2718   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2719   SmallVector<SDValue, 8> MemOpChains;
2720   SDValue StackPtr;
2721
2722   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2723   // of tail call optimization arguments are handle later.
2724   const X86RegisterInfo *RegInfo =
2725     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2726   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2727     // Skip inalloca arguments, they have already been written.
2728     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2729     if (Flags.isInAlloca())
2730       continue;
2731
2732     CCValAssign &VA = ArgLocs[i];
2733     EVT RegVT = VA.getLocVT();
2734     SDValue Arg = OutVals[i];
2735     bool isByVal = Flags.isByVal();
2736
2737     // Promote the value if needed.
2738     switch (VA.getLocInfo()) {
2739     default: llvm_unreachable("Unknown loc info!");
2740     case CCValAssign::Full: break;
2741     case CCValAssign::SExt:
2742       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2743       break;
2744     case CCValAssign::ZExt:
2745       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2746       break;
2747     case CCValAssign::AExt:
2748       if (RegVT.is128BitVector()) {
2749         // Special case: passing MMX values in XMM registers.
2750         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2751         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2752         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2753       } else
2754         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2755       break;
2756     case CCValAssign::BCvt:
2757       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2758       break;
2759     case CCValAssign::Indirect: {
2760       // Store the argument.
2761       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2762       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2763       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2764                            MachinePointerInfo::getFixedStack(FI),
2765                            false, false, 0);
2766       Arg = SpillSlot;
2767       break;
2768     }
2769     }
2770
2771     if (VA.isRegLoc()) {
2772       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2773       if (isVarArg && IsWin64) {
2774         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2775         // shadow reg if callee is a varargs function.
2776         unsigned ShadowReg = 0;
2777         switch (VA.getLocReg()) {
2778         case X86::XMM0: ShadowReg = X86::RCX; break;
2779         case X86::XMM1: ShadowReg = X86::RDX; break;
2780         case X86::XMM2: ShadowReg = X86::R8; break;
2781         case X86::XMM3: ShadowReg = X86::R9; break;
2782         }
2783         if (ShadowReg)
2784           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2785       }
2786     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2787       assert(VA.isMemLoc());
2788       if (!StackPtr.getNode())
2789         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2790                                       getPointerTy());
2791       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2792                                              dl, DAG, VA, Flags));
2793     }
2794   }
2795
2796   if (!MemOpChains.empty())
2797     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2798
2799   if (Subtarget->isPICStyleGOT()) {
2800     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2801     // GOT pointer.
2802     if (!isTailCall) {
2803       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2804                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2805     } else {
2806       // If we are tail calling and generating PIC/GOT style code load the
2807       // address of the callee into ECX. The value in ecx is used as target of
2808       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2809       // for tail calls on PIC/GOT architectures. Normally we would just put the
2810       // address of GOT into ebx and then call target@PLT. But for tail calls
2811       // ebx would be restored (since ebx is callee saved) before jumping to the
2812       // target@PLT.
2813
2814       // Note: The actual moving to ECX is done further down.
2815       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2816       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2817           !G->getGlobal()->hasProtectedVisibility())
2818         Callee = LowerGlobalAddress(Callee, DAG);
2819       else if (isa<ExternalSymbolSDNode>(Callee))
2820         Callee = LowerExternalSymbol(Callee, DAG);
2821     }
2822   }
2823
2824   if (Is64Bit && isVarArg && !IsWin64) {
2825     // From AMD64 ABI document:
2826     // For calls that may call functions that use varargs or stdargs
2827     // (prototype-less calls or calls to functions containing ellipsis (...) in
2828     // the declaration) %al is used as hidden argument to specify the number
2829     // of SSE registers used. The contents of %al do not need to match exactly
2830     // the number of registers, but must be an ubound on the number of SSE
2831     // registers used and is in the range 0 - 8 inclusive.
2832
2833     // Count the number of XMM registers allocated.
2834     static const MCPhysReg XMMArgRegs[] = {
2835       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2836       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2837     };
2838     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2839     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2840            && "SSE registers cannot be used when SSE is disabled");
2841
2842     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2843                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2844   }
2845
2846   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2847   // don't need this because the eligibility check rejects calls that require
2848   // shuffling arguments passed in memory.
2849   if (!IsSibcall && isTailCall) {
2850     // Force all the incoming stack arguments to be loaded from the stack
2851     // before any new outgoing arguments are stored to the stack, because the
2852     // outgoing stack slots may alias the incoming argument stack slots, and
2853     // the alias isn't otherwise explicit. This is slightly more conservative
2854     // than necessary, because it means that each store effectively depends
2855     // on every argument instead of just those arguments it would clobber.
2856     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2857
2858     SmallVector<SDValue, 8> MemOpChains2;
2859     SDValue FIN;
2860     int FI = 0;
2861     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2862       CCValAssign &VA = ArgLocs[i];
2863       if (VA.isRegLoc())
2864         continue;
2865       assert(VA.isMemLoc());
2866       SDValue Arg = OutVals[i];
2867       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2868       // Skip inalloca arguments.  They don't require any work.
2869       if (Flags.isInAlloca())
2870         continue;
2871       // Create frame index.
2872       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2873       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2874       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2875       FIN = DAG.getFrameIndex(FI, getPointerTy());
2876
2877       if (Flags.isByVal()) {
2878         // Copy relative to framepointer.
2879         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2880         if (!StackPtr.getNode())
2881           StackPtr = DAG.getCopyFromReg(Chain, dl,
2882                                         RegInfo->getStackRegister(),
2883                                         getPointerTy());
2884         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2885
2886         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2887                                                          ArgChain,
2888                                                          Flags, DAG, dl));
2889       } else {
2890         // Store relative to framepointer.
2891         MemOpChains2.push_back(
2892           DAG.getStore(ArgChain, dl, Arg, FIN,
2893                        MachinePointerInfo::getFixedStack(FI),
2894                        false, false, 0));
2895       }
2896     }
2897
2898     if (!MemOpChains2.empty())
2899       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2900
2901     // Store the return address to the appropriate stack slot.
2902     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2903                                      getPointerTy(), RegInfo->getSlotSize(),
2904                                      FPDiff, dl);
2905   }
2906
2907   // Build a sequence of copy-to-reg nodes chained together with token chain
2908   // and flag operands which copy the outgoing args into registers.
2909   SDValue InFlag;
2910   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2911     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2912                              RegsToPass[i].second, InFlag);
2913     InFlag = Chain.getValue(1);
2914   }
2915
2916   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2917     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2918     // In the 64-bit large code model, we have to make all calls
2919     // through a register, since the call instruction's 32-bit
2920     // pc-relative offset may not be large enough to hold the whole
2921     // address.
2922   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2923     // If the callee is a GlobalAddress node (quite common, every direct call
2924     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2925     // it.
2926
2927     // We should use extra load for direct calls to dllimported functions in
2928     // non-JIT mode.
2929     const GlobalValue *GV = G->getGlobal();
2930     if (!GV->hasDLLImportStorageClass()) {
2931       unsigned char OpFlags = 0;
2932       bool ExtraLoad = false;
2933       unsigned WrapperKind = ISD::DELETED_NODE;
2934
2935       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2936       // external symbols most go through the PLT in PIC mode.  If the symbol
2937       // has hidden or protected visibility, or if it is static or local, then
2938       // we don't need to use the PLT - we can directly call it.
2939       if (Subtarget->isTargetELF() &&
2940           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2941           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2942         OpFlags = X86II::MO_PLT;
2943       } else if (Subtarget->isPICStyleStubAny() &&
2944                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2945                  (!Subtarget->getTargetTriple().isMacOSX() ||
2946                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2947         // PC-relative references to external symbols should go through $stub,
2948         // unless we're building with the leopard linker or later, which
2949         // automatically synthesizes these stubs.
2950         OpFlags = X86II::MO_DARWIN_STUB;
2951       } else if (Subtarget->isPICStyleRIPRel() &&
2952                  isa<Function>(GV) &&
2953                  cast<Function>(GV)->getAttributes().
2954                    hasAttribute(AttributeSet::FunctionIndex,
2955                                 Attribute::NonLazyBind)) {
2956         // If the function is marked as non-lazy, generate an indirect call
2957         // which loads from the GOT directly. This avoids runtime overhead
2958         // at the cost of eager binding (and one extra byte of encoding).
2959         OpFlags = X86II::MO_GOTPCREL;
2960         WrapperKind = X86ISD::WrapperRIP;
2961         ExtraLoad = true;
2962       }
2963
2964       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2965                                           G->getOffset(), OpFlags);
2966
2967       // Add a wrapper if needed.
2968       if (WrapperKind != ISD::DELETED_NODE)
2969         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2970       // Add extra indirection if needed.
2971       if (ExtraLoad)
2972         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2973                              MachinePointerInfo::getGOT(),
2974                              false, false, false, 0);
2975     }
2976   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2977     unsigned char OpFlags = 0;
2978
2979     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2980     // external symbols should go through the PLT.
2981     if (Subtarget->isTargetELF() &&
2982         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2983       OpFlags = X86II::MO_PLT;
2984     } else if (Subtarget->isPICStyleStubAny() &&
2985                (!Subtarget->getTargetTriple().isMacOSX() ||
2986                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2987       // PC-relative references to external symbols should go through $stub,
2988       // unless we're building with the leopard linker or later, which
2989       // automatically synthesizes these stubs.
2990       OpFlags = X86II::MO_DARWIN_STUB;
2991     }
2992
2993     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2994                                          OpFlags);
2995   }
2996
2997   // Returns a chain & a flag for retval copy to use.
2998   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2999   SmallVector<SDValue, 8> Ops;
3000
3001   if (!IsSibcall && isTailCall) {
3002     Chain = DAG.getCALLSEQ_END(Chain,
3003                                DAG.getIntPtrConstant(NumBytesToPop, true),
3004                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3005     InFlag = Chain.getValue(1);
3006   }
3007
3008   Ops.push_back(Chain);
3009   Ops.push_back(Callee);
3010
3011   if (isTailCall)
3012     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3013
3014   // Add argument registers to the end of the list so that they are known live
3015   // into the call.
3016   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3017     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3018                                   RegsToPass[i].second.getValueType()));
3019
3020   // Add a register mask operand representing the call-preserved registers.
3021   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3022   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3023   assert(Mask && "Missing call preserved mask for calling convention");
3024   Ops.push_back(DAG.getRegisterMask(Mask));
3025
3026   if (InFlag.getNode())
3027     Ops.push_back(InFlag);
3028
3029   if (isTailCall) {
3030     // We used to do:
3031     //// If this is the first return lowered for this function, add the regs
3032     //// to the liveout set for the function.
3033     // This isn't right, although it's probably harmless on x86; liveouts
3034     // should be computed from returns not tail calls.  Consider a void
3035     // function making a tail call to a function returning int.
3036     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3037   }
3038
3039   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3040   InFlag = Chain.getValue(1);
3041
3042   // Create the CALLSEQ_END node.
3043   unsigned NumBytesForCalleeToPop;
3044   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3045                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3046     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3047   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3048            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3049            SR == StackStructReturn)
3050     // If this is a call to a struct-return function, the callee
3051     // pops the hidden struct pointer, so we have to push it back.
3052     // This is common for Darwin/X86, Linux & Mingw32 targets.
3053     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3054     NumBytesForCalleeToPop = 4;
3055   else
3056     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3057
3058   // Returns a flag for retval copy to use.
3059   if (!IsSibcall) {
3060     Chain = DAG.getCALLSEQ_END(Chain,
3061                                DAG.getIntPtrConstant(NumBytesToPop, true),
3062                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3063                                                      true),
3064                                InFlag, dl);
3065     InFlag = Chain.getValue(1);
3066   }
3067
3068   // Handle result values, copying them out of physregs into vregs that we
3069   // return.
3070   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3071                          Ins, dl, DAG, InVals);
3072 }
3073
3074 //===----------------------------------------------------------------------===//
3075 //                Fast Calling Convention (tail call) implementation
3076 //===----------------------------------------------------------------------===//
3077
3078 //  Like std call, callee cleans arguments, convention except that ECX is
3079 //  reserved for storing the tail called function address. Only 2 registers are
3080 //  free for argument passing (inreg). Tail call optimization is performed
3081 //  provided:
3082 //                * tailcallopt is enabled
3083 //                * caller/callee are fastcc
3084 //  On X86_64 architecture with GOT-style position independent code only local
3085 //  (within module) calls are supported at the moment.
3086 //  To keep the stack aligned according to platform abi the function
3087 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3088 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3089 //  If a tail called function callee has more arguments than the caller the
3090 //  caller needs to make sure that there is room to move the RETADDR to. This is
3091 //  achieved by reserving an area the size of the argument delta right after the
3092 //  original RETADDR, but before the saved framepointer or the spilled registers
3093 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3094 //  stack layout:
3095 //    arg1
3096 //    arg2
3097 //    RETADDR
3098 //    [ new RETADDR
3099 //      move area ]
3100 //    (possible EBP)
3101 //    ESI
3102 //    EDI
3103 //    local1 ..
3104
3105 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3106 /// for a 16 byte align requirement.
3107 unsigned
3108 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3109                                                SelectionDAG& DAG) const {
3110   MachineFunction &MF = DAG.getMachineFunction();
3111   const TargetMachine &TM = MF.getTarget();
3112   const X86RegisterInfo *RegInfo =
3113     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3114   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3115   unsigned StackAlignment = TFI.getStackAlignment();
3116   uint64_t AlignMask = StackAlignment - 1;
3117   int64_t Offset = StackSize;
3118   unsigned SlotSize = RegInfo->getSlotSize();
3119   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3120     // Number smaller than 12 so just add the difference.
3121     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3122   } else {
3123     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3124     Offset = ((~AlignMask) & Offset) + StackAlignment +
3125       (StackAlignment-SlotSize);
3126   }
3127   return Offset;
3128 }
3129
3130 /// MatchingStackOffset - Return true if the given stack call argument is
3131 /// already available in the same position (relatively) of the caller's
3132 /// incoming argument stack.
3133 static
3134 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3135                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3136                          const X86InstrInfo *TII) {
3137   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3138   int FI = INT_MAX;
3139   if (Arg.getOpcode() == ISD::CopyFromReg) {
3140     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3141     if (!TargetRegisterInfo::isVirtualRegister(VR))
3142       return false;
3143     MachineInstr *Def = MRI->getVRegDef(VR);
3144     if (!Def)
3145       return false;
3146     if (!Flags.isByVal()) {
3147       if (!TII->isLoadFromStackSlot(Def, FI))
3148         return false;
3149     } else {
3150       unsigned Opcode = Def->getOpcode();
3151       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3152           Def->getOperand(1).isFI()) {
3153         FI = Def->getOperand(1).getIndex();
3154         Bytes = Flags.getByValSize();
3155       } else
3156         return false;
3157     }
3158   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3159     if (Flags.isByVal())
3160       // ByVal argument is passed in as a pointer but it's now being
3161       // dereferenced. e.g.
3162       // define @foo(%struct.X* %A) {
3163       //   tail call @bar(%struct.X* byval %A)
3164       // }
3165       return false;
3166     SDValue Ptr = Ld->getBasePtr();
3167     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3168     if (!FINode)
3169       return false;
3170     FI = FINode->getIndex();
3171   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3172     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3173     FI = FINode->getIndex();
3174     Bytes = Flags.getByValSize();
3175   } else
3176     return false;
3177
3178   assert(FI != INT_MAX);
3179   if (!MFI->isFixedObjectIndex(FI))
3180     return false;
3181   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3182 }
3183
3184 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3185 /// for tail call optimization. Targets which want to do tail call
3186 /// optimization should implement this function.
3187 bool
3188 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3189                                                      CallingConv::ID CalleeCC,
3190                                                      bool isVarArg,
3191                                                      bool isCalleeStructRet,
3192                                                      bool isCallerStructRet,
3193                                                      Type *RetTy,
3194                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3195                                     const SmallVectorImpl<SDValue> &OutVals,
3196                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3197                                                      SelectionDAG &DAG) const {
3198   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3199     return false;
3200
3201   // If -tailcallopt is specified, make fastcc functions tail-callable.
3202   const MachineFunction &MF = DAG.getMachineFunction();
3203   const Function *CallerF = MF.getFunction();
3204
3205   // If the function return type is x86_fp80 and the callee return type is not,
3206   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3207   // perform a tailcall optimization here.
3208   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3209     return false;
3210
3211   CallingConv::ID CallerCC = CallerF->getCallingConv();
3212   bool CCMatch = CallerCC == CalleeCC;
3213   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3214   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3215
3216   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3217     if (IsTailCallConvention(CalleeCC) && CCMatch)
3218       return true;
3219     return false;
3220   }
3221
3222   // Look for obvious safe cases to perform tail call optimization that do not
3223   // require ABI changes. This is what gcc calls sibcall.
3224
3225   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3226   // emit a special epilogue.
3227   const X86RegisterInfo *RegInfo =
3228     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3229   if (RegInfo->needsStackRealignment(MF))
3230     return false;
3231
3232   // Also avoid sibcall optimization if either caller or callee uses struct
3233   // return semantics.
3234   if (isCalleeStructRet || isCallerStructRet)
3235     return false;
3236
3237   // An stdcall/thiscall caller is expected to clean up its arguments; the
3238   // callee isn't going to do that.
3239   // FIXME: this is more restrictive than needed. We could produce a tailcall
3240   // when the stack adjustment matches. For example, with a thiscall that takes
3241   // only one argument.
3242   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3243                    CallerCC == CallingConv::X86_ThisCall))
3244     return false;
3245
3246   // Do not sibcall optimize vararg calls unless all arguments are passed via
3247   // registers.
3248   if (isVarArg && !Outs.empty()) {
3249
3250     // Optimizing for varargs on Win64 is unlikely to be safe without
3251     // additional testing.
3252     if (IsCalleeWin64 || IsCallerWin64)
3253       return false;
3254
3255     SmallVector<CCValAssign, 16> ArgLocs;
3256     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3257                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3258
3259     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3260     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3261       if (!ArgLocs[i].isRegLoc())
3262         return false;
3263   }
3264
3265   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3266   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3267   // this into a sibcall.
3268   bool Unused = false;
3269   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3270     if (!Ins[i].Used) {
3271       Unused = true;
3272       break;
3273     }
3274   }
3275   if (Unused) {
3276     SmallVector<CCValAssign, 16> RVLocs;
3277     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3278                    DAG.getTarget(), RVLocs, *DAG.getContext());
3279     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3280     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3281       CCValAssign &VA = RVLocs[i];
3282       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3283         return false;
3284     }
3285   }
3286
3287   // If the calling conventions do not match, then we'd better make sure the
3288   // results are returned in the same way as what the caller expects.
3289   if (!CCMatch) {
3290     SmallVector<CCValAssign, 16> RVLocs1;
3291     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3292                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3293     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3294
3295     SmallVector<CCValAssign, 16> RVLocs2;
3296     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3297                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3298     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3299
3300     if (RVLocs1.size() != RVLocs2.size())
3301       return false;
3302     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3303       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3304         return false;
3305       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3306         return false;
3307       if (RVLocs1[i].isRegLoc()) {
3308         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3309           return false;
3310       } else {
3311         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3312           return false;
3313       }
3314     }
3315   }
3316
3317   // If the callee takes no arguments then go on to check the results of the
3318   // call.
3319   if (!Outs.empty()) {
3320     // Check if stack adjustment is needed. For now, do not do this if any
3321     // argument is passed on the stack.
3322     SmallVector<CCValAssign, 16> ArgLocs;
3323     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3324                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3325
3326     // Allocate shadow area for Win64
3327     if (IsCalleeWin64)
3328       CCInfo.AllocateStack(32, 8);
3329
3330     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3331     if (CCInfo.getNextStackOffset()) {
3332       MachineFunction &MF = DAG.getMachineFunction();
3333       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3334         return false;
3335
3336       // Check if the arguments are already laid out in the right way as
3337       // the caller's fixed stack objects.
3338       MachineFrameInfo *MFI = MF.getFrameInfo();
3339       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3340       const X86InstrInfo *TII =
3341           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3342       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3343         CCValAssign &VA = ArgLocs[i];
3344         SDValue Arg = OutVals[i];
3345         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3346         if (VA.getLocInfo() == CCValAssign::Indirect)
3347           return false;
3348         if (!VA.isRegLoc()) {
3349           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3350                                    MFI, MRI, TII))
3351             return false;
3352         }
3353       }
3354     }
3355
3356     // If the tailcall address may be in a register, then make sure it's
3357     // possible to register allocate for it. In 32-bit, the call address can
3358     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3359     // callee-saved registers are restored. These happen to be the same
3360     // registers used to pass 'inreg' arguments so watch out for those.
3361     if (!Subtarget->is64Bit() &&
3362         ((!isa<GlobalAddressSDNode>(Callee) &&
3363           !isa<ExternalSymbolSDNode>(Callee)) ||
3364          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3365       unsigned NumInRegs = 0;
3366       // In PIC we need an extra register to formulate the address computation
3367       // for the callee.
3368       unsigned MaxInRegs =
3369         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3370
3371       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3372         CCValAssign &VA = ArgLocs[i];
3373         if (!VA.isRegLoc())
3374           continue;
3375         unsigned Reg = VA.getLocReg();
3376         switch (Reg) {
3377         default: break;
3378         case X86::EAX: case X86::EDX: case X86::ECX:
3379           if (++NumInRegs == MaxInRegs)
3380             return false;
3381           break;
3382         }
3383       }
3384     }
3385   }
3386
3387   return true;
3388 }
3389
3390 FastISel *
3391 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3392                                   const TargetLibraryInfo *libInfo) const {
3393   return X86::createFastISel(funcInfo, libInfo);
3394 }
3395
3396 //===----------------------------------------------------------------------===//
3397 //                           Other Lowering Hooks
3398 //===----------------------------------------------------------------------===//
3399
3400 static bool MayFoldLoad(SDValue Op) {
3401   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3402 }
3403
3404 static bool MayFoldIntoStore(SDValue Op) {
3405   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3406 }
3407
3408 static bool isTargetShuffle(unsigned Opcode) {
3409   switch(Opcode) {
3410   default: return false;
3411   case X86ISD::PSHUFD:
3412   case X86ISD::PSHUFHW:
3413   case X86ISD::PSHUFLW:
3414   case X86ISD::SHUFP:
3415   case X86ISD::PALIGNR:
3416   case X86ISD::MOVLHPS:
3417   case X86ISD::MOVLHPD:
3418   case X86ISD::MOVHLPS:
3419   case X86ISD::MOVLPS:
3420   case X86ISD::MOVLPD:
3421   case X86ISD::MOVSHDUP:
3422   case X86ISD::MOVSLDUP:
3423   case X86ISD::MOVDDUP:
3424   case X86ISD::MOVSS:
3425   case X86ISD::MOVSD:
3426   case X86ISD::UNPCKL:
3427   case X86ISD::UNPCKH:
3428   case X86ISD::VPERMILP:
3429   case X86ISD::VPERM2X128:
3430   case X86ISD::VPERMI:
3431     return true;
3432   }
3433 }
3434
3435 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3436                                     SDValue V1, SelectionDAG &DAG) {
3437   switch(Opc) {
3438   default: llvm_unreachable("Unknown x86 shuffle node");
3439   case X86ISD::MOVSHDUP:
3440   case X86ISD::MOVSLDUP:
3441   case X86ISD::MOVDDUP:
3442     return DAG.getNode(Opc, dl, VT, V1);
3443   }
3444 }
3445
3446 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3447                                     SDValue V1, unsigned TargetMask,
3448                                     SelectionDAG &DAG) {
3449   switch(Opc) {
3450   default: llvm_unreachable("Unknown x86 shuffle node");
3451   case X86ISD::PSHUFD:
3452   case X86ISD::PSHUFHW:
3453   case X86ISD::PSHUFLW:
3454   case X86ISD::VPERMILP:
3455   case X86ISD::VPERMI:
3456     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3457   }
3458 }
3459
3460 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3461                                     SDValue V1, SDValue V2, unsigned TargetMask,
3462                                     SelectionDAG &DAG) {
3463   switch(Opc) {
3464   default: llvm_unreachable("Unknown x86 shuffle node");
3465   case X86ISD::PALIGNR:
3466   case X86ISD::SHUFP:
3467   case X86ISD::VPERM2X128:
3468     return DAG.getNode(Opc, dl, VT, V1, V2,
3469                        DAG.getConstant(TargetMask, MVT::i8));
3470   }
3471 }
3472
3473 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3474                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3475   switch(Opc) {
3476   default: llvm_unreachable("Unknown x86 shuffle node");
3477   case X86ISD::MOVLHPS:
3478   case X86ISD::MOVLHPD:
3479   case X86ISD::MOVHLPS:
3480   case X86ISD::MOVLPS:
3481   case X86ISD::MOVLPD:
3482   case X86ISD::MOVSS:
3483   case X86ISD::MOVSD:
3484   case X86ISD::UNPCKL:
3485   case X86ISD::UNPCKH:
3486     return DAG.getNode(Opc, dl, VT, V1, V2);
3487   }
3488 }
3489
3490 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3491   MachineFunction &MF = DAG.getMachineFunction();
3492   const X86RegisterInfo *RegInfo =
3493     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3494   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3495   int ReturnAddrIndex = FuncInfo->getRAIndex();
3496
3497   if (ReturnAddrIndex == 0) {
3498     // Set up a frame object for the return address.
3499     unsigned SlotSize = RegInfo->getSlotSize();
3500     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3501                                                            -(int64_t)SlotSize,
3502                                                            false);
3503     FuncInfo->setRAIndex(ReturnAddrIndex);
3504   }
3505
3506   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3507 }
3508
3509 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3510                                        bool hasSymbolicDisplacement) {
3511   // Offset should fit into 32 bit immediate field.
3512   if (!isInt<32>(Offset))
3513     return false;
3514
3515   // If we don't have a symbolic displacement - we don't have any extra
3516   // restrictions.
3517   if (!hasSymbolicDisplacement)
3518     return true;
3519
3520   // FIXME: Some tweaks might be needed for medium code model.
3521   if (M != CodeModel::Small && M != CodeModel::Kernel)
3522     return false;
3523
3524   // For small code model we assume that latest object is 16MB before end of 31
3525   // bits boundary. We may also accept pretty large negative constants knowing
3526   // that all objects are in the positive half of address space.
3527   if (M == CodeModel::Small && Offset < 16*1024*1024)
3528     return true;
3529
3530   // For kernel code model we know that all object resist in the negative half
3531   // of 32bits address space. We may not accept negative offsets, since they may
3532   // be just off and we may accept pretty large positive ones.
3533   if (M == CodeModel::Kernel && Offset > 0)
3534     return true;
3535
3536   return false;
3537 }
3538
3539 /// isCalleePop - Determines whether the callee is required to pop its
3540 /// own arguments. Callee pop is necessary to support tail calls.
3541 bool X86::isCalleePop(CallingConv::ID CallingConv,
3542                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3543   if (IsVarArg)
3544     return false;
3545
3546   switch (CallingConv) {
3547   default:
3548     return false;
3549   case CallingConv::X86_StdCall:
3550     return !is64Bit;
3551   case CallingConv::X86_FastCall:
3552     return !is64Bit;
3553   case CallingConv::X86_ThisCall:
3554     return !is64Bit;
3555   case CallingConv::Fast:
3556     return TailCallOpt;
3557   case CallingConv::GHC:
3558     return TailCallOpt;
3559   case CallingConv::HiPE:
3560     return TailCallOpt;
3561   }
3562 }
3563
3564 /// \brief Return true if the condition is an unsigned comparison operation.
3565 static bool isX86CCUnsigned(unsigned X86CC) {
3566   switch (X86CC) {
3567   default: llvm_unreachable("Invalid integer condition!");
3568   case X86::COND_E:     return true;
3569   case X86::COND_G:     return false;
3570   case X86::COND_GE:    return false;
3571   case X86::COND_L:     return false;
3572   case X86::COND_LE:    return false;
3573   case X86::COND_NE:    return true;
3574   case X86::COND_B:     return true;
3575   case X86::COND_A:     return true;
3576   case X86::COND_BE:    return true;
3577   case X86::COND_AE:    return true;
3578   }
3579   llvm_unreachable("covered switch fell through?!");
3580 }
3581
3582 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3583 /// specific condition code, returning the condition code and the LHS/RHS of the
3584 /// comparison to make.
3585 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3586                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3587   if (!isFP) {
3588     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3589       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3590         // X > -1   -> X == 0, jump !sign.
3591         RHS = DAG.getConstant(0, RHS.getValueType());
3592         return X86::COND_NS;
3593       }
3594       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3595         // X < 0   -> X == 0, jump on sign.
3596         return X86::COND_S;
3597       }
3598       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3599         // X < 1   -> X <= 0
3600         RHS = DAG.getConstant(0, RHS.getValueType());
3601         return X86::COND_LE;
3602       }
3603     }
3604
3605     switch (SetCCOpcode) {
3606     default: llvm_unreachable("Invalid integer condition!");
3607     case ISD::SETEQ:  return X86::COND_E;
3608     case ISD::SETGT:  return X86::COND_G;
3609     case ISD::SETGE:  return X86::COND_GE;
3610     case ISD::SETLT:  return X86::COND_L;
3611     case ISD::SETLE:  return X86::COND_LE;
3612     case ISD::SETNE:  return X86::COND_NE;
3613     case ISD::SETULT: return X86::COND_B;
3614     case ISD::SETUGT: return X86::COND_A;
3615     case ISD::SETULE: return X86::COND_BE;
3616     case ISD::SETUGE: return X86::COND_AE;
3617     }
3618   }
3619
3620   // First determine if it is required or is profitable to flip the operands.
3621
3622   // If LHS is a foldable load, but RHS is not, flip the condition.
3623   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3624       !ISD::isNON_EXTLoad(RHS.getNode())) {
3625     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3626     std::swap(LHS, RHS);
3627   }
3628
3629   switch (SetCCOpcode) {
3630   default: break;
3631   case ISD::SETOLT:
3632   case ISD::SETOLE:
3633   case ISD::SETUGT:
3634   case ISD::SETUGE:
3635     std::swap(LHS, RHS);
3636     break;
3637   }
3638
3639   // On a floating point condition, the flags are set as follows:
3640   // ZF  PF  CF   op
3641   //  0 | 0 | 0 | X > Y
3642   //  0 | 0 | 1 | X < Y
3643   //  1 | 0 | 0 | X == Y
3644   //  1 | 1 | 1 | unordered
3645   switch (SetCCOpcode) {
3646   default: llvm_unreachable("Condcode should be pre-legalized away");
3647   case ISD::SETUEQ:
3648   case ISD::SETEQ:   return X86::COND_E;
3649   case ISD::SETOLT:              // flipped
3650   case ISD::SETOGT:
3651   case ISD::SETGT:   return X86::COND_A;
3652   case ISD::SETOLE:              // flipped
3653   case ISD::SETOGE:
3654   case ISD::SETGE:   return X86::COND_AE;
3655   case ISD::SETUGT:              // flipped
3656   case ISD::SETULT:
3657   case ISD::SETLT:   return X86::COND_B;
3658   case ISD::SETUGE:              // flipped
3659   case ISD::SETULE:
3660   case ISD::SETLE:   return X86::COND_BE;
3661   case ISD::SETONE:
3662   case ISD::SETNE:   return X86::COND_NE;
3663   case ISD::SETUO:   return X86::COND_P;
3664   case ISD::SETO:    return X86::COND_NP;
3665   case ISD::SETOEQ:
3666   case ISD::SETUNE:  return X86::COND_INVALID;
3667   }
3668 }
3669
3670 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3671 /// code. Current x86 isa includes the following FP cmov instructions:
3672 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3673 static bool hasFPCMov(unsigned X86CC) {
3674   switch (X86CC) {
3675   default:
3676     return false;
3677   case X86::COND_B:
3678   case X86::COND_BE:
3679   case X86::COND_E:
3680   case X86::COND_P:
3681   case X86::COND_A:
3682   case X86::COND_AE:
3683   case X86::COND_NE:
3684   case X86::COND_NP:
3685     return true;
3686   }
3687 }
3688
3689 /// isFPImmLegal - Returns true if the target can instruction select the
3690 /// specified FP immediate natively. If false, the legalizer will
3691 /// materialize the FP immediate as a load from a constant pool.
3692 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3693   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3694     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3695       return true;
3696   }
3697   return false;
3698 }
3699
3700 /// \brief Returns true if it is beneficial to convert a load of a constant
3701 /// to just the constant itself.
3702 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3703                                                           Type *Ty) const {
3704   assert(Ty->isIntegerTy());
3705
3706   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3707   if (BitSize == 0 || BitSize > 64)
3708     return false;
3709   return true;
3710 }
3711
3712 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3713 /// the specified range (L, H].
3714 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3715   return (Val < 0) || (Val >= Low && Val < Hi);
3716 }
3717
3718 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3719 /// specified value.
3720 static bool isUndefOrEqual(int Val, int CmpVal) {
3721   return (Val < 0 || Val == CmpVal);
3722 }
3723
3724 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3725 /// from position Pos and ending in Pos+Size, falls within the specified
3726 /// sequential range (L, L+Pos]. or is undef.
3727 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3728                                        unsigned Pos, unsigned Size, int Low) {
3729   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3730     if (!isUndefOrEqual(Mask[i], Low))
3731       return false;
3732   return true;
3733 }
3734
3735 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3736 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3737 /// the second operand.
3738 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3739   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3740     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3741   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3742     return (Mask[0] < 2 && Mask[1] < 2);
3743   return false;
3744 }
3745
3746 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3747 /// is suitable for input to PSHUFHW.
3748 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3749   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3750     return false;
3751
3752   // Lower quadword copied in order or undef.
3753   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3754     return false;
3755
3756   // Upper quadword shuffled.
3757   for (unsigned i = 4; i != 8; ++i)
3758     if (!isUndefOrInRange(Mask[i], 4, 8))
3759       return false;
3760
3761   if (VT == MVT::v16i16) {
3762     // Lower quadword copied in order or undef.
3763     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3764       return false;
3765
3766     // Upper quadword shuffled.
3767     for (unsigned i = 12; i != 16; ++i)
3768       if (!isUndefOrInRange(Mask[i], 12, 16))
3769         return false;
3770   }
3771
3772   return true;
3773 }
3774
3775 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3776 /// is suitable for input to PSHUFLW.
3777 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3778   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3779     return false;
3780
3781   // Upper quadword copied in order.
3782   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3783     return false;
3784
3785   // Lower quadword shuffled.
3786   for (unsigned i = 0; i != 4; ++i)
3787     if (!isUndefOrInRange(Mask[i], 0, 4))
3788       return false;
3789
3790   if (VT == MVT::v16i16) {
3791     // Upper quadword copied in order.
3792     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3793       return false;
3794
3795     // Lower quadword shuffled.
3796     for (unsigned i = 8; i != 12; ++i)
3797       if (!isUndefOrInRange(Mask[i], 8, 12))
3798         return false;
3799   }
3800
3801   return true;
3802 }
3803
3804 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3805 /// is suitable for input to PALIGNR.
3806 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3807                           const X86Subtarget *Subtarget) {
3808   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3809       (VT.is256BitVector() && !Subtarget->hasInt256()))
3810     return false;
3811
3812   unsigned NumElts = VT.getVectorNumElements();
3813   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3814   unsigned NumLaneElts = NumElts/NumLanes;
3815
3816   // Do not handle 64-bit element shuffles with palignr.
3817   if (NumLaneElts == 2)
3818     return false;
3819
3820   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3821     unsigned i;
3822     for (i = 0; i != NumLaneElts; ++i) {
3823       if (Mask[i+l] >= 0)
3824         break;
3825     }
3826
3827     // Lane is all undef, go to next lane
3828     if (i == NumLaneElts)
3829       continue;
3830
3831     int Start = Mask[i+l];
3832
3833     // Make sure its in this lane in one of the sources
3834     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3835         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3836       return false;
3837
3838     // If not lane 0, then we must match lane 0
3839     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3840       return false;
3841
3842     // Correct second source to be contiguous with first source
3843     if (Start >= (int)NumElts)
3844       Start -= NumElts - NumLaneElts;
3845
3846     // Make sure we're shifting in the right direction.
3847     if (Start <= (int)(i+l))
3848       return false;
3849
3850     Start -= i;
3851
3852     // Check the rest of the elements to see if they are consecutive.
3853     for (++i; i != NumLaneElts; ++i) {
3854       int Idx = Mask[i+l];
3855
3856       // Make sure its in this lane
3857       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3858           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3859         return false;
3860
3861       // If not lane 0, then we must match lane 0
3862       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3863         return false;
3864
3865       if (Idx >= (int)NumElts)
3866         Idx -= NumElts - NumLaneElts;
3867
3868       if (!isUndefOrEqual(Idx, Start+i))
3869         return false;
3870
3871     }
3872   }
3873
3874   return true;
3875 }
3876
3877 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3878 /// the two vector operands have swapped position.
3879 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3880                                      unsigned NumElems) {
3881   for (unsigned i = 0; i != NumElems; ++i) {
3882     int idx = Mask[i];
3883     if (idx < 0)
3884       continue;
3885     else if (idx < (int)NumElems)
3886       Mask[i] = idx + NumElems;
3887     else
3888       Mask[i] = idx - NumElems;
3889   }
3890 }
3891
3892 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3893 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3894 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3895 /// reverse of what x86 shuffles want.
3896 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3897
3898   unsigned NumElems = VT.getVectorNumElements();
3899   unsigned NumLanes = VT.getSizeInBits()/128;
3900   unsigned NumLaneElems = NumElems/NumLanes;
3901
3902   if (NumLaneElems != 2 && NumLaneElems != 4)
3903     return false;
3904
3905   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3906   bool symetricMaskRequired =
3907     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3908
3909   // VSHUFPSY divides the resulting vector into 4 chunks.
3910   // The sources are also splitted into 4 chunks, and each destination
3911   // chunk must come from a different source chunk.
3912   //
3913   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3914   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3915   //
3916   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3917   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3918   //
3919   // VSHUFPDY divides the resulting vector into 4 chunks.
3920   // The sources are also splitted into 4 chunks, and each destination
3921   // chunk must come from a different source chunk.
3922   //
3923   //  SRC1 =>      X3       X2       X1       X0
3924   //  SRC2 =>      Y3       Y2       Y1       Y0
3925   //
3926   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3927   //
3928   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3929   unsigned HalfLaneElems = NumLaneElems/2;
3930   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3931     for (unsigned i = 0; i != NumLaneElems; ++i) {
3932       int Idx = Mask[i+l];
3933       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3934       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3935         return false;
3936       // For VSHUFPSY, the mask of the second half must be the same as the
3937       // first but with the appropriate offsets. This works in the same way as
3938       // VPERMILPS works with masks.
3939       if (!symetricMaskRequired || Idx < 0)
3940         continue;
3941       if (MaskVal[i] < 0) {
3942         MaskVal[i] = Idx - l;
3943         continue;
3944       }
3945       if ((signed)(Idx - l) != MaskVal[i])
3946         return false;
3947     }
3948   }
3949
3950   return true;
3951 }
3952
3953 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3954 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3955 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3956   if (!VT.is128BitVector())
3957     return false;
3958
3959   unsigned NumElems = VT.getVectorNumElements();
3960
3961   if (NumElems != 4)
3962     return false;
3963
3964   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3965   return isUndefOrEqual(Mask[0], 6) &&
3966          isUndefOrEqual(Mask[1], 7) &&
3967          isUndefOrEqual(Mask[2], 2) &&
3968          isUndefOrEqual(Mask[3], 3);
3969 }
3970
3971 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3972 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3973 /// <2, 3, 2, 3>
3974 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3975   if (!VT.is128BitVector())
3976     return false;
3977
3978   unsigned NumElems = VT.getVectorNumElements();
3979
3980   if (NumElems != 4)
3981     return false;
3982
3983   return isUndefOrEqual(Mask[0], 2) &&
3984          isUndefOrEqual(Mask[1], 3) &&
3985          isUndefOrEqual(Mask[2], 2) &&
3986          isUndefOrEqual(Mask[3], 3);
3987 }
3988
3989 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3990 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3991 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3992   if (!VT.is128BitVector())
3993     return false;
3994
3995   unsigned NumElems = VT.getVectorNumElements();
3996
3997   if (NumElems != 2 && NumElems != 4)
3998     return false;
3999
4000   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4001     if (!isUndefOrEqual(Mask[i], i + NumElems))
4002       return false;
4003
4004   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4005     if (!isUndefOrEqual(Mask[i], i))
4006       return false;
4007
4008   return true;
4009 }
4010
4011 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4012 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4013 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4014   if (!VT.is128BitVector())
4015     return false;
4016
4017   unsigned NumElems = VT.getVectorNumElements();
4018
4019   if (NumElems != 2 && NumElems != 4)
4020     return false;
4021
4022   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4023     if (!isUndefOrEqual(Mask[i], i))
4024       return false;
4025
4026   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4027     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4028       return false;
4029
4030   return true;
4031 }
4032
4033 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4034 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4035 /// i. e: If all but one element come from the same vector.
4036 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4037   // TODO: Deal with AVX's VINSERTPS
4038   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4039     return false;
4040
4041   unsigned CorrectPosV1 = 0;
4042   unsigned CorrectPosV2 = 0;
4043   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4044     if (Mask[i] == -1) {
4045       ++CorrectPosV1;
4046       ++CorrectPosV2;
4047       continue;
4048     }
4049
4050     if (Mask[i] == i)
4051       ++CorrectPosV1;
4052     else if (Mask[i] == i + 4)
4053       ++CorrectPosV2;
4054   }
4055
4056   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4057     // We have 3 elements (undefs count as elements from any vector) from one
4058     // vector, and one from another.
4059     return true;
4060
4061   return false;
4062 }
4063
4064 //
4065 // Some special combinations that can be optimized.
4066 //
4067 static
4068 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4069                                SelectionDAG &DAG) {
4070   MVT VT = SVOp->getSimpleValueType(0);
4071   SDLoc dl(SVOp);
4072
4073   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4074     return SDValue();
4075
4076   ArrayRef<int> Mask = SVOp->getMask();
4077
4078   // These are the special masks that may be optimized.
4079   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4080   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4081   bool MatchEvenMask = true;
4082   bool MatchOddMask  = true;
4083   for (int i=0; i<8; ++i) {
4084     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4085       MatchEvenMask = false;
4086     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4087       MatchOddMask = false;
4088   }
4089
4090   if (!MatchEvenMask && !MatchOddMask)
4091     return SDValue();
4092
4093   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4094
4095   SDValue Op0 = SVOp->getOperand(0);
4096   SDValue Op1 = SVOp->getOperand(1);
4097
4098   if (MatchEvenMask) {
4099     // Shift the second operand right to 32 bits.
4100     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4101     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4102   } else {
4103     // Shift the first operand left to 32 bits.
4104     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4105     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4106   }
4107   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4108   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4109 }
4110
4111 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4112 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4113 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4114                          bool HasInt256, bool V2IsSplat = false) {
4115
4116   assert(VT.getSizeInBits() >= 128 &&
4117          "Unsupported vector type for unpckl");
4118
4119   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4120   unsigned NumLanes;
4121   unsigned NumOf256BitLanes;
4122   unsigned NumElts = VT.getVectorNumElements();
4123   if (VT.is256BitVector()) {
4124     if (NumElts != 4 && NumElts != 8 &&
4125         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4126     return false;
4127     NumLanes = 2;
4128     NumOf256BitLanes = 1;
4129   } else if (VT.is512BitVector()) {
4130     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4131            "Unsupported vector type for unpckh");
4132     NumLanes = 2;
4133     NumOf256BitLanes = 2;
4134   } else {
4135     NumLanes = 1;
4136     NumOf256BitLanes = 1;
4137   }
4138
4139   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4140   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4141
4142   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4143     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4144       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4145         int BitI  = Mask[l256*NumEltsInStride+l+i];
4146         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4147         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4148           return false;
4149         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4150           return false;
4151         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4152           return false;
4153       }
4154     }
4155   }
4156   return true;
4157 }
4158
4159 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4160 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4161 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4162                          bool HasInt256, bool V2IsSplat = false) {
4163   assert(VT.getSizeInBits() >= 128 &&
4164          "Unsupported vector type for unpckh");
4165
4166   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4167   unsigned NumLanes;
4168   unsigned NumOf256BitLanes;
4169   unsigned NumElts = VT.getVectorNumElements();
4170   if (VT.is256BitVector()) {
4171     if (NumElts != 4 && NumElts != 8 &&
4172         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4173     return false;
4174     NumLanes = 2;
4175     NumOf256BitLanes = 1;
4176   } else if (VT.is512BitVector()) {
4177     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4178            "Unsupported vector type for unpckh");
4179     NumLanes = 2;
4180     NumOf256BitLanes = 2;
4181   } else {
4182     NumLanes = 1;
4183     NumOf256BitLanes = 1;
4184   }
4185
4186   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4187   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4188
4189   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4190     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4191       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4192         int BitI  = Mask[l256*NumEltsInStride+l+i];
4193         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4194         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4195           return false;
4196         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4197           return false;
4198         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4199           return false;
4200       }
4201     }
4202   }
4203   return true;
4204 }
4205
4206 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4207 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4208 /// <0, 0, 1, 1>
4209 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4210   unsigned NumElts = VT.getVectorNumElements();
4211   bool Is256BitVec = VT.is256BitVector();
4212
4213   if (VT.is512BitVector())
4214     return false;
4215   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4216          "Unsupported vector type for unpckh");
4217
4218   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4219       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4220     return false;
4221
4222   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4223   // FIXME: Need a better way to get rid of this, there's no latency difference
4224   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4225   // the former later. We should also remove the "_undef" special mask.
4226   if (NumElts == 4 && Is256BitVec)
4227     return false;
4228
4229   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4230   // independently on 128-bit lanes.
4231   unsigned NumLanes = VT.getSizeInBits()/128;
4232   unsigned NumLaneElts = NumElts/NumLanes;
4233
4234   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4235     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4236       int BitI  = Mask[l+i];
4237       int BitI1 = Mask[l+i+1];
4238
4239       if (!isUndefOrEqual(BitI, j))
4240         return false;
4241       if (!isUndefOrEqual(BitI1, j))
4242         return false;
4243     }
4244   }
4245
4246   return true;
4247 }
4248
4249 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4250 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4251 /// <2, 2, 3, 3>
4252 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4253   unsigned NumElts = VT.getVectorNumElements();
4254
4255   if (VT.is512BitVector())
4256     return false;
4257
4258   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4259          "Unsupported vector type for unpckh");
4260
4261   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4262       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4263     return false;
4264
4265   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4266   // independently on 128-bit lanes.
4267   unsigned NumLanes = VT.getSizeInBits()/128;
4268   unsigned NumLaneElts = NumElts/NumLanes;
4269
4270   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4271     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4272       int BitI  = Mask[l+i];
4273       int BitI1 = Mask[l+i+1];
4274       if (!isUndefOrEqual(BitI, j))
4275         return false;
4276       if (!isUndefOrEqual(BitI1, j))
4277         return false;
4278     }
4279   }
4280   return true;
4281 }
4282
4283 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4284 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4285 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4286   if (!VT.is512BitVector())
4287     return false;
4288
4289   unsigned NumElts = VT.getVectorNumElements();
4290   unsigned HalfSize = NumElts/2;
4291   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4292     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4293       *Imm = 1;
4294       return true;
4295     }
4296   }
4297   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4298     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4299       *Imm = 0;
4300       return true;
4301     }
4302   }
4303   return false;
4304 }
4305
4306 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4307 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4308 /// MOVSD, and MOVD, i.e. setting the lowest element.
4309 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4310   if (VT.getVectorElementType().getSizeInBits() < 32)
4311     return false;
4312   if (!VT.is128BitVector())
4313     return false;
4314
4315   unsigned NumElts = VT.getVectorNumElements();
4316
4317   if (!isUndefOrEqual(Mask[0], NumElts))
4318     return false;
4319
4320   for (unsigned i = 1; i != NumElts; ++i)
4321     if (!isUndefOrEqual(Mask[i], i))
4322       return false;
4323
4324   return true;
4325 }
4326
4327 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4328 /// as permutations between 128-bit chunks or halves. As an example: this
4329 /// shuffle bellow:
4330 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4331 /// The first half comes from the second half of V1 and the second half from the
4332 /// the second half of V2.
4333 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4334   if (!HasFp256 || !VT.is256BitVector())
4335     return false;
4336
4337   // The shuffle result is divided into half A and half B. In total the two
4338   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4339   // B must come from C, D, E or F.
4340   unsigned HalfSize = VT.getVectorNumElements()/2;
4341   bool MatchA = false, MatchB = false;
4342
4343   // Check if A comes from one of C, D, E, F.
4344   for (unsigned Half = 0; Half != 4; ++Half) {
4345     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4346       MatchA = true;
4347       break;
4348     }
4349   }
4350
4351   // Check if B comes from one of C, D, E, F.
4352   for (unsigned Half = 0; Half != 4; ++Half) {
4353     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4354       MatchB = true;
4355       break;
4356     }
4357   }
4358
4359   return MatchA && MatchB;
4360 }
4361
4362 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4363 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4364 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4365   MVT VT = SVOp->getSimpleValueType(0);
4366
4367   unsigned HalfSize = VT.getVectorNumElements()/2;
4368
4369   unsigned FstHalf = 0, SndHalf = 0;
4370   for (unsigned i = 0; i < HalfSize; ++i) {
4371     if (SVOp->getMaskElt(i) > 0) {
4372       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4373       break;
4374     }
4375   }
4376   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4377     if (SVOp->getMaskElt(i) > 0) {
4378       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4379       break;
4380     }
4381   }
4382
4383   return (FstHalf | (SndHalf << 4));
4384 }
4385
4386 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4387 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4388   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4389   if (EltSize < 32)
4390     return false;
4391
4392   unsigned NumElts = VT.getVectorNumElements();
4393   Imm8 = 0;
4394   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4395     for (unsigned i = 0; i != NumElts; ++i) {
4396       if (Mask[i] < 0)
4397         continue;
4398       Imm8 |= Mask[i] << (i*2);
4399     }
4400     return true;
4401   }
4402
4403   unsigned LaneSize = 4;
4404   SmallVector<int, 4> MaskVal(LaneSize, -1);
4405
4406   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4407     for (unsigned i = 0; i != LaneSize; ++i) {
4408       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4409         return false;
4410       if (Mask[i+l] < 0)
4411         continue;
4412       if (MaskVal[i] < 0) {
4413         MaskVal[i] = Mask[i+l] - l;
4414         Imm8 |= MaskVal[i] << (i*2);
4415         continue;
4416       }
4417       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4418         return false;
4419     }
4420   }
4421   return true;
4422 }
4423
4424 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4425 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4426 /// Note that VPERMIL mask matching is different depending whether theunderlying
4427 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4428 /// to the same elements of the low, but to the higher half of the source.
4429 /// In VPERMILPD the two lanes could be shuffled independently of each other
4430 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4431 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4432   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4433   if (VT.getSizeInBits() < 256 || EltSize < 32)
4434     return false;
4435   bool symetricMaskRequired = (EltSize == 32);
4436   unsigned NumElts = VT.getVectorNumElements();
4437
4438   unsigned NumLanes = VT.getSizeInBits()/128;
4439   unsigned LaneSize = NumElts/NumLanes;
4440   // 2 or 4 elements in one lane
4441
4442   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4443   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4444     for (unsigned i = 0; i != LaneSize; ++i) {
4445       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4446         return false;
4447       if (symetricMaskRequired) {
4448         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4449           ExpectedMaskVal[i] = Mask[i+l] - l;
4450           continue;
4451         }
4452         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4453           return false;
4454       }
4455     }
4456   }
4457   return true;
4458 }
4459
4460 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4461 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4462 /// element of vector 2 and the other elements to come from vector 1 in order.
4463 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4464                                bool V2IsSplat = false, bool V2IsUndef = false) {
4465   if (!VT.is128BitVector())
4466     return false;
4467
4468   unsigned NumOps = VT.getVectorNumElements();
4469   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4470     return false;
4471
4472   if (!isUndefOrEqual(Mask[0], 0))
4473     return false;
4474
4475   for (unsigned i = 1; i != NumOps; ++i)
4476     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4477           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4478           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4479       return false;
4480
4481   return true;
4482 }
4483
4484 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4485 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4486 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4487 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4488                            const X86Subtarget *Subtarget) {
4489   if (!Subtarget->hasSSE3())
4490     return false;
4491
4492   unsigned NumElems = VT.getVectorNumElements();
4493
4494   if ((VT.is128BitVector() && NumElems != 4) ||
4495       (VT.is256BitVector() && NumElems != 8) ||
4496       (VT.is512BitVector() && NumElems != 16))
4497     return false;
4498
4499   // "i+1" is the value the indexed mask element must have
4500   for (unsigned i = 0; i != NumElems; i += 2)
4501     if (!isUndefOrEqual(Mask[i], i+1) ||
4502         !isUndefOrEqual(Mask[i+1], i+1))
4503       return false;
4504
4505   return true;
4506 }
4507
4508 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4509 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4510 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4511 static bool isMOVSLDUPMask(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" is the value the indexed mask element must have
4524   for (unsigned i = 0; i != NumElems; i += 2)
4525     if (!isUndefOrEqual(Mask[i], i) ||
4526         !isUndefOrEqual(Mask[i+1], i))
4527       return false;
4528
4529   return true;
4530 }
4531
4532 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4533 /// specifies a shuffle of elements that is suitable for input to 256-bit
4534 /// version of MOVDDUP.
4535 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4536   if (!HasFp256 || !VT.is256BitVector())
4537     return false;
4538
4539   unsigned NumElts = VT.getVectorNumElements();
4540   if (NumElts != 4)
4541     return false;
4542
4543   for (unsigned i = 0; i != NumElts/2; ++i)
4544     if (!isUndefOrEqual(Mask[i], 0))
4545       return false;
4546   for (unsigned i = NumElts/2; i != NumElts; ++i)
4547     if (!isUndefOrEqual(Mask[i], NumElts/2))
4548       return false;
4549   return true;
4550 }
4551
4552 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4553 /// specifies a shuffle of elements that is suitable for input to 128-bit
4554 /// version of MOVDDUP.
4555 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4556   if (!VT.is128BitVector())
4557     return false;
4558
4559   unsigned e = VT.getVectorNumElements() / 2;
4560   for (unsigned i = 0; i != e; ++i)
4561     if (!isUndefOrEqual(Mask[i], i))
4562       return false;
4563   for (unsigned i = 0; i != e; ++i)
4564     if (!isUndefOrEqual(Mask[e+i], i))
4565       return false;
4566   return true;
4567 }
4568
4569 /// isVEXTRACTIndex - Return true if the specified
4570 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4571 /// suitable for instruction that extract 128 or 256 bit vectors
4572 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4573   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4574   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4575     return false;
4576
4577   // The index should be aligned on a vecWidth-bit boundary.
4578   uint64_t Index =
4579     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4580
4581   MVT VT = N->getSimpleValueType(0);
4582   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4583   bool Result = (Index * ElSize) % vecWidth == 0;
4584
4585   return Result;
4586 }
4587
4588 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4589 /// operand specifies a subvector insert that is suitable for input to
4590 /// insertion of 128 or 256-bit subvectors
4591 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4592   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4593   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4594     return false;
4595   // The index should be aligned on a vecWidth-bit boundary.
4596   uint64_t Index =
4597     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4598
4599   MVT VT = N->getSimpleValueType(0);
4600   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4601   bool Result = (Index * ElSize) % vecWidth == 0;
4602
4603   return Result;
4604 }
4605
4606 bool X86::isVINSERT128Index(SDNode *N) {
4607   return isVINSERTIndex(N, 128);
4608 }
4609
4610 bool X86::isVINSERT256Index(SDNode *N) {
4611   return isVINSERTIndex(N, 256);
4612 }
4613
4614 bool X86::isVEXTRACT128Index(SDNode *N) {
4615   return isVEXTRACTIndex(N, 128);
4616 }
4617
4618 bool X86::isVEXTRACT256Index(SDNode *N) {
4619   return isVEXTRACTIndex(N, 256);
4620 }
4621
4622 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4623 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4624 /// Handles 128-bit and 256-bit.
4625 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4626   MVT VT = N->getSimpleValueType(0);
4627
4628   assert((VT.getSizeInBits() >= 128) &&
4629          "Unsupported vector type for PSHUF/SHUFP");
4630
4631   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4632   // independently on 128-bit lanes.
4633   unsigned NumElts = VT.getVectorNumElements();
4634   unsigned NumLanes = VT.getSizeInBits()/128;
4635   unsigned NumLaneElts = NumElts/NumLanes;
4636
4637   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4638          "Only supports 2, 4 or 8 elements per lane");
4639
4640   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4641   unsigned Mask = 0;
4642   for (unsigned i = 0; i != NumElts; ++i) {
4643     int Elt = N->getMaskElt(i);
4644     if (Elt < 0) continue;
4645     Elt &= NumLaneElts - 1;
4646     unsigned ShAmt = (i << Shift) % 8;
4647     Mask |= Elt << ShAmt;
4648   }
4649
4650   return Mask;
4651 }
4652
4653 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4654 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4655 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4656   MVT VT = N->getSimpleValueType(0);
4657
4658   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4659          "Unsupported vector type for PSHUFHW");
4660
4661   unsigned NumElts = VT.getVectorNumElements();
4662
4663   unsigned Mask = 0;
4664   for (unsigned l = 0; l != NumElts; l += 8) {
4665     // 8 nodes per lane, but we only care about the last 4.
4666     for (unsigned i = 0; i < 4; ++i) {
4667       int Elt = N->getMaskElt(l+i+4);
4668       if (Elt < 0) continue;
4669       Elt &= 0x3; // only 2-bits.
4670       Mask |= Elt << (i * 2);
4671     }
4672   }
4673
4674   return Mask;
4675 }
4676
4677 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4678 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4679 static unsigned getShufflePSHUFLWImmediate(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 first 4.
4690     for (unsigned i = 0; i < 4; ++i) {
4691       int Elt = N->getMaskElt(l+i);
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 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4702 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4703 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4704   MVT VT = SVOp->getSimpleValueType(0);
4705   unsigned EltSize = VT.is512BitVector() ? 1 :
4706     VT.getVectorElementType().getSizeInBits() >> 3;
4707
4708   unsigned NumElts = VT.getVectorNumElements();
4709   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4710   unsigned NumLaneElts = NumElts/NumLanes;
4711
4712   int Val = 0;
4713   unsigned i;
4714   for (i = 0; i != NumElts; ++i) {
4715     Val = SVOp->getMaskElt(i);
4716     if (Val >= 0)
4717       break;
4718   }
4719   if (Val >= (int)NumElts)
4720     Val -= NumElts - NumLaneElts;
4721
4722   assert(Val - i > 0 && "PALIGNR imm should be positive");
4723   return (Val - i) * EltSize;
4724 }
4725
4726 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4727   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4728   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4729     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4730
4731   uint64_t Index =
4732     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4733
4734   MVT VecVT = N->getOperand(0).getSimpleValueType();
4735   MVT ElVT = VecVT.getVectorElementType();
4736
4737   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4738   return Index / NumElemsPerChunk;
4739 }
4740
4741 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4742   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4743   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4744     llvm_unreachable("Illegal insert subvector for VINSERT");
4745
4746   uint64_t Index =
4747     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4748
4749   MVT VecVT = N->getSimpleValueType(0);
4750   MVT ElVT = VecVT.getVectorElementType();
4751
4752   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4753   return Index / NumElemsPerChunk;
4754 }
4755
4756 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4757 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4758 /// and VINSERTI128 instructions.
4759 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4760   return getExtractVEXTRACTImmediate(N, 128);
4761 }
4762
4763 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4764 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4765 /// and VINSERTI64x4 instructions.
4766 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4767   return getExtractVEXTRACTImmediate(N, 256);
4768 }
4769
4770 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4771 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4772 /// and VINSERTI128 instructions.
4773 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4774   return getInsertVINSERTImmediate(N, 128);
4775 }
4776
4777 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4778 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4779 /// and VINSERTI64x4 instructions.
4780 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4781   return getInsertVINSERTImmediate(N, 256);
4782 }
4783
4784 /// isZero - Returns true if Elt is a constant integer zero
4785 static bool isZero(SDValue V) {
4786   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4787   return C && C->isNullValue();
4788 }
4789
4790 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4791 /// constant +0.0.
4792 bool X86::isZeroNode(SDValue Elt) {
4793   if (isZero(Elt))
4794     return true;
4795   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4796     return CFP->getValueAPF().isPosZero();
4797   return false;
4798 }
4799
4800 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4801 /// match movhlps. The lower half elements should come from upper half of
4802 /// V1 (and in order), and the upper half elements should come from the upper
4803 /// half of V2 (and in order).
4804 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4805   if (!VT.is128BitVector())
4806     return false;
4807   if (VT.getVectorNumElements() != 4)
4808     return false;
4809   for (unsigned i = 0, e = 2; i != e; ++i)
4810     if (!isUndefOrEqual(Mask[i], i+2))
4811       return false;
4812   for (unsigned i = 2; i != 4; ++i)
4813     if (!isUndefOrEqual(Mask[i], i+4))
4814       return false;
4815   return true;
4816 }
4817
4818 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4819 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4820 /// required.
4821 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4822   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4823     return false;
4824   N = N->getOperand(0).getNode();
4825   if (!ISD::isNON_EXTLoad(N))
4826     return false;
4827   if (LD)
4828     *LD = cast<LoadSDNode>(N);
4829   return true;
4830 }
4831
4832 // Test whether the given value is a vector value which will be legalized
4833 // into a load.
4834 static bool WillBeConstantPoolLoad(SDNode *N) {
4835   if (N->getOpcode() != ISD::BUILD_VECTOR)
4836     return false;
4837
4838   // Check for any non-constant elements.
4839   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4840     switch (N->getOperand(i).getNode()->getOpcode()) {
4841     case ISD::UNDEF:
4842     case ISD::ConstantFP:
4843     case ISD::Constant:
4844       break;
4845     default:
4846       return false;
4847     }
4848
4849   // Vectors of all-zeros and all-ones are materialized with special
4850   // instructions rather than being loaded.
4851   return !ISD::isBuildVectorAllZeros(N) &&
4852          !ISD::isBuildVectorAllOnes(N);
4853 }
4854
4855 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4856 /// match movlp{s|d}. The lower half elements should come from lower half of
4857 /// V1 (and in order), and the upper half elements should come from the upper
4858 /// half of V2 (and in order). And since V1 will become the source of the
4859 /// MOVLP, it must be either a vector load or a scalar load to vector.
4860 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4861                                ArrayRef<int> Mask, MVT VT) {
4862   if (!VT.is128BitVector())
4863     return false;
4864
4865   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4866     return false;
4867   // Is V2 is a vector load, don't do this transformation. We will try to use
4868   // load folding shufps op.
4869   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4870     return false;
4871
4872   unsigned NumElems = VT.getVectorNumElements();
4873
4874   if (NumElems != 2 && NumElems != 4)
4875     return false;
4876   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4877     if (!isUndefOrEqual(Mask[i], i))
4878       return false;
4879   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4880     if (!isUndefOrEqual(Mask[i], i+NumElems))
4881       return false;
4882   return true;
4883 }
4884
4885 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4886 /// to an zero vector.
4887 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4888 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4889   SDValue V1 = N->getOperand(0);
4890   SDValue V2 = N->getOperand(1);
4891   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4892   for (unsigned i = 0; i != NumElems; ++i) {
4893     int Idx = N->getMaskElt(i);
4894     if (Idx >= (int)NumElems) {
4895       unsigned Opc = V2.getOpcode();
4896       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4897         continue;
4898       if (Opc != ISD::BUILD_VECTOR ||
4899           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4900         return false;
4901     } else if (Idx >= 0) {
4902       unsigned Opc = V1.getOpcode();
4903       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4904         continue;
4905       if (Opc != ISD::BUILD_VECTOR ||
4906           !X86::isZeroNode(V1.getOperand(Idx)))
4907         return false;
4908     }
4909   }
4910   return true;
4911 }
4912
4913 /// getZeroVector - Returns a vector of specified type with all zero elements.
4914 ///
4915 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4916                              SelectionDAG &DAG, SDLoc dl) {
4917   assert(VT.isVector() && "Expected a vector type");
4918
4919   // Always build SSE zero vectors as <4 x i32> bitcasted
4920   // to their dest type. This ensures they get CSE'd.
4921   SDValue Vec;
4922   if (VT.is128BitVector()) {  // SSE
4923     if (Subtarget->hasSSE2()) {  // SSE2
4924       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4925       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4926     } else { // SSE1
4927       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4928       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4929     }
4930   } else if (VT.is256BitVector()) { // AVX
4931     if (Subtarget->hasInt256()) { // AVX2
4932       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4933       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4934       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4935     } else {
4936       // 256-bit logic and arithmetic instructions in AVX are all
4937       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4938       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4939       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4940       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4941     }
4942   } else if (VT.is512BitVector()) { // AVX-512
4943       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4944       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4945                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4946       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4947   } else if (VT.getScalarType() == MVT::i1) {
4948     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4949     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4950     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4951     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4952   } else
4953     llvm_unreachable("Unexpected vector type");
4954
4955   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4956 }
4957
4958 /// getOnesVector - Returns a vector of specified type with all bits set.
4959 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4960 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4961 /// Then bitcast to their original type, ensuring they get CSE'd.
4962 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4963                              SDLoc dl) {
4964   assert(VT.isVector() && "Expected a vector type");
4965
4966   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4967   SDValue Vec;
4968   if (VT.is256BitVector()) {
4969     if (HasInt256) { // AVX2
4970       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4971       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4972     } else { // AVX
4973       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4974       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4975     }
4976   } else if (VT.is128BitVector()) {
4977     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4978   } else
4979     llvm_unreachable("Unexpected vector type");
4980
4981   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4982 }
4983
4984 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4985 /// that point to V2 points to its first element.
4986 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4987   for (unsigned i = 0; i != NumElems; ++i) {
4988     if (Mask[i] > (int)NumElems) {
4989       Mask[i] = NumElems;
4990     }
4991   }
4992 }
4993
4994 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4995 /// operation of specified width.
4996 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4997                        SDValue V2) {
4998   unsigned NumElems = VT.getVectorNumElements();
4999   SmallVector<int, 8> Mask;
5000   Mask.push_back(NumElems);
5001   for (unsigned i = 1; i != NumElems; ++i)
5002     Mask.push_back(i);
5003   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5004 }
5005
5006 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5007 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5008                           SDValue V2) {
5009   unsigned NumElems = VT.getVectorNumElements();
5010   SmallVector<int, 8> Mask;
5011   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5012     Mask.push_back(i);
5013     Mask.push_back(i + NumElems);
5014   }
5015   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5016 }
5017
5018 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5019 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5020                           SDValue V2) {
5021   unsigned NumElems = VT.getVectorNumElements();
5022   SmallVector<int, 8> Mask;
5023   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5024     Mask.push_back(i + Half);
5025     Mask.push_back(i + NumElems + Half);
5026   }
5027   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5028 }
5029
5030 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5031 // a generic shuffle instruction because the target has no such instructions.
5032 // Generate shuffles which repeat i16 and i8 several times until they can be
5033 // represented by v4f32 and then be manipulated by target suported shuffles.
5034 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5035   MVT VT = V.getSimpleValueType();
5036   int NumElems = VT.getVectorNumElements();
5037   SDLoc dl(V);
5038
5039   while (NumElems > 4) {
5040     if (EltNo < NumElems/2) {
5041       V = getUnpackl(DAG, dl, VT, V, V);
5042     } else {
5043       V = getUnpackh(DAG, dl, VT, V, V);
5044       EltNo -= NumElems/2;
5045     }
5046     NumElems >>= 1;
5047   }
5048   return V;
5049 }
5050
5051 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5052 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5053   MVT VT = V.getSimpleValueType();
5054   SDLoc dl(V);
5055
5056   if (VT.is128BitVector()) {
5057     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5058     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5059     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5060                              &SplatMask[0]);
5061   } else if (VT.is256BitVector()) {
5062     // To use VPERMILPS to splat scalars, the second half of indicies must
5063     // refer to the higher part, which is a duplication of the lower one,
5064     // because VPERMILPS can only handle in-lane permutations.
5065     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5066                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5067
5068     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5069     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5070                              &SplatMask[0]);
5071   } else
5072     llvm_unreachable("Vector size not supported");
5073
5074   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5075 }
5076
5077 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5078 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5079   MVT SrcVT = SV->getSimpleValueType(0);
5080   SDValue V1 = SV->getOperand(0);
5081   SDLoc dl(SV);
5082
5083   int EltNo = SV->getSplatIndex();
5084   int NumElems = SrcVT.getVectorNumElements();
5085   bool Is256BitVec = SrcVT.is256BitVector();
5086
5087   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5088          "Unknown how to promote splat for type");
5089
5090   // Extract the 128-bit part containing the splat element and update
5091   // the splat element index when it refers to the higher register.
5092   if (Is256BitVec) {
5093     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5094     if (EltNo >= NumElems/2)
5095       EltNo -= NumElems/2;
5096   }
5097
5098   // All i16 and i8 vector types can't be used directly by a generic shuffle
5099   // instruction because the target has no such instruction. Generate shuffles
5100   // which repeat i16 and i8 several times until they fit in i32, and then can
5101   // be manipulated by target suported shuffles.
5102   MVT EltVT = SrcVT.getVectorElementType();
5103   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5104     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5105
5106   // Recreate the 256-bit vector and place the same 128-bit vector
5107   // into the low and high part. This is necessary because we want
5108   // to use VPERM* to shuffle the vectors
5109   if (Is256BitVec) {
5110     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5111   }
5112
5113   return getLegalSplat(DAG, V1, EltNo);
5114 }
5115
5116 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5117 /// vector of zero or undef vector.  This produces a shuffle where the low
5118 /// element of V2 is swizzled into the zero/undef vector, landing at element
5119 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5120 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5121                                            bool IsZero,
5122                                            const X86Subtarget *Subtarget,
5123                                            SelectionDAG &DAG) {
5124   MVT VT = V2.getSimpleValueType();
5125   SDValue V1 = IsZero
5126     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5127   unsigned NumElems = VT.getVectorNumElements();
5128   SmallVector<int, 16> MaskVec;
5129   for (unsigned i = 0; i != NumElems; ++i)
5130     // If this is the insertion idx, put the low elt of V2 here.
5131     MaskVec.push_back(i == Idx ? NumElems : i);
5132   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5133 }
5134
5135 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5136 /// target specific opcode. Returns true if the Mask could be calculated.
5137 /// Sets IsUnary to true if only uses one source.
5138 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5139                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5140   unsigned NumElems = VT.getVectorNumElements();
5141   SDValue ImmN;
5142
5143   IsUnary = false;
5144   switch(N->getOpcode()) {
5145   case X86ISD::SHUFP:
5146     ImmN = N->getOperand(N->getNumOperands()-1);
5147     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5148     break;
5149   case X86ISD::UNPCKH:
5150     DecodeUNPCKHMask(VT, Mask);
5151     break;
5152   case X86ISD::UNPCKL:
5153     DecodeUNPCKLMask(VT, Mask);
5154     break;
5155   case X86ISD::MOVHLPS:
5156     DecodeMOVHLPSMask(NumElems, Mask);
5157     break;
5158   case X86ISD::MOVLHPS:
5159     DecodeMOVLHPSMask(NumElems, Mask);
5160     break;
5161   case X86ISD::PALIGNR:
5162     ImmN = N->getOperand(N->getNumOperands()-1);
5163     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5164     break;
5165   case X86ISD::PSHUFD:
5166   case X86ISD::VPERMILP:
5167     ImmN = N->getOperand(N->getNumOperands()-1);
5168     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5169     IsUnary = true;
5170     break;
5171   case X86ISD::PSHUFHW:
5172     ImmN = N->getOperand(N->getNumOperands()-1);
5173     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5174     IsUnary = true;
5175     break;
5176   case X86ISD::PSHUFLW:
5177     ImmN = N->getOperand(N->getNumOperands()-1);
5178     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5179     IsUnary = true;
5180     break;
5181   case X86ISD::VPERMI:
5182     ImmN = N->getOperand(N->getNumOperands()-1);
5183     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5184     IsUnary = true;
5185     break;
5186   case X86ISD::MOVSS:
5187   case X86ISD::MOVSD: {
5188     // The index 0 always comes from the first element of the second source,
5189     // this is why MOVSS and MOVSD are used in the first place. The other
5190     // elements come from the other positions of the first source vector
5191     Mask.push_back(NumElems);
5192     for (unsigned i = 1; i != NumElems; ++i) {
5193       Mask.push_back(i);
5194     }
5195     break;
5196   }
5197   case X86ISD::VPERM2X128:
5198     ImmN = N->getOperand(N->getNumOperands()-1);
5199     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5200     if (Mask.empty()) return false;
5201     break;
5202   case X86ISD::MOVDDUP:
5203   case X86ISD::MOVLHPD:
5204   case X86ISD::MOVLPD:
5205   case X86ISD::MOVLPS:
5206   case X86ISD::MOVSHDUP:
5207   case X86ISD::MOVSLDUP:
5208     // Not yet implemented
5209     return false;
5210   default: llvm_unreachable("unknown target shuffle node");
5211   }
5212
5213   return true;
5214 }
5215
5216 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5217 /// element of the result of the vector shuffle.
5218 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5219                                    unsigned Depth) {
5220   if (Depth == 6)
5221     return SDValue();  // Limit search depth.
5222
5223   SDValue V = SDValue(N, 0);
5224   EVT VT = V.getValueType();
5225   unsigned Opcode = V.getOpcode();
5226
5227   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5228   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5229     int Elt = SV->getMaskElt(Index);
5230
5231     if (Elt < 0)
5232       return DAG.getUNDEF(VT.getVectorElementType());
5233
5234     unsigned NumElems = VT.getVectorNumElements();
5235     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5236                                          : SV->getOperand(1);
5237     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5238   }
5239
5240   // Recurse into target specific vector shuffles to find scalars.
5241   if (isTargetShuffle(Opcode)) {
5242     MVT ShufVT = V.getSimpleValueType();
5243     unsigned NumElems = ShufVT.getVectorNumElements();
5244     SmallVector<int, 16> ShuffleMask;
5245     bool IsUnary;
5246
5247     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5248       return SDValue();
5249
5250     int Elt = ShuffleMask[Index];
5251     if (Elt < 0)
5252       return DAG.getUNDEF(ShufVT.getVectorElementType());
5253
5254     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5255                                          : N->getOperand(1);
5256     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5257                                Depth+1);
5258   }
5259
5260   // Actual nodes that may contain scalar elements
5261   if (Opcode == ISD::BITCAST) {
5262     V = V.getOperand(0);
5263     EVT SrcVT = V.getValueType();
5264     unsigned NumElems = VT.getVectorNumElements();
5265
5266     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5267       return SDValue();
5268   }
5269
5270   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5271     return (Index == 0) ? V.getOperand(0)
5272                         : DAG.getUNDEF(VT.getVectorElementType());
5273
5274   if (V.getOpcode() == ISD::BUILD_VECTOR)
5275     return V.getOperand(Index);
5276
5277   return SDValue();
5278 }
5279
5280 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5281 /// shuffle operation which come from a consecutively from a zero. The
5282 /// search can start in two different directions, from left or right.
5283 /// We count undefs as zeros until PreferredNum is reached.
5284 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5285                                          unsigned NumElems, bool ZerosFromLeft,
5286                                          SelectionDAG &DAG,
5287                                          unsigned PreferredNum = -1U) {
5288   unsigned NumZeros = 0;
5289   for (unsigned i = 0; i != NumElems; ++i) {
5290     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5291     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5292     if (!Elt.getNode())
5293       break;
5294
5295     if (X86::isZeroNode(Elt))
5296       ++NumZeros;
5297     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5298       NumZeros = std::min(NumZeros + 1, PreferredNum);
5299     else
5300       break;
5301   }
5302
5303   return NumZeros;
5304 }
5305
5306 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5307 /// correspond consecutively to elements from one of the vector operands,
5308 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5309 static
5310 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5311                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5312                               unsigned NumElems, unsigned &OpNum) {
5313   bool SeenV1 = false;
5314   bool SeenV2 = false;
5315
5316   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5317     int Idx = SVOp->getMaskElt(i);
5318     // Ignore undef indicies
5319     if (Idx < 0)
5320       continue;
5321
5322     if (Idx < (int)NumElems)
5323       SeenV1 = true;
5324     else
5325       SeenV2 = true;
5326
5327     // Only accept consecutive elements from the same vector
5328     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5329       return false;
5330   }
5331
5332   OpNum = SeenV1 ? 0 : 1;
5333   return true;
5334 }
5335
5336 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5337 /// logical left shift of a vector.
5338 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5339                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5340   unsigned NumElems =
5341     SVOp->getSimpleValueType(0).getVectorNumElements();
5342   unsigned NumZeros = getNumOfConsecutiveZeros(
5343       SVOp, NumElems, false /* check zeros from right */, DAG,
5344       SVOp->getMaskElt(0));
5345   unsigned OpSrc;
5346
5347   if (!NumZeros)
5348     return false;
5349
5350   // Considering the elements in the mask that are not consecutive zeros,
5351   // check if they consecutively come from only one of the source vectors.
5352   //
5353   //               V1 = {X, A, B, C}     0
5354   //                         \  \  \    /
5355   //   vector_shuffle V1, V2 <1, 2, 3, X>
5356   //
5357   if (!isShuffleMaskConsecutive(SVOp,
5358             0,                   // Mask Start Index
5359             NumElems-NumZeros,   // Mask End Index(exclusive)
5360             NumZeros,            // Where to start looking in the src vector
5361             NumElems,            // Number of elements in vector
5362             OpSrc))              // Which source operand ?
5363     return false;
5364
5365   isLeft = false;
5366   ShAmt = NumZeros;
5367   ShVal = SVOp->getOperand(OpSrc);
5368   return true;
5369 }
5370
5371 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5372 /// logical left shift of a vector.
5373 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5374                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5375   unsigned NumElems =
5376     SVOp->getSimpleValueType(0).getVectorNumElements();
5377   unsigned NumZeros = getNumOfConsecutiveZeros(
5378       SVOp, NumElems, true /* check zeros from left */, DAG,
5379       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5380   unsigned OpSrc;
5381
5382   if (!NumZeros)
5383     return false;
5384
5385   // Considering the elements in the mask that are not consecutive zeros,
5386   // check if they consecutively come from only one of the source vectors.
5387   //
5388   //                           0    { A, B, X, X } = V2
5389   //                          / \    /  /
5390   //   vector_shuffle V1, V2 <X, X, 4, 5>
5391   //
5392   if (!isShuffleMaskConsecutive(SVOp,
5393             NumZeros,     // Mask Start Index
5394             NumElems,     // Mask End Index(exclusive)
5395             0,            // Where to start looking in the src vector
5396             NumElems,     // Number of elements in vector
5397             OpSrc))       // Which source operand ?
5398     return false;
5399
5400   isLeft = true;
5401   ShAmt = NumZeros;
5402   ShVal = SVOp->getOperand(OpSrc);
5403   return true;
5404 }
5405
5406 /// isVectorShift - Returns true if the shuffle can be implemented as a
5407 /// logical left or right shift of a vector.
5408 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5409                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5410   // Although the logic below support any bitwidth size, there are no
5411   // shift instructions which handle more than 128-bit vectors.
5412   if (!SVOp->getSimpleValueType(0).is128BitVector())
5413     return false;
5414
5415   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5416       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5417     return true;
5418
5419   return false;
5420 }
5421
5422 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5423 ///
5424 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5425                                        unsigned NumNonZero, unsigned NumZero,
5426                                        SelectionDAG &DAG,
5427                                        const X86Subtarget* Subtarget,
5428                                        const TargetLowering &TLI) {
5429   if (NumNonZero > 8)
5430     return SDValue();
5431
5432   SDLoc dl(Op);
5433   SDValue V;
5434   bool First = true;
5435   for (unsigned i = 0; i < 16; ++i) {
5436     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5437     if (ThisIsNonZero && First) {
5438       if (NumZero)
5439         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5440       else
5441         V = DAG.getUNDEF(MVT::v8i16);
5442       First = false;
5443     }
5444
5445     if ((i & 1) != 0) {
5446       SDValue ThisElt, LastElt;
5447       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5448       if (LastIsNonZero) {
5449         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5450                               MVT::i16, Op.getOperand(i-1));
5451       }
5452       if (ThisIsNonZero) {
5453         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5454         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5455                               ThisElt, DAG.getConstant(8, MVT::i8));
5456         if (LastIsNonZero)
5457           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5458       } else
5459         ThisElt = LastElt;
5460
5461       if (ThisElt.getNode())
5462         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5463                         DAG.getIntPtrConstant(i/2));
5464     }
5465   }
5466
5467   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5468 }
5469
5470 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5471 ///
5472 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5473                                      unsigned NumNonZero, unsigned NumZero,
5474                                      SelectionDAG &DAG,
5475                                      const X86Subtarget* Subtarget,
5476                                      const TargetLowering &TLI) {
5477   if (NumNonZero > 4)
5478     return SDValue();
5479
5480   SDLoc dl(Op);
5481   SDValue V;
5482   bool First = true;
5483   for (unsigned i = 0; i < 8; ++i) {
5484     bool isNonZero = (NonZeros & (1 << i)) != 0;
5485     if (isNonZero) {
5486       if (First) {
5487         if (NumZero)
5488           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5489         else
5490           V = DAG.getUNDEF(MVT::v8i16);
5491         First = false;
5492       }
5493       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5494                       MVT::v8i16, V, Op.getOperand(i),
5495                       DAG.getIntPtrConstant(i));
5496     }
5497   }
5498
5499   return V;
5500 }
5501
5502 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5503 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5504                                      unsigned NonZeros, unsigned NumNonZero,
5505                                      unsigned NumZero, SelectionDAG &DAG,
5506                                      const X86Subtarget *Subtarget,
5507                                      const TargetLowering &TLI) {
5508   // We know there's at least one non-zero element
5509   unsigned FirstNonZeroIdx = 0;
5510   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5511   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5512          X86::isZeroNode(FirstNonZero)) {
5513     ++FirstNonZeroIdx;
5514     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5515   }
5516
5517   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5518       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5519     return SDValue();
5520
5521   SDValue V = FirstNonZero.getOperand(0);
5522   MVT VVT = V.getSimpleValueType();
5523   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5524     return SDValue();
5525
5526   unsigned FirstNonZeroDst =
5527       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5528   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5529   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5530   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5531
5532   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5533     SDValue Elem = Op.getOperand(Idx);
5534     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5535       continue;
5536
5537     // TODO: What else can be here? Deal with it.
5538     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5539       return SDValue();
5540
5541     // TODO: Some optimizations are still possible here
5542     // ex: Getting one element from a vector, and the rest from another.
5543     if (Elem.getOperand(0) != V)
5544       return SDValue();
5545
5546     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5547     if (Dst == Idx)
5548       ++CorrectIdx;
5549     else if (IncorrectIdx == -1U) {
5550       IncorrectIdx = Idx;
5551       IncorrectDst = Dst;
5552     } else
5553       // There was already one element with an incorrect index.
5554       // We can't optimize this case to an insertps.
5555       return SDValue();
5556   }
5557
5558   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5559     SDLoc dl(Op);
5560     EVT VT = Op.getSimpleValueType();
5561     unsigned ElementMoveMask = 0;
5562     if (IncorrectIdx == -1U)
5563       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5564     else
5565       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5566
5567     SDValue InsertpsMask =
5568         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5569     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5570   }
5571
5572   return SDValue();
5573 }
5574
5575 /// getVShift - Return a vector logical shift node.
5576 ///
5577 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5578                          unsigned NumBits, SelectionDAG &DAG,
5579                          const TargetLowering &TLI, SDLoc dl) {
5580   assert(VT.is128BitVector() && "Unknown type for VShift");
5581   EVT ShVT = MVT::v2i64;
5582   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5583   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5584   return DAG.getNode(ISD::BITCAST, dl, VT,
5585                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5586                              DAG.getConstant(NumBits,
5587                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5588 }
5589
5590 static SDValue
5591 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5592
5593   // Check if the scalar load can be widened into a vector load. And if
5594   // the address is "base + cst" see if the cst can be "absorbed" into
5595   // the shuffle mask.
5596   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5597     SDValue Ptr = LD->getBasePtr();
5598     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5599       return SDValue();
5600     EVT PVT = LD->getValueType(0);
5601     if (PVT != MVT::i32 && PVT != MVT::f32)
5602       return SDValue();
5603
5604     int FI = -1;
5605     int64_t Offset = 0;
5606     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5607       FI = FINode->getIndex();
5608       Offset = 0;
5609     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5610                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5611       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5612       Offset = Ptr.getConstantOperandVal(1);
5613       Ptr = Ptr.getOperand(0);
5614     } else {
5615       return SDValue();
5616     }
5617
5618     // FIXME: 256-bit vector instructions don't require a strict alignment,
5619     // improve this code to support it better.
5620     unsigned RequiredAlign = VT.getSizeInBits()/8;
5621     SDValue Chain = LD->getChain();
5622     // Make sure the stack object alignment is at least 16 or 32.
5623     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5624     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5625       if (MFI->isFixedObjectIndex(FI)) {
5626         // Can't change the alignment. FIXME: It's possible to compute
5627         // the exact stack offset and reference FI + adjust offset instead.
5628         // If someone *really* cares about this. That's the way to implement it.
5629         return SDValue();
5630       } else {
5631         MFI->setObjectAlignment(FI, RequiredAlign);
5632       }
5633     }
5634
5635     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5636     // Ptr + (Offset & ~15).
5637     if (Offset < 0)
5638       return SDValue();
5639     if ((Offset % RequiredAlign) & 3)
5640       return SDValue();
5641     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5642     if (StartOffset)
5643       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5644                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5645
5646     int EltNo = (Offset - StartOffset) >> 2;
5647     unsigned NumElems = VT.getVectorNumElements();
5648
5649     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5650     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5651                              LD->getPointerInfo().getWithOffset(StartOffset),
5652                              false, false, false, 0);
5653
5654     SmallVector<int, 8> Mask;
5655     for (unsigned i = 0; i != NumElems; ++i)
5656       Mask.push_back(EltNo);
5657
5658     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5659   }
5660
5661   return SDValue();
5662 }
5663
5664 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5665 /// vector of type 'VT', see if the elements can be replaced by a single large
5666 /// load which has the same value as a build_vector whose operands are 'elts'.
5667 ///
5668 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5669 ///
5670 /// FIXME: we'd also like to handle the case where the last elements are zero
5671 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5672 /// There's even a handy isZeroNode for that purpose.
5673 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5674                                         SDLoc &DL, SelectionDAG &DAG,
5675                                         bool isAfterLegalize) {
5676   EVT EltVT = VT.getVectorElementType();
5677   unsigned NumElems = Elts.size();
5678
5679   LoadSDNode *LDBase = nullptr;
5680   unsigned LastLoadedElt = -1U;
5681
5682   // For each element in the initializer, see if we've found a load or an undef.
5683   // If we don't find an initial load element, or later load elements are
5684   // non-consecutive, bail out.
5685   for (unsigned i = 0; i < NumElems; ++i) {
5686     SDValue Elt = Elts[i];
5687
5688     if (!Elt.getNode() ||
5689         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5690       return SDValue();
5691     if (!LDBase) {
5692       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5693         return SDValue();
5694       LDBase = cast<LoadSDNode>(Elt.getNode());
5695       LastLoadedElt = i;
5696       continue;
5697     }
5698     if (Elt.getOpcode() == ISD::UNDEF)
5699       continue;
5700
5701     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5702     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5703       return SDValue();
5704     LastLoadedElt = i;
5705   }
5706
5707   // If we have found an entire vector of loads and undefs, then return a large
5708   // load of the entire vector width starting at the base pointer.  If we found
5709   // consecutive loads for the low half, generate a vzext_load node.
5710   if (LastLoadedElt == NumElems - 1) {
5711
5712     if (isAfterLegalize &&
5713         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5714       return SDValue();
5715
5716     SDValue NewLd = SDValue();
5717
5718     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5719       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5720                           LDBase->getPointerInfo(),
5721                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5722                           LDBase->isInvariant(), 0);
5723     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5724                         LDBase->getPointerInfo(),
5725                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5726                         LDBase->isInvariant(), LDBase->getAlignment());
5727
5728     if (LDBase->hasAnyUseOfValue(1)) {
5729       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5730                                      SDValue(LDBase, 1),
5731                                      SDValue(NewLd.getNode(), 1));
5732       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5733       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5734                              SDValue(NewLd.getNode(), 1));
5735     }
5736
5737     return NewLd;
5738   }
5739   if (NumElems == 4 && LastLoadedElt == 1 &&
5740       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5741     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5742     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5743     SDValue ResNode =
5744         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5745                                 LDBase->getPointerInfo(),
5746                                 LDBase->getAlignment(),
5747                                 false/*isVolatile*/, true/*ReadMem*/,
5748                                 false/*WriteMem*/);
5749
5750     // Make sure the newly-created LOAD is in the same position as LDBase in
5751     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5752     // update uses of LDBase's output chain to use the TokenFactor.
5753     if (LDBase->hasAnyUseOfValue(1)) {
5754       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5755                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5756       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5757       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5758                              SDValue(ResNode.getNode(), 1));
5759     }
5760
5761     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5762   }
5763   return SDValue();
5764 }
5765
5766 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5767 /// to generate a splat value for the following cases:
5768 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5769 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5770 /// a scalar load, or a constant.
5771 /// The VBROADCAST node is returned when a pattern is found,
5772 /// or SDValue() otherwise.
5773 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5774                                     SelectionDAG &DAG) {
5775   if (!Subtarget->hasFp256())
5776     return SDValue();
5777
5778   MVT VT = Op.getSimpleValueType();
5779   SDLoc dl(Op);
5780
5781   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5782          "Unsupported vector type for broadcast.");
5783
5784   SDValue Ld;
5785   bool ConstSplatVal;
5786
5787   switch (Op.getOpcode()) {
5788     default:
5789       // Unknown pattern found.
5790       return SDValue();
5791
5792     case ISD::BUILD_VECTOR: {
5793       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5794       BitVector UndefElements;
5795       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5796
5797       // We need a splat of a single value to use broadcast, and it doesn't
5798       // make any sense if the value is only in one element of the vector.
5799       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5800         return SDValue();
5801
5802       Ld = Splat;
5803       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5804                        Ld.getOpcode() == ISD::ConstantFP);
5805
5806       // Make sure that all of the users of a non-constant load are from the
5807       // BUILD_VECTOR node.
5808       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5809         return SDValue();
5810       break;
5811     }
5812
5813     case ISD::VECTOR_SHUFFLE: {
5814       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5815
5816       // Shuffles must have a splat mask where the first element is
5817       // broadcasted.
5818       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5819         return SDValue();
5820
5821       SDValue Sc = Op.getOperand(0);
5822       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5823           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5824
5825         if (!Subtarget->hasInt256())
5826           return SDValue();
5827
5828         // Use the register form of the broadcast instruction available on AVX2.
5829         if (VT.getSizeInBits() >= 256)
5830           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5831         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5832       }
5833
5834       Ld = Sc.getOperand(0);
5835       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5836                        Ld.getOpcode() == ISD::ConstantFP);
5837
5838       // The scalar_to_vector node and the suspected
5839       // load node must have exactly one user.
5840       // Constants may have multiple users.
5841
5842       // AVX-512 has register version of the broadcast
5843       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5844         Ld.getValueType().getSizeInBits() >= 32;
5845       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5846           !hasRegVer))
5847         return SDValue();
5848       break;
5849     }
5850   }
5851
5852   bool IsGE256 = (VT.getSizeInBits() >= 256);
5853
5854   // Handle the broadcasting a single constant scalar from the constant pool
5855   // into a vector. On Sandybridge it is still better to load a constant vector
5856   // from the constant pool and not to broadcast it from a scalar.
5857   if (ConstSplatVal && Subtarget->hasInt256()) {
5858     EVT CVT = Ld.getValueType();
5859     assert(!CVT.isVector() && "Must not broadcast a vector type");
5860     unsigned ScalarSize = CVT.getSizeInBits();
5861
5862     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5863       const Constant *C = nullptr;
5864       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5865         C = CI->getConstantIntValue();
5866       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5867         C = CF->getConstantFPValue();
5868
5869       assert(C && "Invalid constant type");
5870
5871       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5872       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5873       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5874       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5875                        MachinePointerInfo::getConstantPool(),
5876                        false, false, false, Alignment);
5877
5878       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5879     }
5880   }
5881
5882   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5883   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5884
5885   // Handle AVX2 in-register broadcasts.
5886   if (!IsLoad && Subtarget->hasInt256() &&
5887       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5888     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5889
5890   // The scalar source must be a normal load.
5891   if (!IsLoad)
5892     return SDValue();
5893
5894   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5895     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5896
5897   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5898   // double since there is no vbroadcastsd xmm
5899   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5900     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5901       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5902   }
5903
5904   // Unsupported broadcast.
5905   return SDValue();
5906 }
5907
5908 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5909 /// underlying vector and index.
5910 ///
5911 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5912 /// index.
5913 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5914                                          SDValue ExtIdx) {
5915   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5916   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5917     return Idx;
5918
5919   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5920   // lowered this:
5921   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5922   // to:
5923   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5924   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5925   //                           undef)
5926   //                       Constant<0>)
5927   // In this case the vector is the extract_subvector expression and the index
5928   // is 2, as specified by the shuffle.
5929   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5930   SDValue ShuffleVec = SVOp->getOperand(0);
5931   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5932   assert(ShuffleVecVT.getVectorElementType() ==
5933          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5934
5935   int ShuffleIdx = SVOp->getMaskElt(Idx);
5936   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5937     ExtractedFromVec = ShuffleVec;
5938     return ShuffleIdx;
5939   }
5940   return Idx;
5941 }
5942
5943 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5944   MVT VT = Op.getSimpleValueType();
5945
5946   // Skip if insert_vec_elt is not supported.
5947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5948   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5949     return SDValue();
5950
5951   SDLoc DL(Op);
5952   unsigned NumElems = Op.getNumOperands();
5953
5954   SDValue VecIn1;
5955   SDValue VecIn2;
5956   SmallVector<unsigned, 4> InsertIndices;
5957   SmallVector<int, 8> Mask(NumElems, -1);
5958
5959   for (unsigned i = 0; i != NumElems; ++i) {
5960     unsigned Opc = Op.getOperand(i).getOpcode();
5961
5962     if (Opc == ISD::UNDEF)
5963       continue;
5964
5965     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5966       // Quit if more than 1 elements need inserting.
5967       if (InsertIndices.size() > 1)
5968         return SDValue();
5969
5970       InsertIndices.push_back(i);
5971       continue;
5972     }
5973
5974     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5975     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5976     // Quit if non-constant index.
5977     if (!isa<ConstantSDNode>(ExtIdx))
5978       return SDValue();
5979     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5980
5981     // Quit if extracted from vector of different type.
5982     if (ExtractedFromVec.getValueType() != VT)
5983       return SDValue();
5984
5985     if (!VecIn1.getNode())
5986       VecIn1 = ExtractedFromVec;
5987     else if (VecIn1 != ExtractedFromVec) {
5988       if (!VecIn2.getNode())
5989         VecIn2 = ExtractedFromVec;
5990       else if (VecIn2 != ExtractedFromVec)
5991         // Quit if more than 2 vectors to shuffle
5992         return SDValue();
5993     }
5994
5995     if (ExtractedFromVec == VecIn1)
5996       Mask[i] = Idx;
5997     else if (ExtractedFromVec == VecIn2)
5998       Mask[i] = Idx + NumElems;
5999   }
6000
6001   if (!VecIn1.getNode())
6002     return SDValue();
6003
6004   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6005   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6006   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6007     unsigned Idx = InsertIndices[i];
6008     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6009                      DAG.getIntPtrConstant(Idx));
6010   }
6011
6012   return NV;
6013 }
6014
6015 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6016 SDValue
6017 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6018
6019   MVT VT = Op.getSimpleValueType();
6020   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6021          "Unexpected type in LowerBUILD_VECTORvXi1!");
6022
6023   SDLoc dl(Op);
6024   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6025     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6026     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6027     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6028   }
6029
6030   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6031     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6032     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6033     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6034   }
6035
6036   bool AllContants = true;
6037   uint64_t Immediate = 0;
6038   int NonConstIdx = -1;
6039   bool IsSplat = true;
6040   unsigned NumNonConsts = 0;
6041   unsigned NumConsts = 0;
6042   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6043     SDValue In = Op.getOperand(idx);
6044     if (In.getOpcode() == ISD::UNDEF)
6045       continue;
6046     if (!isa<ConstantSDNode>(In)) {
6047       AllContants = false;
6048       NonConstIdx = idx;
6049       NumNonConsts++;
6050     }
6051     else {
6052       NumConsts++;
6053       if (cast<ConstantSDNode>(In)->getZExtValue())
6054       Immediate |= (1ULL << idx);
6055     }
6056     if (In != Op.getOperand(0))
6057       IsSplat = false;
6058   }
6059
6060   if (AllContants) {
6061     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6062       DAG.getConstant(Immediate, MVT::i16));
6063     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6064                        DAG.getIntPtrConstant(0));
6065   }
6066
6067   if (NumNonConsts == 1 && NonConstIdx != 0) {
6068     SDValue DstVec;
6069     if (NumConsts) {
6070       SDValue VecAsImm = DAG.getConstant(Immediate,
6071                                          MVT::getIntegerVT(VT.getSizeInBits()));
6072       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6073     }
6074     else 
6075       DstVec = DAG.getUNDEF(VT);
6076     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6077                        Op.getOperand(NonConstIdx),
6078                        DAG.getIntPtrConstant(NonConstIdx));
6079   }
6080   if (!IsSplat && (NonConstIdx != 0))
6081     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6082   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6083   SDValue Select;
6084   if (IsSplat)
6085     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6086                           DAG.getConstant(-1, SelectVT),
6087                           DAG.getConstant(0, SelectVT));
6088   else
6089     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6090                          DAG.getConstant((Immediate | 1), SelectVT),
6091                          DAG.getConstant(Immediate, SelectVT));
6092   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6093 }
6094
6095 /// \brief Return true if \p N implements a horizontal binop and return the
6096 /// operands for the horizontal binop into V0 and V1.
6097 /// 
6098 /// This is a helper function of PerformBUILD_VECTORCombine.
6099 /// This function checks that the build_vector \p N in input implements a
6100 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6101 /// operation to match.
6102 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6103 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6104 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6105 /// arithmetic sub.
6106 ///
6107 /// This function only analyzes elements of \p N whose indices are
6108 /// in range [BaseIdx, LastIdx).
6109 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6110                               SelectionDAG &DAG,
6111                               unsigned BaseIdx, unsigned LastIdx,
6112                               SDValue &V0, SDValue &V1) {
6113   EVT VT = N->getValueType(0);
6114
6115   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6116   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6117          "Invalid Vector in input!");
6118   
6119   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6120   bool CanFold = true;
6121   unsigned ExpectedVExtractIdx = BaseIdx;
6122   unsigned NumElts = LastIdx - BaseIdx;
6123   V0 = DAG.getUNDEF(VT);
6124   V1 = DAG.getUNDEF(VT);
6125
6126   // Check if N implements a horizontal binop.
6127   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6128     SDValue Op = N->getOperand(i + BaseIdx);
6129
6130     // Skip UNDEFs.
6131     if (Op->getOpcode() == ISD::UNDEF) {
6132       // Update the expected vector extract index.
6133       if (i * 2 == NumElts)
6134         ExpectedVExtractIdx = BaseIdx;
6135       ExpectedVExtractIdx += 2;
6136       continue;
6137     }
6138
6139     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6140
6141     if (!CanFold)
6142       break;
6143
6144     SDValue Op0 = Op.getOperand(0);
6145     SDValue Op1 = Op.getOperand(1);
6146
6147     // Try to match the following pattern:
6148     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6149     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6150         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6151         Op0.getOperand(0) == Op1.getOperand(0) &&
6152         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6153         isa<ConstantSDNode>(Op1.getOperand(1)));
6154     if (!CanFold)
6155       break;
6156
6157     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6158     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6159
6160     if (i * 2 < NumElts) {
6161       if (V0.getOpcode() == ISD::UNDEF)
6162         V0 = Op0.getOperand(0);
6163     } else {
6164       if (V1.getOpcode() == ISD::UNDEF)
6165         V1 = Op0.getOperand(0);
6166       if (i * 2 == NumElts)
6167         ExpectedVExtractIdx = BaseIdx;
6168     }
6169
6170     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6171     if (I0 == ExpectedVExtractIdx)
6172       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6173     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6174       // Try to match the following dag sequence:
6175       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6176       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6177     } else
6178       CanFold = false;
6179
6180     ExpectedVExtractIdx += 2;
6181   }
6182
6183   return CanFold;
6184 }
6185
6186 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6187 /// a concat_vector. 
6188 ///
6189 /// This is a helper function of PerformBUILD_VECTORCombine.
6190 /// This function expects two 256-bit vectors called V0 and V1.
6191 /// At first, each vector is split into two separate 128-bit vectors.
6192 /// Then, the resulting 128-bit vectors are used to implement two
6193 /// horizontal binary operations. 
6194 ///
6195 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6196 ///
6197 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6198 /// the two new horizontal binop.
6199 /// When Mode is set, the first horizontal binop dag node would take as input
6200 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6201 /// horizontal binop dag node would take as input the lower 128-bit of V1
6202 /// and the upper 128-bit of V1.
6203 ///   Example:
6204 ///     HADD V0_LO, V0_HI
6205 ///     HADD V1_LO, V1_HI
6206 ///
6207 /// Otherwise, the first horizontal binop dag node takes as input the lower
6208 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6209 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6210 ///   Example:
6211 ///     HADD V0_LO, V1_LO
6212 ///     HADD V0_HI, V1_HI
6213 ///
6214 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6215 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6216 /// the upper 128-bits of the result.
6217 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6218                                      SDLoc DL, SelectionDAG &DAG,
6219                                      unsigned X86Opcode, bool Mode,
6220                                      bool isUndefLO, bool isUndefHI) {
6221   EVT VT = V0.getValueType();
6222   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6223          "Invalid nodes in input!");
6224
6225   unsigned NumElts = VT.getVectorNumElements();
6226   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6227   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6228   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6229   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6230   EVT NewVT = V0_LO.getValueType();
6231
6232   SDValue LO = DAG.getUNDEF(NewVT);
6233   SDValue HI = DAG.getUNDEF(NewVT);
6234
6235   if (Mode) {
6236     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6237     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6238       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6239     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6240       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6241   } else {
6242     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6243     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6244                        V1_LO->getOpcode() != ISD::UNDEF))
6245       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6246
6247     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6248                        V1_HI->getOpcode() != ISD::UNDEF))
6249       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6250   }
6251
6252   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6253 }
6254
6255 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6256 /// sequence of 'vadd + vsub + blendi'.
6257 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6258                            const X86Subtarget *Subtarget) {
6259   SDLoc DL(BV);
6260   EVT VT = BV->getValueType(0);
6261   unsigned NumElts = VT.getVectorNumElements();
6262   SDValue InVec0 = DAG.getUNDEF(VT);
6263   SDValue InVec1 = DAG.getUNDEF(VT);
6264
6265   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6266           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6267
6268   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6270   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6271     return SDValue();
6272
6273   // Odd-numbered elements in the input build vector are obtained from
6274   // adding two integer/float elements.
6275   // Even-numbered elements in the input build vector are obtained from
6276   // subtracting two integer/float elements.
6277   unsigned ExpectedOpcode = ISD::FSUB;
6278   unsigned NextExpectedOpcode = ISD::FADD;
6279   bool AddFound = false;
6280   bool SubFound = false;
6281
6282   for (unsigned i = 0, e = NumElts; i != e; i++) {
6283     SDValue Op = BV->getOperand(i);
6284       
6285     // Skip 'undef' values.
6286     unsigned Opcode = Op.getOpcode();
6287     if (Opcode == ISD::UNDEF) {
6288       std::swap(ExpectedOpcode, NextExpectedOpcode);
6289       continue;
6290     }
6291       
6292     // Early exit if we found an unexpected opcode.
6293     if (Opcode != ExpectedOpcode)
6294       return SDValue();
6295
6296     SDValue Op0 = Op.getOperand(0);
6297     SDValue Op1 = Op.getOperand(1);
6298
6299     // Try to match the following pattern:
6300     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6301     // Early exit if we cannot match that sequence.
6302     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6303         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6304         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6305         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6306         Op0.getOperand(1) != Op1.getOperand(1))
6307       return SDValue();
6308
6309     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6310     if (I0 != i)
6311       return SDValue();
6312
6313     // We found a valid add/sub node. Update the information accordingly.
6314     if (i & 1)
6315       AddFound = true;
6316     else
6317       SubFound = true;
6318
6319     // Update InVec0 and InVec1.
6320     if (InVec0.getOpcode() == ISD::UNDEF)
6321       InVec0 = Op0.getOperand(0);
6322     if (InVec1.getOpcode() == ISD::UNDEF)
6323       InVec1 = Op1.getOperand(0);
6324
6325     // Make sure that operands in input to each add/sub node always
6326     // come from a same pair of vectors.
6327     if (InVec0 != Op0.getOperand(0)) {
6328       if (ExpectedOpcode == ISD::FSUB)
6329         return SDValue();
6330
6331       // FADD is commutable. Try to commute the operands
6332       // and then test again.
6333       std::swap(Op0, Op1);
6334       if (InVec0 != Op0.getOperand(0))
6335         return SDValue();
6336     }
6337
6338     if (InVec1 != Op1.getOperand(0))
6339       return SDValue();
6340
6341     // Update the pair of expected opcodes.
6342     std::swap(ExpectedOpcode, NextExpectedOpcode);
6343   }
6344
6345   // Don't try to fold this build_vector into a VSELECT if it has
6346   // too many UNDEF operands.
6347   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6348       InVec1.getOpcode() != ISD::UNDEF) {
6349     // Emit a sequence of vector add and sub followed by a VSELECT.
6350     // The new VSELECT will be lowered into a BLENDI.
6351     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6352     // and emit a single ADDSUB instruction.
6353     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6354     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6355
6356     // Construct the VSELECT mask.
6357     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6358     EVT SVT = MaskVT.getVectorElementType();
6359     unsigned SVTBits = SVT.getSizeInBits();
6360     SmallVector<SDValue, 8> Ops;
6361
6362     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6363       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6364                             APInt::getAllOnesValue(SVTBits);
6365       SDValue Constant = DAG.getConstant(Value, SVT);
6366       Ops.push_back(Constant);
6367     }
6368
6369     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6370     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6371   }
6372   
6373   return SDValue();
6374 }
6375
6376 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6377                                           const X86Subtarget *Subtarget) {
6378   SDLoc DL(N);
6379   EVT VT = N->getValueType(0);
6380   unsigned NumElts = VT.getVectorNumElements();
6381   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6382   SDValue InVec0, InVec1;
6383
6384   // Try to match an ADDSUB.
6385   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6386       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6387     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6388     if (Value.getNode())
6389       return Value;
6390   }
6391
6392   // Try to match horizontal ADD/SUB.
6393   unsigned NumUndefsLO = 0;
6394   unsigned NumUndefsHI = 0;
6395   unsigned Half = NumElts/2;
6396
6397   // Count the number of UNDEF operands in the build_vector in input.
6398   for (unsigned i = 0, e = Half; i != e; ++i)
6399     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6400       NumUndefsLO++;
6401
6402   for (unsigned i = Half, e = NumElts; i != e; ++i)
6403     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6404       NumUndefsHI++;
6405
6406   // Early exit if this is either a build_vector of all UNDEFs or all the
6407   // operands but one are UNDEF.
6408   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6409     return SDValue();
6410
6411   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6412     // Try to match an SSE3 float HADD/HSUB.
6413     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6414       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6415     
6416     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6417       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6418   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6419     // Try to match an SSSE3 integer HADD/HSUB.
6420     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6421       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6422     
6423     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6424       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6425   }
6426   
6427   if (!Subtarget->hasAVX())
6428     return SDValue();
6429
6430   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6431     // Try to match an AVX horizontal add/sub of packed single/double
6432     // precision floating point values from 256-bit vectors.
6433     SDValue InVec2, InVec3;
6434     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6435         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6436         ((InVec0.getOpcode() == ISD::UNDEF ||
6437           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6438         ((InVec1.getOpcode() == ISD::UNDEF ||
6439           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6440       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6441
6442     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6443         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6444         ((InVec0.getOpcode() == ISD::UNDEF ||
6445           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6446         ((InVec1.getOpcode() == ISD::UNDEF ||
6447           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6448       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6449   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6450     // Try to match an AVX2 horizontal add/sub of signed integers.
6451     SDValue InVec2, InVec3;
6452     unsigned X86Opcode;
6453     bool CanFold = true;
6454
6455     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6456         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6457         ((InVec0.getOpcode() == ISD::UNDEF ||
6458           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6459         ((InVec1.getOpcode() == ISD::UNDEF ||
6460           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6461       X86Opcode = X86ISD::HADD;
6462     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6463         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6464         ((InVec0.getOpcode() == ISD::UNDEF ||
6465           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6466         ((InVec1.getOpcode() == ISD::UNDEF ||
6467           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6468       X86Opcode = X86ISD::HSUB;
6469     else
6470       CanFold = false;
6471
6472     if (CanFold) {
6473       // Fold this build_vector into a single horizontal add/sub.
6474       // Do this only if the target has AVX2.
6475       if (Subtarget->hasAVX2())
6476         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6477  
6478       // Do not try to expand this build_vector into a pair of horizontal
6479       // add/sub if we can emit a pair of scalar add/sub.
6480       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6481         return SDValue();
6482
6483       // Convert this build_vector into a pair of horizontal binop followed by
6484       // a concat vector.
6485       bool isUndefLO = NumUndefsLO == Half;
6486       bool isUndefHI = NumUndefsHI == Half;
6487       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6488                                    isUndefLO, isUndefHI);
6489     }
6490   }
6491
6492   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6493        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6494     unsigned X86Opcode;
6495     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6496       X86Opcode = X86ISD::HADD;
6497     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6498       X86Opcode = X86ISD::HSUB;
6499     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6500       X86Opcode = X86ISD::FHADD;
6501     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6502       X86Opcode = X86ISD::FHSUB;
6503     else
6504       return SDValue();
6505
6506     // Don't try to expand this build_vector into a pair of horizontal add/sub
6507     // if we can simply emit a pair of scalar add/sub.
6508     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6509       return SDValue();
6510
6511     // Convert this build_vector into two horizontal add/sub followed by
6512     // a concat vector.
6513     bool isUndefLO = NumUndefsLO == Half;
6514     bool isUndefHI = NumUndefsHI == Half;
6515     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6516                                  isUndefLO, isUndefHI);
6517   }
6518
6519   return SDValue();
6520 }
6521
6522 SDValue
6523 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6524   SDLoc dl(Op);
6525
6526   MVT VT = Op.getSimpleValueType();
6527   MVT ExtVT = VT.getVectorElementType();
6528   unsigned NumElems = Op.getNumOperands();
6529
6530   // Generate vectors for predicate vectors.
6531   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6532     return LowerBUILD_VECTORvXi1(Op, DAG);
6533
6534   // Vectors containing all zeros can be matched by pxor and xorps later
6535   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6536     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6537     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6538     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6539       return Op;
6540
6541     return getZeroVector(VT, Subtarget, DAG, dl);
6542   }
6543
6544   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6545   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6546   // vpcmpeqd on 256-bit vectors.
6547   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6548     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6549       return Op;
6550
6551     if (!VT.is512BitVector())
6552       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6553   }
6554
6555   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6556   if (Broadcast.getNode())
6557     return Broadcast;
6558
6559   unsigned EVTBits = ExtVT.getSizeInBits();
6560
6561   unsigned NumZero  = 0;
6562   unsigned NumNonZero = 0;
6563   unsigned NonZeros = 0;
6564   bool IsAllConstants = true;
6565   SmallSet<SDValue, 8> Values;
6566   for (unsigned i = 0; i < NumElems; ++i) {
6567     SDValue Elt = Op.getOperand(i);
6568     if (Elt.getOpcode() == ISD::UNDEF)
6569       continue;
6570     Values.insert(Elt);
6571     if (Elt.getOpcode() != ISD::Constant &&
6572         Elt.getOpcode() != ISD::ConstantFP)
6573       IsAllConstants = false;
6574     if (X86::isZeroNode(Elt))
6575       NumZero++;
6576     else {
6577       NonZeros |= (1 << i);
6578       NumNonZero++;
6579     }
6580   }
6581
6582   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6583   if (NumNonZero == 0)
6584     return DAG.getUNDEF(VT);
6585
6586   // Special case for single non-zero, non-undef, element.
6587   if (NumNonZero == 1) {
6588     unsigned Idx = countTrailingZeros(NonZeros);
6589     SDValue Item = Op.getOperand(Idx);
6590
6591     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6592     // the value are obviously zero, truncate the value to i32 and do the
6593     // insertion that way.  Only do this if the value is non-constant or if the
6594     // value is a constant being inserted into element 0.  It is cheaper to do
6595     // a constant pool load than it is to do a movd + shuffle.
6596     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6597         (!IsAllConstants || Idx == 0)) {
6598       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6599         // Handle SSE only.
6600         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6601         EVT VecVT = MVT::v4i32;
6602         unsigned VecElts = 4;
6603
6604         // Truncate the value (which may itself be a constant) to i32, and
6605         // convert it to a vector with movd (S2V+shuffle to zero extend).
6606         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6607         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6608         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6609
6610         // Now we have our 32-bit value zero extended in the low element of
6611         // a vector.  If Idx != 0, swizzle it into place.
6612         if (Idx != 0) {
6613           SmallVector<int, 4> Mask;
6614           Mask.push_back(Idx);
6615           for (unsigned i = 1; i != VecElts; ++i)
6616             Mask.push_back(i);
6617           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6618                                       &Mask[0]);
6619         }
6620         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6621       }
6622     }
6623
6624     // If we have a constant or non-constant insertion into the low element of
6625     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6626     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6627     // depending on what the source datatype is.
6628     if (Idx == 0) {
6629       if (NumZero == 0)
6630         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6631
6632       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6633           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6634         if (VT.is256BitVector() || VT.is512BitVector()) {
6635           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6636           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6637                              Item, DAG.getIntPtrConstant(0));
6638         }
6639         assert(VT.is128BitVector() && "Expected an SSE value type!");
6640         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6641         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6642         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6643       }
6644
6645       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6646         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6647         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6648         if (VT.is256BitVector()) {
6649           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6650           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6651         } else {
6652           assert(VT.is128BitVector() && "Expected an SSE value type!");
6653           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6654         }
6655         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6656       }
6657     }
6658
6659     // Is it a vector logical left shift?
6660     if (NumElems == 2 && Idx == 1 &&
6661         X86::isZeroNode(Op.getOperand(0)) &&
6662         !X86::isZeroNode(Op.getOperand(1))) {
6663       unsigned NumBits = VT.getSizeInBits();
6664       return getVShift(true, VT,
6665                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6666                                    VT, Op.getOperand(1)),
6667                        NumBits/2, DAG, *this, dl);
6668     }
6669
6670     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6671       return SDValue();
6672
6673     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6674     // is a non-constant being inserted into an element other than the low one,
6675     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6676     // movd/movss) to move this into the low element, then shuffle it into
6677     // place.
6678     if (EVTBits == 32) {
6679       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6680
6681       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6682       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6683       SmallVector<int, 8> MaskVec;
6684       for (unsigned i = 0; i != NumElems; ++i)
6685         MaskVec.push_back(i == Idx ? 0 : 1);
6686       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6687     }
6688   }
6689
6690   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6691   if (Values.size() == 1) {
6692     if (EVTBits == 32) {
6693       // Instead of a shuffle like this:
6694       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6695       // Check if it's possible to issue this instead.
6696       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6697       unsigned Idx = countTrailingZeros(NonZeros);
6698       SDValue Item = Op.getOperand(Idx);
6699       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6700         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6701     }
6702     return SDValue();
6703   }
6704
6705   // A vector full of immediates; various special cases are already
6706   // handled, so this is best done with a single constant-pool load.
6707   if (IsAllConstants)
6708     return SDValue();
6709
6710   // For AVX-length vectors, build the individual 128-bit pieces and use
6711   // shuffles to put them in place.
6712   if (VT.is256BitVector() || VT.is512BitVector()) {
6713     SmallVector<SDValue, 64> V;
6714     for (unsigned i = 0; i != NumElems; ++i)
6715       V.push_back(Op.getOperand(i));
6716
6717     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6718
6719     // Build both the lower and upper subvector.
6720     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6721                                 makeArrayRef(&V[0], NumElems/2));
6722     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6723                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6724
6725     // Recreate the wider vector with the lower and upper part.
6726     if (VT.is256BitVector())
6727       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6728     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6729   }
6730
6731   // Let legalizer expand 2-wide build_vectors.
6732   if (EVTBits == 64) {
6733     if (NumNonZero == 1) {
6734       // One half is zero or undef.
6735       unsigned Idx = countTrailingZeros(NonZeros);
6736       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6737                                  Op.getOperand(Idx));
6738       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6739     }
6740     return SDValue();
6741   }
6742
6743   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6744   if (EVTBits == 8 && NumElems == 16) {
6745     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6746                                         Subtarget, *this);
6747     if (V.getNode()) return V;
6748   }
6749
6750   if (EVTBits == 16 && NumElems == 8) {
6751     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6752                                       Subtarget, *this);
6753     if (V.getNode()) return V;
6754   }
6755
6756   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6757   if (EVTBits == 32 && NumElems == 4) {
6758     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6759                                       NumZero, DAG, Subtarget, *this);
6760     if (V.getNode())
6761       return V;
6762   }
6763
6764   // If element VT is == 32 bits, turn it into a number of shuffles.
6765   SmallVector<SDValue, 8> V(NumElems);
6766   if (NumElems == 4 && NumZero > 0) {
6767     for (unsigned i = 0; i < 4; ++i) {
6768       bool isZero = !(NonZeros & (1 << i));
6769       if (isZero)
6770         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6771       else
6772         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6773     }
6774
6775     for (unsigned i = 0; i < 2; ++i) {
6776       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6777         default: break;
6778         case 0:
6779           V[i] = V[i*2];  // Must be a zero vector.
6780           break;
6781         case 1:
6782           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6783           break;
6784         case 2:
6785           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6786           break;
6787         case 3:
6788           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6789           break;
6790       }
6791     }
6792
6793     bool Reverse1 = (NonZeros & 0x3) == 2;
6794     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6795     int MaskVec[] = {
6796       Reverse1 ? 1 : 0,
6797       Reverse1 ? 0 : 1,
6798       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6799       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6800     };
6801     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6802   }
6803
6804   if (Values.size() > 1 && VT.is128BitVector()) {
6805     // Check for a build vector of consecutive loads.
6806     for (unsigned i = 0; i < NumElems; ++i)
6807       V[i] = Op.getOperand(i);
6808
6809     // Check for elements which are consecutive loads.
6810     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6811     if (LD.getNode())
6812       return LD;
6813
6814     // Check for a build vector from mostly shuffle plus few inserting.
6815     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6816     if (Sh.getNode())
6817       return Sh;
6818
6819     // For SSE 4.1, use insertps to put the high elements into the low element.
6820     if (getSubtarget()->hasSSE41()) {
6821       SDValue Result;
6822       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6823         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6824       else
6825         Result = DAG.getUNDEF(VT);
6826
6827       for (unsigned i = 1; i < NumElems; ++i) {
6828         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6829         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6830                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6831       }
6832       return Result;
6833     }
6834
6835     // Otherwise, expand into a number of unpckl*, start by extending each of
6836     // our (non-undef) elements to the full vector width with the element in the
6837     // bottom slot of the vector (which generates no code for SSE).
6838     for (unsigned i = 0; i < NumElems; ++i) {
6839       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6840         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6841       else
6842         V[i] = DAG.getUNDEF(VT);
6843     }
6844
6845     // Next, we iteratively mix elements, e.g. for v4f32:
6846     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6847     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6848     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6849     unsigned EltStride = NumElems >> 1;
6850     while (EltStride != 0) {
6851       for (unsigned i = 0; i < EltStride; ++i) {
6852         // If V[i+EltStride] is undef and this is the first round of mixing,
6853         // then it is safe to just drop this shuffle: V[i] is already in the
6854         // right place, the one element (since it's the first round) being
6855         // inserted as undef can be dropped.  This isn't safe for successive
6856         // rounds because they will permute elements within both vectors.
6857         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6858             EltStride == NumElems/2)
6859           continue;
6860
6861         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6862       }
6863       EltStride >>= 1;
6864     }
6865     return V[0];
6866   }
6867   return SDValue();
6868 }
6869
6870 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6871 // to create 256-bit vectors from two other 128-bit ones.
6872 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6873   SDLoc dl(Op);
6874   MVT ResVT = Op.getSimpleValueType();
6875
6876   assert((ResVT.is256BitVector() ||
6877           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6878
6879   SDValue V1 = Op.getOperand(0);
6880   SDValue V2 = Op.getOperand(1);
6881   unsigned NumElems = ResVT.getVectorNumElements();
6882   if(ResVT.is256BitVector())
6883     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6884
6885   if (Op.getNumOperands() == 4) {
6886     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6887                                 ResVT.getVectorNumElements()/2);
6888     SDValue V3 = Op.getOperand(2);
6889     SDValue V4 = Op.getOperand(3);
6890     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6891       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6892   }
6893   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6894 }
6895
6896 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6897   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6898   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6899          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6900           Op.getNumOperands() == 4)));
6901
6902   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6903   // from two other 128-bit ones.
6904
6905   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6906   return LowerAVXCONCAT_VECTORS(Op, DAG);
6907 }
6908
6909
6910 //===----------------------------------------------------------------------===//
6911 // Vector shuffle lowering
6912 //
6913 // This is an experimental code path for lowering vector shuffles on x86. It is
6914 // designed to handle arbitrary vector shuffles and blends, gracefully
6915 // degrading performance as necessary. It works hard to recognize idiomatic
6916 // shuffles and lower them to optimal instruction patterns without leaving
6917 // a framework that allows reasonably efficient handling of all vector shuffle
6918 // patterns.
6919 //===----------------------------------------------------------------------===//
6920
6921 /// \brief Tiny helper function to identify a no-op mask.
6922 ///
6923 /// This is a somewhat boring predicate function. It checks whether the mask
6924 /// array input, which is assumed to be a single-input shuffle mask of the kind
6925 /// used by the X86 shuffle instructions (not a fully general
6926 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6927 /// in-place shuffle are 'no-op's.
6928 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6929   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6930     if (Mask[i] != -1 && Mask[i] != i)
6931       return false;
6932   return true;
6933 }
6934
6935 /// \brief Helper function to classify a mask as a single-input mask.
6936 ///
6937 /// This isn't a generic single-input test because in the vector shuffle
6938 /// lowering we canonicalize single inputs to be the first input operand. This
6939 /// means we can more quickly test for a single input by only checking whether
6940 /// an input from the second operand exists. We also assume that the size of
6941 /// mask corresponds to the size of the input vectors which isn't true in the
6942 /// fully general case.
6943 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6944   for (int M : Mask)
6945     if (M >= (int)Mask.size())
6946       return false;
6947   return true;
6948 }
6949
6950 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6951 ///
6952 /// This helper function produces an 8-bit shuffle immediate corresponding to
6953 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6954 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6955 /// example.
6956 ///
6957 /// NB: We rely heavily on "undef" masks preserving the input lane.
6958 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6959                                           SelectionDAG &DAG) {
6960   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6961   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6962   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6963   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6964   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6965
6966   unsigned Imm = 0;
6967   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6968   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6969   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6970   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6971   return DAG.getConstant(Imm, MVT::i8);
6972 }
6973
6974 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6975 ///
6976 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6977 /// support for floating point shuffles but not integer shuffles. These
6978 /// instructions will incur a domain crossing penalty on some chips though so
6979 /// it is better to avoid lowering through this for integer vectors where
6980 /// possible.
6981 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6982                                        const X86Subtarget *Subtarget,
6983                                        SelectionDAG &DAG) {
6984   SDLoc DL(Op);
6985   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6986   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6987   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6988   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6989   ArrayRef<int> Mask = SVOp->getMask();
6990   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6991
6992   if (isSingleInputShuffleMask(Mask)) {
6993     // Straight shuffle of a single input vector. Simulate this by using the
6994     // single input as both of the "inputs" to this instruction..
6995     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6996     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6997                        DAG.getConstant(SHUFPDMask, MVT::i8));
6998   }
6999   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7000   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7001
7002   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7003   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7004                      DAG.getConstant(SHUFPDMask, MVT::i8));
7005 }
7006
7007 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7008 ///
7009 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7010 /// the integer unit to minimize domain crossing penalties. However, for blends
7011 /// it falls back to the floating point shuffle operation with appropriate bit
7012 /// casting.
7013 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7014                                        const X86Subtarget *Subtarget,
7015                                        SelectionDAG &DAG) {
7016   SDLoc DL(Op);
7017   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7018   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7019   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7020   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7021   ArrayRef<int> Mask = SVOp->getMask();
7022   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7023
7024   if (isSingleInputShuffleMask(Mask)) {
7025     // Straight shuffle of a single input vector. For everything from SSE2
7026     // onward this has a single fast instruction with no scary immediates.
7027     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7028     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7029     int WidenedMask[4] = {
7030         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7031         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7032     return DAG.getNode(
7033         ISD::BITCAST, DL, MVT::v2i64,
7034         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7035                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7036   }
7037
7038   // We implement this with SHUFPD which is pretty lame because it will likely
7039   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7040   // However, all the alternatives are still more cycles and newer chips don't
7041   // have this problem. It would be really nice if x86 had better shuffles here.
7042   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7043   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7044   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7045                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7046 }
7047
7048 /// \brief Lower 4-lane 32-bit floating point shuffles.
7049 ///
7050 /// Uses instructions exclusively from the floating point unit to minimize
7051 /// domain crossing penalties, as these are sufficient to implement all v4f32
7052 /// shuffles.
7053 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7054                                        const X86Subtarget *Subtarget,
7055                                        SelectionDAG &DAG) {
7056   SDLoc DL(Op);
7057   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7058   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7059   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7060   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7061   ArrayRef<int> Mask = SVOp->getMask();
7062   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7063
7064   SDValue LowV = V1, HighV = V2;
7065   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7066
7067   int NumV2Elements =
7068       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7069
7070   if (NumV2Elements == 0)
7071     // Straight shuffle of a single input vector. We pass the input vector to
7072     // both operands to simulate this with a SHUFPS.
7073     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7074                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7075
7076   if (NumV2Elements == 1) {
7077     int V2Index =
7078         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7079         Mask.begin();
7080     // Compute the index adjacent to V2Index and in the same half by toggling
7081     // the low bit.
7082     int V2AdjIndex = V2Index ^ 1;
7083
7084     if (Mask[V2AdjIndex] == -1) {
7085       // Handles all the cases where we have a single V2 element and an undef.
7086       // This will only ever happen in the high lanes because we commute the
7087       // vector otherwise.
7088       if (V2Index < 2)
7089         std::swap(LowV, HighV);
7090       NewMask[V2Index] -= 4;
7091     } else {
7092       // Handle the case where the V2 element ends up adjacent to a V1 element.
7093       // To make this work, blend them together as the first step.
7094       int V1Index = V2AdjIndex;
7095       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7096       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7097                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7098
7099       // Now proceed to reconstruct the final blend as we have the necessary
7100       // high or low half formed.
7101       if (V2Index < 2) {
7102         LowV = V2;
7103         HighV = V1;
7104       } else {
7105         HighV = V2;
7106       }
7107       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7108       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7109     }
7110   } else if (NumV2Elements == 2) {
7111     if (Mask[0] < 4 && Mask[1] < 4) {
7112       // Handle the easy case where we have V1 in the low lanes and V2 in the
7113       // high lanes. We never see this reversed because we sort the shuffle.
7114       NewMask[2] -= 4;
7115       NewMask[3] -= 4;
7116     } else {
7117       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7118       // trying to place elements directly, just blend them and set up the final
7119       // shuffle to place them.
7120
7121       // The first two blend mask elements are for V1, the second two are for
7122       // V2.
7123       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7124                           Mask[2] < 4 ? Mask[2] : Mask[3],
7125                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7126                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7127       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7128                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7129
7130       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7131       // a blend.
7132       LowV = HighV = V1;
7133       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7134       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7135       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7136       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7137     }
7138   }
7139   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7140                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7141 }
7142
7143 /// \brief Lower 4-lane i32 vector shuffles.
7144 ///
7145 /// We try to handle these with integer-domain shuffles where we can, but for
7146 /// blends we use the floating point domain blend instructions.
7147 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7148                                        const X86Subtarget *Subtarget,
7149                                        SelectionDAG &DAG) {
7150   SDLoc DL(Op);
7151   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7152   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7153   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7154   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7155   ArrayRef<int> Mask = SVOp->getMask();
7156   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7157
7158   if (isSingleInputShuffleMask(Mask))
7159     // Straight shuffle of a single input vector. For everything from SSE2
7160     // onward this has a single fast instruction with no scary immediates.
7161     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7162                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7163
7164   // We implement this with SHUFPS because it can blend from two vectors.
7165   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7166   // up the inputs, bypassing domain shift penalties that we would encur if we
7167   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7168   // relevant.
7169   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7170                      DAG.getVectorShuffle(
7171                          MVT::v4f32, DL,
7172                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7173                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7174 }
7175
7176 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7177 /// shuffle lowering, and the most complex part.
7178 ///
7179 /// The lowering strategy is to try to form pairs of input lanes which are
7180 /// targeted at the same half of the final vector, and then use a dword shuffle
7181 /// to place them onto the right half, and finally unpack the paired lanes into
7182 /// their final position.
7183 ///
7184 /// The exact breakdown of how to form these dword pairs and align them on the
7185 /// correct sides is really tricky. See the comments within the function for
7186 /// more of the details.
7187 static SDValue lowerV8I16SingleInputVectorShuffle(
7188     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7189     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7190   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7191   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7192   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7193
7194   SmallVector<int, 4> LoInputs;
7195   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7196                [](int M) { return M >= 0; });
7197   std::sort(LoInputs.begin(), LoInputs.end());
7198   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7199   SmallVector<int, 4> HiInputs;
7200   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7201                [](int M) { return M >= 0; });
7202   std::sort(HiInputs.begin(), HiInputs.end());
7203   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7204   int NumLToL =
7205       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7206   int NumHToL = LoInputs.size() - NumLToL;
7207   int NumLToH =
7208       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7209   int NumHToH = HiInputs.size() - NumLToH;
7210   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7211   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7212   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7213   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7214
7215   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7216   // such inputs we can swap two of the dwords across the half mark and end up
7217   // with <=2 inputs to each half in each half. Once there, we can fall through
7218   // to the generic code below. For example:
7219   //
7220   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7221   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7222   //
7223   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7224   // and 2-2.
7225   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7226                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7227     // Compute the index of dword with only one word among the three inputs in
7228     // a half by taking the sum of the half with three inputs and subtracting
7229     // the sum of the actual three inputs. The difference is the remaining
7230     // slot.
7231     int DWordA = (ThreeInputHalfSum -
7232                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7233                  2;
7234     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7235
7236     int PSHUFDMask[] = {0, 1, 2, 3};
7237     PSHUFDMask[DWordA] = DWordB;
7238     PSHUFDMask[DWordB] = DWordA;
7239     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7240                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7241                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7242                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7243
7244     // Adjust the mask to match the new locations of A and B.
7245     for (int &M : Mask)
7246       if (M != -1 && M/2 == DWordA)
7247         M = 2 * DWordB + M % 2;
7248       else if (M != -1 && M/2 == DWordB)
7249         M = 2 * DWordA + M % 2;
7250
7251     // Recurse back into this routine to re-compute state now that this isn't
7252     // a 3 and 1 problem.
7253     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7254                                 Mask);
7255   };
7256   if (NumLToL == 3 && NumHToL == 1)
7257     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7258   else if (NumLToL == 1 && NumHToL == 3)
7259     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7260   else if (NumLToH == 1 && NumHToH == 3)
7261     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7262   else if (NumLToH == 3 && NumHToH == 1)
7263     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7264
7265   // At this point there are at most two inputs to the low and high halves from
7266   // each half. That means the inputs can always be grouped into dwords and
7267   // those dwords can then be moved to the correct half with a dword shuffle.
7268   // We use at most one low and one high word shuffle to collect these paired
7269   // inputs into dwords, and finally a dword shuffle to place them.
7270   int PSHUFLMask[4] = {-1, -1, -1, -1};
7271   int PSHUFHMask[4] = {-1, -1, -1, -1};
7272   int PSHUFDMask[4] = {-1, -1, -1, -1};
7273
7274   // First fix the masks for all the inputs that are staying in their
7275   // original halves. This will then dictate the targets of the cross-half
7276   // shuffles.
7277   auto fixInPlaceInputs = [&PSHUFDMask](
7278       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7279       MutableArrayRef<int> HalfMask, int HalfOffset) {
7280     if (InPlaceInputs.empty())
7281       return;
7282     if (InPlaceInputs.size() == 1) {
7283       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7284           InPlaceInputs[0] - HalfOffset;
7285       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7286       return;
7287     }
7288
7289     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7290     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7291         InPlaceInputs[0] - HalfOffset;
7292     // Put the second input next to the first so that they are packed into
7293     // a dword. We find the adjacent index by toggling the low bit.
7294     int AdjIndex = InPlaceInputs[0] ^ 1;
7295     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7296     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7297     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7298   };
7299   if (!HToLInputs.empty())
7300     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7301   if (!LToHInputs.empty())
7302     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7303
7304   // Now gather the cross-half inputs and place them into a free dword of
7305   // their target half.
7306   // FIXME: This operation could almost certainly be simplified dramatically to
7307   // look more like the 3-1 fixing operation.
7308   auto moveInputsToRightHalf = [&PSHUFDMask](
7309       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7310       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7311       int SourceOffset, int DestOffset) {
7312     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7313       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7314     };
7315     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7316                                                int Word) {
7317       int LowWord = Word & ~1;
7318       int HighWord = Word | 1;
7319       return isWordClobbered(SourceHalfMask, LowWord) ||
7320              isWordClobbered(SourceHalfMask, HighWord);
7321     };
7322
7323     if (IncomingInputs.empty())
7324       return;
7325
7326     if (ExistingInputs.empty()) {
7327       // Map any dwords with inputs from them into the right half.
7328       for (int Input : IncomingInputs) {
7329         // If the source half mask maps over the inputs, turn those into
7330         // swaps and use the swapped lane.
7331         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7332           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7333             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7334                 Input - SourceOffset;
7335             // We have to swap the uses in our half mask in one sweep.
7336             for (int &M : HalfMask)
7337               if (M == SourceHalfMask[Input - SourceOffset])
7338                 M = Input;
7339               else if (M == Input)
7340                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7341           } else {
7342             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7343                        Input - SourceOffset &&
7344                    "Previous placement doesn't match!");
7345           }
7346           // Note that this correctly re-maps both when we do a swap and when
7347           // we observe the other side of the swap above. We rely on that to
7348           // avoid swapping the members of the input list directly.
7349           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7350         }
7351
7352         // Map the input's dword into the correct half.
7353         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7354           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7355         else
7356           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7357                      Input / 2 &&
7358                  "Previous placement doesn't match!");
7359       }
7360
7361       // And just directly shift any other-half mask elements to be same-half
7362       // as we will have mirrored the dword containing the element into the
7363       // same position within that half.
7364       for (int &M : HalfMask)
7365         if (M >= SourceOffset && M < SourceOffset + 4) {
7366           M = M - SourceOffset + DestOffset;
7367           assert(M >= 0 && "This should never wrap below zero!");
7368         }
7369       return;
7370     }
7371
7372     // Ensure we have the input in a viable dword of its current half. This
7373     // is particularly tricky because the original position may be clobbered
7374     // by inputs being moved and *staying* in that half.
7375     if (IncomingInputs.size() == 1) {
7376       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7377         int InputFixed = std::find(std::begin(SourceHalfMask),
7378                                    std::end(SourceHalfMask), -1) -
7379                          std::begin(SourceHalfMask) + SourceOffset;
7380         SourceHalfMask[InputFixed - SourceOffset] =
7381             IncomingInputs[0] - SourceOffset;
7382         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7383                      InputFixed);
7384         IncomingInputs[0] = InputFixed;
7385       }
7386     } else if (IncomingInputs.size() == 2) {
7387       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7388           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7389         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7390         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7391                "Not all dwords can be clobbered!");
7392         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7393         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7394         for (int &M : HalfMask)
7395           if (M == IncomingInputs[0])
7396             M = SourceDWordBase + SourceOffset;
7397           else if (M == IncomingInputs[1])
7398             M = SourceDWordBase + 1 + SourceOffset;
7399         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7400         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7401       }
7402     } else {
7403       llvm_unreachable("Unhandled input size!");
7404     }
7405
7406     // Now hoist the DWord down to the right half.
7407     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7408     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7409     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7410     for (int Input : IncomingInputs)
7411       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7412                    FreeDWord * 2 + Input % 2);
7413   };
7414   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7415                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7416   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7417                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7418
7419   // Now enact all the shuffles we've computed to move the inputs into their
7420   // target half.
7421   if (!isNoopShuffleMask(PSHUFLMask))
7422     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7423                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7424   if (!isNoopShuffleMask(PSHUFHMask))
7425     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7426                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7427   if (!isNoopShuffleMask(PSHUFDMask))
7428     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7429                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7430                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7431                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7432
7433   // At this point, each half should contain all its inputs, and we can then
7434   // just shuffle them into their final position.
7435   assert(std::count_if(LoMask.begin(), LoMask.end(),
7436                        [](int M) { return M >= 4; }) == 0 &&
7437          "Failed to lift all the high half inputs to the low mask!");
7438   assert(std::count_if(HiMask.begin(), HiMask.end(),
7439                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7440          "Failed to lift all the low half inputs to the high mask!");
7441
7442   // Do a half shuffle for the low mask.
7443   if (!isNoopShuffleMask(LoMask))
7444     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7445                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7446
7447   // Do a half shuffle with the high mask after shifting its values down.
7448   for (int &M : HiMask)
7449     if (M >= 0)
7450       M -= 4;
7451   if (!isNoopShuffleMask(HiMask))
7452     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7453                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7454
7455   return V;
7456 }
7457
7458 /// \brief Detect whether the mask pattern should be lowered through
7459 /// interleaving.
7460 ///
7461 /// This essentially tests whether viewing the mask as an interleaving of two
7462 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7463 /// lowering it through interleaving is a significantly better strategy.
7464 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7465   int NumEvenInputs[2] = {0, 0};
7466   int NumOddInputs[2] = {0, 0};
7467   int NumLoInputs[2] = {0, 0};
7468   int NumHiInputs[2] = {0, 0};
7469   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7470     if (Mask[i] < 0)
7471       continue;
7472
7473     int InputIdx = Mask[i] >= Size;
7474
7475     if (i < Size / 2)
7476       ++NumLoInputs[InputIdx];
7477     else
7478       ++NumHiInputs[InputIdx];
7479
7480     if ((i % 2) == 0)
7481       ++NumEvenInputs[InputIdx];
7482     else
7483       ++NumOddInputs[InputIdx];
7484   }
7485
7486   // The minimum number of cross-input results for both the interleaved and
7487   // split cases. If interleaving results in fewer cross-input results, return
7488   // true.
7489   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7490                                     NumEvenInputs[0] + NumOddInputs[1]);
7491   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7492                               NumLoInputs[0] + NumHiInputs[1]);
7493   return InterleavedCrosses < SplitCrosses;
7494 }
7495
7496 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7497 ///
7498 /// This strategy only works when the inputs from each vector fit into a single
7499 /// half of that vector, and generally there are not so many inputs as to leave
7500 /// the in-place shuffles required highly constrained (and thus expensive). It
7501 /// shifts all the inputs into a single side of both input vectors and then
7502 /// uses an unpack to interleave these inputs in a single vector. At that
7503 /// point, we will fall back on the generic single input shuffle lowering.
7504 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7505                                                  SDValue V2,
7506                                                  MutableArrayRef<int> Mask,
7507                                                  const X86Subtarget *Subtarget,
7508                                                  SelectionDAG &DAG) {
7509   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7510   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7511   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7512   for (int i = 0; i < 8; ++i)
7513     if (Mask[i] >= 0 && Mask[i] < 4)
7514       LoV1Inputs.push_back(i);
7515     else if (Mask[i] >= 4 && Mask[i] < 8)
7516       HiV1Inputs.push_back(i);
7517     else if (Mask[i] >= 8 && Mask[i] < 12)
7518       LoV2Inputs.push_back(i);
7519     else if (Mask[i] >= 12)
7520       HiV2Inputs.push_back(i);
7521
7522   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7523   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7524   (void)NumV1Inputs;
7525   (void)NumV2Inputs;
7526   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7527   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7528   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7529
7530   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7531                      HiV1Inputs.size() + HiV2Inputs.size();
7532
7533   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7534                               ArrayRef<int> HiInputs, bool MoveToLo,
7535                               int MaskOffset) {
7536     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7537     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7538     if (BadInputs.empty())
7539       return V;
7540
7541     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7542     int MoveOffset = MoveToLo ? 0 : 4;
7543
7544     if (GoodInputs.empty()) {
7545       for (int BadInput : BadInputs) {
7546         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7547         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7548       }
7549     } else {
7550       if (GoodInputs.size() == 2) {
7551         // If the low inputs are spread across two dwords, pack them into
7552         // a single dword.
7553         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7554             Mask[GoodInputs[0]] - MaskOffset;
7555         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7556             Mask[GoodInputs[1]] - MaskOffset;
7557         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7558         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7559       } else {
7560         // Otherwise pin the low inputs.
7561         for (int GoodInput : GoodInputs)
7562           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7563       }
7564
7565       int MoveMaskIdx =
7566           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7567           std::begin(MoveMask);
7568       assert(MoveMaskIdx >= MoveOffset && "Established above");
7569
7570       if (BadInputs.size() == 2) {
7571         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7572         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7573         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7574             Mask[BadInputs[0]] - MaskOffset;
7575         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7576             Mask[BadInputs[1]] - MaskOffset;
7577         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7578         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7579       } else {
7580         assert(BadInputs.size() == 1 && "All sizes handled");
7581         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7582         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7583       }
7584     }
7585
7586     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7587                                 MoveMask);
7588   };
7589   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7590                         /*MaskOffset*/ 0);
7591   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7592                         /*MaskOffset*/ 8);
7593
7594   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7595   // cross-half traffic in the final shuffle.
7596
7597   // Munge the mask to be a single-input mask after the unpack merges the
7598   // results.
7599   for (int &M : Mask)
7600     if (M != -1)
7601       M = 2 * (M % 4) + (M / 8);
7602
7603   return DAG.getVectorShuffle(
7604       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7605                                   DL, MVT::v8i16, V1, V2),
7606       DAG.getUNDEF(MVT::v8i16), Mask);
7607 }
7608
7609 /// \brief Generic lowering of 8-lane i16 shuffles.
7610 ///
7611 /// This handles both single-input shuffles and combined shuffle/blends with
7612 /// two inputs. The single input shuffles are immediately delegated to
7613 /// a dedicated lowering routine.
7614 ///
7615 /// The blends are lowered in one of three fundamental ways. If there are few
7616 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7617 /// of the input is significantly cheaper when lowered as an interleaving of
7618 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7619 /// halves of the inputs separately (making them have relatively few inputs)
7620 /// and then concatenate them.
7621 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7622                                        const X86Subtarget *Subtarget,
7623                                        SelectionDAG &DAG) {
7624   SDLoc DL(Op);
7625   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7626   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7627   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7628   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7629   ArrayRef<int> OrigMask = SVOp->getMask();
7630   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7631                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7632   MutableArrayRef<int> Mask(MaskStorage);
7633
7634   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7635
7636   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7637   auto isV2 = [](int M) { return M >= 8; };
7638
7639   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7640   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7641
7642   if (NumV2Inputs == 0)
7643     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7644
7645   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7646                             "to be V1-input shuffles.");
7647
7648   if (NumV1Inputs + NumV2Inputs <= 4)
7649     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7650
7651   // Check whether an interleaving lowering is likely to be more efficient.
7652   // This isn't perfect but it is a strong heuristic that tends to work well on
7653   // the kinds of shuffles that show up in practice.
7654   //
7655   // FIXME: Handle 1x, 2x, and 4x interleaving.
7656   if (shouldLowerAsInterleaving(Mask)) {
7657     // FIXME: Figure out whether we should pack these into the low or high
7658     // halves.
7659
7660     int EMask[8], OMask[8];
7661     for (int i = 0; i < 4; ++i) {
7662       EMask[i] = Mask[2*i];
7663       OMask[i] = Mask[2*i + 1];
7664       EMask[i + 4] = -1;
7665       OMask[i + 4] = -1;
7666     }
7667
7668     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7669     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7670
7671     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7672   }
7673
7674   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7675   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7676
7677   for (int i = 0; i < 4; ++i) {
7678     LoBlendMask[i] = Mask[i];
7679     HiBlendMask[i] = Mask[i + 4];
7680   }
7681
7682   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7683   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7684   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7685   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7686
7687   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7688                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7689 }
7690
7691 /// \brief Generic lowering of v16i8 shuffles.
7692 ///
7693 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7694 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7695 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7696 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7697 /// back together.
7698 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7699                                        const X86Subtarget *Subtarget,
7700                                        SelectionDAG &DAG) {
7701   SDLoc DL(Op);
7702   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7703   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7704   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7705   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7706   ArrayRef<int> OrigMask = SVOp->getMask();
7707   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7708   int MaskStorage[16] = {
7709       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7710       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7711       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7712       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7713   MutableArrayRef<int> Mask(MaskStorage);
7714   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7715   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7716
7717   // For single-input shuffles, there are some nicer lowering tricks we can use.
7718   if (isSingleInputShuffleMask(Mask)) {
7719     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7720     // Notably, this handles splat and partial-splat shuffles more efficiently.
7721     // However, it only makes sense if the pre-duplication shuffle simplifies
7722     // things significantly. Currently, this means we need to be able to
7723     // express the pre-duplication shuffle as an i16 shuffle.
7724     //
7725     // FIXME: We should check for other patterns which can be widened into an
7726     // i16 shuffle as well.
7727     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7728       for (int i = 0; i < 16; i += 2) {
7729         if (Mask[i] != Mask[i + 1])
7730           return false;
7731       }
7732       return true;
7733     };
7734     auto tryToWidenViaDuplication = [&]() -> SDValue {
7735       if (!canWidenViaDuplication(Mask))
7736         return SDValue();
7737       SmallVector<int, 4> LoInputs;
7738       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7739                    [](int M) { return M >= 0 && M < 8; });
7740       std::sort(LoInputs.begin(), LoInputs.end());
7741       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7742                      LoInputs.end());
7743       SmallVector<int, 4> HiInputs;
7744       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7745                    [](int M) { return M >= 8; });
7746       std::sort(HiInputs.begin(), HiInputs.end());
7747       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7748                      HiInputs.end());
7749
7750       bool TargetLo = LoInputs.size() >= HiInputs.size();
7751       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7752       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7753
7754       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7755       SmallDenseMap<int, int, 8> LaneMap;
7756       for (int I : InPlaceInputs) {
7757         PreDupI16Shuffle[I/2] = I/2;
7758         LaneMap[I] = I;
7759       }
7760       int j = TargetLo ? 0 : 4, je = j + 4;
7761       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7762         // Check if j is already a shuffle of this input. This happens when
7763         // there are two adjacent bytes after we move the low one.
7764         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7765           // If we haven't yet mapped the input, search for a slot into which
7766           // we can map it.
7767           while (j < je && PreDupI16Shuffle[j] != -1)
7768             ++j;
7769
7770           if (j == je)
7771             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7772             return SDValue();
7773
7774           // Map this input with the i16 shuffle.
7775           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7776         }
7777
7778         // Update the lane map based on the mapping we ended up with.
7779         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7780       }
7781       V1 = DAG.getNode(
7782           ISD::BITCAST, DL, MVT::v16i8,
7783           DAG.getVectorShuffle(MVT::v8i16, DL,
7784                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7785                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7786
7787       // Unpack the bytes to form the i16s that will be shuffled into place.
7788       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7789                        MVT::v16i8, V1, V1);
7790
7791       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7792       for (int i = 0; i < 16; i += 2) {
7793         if (Mask[i] != -1)
7794           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7795         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7796       }
7797       return DAG.getNode(
7798           ISD::BITCAST, DL, MVT::v16i8,
7799           DAG.getVectorShuffle(MVT::v8i16, DL,
7800                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7801                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7802     };
7803     if (SDValue V = tryToWidenViaDuplication())
7804       return V;
7805   }
7806
7807   // Check whether an interleaving lowering is likely to be more efficient.
7808   // This isn't perfect but it is a strong heuristic that tends to work well on
7809   // the kinds of shuffles that show up in practice.
7810   //
7811   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7812   if (shouldLowerAsInterleaving(Mask)) {
7813     // FIXME: Figure out whether we should pack these into the low or high
7814     // halves.
7815
7816     int EMask[16], OMask[16];
7817     for (int i = 0; i < 8; ++i) {
7818       EMask[i] = Mask[2*i];
7819       OMask[i] = Mask[2*i + 1];
7820       EMask[i + 8] = -1;
7821       OMask[i + 8] = -1;
7822     }
7823
7824     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7825     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7826
7827     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7828   }
7829
7830   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7831   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7832   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7833   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7834
7835   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7836                             MutableArrayRef<int> V1HalfBlendMask,
7837                             MutableArrayRef<int> V2HalfBlendMask) {
7838     for (int i = 0; i < 8; ++i)
7839       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7840         V1HalfBlendMask[i] = HalfMask[i];
7841         HalfMask[i] = i;
7842       } else if (HalfMask[i] >= 16) {
7843         V2HalfBlendMask[i] = HalfMask[i] - 16;
7844         HalfMask[i] = i + 8;
7845       }
7846   };
7847   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7848   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7849
7850   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7851
7852   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7853                              MutableArrayRef<int> HiBlendMask) {
7854     SDValue V1, V2;
7855     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7856     // them out and avoid using UNPCK{L,H} to extract the elements of V as
7857     // i16s.
7858     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7859                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
7860         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7861                      [](int M) { return M >= 0 && M % 2 == 1; })) {
7862       // Use a mask to drop the high bytes.
7863       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7864       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7865                        DAG.getConstant(0x00FF, MVT::v8i16));
7866
7867       // This will be a single vector shuffle instead of a blend so nuke V2.
7868       V2 = DAG.getUNDEF(MVT::v8i16);
7869
7870       // Squash the masks to point directly into V1.
7871       for (int &M : LoBlendMask)
7872         if (M >= 0)
7873           M /= 2;
7874       for (int &M : HiBlendMask)
7875         if (M >= 0)
7876           M /= 2;
7877     } else {
7878       // Otherwise just unpack the low half of V into V1 and the high half into
7879       // V2 so that we can blend them as i16s.
7880       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7881                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7882       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7883                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7884     }
7885
7886     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7887     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7888     return std::make_pair(BlendedLo, BlendedHi);
7889   };
7890   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7891   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7892   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7893
7894   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7895   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7896
7897   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7898 }
7899
7900 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7901 ///
7902 /// This routine breaks down the specific type of 128-bit shuffle and
7903 /// dispatches to the lowering routines accordingly.
7904 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7905                                         MVT VT, const X86Subtarget *Subtarget,
7906                                         SelectionDAG &DAG) {
7907   switch (VT.SimpleTy) {
7908   case MVT::v2i64:
7909     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7910   case MVT::v2f64:
7911     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7912   case MVT::v4i32:
7913     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7914   case MVT::v4f32:
7915     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7916   case MVT::v8i16:
7917     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7918   case MVT::v16i8:
7919     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7920
7921   default:
7922     llvm_unreachable("Unimplemented!");
7923   }
7924 }
7925
7926 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7927 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7928   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7929     if (Mask[i] + 1 != Mask[i+1])
7930       return false;
7931
7932   return true;
7933 }
7934
7935 /// \brief Top-level lowering for x86 vector shuffles.
7936 ///
7937 /// This handles decomposition, canonicalization, and lowering of all x86
7938 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7939 /// above in helper routines. The canonicalization attempts to widen shuffles
7940 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7941 /// s.t. only one of the two inputs needs to be tested, etc.
7942 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7943                                   SelectionDAG &DAG) {
7944   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7945   ArrayRef<int> Mask = SVOp->getMask();
7946   SDValue V1 = Op.getOperand(0);
7947   SDValue V2 = Op.getOperand(1);
7948   MVT VT = Op.getSimpleValueType();
7949   int NumElements = VT.getVectorNumElements();
7950   SDLoc dl(Op);
7951
7952   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7953
7954   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7955   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7956   if (V1IsUndef && V2IsUndef)
7957     return DAG.getUNDEF(VT);
7958
7959   // When we create a shuffle node we put the UNDEF node to second operand,
7960   // but in some cases the first operand may be transformed to UNDEF.
7961   // In this case we should just commute the node.
7962   if (V1IsUndef)
7963     return DAG.getCommutedVectorShuffle(*SVOp);
7964
7965   // Check for non-undef masks pointing at an undef vector and make the masks
7966   // undef as well. This makes it easier to match the shuffle based solely on
7967   // the mask.
7968   if (V2IsUndef)
7969     for (int M : Mask)
7970       if (M >= NumElements) {
7971         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7972         for (int &M : NewMask)
7973           if (M >= NumElements)
7974             M = -1;
7975         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7976       }
7977
7978   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7979   // lanes but wider integers. We cap this to not form integers larger than i64
7980   // but it might be interesting to form i128 integers to handle flipping the
7981   // low and high halves of AVX 256-bit vectors.
7982   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7983       areAdjacentMasksSequential(Mask)) {
7984     SmallVector<int, 8> NewMask;
7985     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7986       NewMask.push_back(Mask[i] / 2);
7987     MVT NewVT =
7988         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7989                          VT.getVectorNumElements() / 2);
7990     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7991     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7992     return DAG.getNode(ISD::BITCAST, dl, VT,
7993                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7994   }
7995
7996   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7997   for (int M : SVOp->getMask())
7998     if (M < 0)
7999       ++NumUndefElements;
8000     else if (M < NumElements)
8001       ++NumV1Elements;
8002     else
8003       ++NumV2Elements;
8004
8005   // Commute the shuffle as needed such that more elements come from V1 than
8006   // V2. This allows us to match the shuffle pattern strictly on how many
8007   // elements come from V1 without handling the symmetric cases.
8008   if (NumV2Elements > NumV1Elements)
8009     return DAG.getCommutedVectorShuffle(*SVOp);
8010
8011   // When the number of V1 and V2 elements are the same, try to minimize the
8012   // number of uses of V2 in the low half of the vector.
8013   if (NumV1Elements == NumV2Elements) {
8014     int LowV1Elements = 0, LowV2Elements = 0;
8015     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8016       if (M >= NumElements)
8017         ++LowV2Elements;
8018       else if (M >= 0)
8019         ++LowV1Elements;
8020     if (LowV2Elements > LowV1Elements)
8021       return DAG.getCommutedVectorShuffle(*SVOp);
8022   }
8023
8024   // For each vector width, delegate to a specialized lowering routine.
8025   if (VT.getSizeInBits() == 128)
8026     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8027
8028   llvm_unreachable("Unimplemented!");
8029 }
8030
8031
8032 //===----------------------------------------------------------------------===//
8033 // Legacy vector shuffle lowering
8034 //
8035 // This code is the legacy code handling vector shuffles until the above
8036 // replaces its functionality and performance.
8037 //===----------------------------------------------------------------------===//
8038
8039 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8040                         bool hasInt256, unsigned *MaskOut = nullptr) {
8041   MVT EltVT = VT.getVectorElementType();
8042
8043   // There is no blend with immediate in AVX-512.
8044   if (VT.is512BitVector())
8045     return false;
8046
8047   if (!hasSSE41 || EltVT == MVT::i8)
8048     return false;
8049   if (!hasInt256 && VT == MVT::v16i16)
8050     return false;
8051
8052   unsigned MaskValue = 0;
8053   unsigned NumElems = VT.getVectorNumElements();
8054   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8055   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8056   unsigned NumElemsInLane = NumElems / NumLanes;
8057
8058   // Blend for v16i16 should be symetric for the both lanes.
8059   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8060
8061     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8062     int EltIdx = MaskVals[i];
8063
8064     if ((EltIdx < 0 || EltIdx == (int)i) &&
8065         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8066       continue;
8067
8068     if (((unsigned)EltIdx == (i + NumElems)) &&
8069         (SndLaneEltIdx < 0 ||
8070          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8071       MaskValue |= (1 << i);
8072     else
8073       return false;
8074   }
8075
8076   if (MaskOut)
8077     *MaskOut = MaskValue;
8078   return true;
8079 }
8080
8081 // Try to lower a shuffle node into a simple blend instruction.
8082 // This function assumes isBlendMask returns true for this
8083 // SuffleVectorSDNode
8084 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8085                                           unsigned MaskValue,
8086                                           const X86Subtarget *Subtarget,
8087                                           SelectionDAG &DAG) {
8088   MVT VT = SVOp->getSimpleValueType(0);
8089   MVT EltVT = VT.getVectorElementType();
8090   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8091                      Subtarget->hasInt256() && "Trying to lower a "
8092                                                "VECTOR_SHUFFLE to a Blend but "
8093                                                "with the wrong mask"));
8094   SDValue V1 = SVOp->getOperand(0);
8095   SDValue V2 = SVOp->getOperand(1);
8096   SDLoc dl(SVOp);
8097   unsigned NumElems = VT.getVectorNumElements();
8098
8099   // Convert i32 vectors to floating point if it is not AVX2.
8100   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8101   MVT BlendVT = VT;
8102   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8103     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8104                                NumElems);
8105     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8106     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8107   }
8108
8109   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8110                             DAG.getConstant(MaskValue, MVT::i32));
8111   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8112 }
8113
8114 /// In vector type \p VT, return true if the element at index \p InputIdx
8115 /// falls on a different 128-bit lane than \p OutputIdx.
8116 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8117                                      unsigned OutputIdx) {
8118   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8119   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8120 }
8121
8122 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8123 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8124 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8125 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8126 /// zero.
8127 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8128                          SelectionDAG &DAG) {
8129   MVT VT = V1.getSimpleValueType();
8130   assert(VT.is128BitVector() || VT.is256BitVector());
8131
8132   MVT EltVT = VT.getVectorElementType();
8133   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8134   unsigned NumElts = VT.getVectorNumElements();
8135
8136   SmallVector<SDValue, 32> PshufbMask;
8137   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8138     int InputIdx = MaskVals[OutputIdx];
8139     unsigned InputByteIdx;
8140
8141     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8142       InputByteIdx = 0x80;
8143     else {
8144       // Cross lane is not allowed.
8145       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8146         return SDValue();
8147       InputByteIdx = InputIdx * EltSizeInBytes;
8148       // Index is an byte offset within the 128-bit lane.
8149       InputByteIdx &= 0xf;
8150     }
8151
8152     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8153       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8154       if (InputByteIdx != 0x80)
8155         ++InputByteIdx;
8156     }
8157   }
8158
8159   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8160   if (ShufVT != VT)
8161     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8162   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8163                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8164 }
8165
8166 // v8i16 shuffles - Prefer shuffles in the following order:
8167 // 1. [all]   pshuflw, pshufhw, optional move
8168 // 2. [ssse3] 1 x pshufb
8169 // 3. [ssse3] 2 x pshufb + 1 x por
8170 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8171 static SDValue
8172 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8173                          SelectionDAG &DAG) {
8174   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8175   SDValue V1 = SVOp->getOperand(0);
8176   SDValue V2 = SVOp->getOperand(1);
8177   SDLoc dl(SVOp);
8178   SmallVector<int, 8> MaskVals;
8179
8180   // Determine if more than 1 of the words in each of the low and high quadwords
8181   // of the result come from the same quadword of one of the two inputs.  Undef
8182   // mask values count as coming from any quadword, for better codegen.
8183   //
8184   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8185   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8186   unsigned LoQuad[] = { 0, 0, 0, 0 };
8187   unsigned HiQuad[] = { 0, 0, 0, 0 };
8188   // Indices of quads used.
8189   std::bitset<4> InputQuads;
8190   for (unsigned i = 0; i < 8; ++i) {
8191     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8192     int EltIdx = SVOp->getMaskElt(i);
8193     MaskVals.push_back(EltIdx);
8194     if (EltIdx < 0) {
8195       ++Quad[0];
8196       ++Quad[1];
8197       ++Quad[2];
8198       ++Quad[3];
8199       continue;
8200     }
8201     ++Quad[EltIdx / 4];
8202     InputQuads.set(EltIdx / 4);
8203   }
8204
8205   int BestLoQuad = -1;
8206   unsigned MaxQuad = 1;
8207   for (unsigned i = 0; i < 4; ++i) {
8208     if (LoQuad[i] > MaxQuad) {
8209       BestLoQuad = i;
8210       MaxQuad = LoQuad[i];
8211     }
8212   }
8213
8214   int BestHiQuad = -1;
8215   MaxQuad = 1;
8216   for (unsigned i = 0; i < 4; ++i) {
8217     if (HiQuad[i] > MaxQuad) {
8218       BestHiQuad = i;
8219       MaxQuad = HiQuad[i];
8220     }
8221   }
8222
8223   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8224   // of the two input vectors, shuffle them into one input vector so only a
8225   // single pshufb instruction is necessary. If there are more than 2 input
8226   // quads, disable the next transformation since it does not help SSSE3.
8227   bool V1Used = InputQuads[0] || InputQuads[1];
8228   bool V2Used = InputQuads[2] || InputQuads[3];
8229   if (Subtarget->hasSSSE3()) {
8230     if (InputQuads.count() == 2 && V1Used && V2Used) {
8231       BestLoQuad = InputQuads[0] ? 0 : 1;
8232       BestHiQuad = InputQuads[2] ? 2 : 3;
8233     }
8234     if (InputQuads.count() > 2) {
8235       BestLoQuad = -1;
8236       BestHiQuad = -1;
8237     }
8238   }
8239
8240   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8241   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8242   // words from all 4 input quadwords.
8243   SDValue NewV;
8244   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8245     int MaskV[] = {
8246       BestLoQuad < 0 ? 0 : BestLoQuad,
8247       BestHiQuad < 0 ? 1 : BestHiQuad
8248     };
8249     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8250                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8251                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8252     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8253
8254     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8255     // source words for the shuffle, to aid later transformations.
8256     bool AllWordsInNewV = true;
8257     bool InOrder[2] = { true, true };
8258     for (unsigned i = 0; i != 8; ++i) {
8259       int idx = MaskVals[i];
8260       if (idx != (int)i)
8261         InOrder[i/4] = false;
8262       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8263         continue;
8264       AllWordsInNewV = false;
8265       break;
8266     }
8267
8268     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8269     if (AllWordsInNewV) {
8270       for (int i = 0; i != 8; ++i) {
8271         int idx = MaskVals[i];
8272         if (idx < 0)
8273           continue;
8274         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8275         if ((idx != i) && idx < 4)
8276           pshufhw = false;
8277         if ((idx != i) && idx > 3)
8278           pshuflw = false;
8279       }
8280       V1 = NewV;
8281       V2Used = false;
8282       BestLoQuad = 0;
8283       BestHiQuad = 1;
8284     }
8285
8286     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8287     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8288     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8289       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8290       unsigned TargetMask = 0;
8291       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8292                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8293       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8294       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8295                              getShufflePSHUFLWImmediate(SVOp);
8296       V1 = NewV.getOperand(0);
8297       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8298     }
8299   }
8300
8301   // Promote splats to a larger type which usually leads to more efficient code.
8302   // FIXME: Is this true if pshufb is available?
8303   if (SVOp->isSplat())
8304     return PromoteSplat(SVOp, DAG);
8305
8306   // If we have SSSE3, and all words of the result are from 1 input vector,
8307   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8308   // is present, fall back to case 4.
8309   if (Subtarget->hasSSSE3()) {
8310     SmallVector<SDValue,16> pshufbMask;
8311
8312     // If we have elements from both input vectors, set the high bit of the
8313     // shuffle mask element to zero out elements that come from V2 in the V1
8314     // mask, and elements that come from V1 in the V2 mask, so that the two
8315     // results can be OR'd together.
8316     bool TwoInputs = V1Used && V2Used;
8317     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8318     if (!TwoInputs)
8319       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8320
8321     // Calculate the shuffle mask for the second input, shuffle it, and
8322     // OR it with the first shuffled input.
8323     CommuteVectorShuffleMask(MaskVals, 8);
8324     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8325     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8326     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8327   }
8328
8329   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8330   // and update MaskVals with new element order.
8331   std::bitset<8> InOrder;
8332   if (BestLoQuad >= 0) {
8333     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8334     for (int i = 0; i != 4; ++i) {
8335       int idx = MaskVals[i];
8336       if (idx < 0) {
8337         InOrder.set(i);
8338       } else if ((idx / 4) == BestLoQuad) {
8339         MaskV[i] = idx & 3;
8340         InOrder.set(i);
8341       }
8342     }
8343     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8344                                 &MaskV[0]);
8345
8346     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8347       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8348       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8349                                   NewV.getOperand(0),
8350                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8351     }
8352   }
8353
8354   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8355   // and update MaskVals with the new element order.
8356   if (BestHiQuad >= 0) {
8357     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8358     for (unsigned i = 4; i != 8; ++i) {
8359       int idx = MaskVals[i];
8360       if (idx < 0) {
8361         InOrder.set(i);
8362       } else if ((idx / 4) == BestHiQuad) {
8363         MaskV[i] = (idx & 3) + 4;
8364         InOrder.set(i);
8365       }
8366     }
8367     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8368                                 &MaskV[0]);
8369
8370     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8371       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8372       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8373                                   NewV.getOperand(0),
8374                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8375     }
8376   }
8377
8378   // In case BestHi & BestLo were both -1, which means each quadword has a word
8379   // from each of the four input quadwords, calculate the InOrder bitvector now
8380   // before falling through to the insert/extract cleanup.
8381   if (BestLoQuad == -1 && BestHiQuad == -1) {
8382     NewV = V1;
8383     for (int i = 0; i != 8; ++i)
8384       if (MaskVals[i] < 0 || MaskVals[i] == i)
8385         InOrder.set(i);
8386   }
8387
8388   // The other elements are put in the right place using pextrw and pinsrw.
8389   for (unsigned i = 0; i != 8; ++i) {
8390     if (InOrder[i])
8391       continue;
8392     int EltIdx = MaskVals[i];
8393     if (EltIdx < 0)
8394       continue;
8395     SDValue ExtOp = (EltIdx < 8) ?
8396       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8397                   DAG.getIntPtrConstant(EltIdx)) :
8398       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8399                   DAG.getIntPtrConstant(EltIdx - 8));
8400     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8401                        DAG.getIntPtrConstant(i));
8402   }
8403   return NewV;
8404 }
8405
8406 /// \brief v16i16 shuffles
8407 ///
8408 /// FIXME: We only support generation of a single pshufb currently.  We can
8409 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8410 /// well (e.g 2 x pshufb + 1 x por).
8411 static SDValue
8412 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8413   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8414   SDValue V1 = SVOp->getOperand(0);
8415   SDValue V2 = SVOp->getOperand(1);
8416   SDLoc dl(SVOp);
8417
8418   if (V2.getOpcode() != ISD::UNDEF)
8419     return SDValue();
8420
8421   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8422   return getPSHUFB(MaskVals, V1, dl, DAG);
8423 }
8424
8425 // v16i8 shuffles - Prefer shuffles in the following order:
8426 // 1. [ssse3] 1 x pshufb
8427 // 2. [ssse3] 2 x pshufb + 1 x por
8428 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8429 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8430                                         const X86Subtarget* Subtarget,
8431                                         SelectionDAG &DAG) {
8432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8433   SDValue V1 = SVOp->getOperand(0);
8434   SDValue V2 = SVOp->getOperand(1);
8435   SDLoc dl(SVOp);
8436   ArrayRef<int> MaskVals = SVOp->getMask();
8437
8438   // Promote splats to a larger type which usually leads to more efficient code.
8439   // FIXME: Is this true if pshufb is available?
8440   if (SVOp->isSplat())
8441     return PromoteSplat(SVOp, DAG);
8442
8443   // If we have SSSE3, case 1 is generated when all result bytes come from
8444   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8445   // present, fall back to case 3.
8446
8447   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8448   if (Subtarget->hasSSSE3()) {
8449     SmallVector<SDValue,16> pshufbMask;
8450
8451     // If all result elements are from one input vector, then only translate
8452     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8453     //
8454     // Otherwise, we have elements from both input vectors, and must zero out
8455     // elements that come from V2 in the first mask, and V1 in the second mask
8456     // so that we can OR them together.
8457     for (unsigned i = 0; i != 16; ++i) {
8458       int EltIdx = MaskVals[i];
8459       if (EltIdx < 0 || EltIdx >= 16)
8460         EltIdx = 0x80;
8461       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8462     }
8463     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8464                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8465                                  MVT::v16i8, pshufbMask));
8466
8467     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8468     // the 2nd operand if it's undefined or zero.
8469     if (V2.getOpcode() == ISD::UNDEF ||
8470         ISD::isBuildVectorAllZeros(V2.getNode()))
8471       return V1;
8472
8473     // Calculate the shuffle mask for the second input, shuffle it, and
8474     // OR it with the first shuffled input.
8475     pshufbMask.clear();
8476     for (unsigned i = 0; i != 16; ++i) {
8477       int EltIdx = MaskVals[i];
8478       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8479       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8480     }
8481     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8482                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8483                                  MVT::v16i8, pshufbMask));
8484     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8485   }
8486
8487   // No SSSE3 - Calculate in place words and then fix all out of place words
8488   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8489   // the 16 different words that comprise the two doublequadword input vectors.
8490   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8491   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8492   SDValue NewV = V1;
8493   for (int i = 0; i != 8; ++i) {
8494     int Elt0 = MaskVals[i*2];
8495     int Elt1 = MaskVals[i*2+1];
8496
8497     // This word of the result is all undef, skip it.
8498     if (Elt0 < 0 && Elt1 < 0)
8499       continue;
8500
8501     // This word of the result is already in the correct place, skip it.
8502     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8503       continue;
8504
8505     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8506     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8507     SDValue InsElt;
8508
8509     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8510     // using a single extract together, load it and store it.
8511     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8512       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8513                            DAG.getIntPtrConstant(Elt1 / 2));
8514       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8515                         DAG.getIntPtrConstant(i));
8516       continue;
8517     }
8518
8519     // If Elt1 is defined, extract it from the appropriate source.  If the
8520     // source byte is not also odd, shift the extracted word left 8 bits
8521     // otherwise clear the bottom 8 bits if we need to do an or.
8522     if (Elt1 >= 0) {
8523       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8524                            DAG.getIntPtrConstant(Elt1 / 2));
8525       if ((Elt1 & 1) == 0)
8526         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8527                              DAG.getConstant(8,
8528                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8529       else if (Elt0 >= 0)
8530         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8531                              DAG.getConstant(0xFF00, MVT::i16));
8532     }
8533     // If Elt0 is defined, extract it from the appropriate source.  If the
8534     // source byte is not also even, shift the extracted word right 8 bits. If
8535     // Elt1 was also defined, OR the extracted values together before
8536     // inserting them in the result.
8537     if (Elt0 >= 0) {
8538       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8539                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8540       if ((Elt0 & 1) != 0)
8541         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8542                               DAG.getConstant(8,
8543                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8544       else if (Elt1 >= 0)
8545         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8546                              DAG.getConstant(0x00FF, MVT::i16));
8547       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8548                          : InsElt0;
8549     }
8550     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8551                        DAG.getIntPtrConstant(i));
8552   }
8553   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8554 }
8555
8556 // v32i8 shuffles - Translate to VPSHUFB if possible.
8557 static
8558 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8559                                  const X86Subtarget *Subtarget,
8560                                  SelectionDAG &DAG) {
8561   MVT VT = SVOp->getSimpleValueType(0);
8562   SDValue V1 = SVOp->getOperand(0);
8563   SDValue V2 = SVOp->getOperand(1);
8564   SDLoc dl(SVOp);
8565   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8566
8567   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8568   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8569   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8570
8571   // VPSHUFB may be generated if
8572   // (1) one of input vector is undefined or zeroinitializer.
8573   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8574   // And (2) the mask indexes don't cross the 128-bit lane.
8575   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8576       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8577     return SDValue();
8578
8579   if (V1IsAllZero && !V2IsAllZero) {
8580     CommuteVectorShuffleMask(MaskVals, 32);
8581     V1 = V2;
8582   }
8583   return getPSHUFB(MaskVals, V1, dl, DAG);
8584 }
8585
8586 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8587 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8588 /// done when every pair / quad of shuffle mask elements point to elements in
8589 /// the right sequence. e.g.
8590 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8591 static
8592 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8593                                  SelectionDAG &DAG) {
8594   MVT VT = SVOp->getSimpleValueType(0);
8595   SDLoc dl(SVOp);
8596   unsigned NumElems = VT.getVectorNumElements();
8597   MVT NewVT;
8598   unsigned Scale;
8599   switch (VT.SimpleTy) {
8600   default: llvm_unreachable("Unexpected!");
8601   case MVT::v2i64:
8602   case MVT::v2f64:
8603            return SDValue(SVOp, 0);
8604   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8605   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8606   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8607   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8608   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8609   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8610   }
8611
8612   SmallVector<int, 8> MaskVec;
8613   for (unsigned i = 0; i != NumElems; i += Scale) {
8614     int StartIdx = -1;
8615     for (unsigned j = 0; j != Scale; ++j) {
8616       int EltIdx = SVOp->getMaskElt(i+j);
8617       if (EltIdx < 0)
8618         continue;
8619       if (StartIdx < 0)
8620         StartIdx = (EltIdx / Scale);
8621       if (EltIdx != (int)(StartIdx*Scale + j))
8622         return SDValue();
8623     }
8624     MaskVec.push_back(StartIdx);
8625   }
8626
8627   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8628   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8629   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8630 }
8631
8632 /// getVZextMovL - Return a zero-extending vector move low node.
8633 ///
8634 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8635                             SDValue SrcOp, SelectionDAG &DAG,
8636                             const X86Subtarget *Subtarget, SDLoc dl) {
8637   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8638     LoadSDNode *LD = nullptr;
8639     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8640       LD = dyn_cast<LoadSDNode>(SrcOp);
8641     if (!LD) {
8642       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8643       // instead.
8644       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8645       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8646           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8647           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8648           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8649         // PR2108
8650         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8651         return DAG.getNode(ISD::BITCAST, dl, VT,
8652                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8653                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8654                                                    OpVT,
8655                                                    SrcOp.getOperand(0)
8656                                                           .getOperand(0))));
8657       }
8658     }
8659   }
8660
8661   return DAG.getNode(ISD::BITCAST, dl, VT,
8662                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8663                                  DAG.getNode(ISD::BITCAST, dl,
8664                                              OpVT, SrcOp)));
8665 }
8666
8667 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8668 /// which could not be matched by any known target speficic shuffle
8669 static SDValue
8670 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8671
8672   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8673   if (NewOp.getNode())
8674     return NewOp;
8675
8676   MVT VT = SVOp->getSimpleValueType(0);
8677
8678   unsigned NumElems = VT.getVectorNumElements();
8679   unsigned NumLaneElems = NumElems / 2;
8680
8681   SDLoc dl(SVOp);
8682   MVT EltVT = VT.getVectorElementType();
8683   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8684   SDValue Output[2];
8685
8686   SmallVector<int, 16> Mask;
8687   for (unsigned l = 0; l < 2; ++l) {
8688     // Build a shuffle mask for the output, discovering on the fly which
8689     // input vectors to use as shuffle operands (recorded in InputUsed).
8690     // If building a suitable shuffle vector proves too hard, then bail
8691     // out with UseBuildVector set.
8692     bool UseBuildVector = false;
8693     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8694     unsigned LaneStart = l * NumLaneElems;
8695     for (unsigned i = 0; i != NumLaneElems; ++i) {
8696       // The mask element.  This indexes into the input.
8697       int Idx = SVOp->getMaskElt(i+LaneStart);
8698       if (Idx < 0) {
8699         // the mask element does not index into any input vector.
8700         Mask.push_back(-1);
8701         continue;
8702       }
8703
8704       // The input vector this mask element indexes into.
8705       int Input = Idx / NumLaneElems;
8706
8707       // Turn the index into an offset from the start of the input vector.
8708       Idx -= Input * NumLaneElems;
8709
8710       // Find or create a shuffle vector operand to hold this input.
8711       unsigned OpNo;
8712       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8713         if (InputUsed[OpNo] == Input)
8714           // This input vector is already an operand.
8715           break;
8716         if (InputUsed[OpNo] < 0) {
8717           // Create a new operand for this input vector.
8718           InputUsed[OpNo] = Input;
8719           break;
8720         }
8721       }
8722
8723       if (OpNo >= array_lengthof(InputUsed)) {
8724         // More than two input vectors used!  Give up on trying to create a
8725         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8726         UseBuildVector = true;
8727         break;
8728       }
8729
8730       // Add the mask index for the new shuffle vector.
8731       Mask.push_back(Idx + OpNo * NumLaneElems);
8732     }
8733
8734     if (UseBuildVector) {
8735       SmallVector<SDValue, 16> SVOps;
8736       for (unsigned i = 0; i != NumLaneElems; ++i) {
8737         // The mask element.  This indexes into the input.
8738         int Idx = SVOp->getMaskElt(i+LaneStart);
8739         if (Idx < 0) {
8740           SVOps.push_back(DAG.getUNDEF(EltVT));
8741           continue;
8742         }
8743
8744         // The input vector this mask element indexes into.
8745         int Input = Idx / NumElems;
8746
8747         // Turn the index into an offset from the start of the input vector.
8748         Idx -= Input * NumElems;
8749
8750         // Extract the vector element by hand.
8751         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8752                                     SVOp->getOperand(Input),
8753                                     DAG.getIntPtrConstant(Idx)));
8754       }
8755
8756       // Construct the output using a BUILD_VECTOR.
8757       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8758     } else if (InputUsed[0] < 0) {
8759       // No input vectors were used! The result is undefined.
8760       Output[l] = DAG.getUNDEF(NVT);
8761     } else {
8762       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8763                                         (InputUsed[0] % 2) * NumLaneElems,
8764                                         DAG, dl);
8765       // If only one input was used, use an undefined vector for the other.
8766       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8767         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8768                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8769       // At least one input vector was used. Create a new shuffle vector.
8770       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8771     }
8772
8773     Mask.clear();
8774   }
8775
8776   // Concatenate the result back
8777   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8778 }
8779
8780 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8781 /// 4 elements, and match them with several different shuffle types.
8782 static SDValue
8783 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8784   SDValue V1 = SVOp->getOperand(0);
8785   SDValue V2 = SVOp->getOperand(1);
8786   SDLoc dl(SVOp);
8787   MVT VT = SVOp->getSimpleValueType(0);
8788
8789   assert(VT.is128BitVector() && "Unsupported vector size");
8790
8791   std::pair<int, int> Locs[4];
8792   int Mask1[] = { -1, -1, -1, -1 };
8793   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8794
8795   unsigned NumHi = 0;
8796   unsigned NumLo = 0;
8797   for (unsigned i = 0; i != 4; ++i) {
8798     int Idx = PermMask[i];
8799     if (Idx < 0) {
8800       Locs[i] = std::make_pair(-1, -1);
8801     } else {
8802       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8803       if (Idx < 4) {
8804         Locs[i] = std::make_pair(0, NumLo);
8805         Mask1[NumLo] = Idx;
8806         NumLo++;
8807       } else {
8808         Locs[i] = std::make_pair(1, NumHi);
8809         if (2+NumHi < 4)
8810           Mask1[2+NumHi] = Idx;
8811         NumHi++;
8812       }
8813     }
8814   }
8815
8816   if (NumLo <= 2 && NumHi <= 2) {
8817     // If no more than two elements come from either vector. This can be
8818     // implemented with two shuffles. First shuffle gather the elements.
8819     // The second shuffle, which takes the first shuffle as both of its
8820     // vector operands, put the elements into the right order.
8821     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8822
8823     int Mask2[] = { -1, -1, -1, -1 };
8824
8825     for (unsigned i = 0; i != 4; ++i)
8826       if (Locs[i].first != -1) {
8827         unsigned Idx = (i < 2) ? 0 : 4;
8828         Idx += Locs[i].first * 2 + Locs[i].second;
8829         Mask2[i] = Idx;
8830       }
8831
8832     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8833   }
8834
8835   if (NumLo == 3 || NumHi == 3) {
8836     // Otherwise, we must have three elements from one vector, call it X, and
8837     // one element from the other, call it Y.  First, use a shufps to build an
8838     // intermediate vector with the one element from Y and the element from X
8839     // that will be in the same half in the final destination (the indexes don't
8840     // matter). Then, use a shufps to build the final vector, taking the half
8841     // containing the element from Y from the intermediate, and the other half
8842     // from X.
8843     if (NumHi == 3) {
8844       // Normalize it so the 3 elements come from V1.
8845       CommuteVectorShuffleMask(PermMask, 4);
8846       std::swap(V1, V2);
8847     }
8848
8849     // Find the element from V2.
8850     unsigned HiIndex;
8851     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8852       int Val = PermMask[HiIndex];
8853       if (Val < 0)
8854         continue;
8855       if (Val >= 4)
8856         break;
8857     }
8858
8859     Mask1[0] = PermMask[HiIndex];
8860     Mask1[1] = -1;
8861     Mask1[2] = PermMask[HiIndex^1];
8862     Mask1[3] = -1;
8863     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8864
8865     if (HiIndex >= 2) {
8866       Mask1[0] = PermMask[0];
8867       Mask1[1] = PermMask[1];
8868       Mask1[2] = HiIndex & 1 ? 6 : 4;
8869       Mask1[3] = HiIndex & 1 ? 4 : 6;
8870       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8871     }
8872
8873     Mask1[0] = HiIndex & 1 ? 2 : 0;
8874     Mask1[1] = HiIndex & 1 ? 0 : 2;
8875     Mask1[2] = PermMask[2];
8876     Mask1[3] = PermMask[3];
8877     if (Mask1[2] >= 0)
8878       Mask1[2] += 4;
8879     if (Mask1[3] >= 0)
8880       Mask1[3] += 4;
8881     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8882   }
8883
8884   // Break it into (shuffle shuffle_hi, shuffle_lo).
8885   int LoMask[] = { -1, -1, -1, -1 };
8886   int HiMask[] = { -1, -1, -1, -1 };
8887
8888   int *MaskPtr = LoMask;
8889   unsigned MaskIdx = 0;
8890   unsigned LoIdx = 0;
8891   unsigned HiIdx = 2;
8892   for (unsigned i = 0; i != 4; ++i) {
8893     if (i == 2) {
8894       MaskPtr = HiMask;
8895       MaskIdx = 1;
8896       LoIdx = 0;
8897       HiIdx = 2;
8898     }
8899     int Idx = PermMask[i];
8900     if (Idx < 0) {
8901       Locs[i] = std::make_pair(-1, -1);
8902     } else if (Idx < 4) {
8903       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8904       MaskPtr[LoIdx] = Idx;
8905       LoIdx++;
8906     } else {
8907       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8908       MaskPtr[HiIdx] = Idx;
8909       HiIdx++;
8910     }
8911   }
8912
8913   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8914   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8915   int MaskOps[] = { -1, -1, -1, -1 };
8916   for (unsigned i = 0; i != 4; ++i)
8917     if (Locs[i].first != -1)
8918       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8919   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8920 }
8921
8922 static bool MayFoldVectorLoad(SDValue V) {
8923   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8924     V = V.getOperand(0);
8925
8926   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8927     V = V.getOperand(0);
8928   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8929       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8930     // BUILD_VECTOR (load), undef
8931     V = V.getOperand(0);
8932
8933   return MayFoldLoad(V);
8934 }
8935
8936 static
8937 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8938   MVT VT = Op.getSimpleValueType();
8939
8940   // Canonizalize to v2f64.
8941   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8942   return DAG.getNode(ISD::BITCAST, dl, VT,
8943                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8944                                           V1, DAG));
8945 }
8946
8947 static
8948 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8949                         bool HasSSE2) {
8950   SDValue V1 = Op.getOperand(0);
8951   SDValue V2 = Op.getOperand(1);
8952   MVT VT = Op.getSimpleValueType();
8953
8954   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8955
8956   if (HasSSE2 && VT == MVT::v2f64)
8957     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8958
8959   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8960   return DAG.getNode(ISD::BITCAST, dl, VT,
8961                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8962                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8963                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8964 }
8965
8966 static
8967 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8968   SDValue V1 = Op.getOperand(0);
8969   SDValue V2 = Op.getOperand(1);
8970   MVT VT = Op.getSimpleValueType();
8971
8972   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8973          "unsupported shuffle type");
8974
8975   if (V2.getOpcode() == ISD::UNDEF)
8976     V2 = V1;
8977
8978   // v4i32 or v4f32
8979   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8980 }
8981
8982 static
8983 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8984   SDValue V1 = Op.getOperand(0);
8985   SDValue V2 = Op.getOperand(1);
8986   MVT VT = Op.getSimpleValueType();
8987   unsigned NumElems = VT.getVectorNumElements();
8988
8989   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8990   // operand of these instructions is only memory, so check if there's a
8991   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8992   // same masks.
8993   bool CanFoldLoad = false;
8994
8995   // Trivial case, when V2 comes from a load.
8996   if (MayFoldVectorLoad(V2))
8997     CanFoldLoad = true;
8998
8999   // When V1 is a load, it can be folded later into a store in isel, example:
9000   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9001   //    turns into:
9002   //  (MOVLPSmr addr:$src1, VR128:$src2)
9003   // So, recognize this potential and also use MOVLPS or MOVLPD
9004   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9005     CanFoldLoad = true;
9006
9007   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9008   if (CanFoldLoad) {
9009     if (HasSSE2 && NumElems == 2)
9010       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9011
9012     if (NumElems == 4)
9013       // If we don't care about the second element, proceed to use movss.
9014       if (SVOp->getMaskElt(1) != -1)
9015         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9016   }
9017
9018   // movl and movlp will both match v2i64, but v2i64 is never matched by
9019   // movl earlier because we make it strict to avoid messing with the movlp load
9020   // folding logic (see the code above getMOVLP call). Match it here then,
9021   // this is horrible, but will stay like this until we move all shuffle
9022   // matching to x86 specific nodes. Note that for the 1st condition all
9023   // types are matched with movsd.
9024   if (HasSSE2) {
9025     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9026     // as to remove this logic from here, as much as possible
9027     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9028       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9029     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9030   }
9031
9032   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9033
9034   // Invert the operand order and use SHUFPS to match it.
9035   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9036                               getShuffleSHUFImmediate(SVOp), DAG);
9037 }
9038
9039 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9040                                          SelectionDAG &DAG) {
9041   SDLoc dl(Load);
9042   MVT VT = Load->getSimpleValueType(0);
9043   MVT EVT = VT.getVectorElementType();
9044   SDValue Addr = Load->getOperand(1);
9045   SDValue NewAddr = DAG.getNode(
9046       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9047       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9048
9049   SDValue NewLoad =
9050       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9051                   DAG.getMachineFunction().getMachineMemOperand(
9052                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9053   return NewLoad;
9054 }
9055
9056 // It is only safe to call this function if isINSERTPSMask is true for
9057 // this shufflevector mask.
9058 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9059                            SelectionDAG &DAG) {
9060   // Generate an insertps instruction when inserting an f32 from memory onto a
9061   // v4f32 or when copying a member from one v4f32 to another.
9062   // We also use it for transferring i32 from one register to another,
9063   // since it simply copies the same bits.
9064   // If we're transferring an i32 from memory to a specific element in a
9065   // register, we output a generic DAG that will match the PINSRD
9066   // instruction.
9067   MVT VT = SVOp->getSimpleValueType(0);
9068   MVT EVT = VT.getVectorElementType();
9069   SDValue V1 = SVOp->getOperand(0);
9070   SDValue V2 = SVOp->getOperand(1);
9071   auto Mask = SVOp->getMask();
9072   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9073          "unsupported vector type for insertps/pinsrd");
9074
9075   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9076   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9077   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9078
9079   SDValue From;
9080   SDValue To;
9081   unsigned DestIndex;
9082   if (FromV1 == 1) {
9083     From = V1;
9084     To = V2;
9085     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9086                 Mask.begin();
9087
9088     // If we have 1 element from each vector, we have to check if we're
9089     // changing V1's element's place. If so, we're done. Otherwise, we
9090     // should assume we're changing V2's element's place and behave
9091     // accordingly.
9092     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9093     assert(DestIndex <= INT32_MAX && "truncated destination index");
9094     if (FromV1 == FromV2 &&
9095         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9096       From = V2;
9097       To = V1;
9098       DestIndex =
9099           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9100     }
9101   } else {
9102     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9103            "More than one element from V1 and from V2, or no elements from one "
9104            "of the vectors. This case should not have returned true from "
9105            "isINSERTPSMask");
9106     From = V2;
9107     To = V1;
9108     DestIndex =
9109         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9110   }
9111
9112   // Get an index into the source vector in the range [0,4) (the mask is
9113   // in the range [0,8) because it can address V1 and V2)
9114   unsigned SrcIndex = Mask[DestIndex] % 4;
9115   if (MayFoldLoad(From)) {
9116     // Trivial case, when From comes from a load and is only used by the
9117     // shuffle. Make it use insertps from the vector that we need from that
9118     // load.
9119     SDValue NewLoad =
9120         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9121     if (!NewLoad.getNode())
9122       return SDValue();
9123
9124     if (EVT == MVT::f32) {
9125       // Create this as a scalar to vector to match the instruction pattern.
9126       SDValue LoadScalarToVector =
9127           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9128       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9129       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9130                          InsertpsMask);
9131     } else { // EVT == MVT::i32
9132       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9133       // instruction, to match the PINSRD instruction, which loads an i32 to a
9134       // certain vector element.
9135       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9136                          DAG.getConstant(DestIndex, MVT::i32));
9137     }
9138   }
9139
9140   // Vector-element-to-vector
9141   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9142   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9143 }
9144
9145 // Reduce a vector shuffle to zext.
9146 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9147                                     SelectionDAG &DAG) {
9148   // PMOVZX is only available from SSE41.
9149   if (!Subtarget->hasSSE41())
9150     return SDValue();
9151
9152   MVT VT = Op.getSimpleValueType();
9153
9154   // Only AVX2 support 256-bit vector integer extending.
9155   if (!Subtarget->hasInt256() && VT.is256BitVector())
9156     return SDValue();
9157
9158   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9159   SDLoc DL(Op);
9160   SDValue V1 = Op.getOperand(0);
9161   SDValue V2 = Op.getOperand(1);
9162   unsigned NumElems = VT.getVectorNumElements();
9163
9164   // Extending is an unary operation and the element type of the source vector
9165   // won't be equal to or larger than i64.
9166   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9167       VT.getVectorElementType() == MVT::i64)
9168     return SDValue();
9169
9170   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9171   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9172   while ((1U << Shift) < NumElems) {
9173     if (SVOp->getMaskElt(1U << Shift) == 1)
9174       break;
9175     Shift += 1;
9176     // The maximal ratio is 8, i.e. from i8 to i64.
9177     if (Shift > 3)
9178       return SDValue();
9179   }
9180
9181   // Check the shuffle mask.
9182   unsigned Mask = (1U << Shift) - 1;
9183   for (unsigned i = 0; i != NumElems; ++i) {
9184     int EltIdx = SVOp->getMaskElt(i);
9185     if ((i & Mask) != 0 && EltIdx != -1)
9186       return SDValue();
9187     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9188       return SDValue();
9189   }
9190
9191   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9192   MVT NeVT = MVT::getIntegerVT(NBits);
9193   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9194
9195   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9196     return SDValue();
9197
9198   // Simplify the operand as it's prepared to be fed into shuffle.
9199   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9200   if (V1.getOpcode() == ISD::BITCAST &&
9201       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9202       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9203       V1.getOperand(0).getOperand(0)
9204         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9205     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9206     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9207     ConstantSDNode *CIdx =
9208       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9209     // If it's foldable, i.e. normal load with single use, we will let code
9210     // selection to fold it. Otherwise, we will short the conversion sequence.
9211     if (CIdx && CIdx->getZExtValue() == 0 &&
9212         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9213       MVT FullVT = V.getSimpleValueType();
9214       MVT V1VT = V1.getSimpleValueType();
9215       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9216         // The "ext_vec_elt" node is wider than the result node.
9217         // In this case we should extract subvector from V.
9218         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9219         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9220         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9221                                         FullVT.getVectorNumElements()/Ratio);
9222         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9223                         DAG.getIntPtrConstant(0));
9224       }
9225       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9226     }
9227   }
9228
9229   return DAG.getNode(ISD::BITCAST, DL, VT,
9230                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9231 }
9232
9233 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9234                                       SelectionDAG &DAG) {
9235   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9236   MVT VT = Op.getSimpleValueType();
9237   SDLoc dl(Op);
9238   SDValue V1 = Op.getOperand(0);
9239   SDValue V2 = Op.getOperand(1);
9240
9241   if (isZeroShuffle(SVOp))
9242     return getZeroVector(VT, Subtarget, DAG, dl);
9243
9244   // Handle splat operations
9245   if (SVOp->isSplat()) {
9246     // Use vbroadcast whenever the splat comes from a foldable load
9247     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9248     if (Broadcast.getNode())
9249       return Broadcast;
9250   }
9251
9252   // Check integer expanding shuffles.
9253   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9254   if (NewOp.getNode())
9255     return NewOp;
9256
9257   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9258   // do it!
9259   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9260       VT == MVT::v32i8) {
9261     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9262     if (NewOp.getNode())
9263       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9264   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9265     // FIXME: Figure out a cleaner way to do this.
9266     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9267       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9268       if (NewOp.getNode()) {
9269         MVT NewVT = NewOp.getSimpleValueType();
9270         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9271                                NewVT, true, false))
9272           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9273                               dl);
9274       }
9275     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9276       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9277       if (NewOp.getNode()) {
9278         MVT NewVT = NewOp.getSimpleValueType();
9279         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9280           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9281                               dl);
9282       }
9283     }
9284   }
9285   return SDValue();
9286 }
9287
9288 SDValue
9289 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9290   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9291   SDValue V1 = Op.getOperand(0);
9292   SDValue V2 = Op.getOperand(1);
9293   MVT VT = Op.getSimpleValueType();
9294   SDLoc dl(Op);
9295   unsigned NumElems = VT.getVectorNumElements();
9296   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9297   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9298   bool V1IsSplat = false;
9299   bool V2IsSplat = false;
9300   bool HasSSE2 = Subtarget->hasSSE2();
9301   bool HasFp256    = Subtarget->hasFp256();
9302   bool HasInt256   = Subtarget->hasInt256();
9303   MachineFunction &MF = DAG.getMachineFunction();
9304   bool OptForSize = MF.getFunction()->getAttributes().
9305     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9306
9307   // Check if we should use the experimental vector shuffle lowering. If so,
9308   // delegate completely to that code path.
9309   if (ExperimentalVectorShuffleLowering)
9310     return lowerVectorShuffle(Op, Subtarget, DAG);
9311
9312   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9313
9314   if (V1IsUndef && V2IsUndef)
9315     return DAG.getUNDEF(VT);
9316
9317   // When we create a shuffle node we put the UNDEF node to second operand,
9318   // but in some cases the first operand may be transformed to UNDEF.
9319   // In this case we should just commute the node.
9320   if (V1IsUndef)
9321     return DAG.getCommutedVectorShuffle(*SVOp);
9322
9323   // Vector shuffle lowering takes 3 steps:
9324   //
9325   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9326   //    narrowing and commutation of operands should be handled.
9327   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9328   //    shuffle nodes.
9329   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9330   //    so the shuffle can be broken into other shuffles and the legalizer can
9331   //    try the lowering again.
9332   //
9333   // The general idea is that no vector_shuffle operation should be left to
9334   // be matched during isel, all of them must be converted to a target specific
9335   // node here.
9336
9337   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9338   // narrowing and commutation of operands should be handled. The actual code
9339   // doesn't include all of those, work in progress...
9340   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9341   if (NewOp.getNode())
9342     return NewOp;
9343
9344   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9345
9346   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9347   // unpckh_undef). Only use pshufd if speed is more important than size.
9348   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9349     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9350   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9351     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9352
9353   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9354       V2IsUndef && MayFoldVectorLoad(V1))
9355     return getMOVDDup(Op, dl, V1, DAG);
9356
9357   if (isMOVHLPS_v_undef_Mask(M, VT))
9358     return getMOVHighToLow(Op, dl, DAG);
9359
9360   // Use to match splats
9361   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9362       (VT == MVT::v2f64 || VT == MVT::v2i64))
9363     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9364
9365   if (isPSHUFDMask(M, VT)) {
9366     // The actual implementation will match the mask in the if above and then
9367     // during isel it can match several different instructions, not only pshufd
9368     // as its name says, sad but true, emulate the behavior for now...
9369     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9370       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9371
9372     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9373
9374     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9375       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9376
9377     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9378       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9379                                   DAG);
9380
9381     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9382                                 TargetMask, DAG);
9383   }
9384
9385   if (isPALIGNRMask(M, VT, Subtarget))
9386     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9387                                 getShufflePALIGNRImmediate(SVOp),
9388                                 DAG);
9389
9390   // Check if this can be converted into a logical shift.
9391   bool isLeft = false;
9392   unsigned ShAmt = 0;
9393   SDValue ShVal;
9394   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9395   if (isShift && ShVal.hasOneUse()) {
9396     // If the shifted value has multiple uses, it may be cheaper to use
9397     // v_set0 + movlhps or movhlps, etc.
9398     MVT EltVT = VT.getVectorElementType();
9399     ShAmt *= EltVT.getSizeInBits();
9400     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9401   }
9402
9403   if (isMOVLMask(M, VT)) {
9404     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9405       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9406     if (!isMOVLPMask(M, VT)) {
9407       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9408         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9409
9410       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9411         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9412     }
9413   }
9414
9415   // FIXME: fold these into legal mask.
9416   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9417     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9418
9419   if (isMOVHLPSMask(M, VT))
9420     return getMOVHighToLow(Op, dl, DAG);
9421
9422   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9423     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9424
9425   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9426     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9427
9428   if (isMOVLPMask(M, VT))
9429     return getMOVLP(Op, dl, DAG, HasSSE2);
9430
9431   if (ShouldXformToMOVHLPS(M, VT) ||
9432       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9433     return DAG.getCommutedVectorShuffle(*SVOp);
9434
9435   if (isShift) {
9436     // No better options. Use a vshldq / vsrldq.
9437     MVT EltVT = VT.getVectorElementType();
9438     ShAmt *= EltVT.getSizeInBits();
9439     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9440   }
9441
9442   bool Commuted = false;
9443   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9444   // 1,1,1,1 -> v8i16 though.
9445   BitVector UndefElements;
9446   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9447     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9448       V1IsSplat = true;
9449   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9450     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9451       V2IsSplat = true;
9452
9453   // Canonicalize the splat or undef, if present, to be on the RHS.
9454   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9455     CommuteVectorShuffleMask(M, NumElems);
9456     std::swap(V1, V2);
9457     std::swap(V1IsSplat, V2IsSplat);
9458     Commuted = true;
9459   }
9460
9461   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9462     // Shuffling low element of v1 into undef, just return v1.
9463     if (V2IsUndef)
9464       return V1;
9465     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9466     // the instruction selector will not match, so get a canonical MOVL with
9467     // swapped operands to undo the commute.
9468     return getMOVL(DAG, dl, VT, V2, V1);
9469   }
9470
9471   if (isUNPCKLMask(M, VT, HasInt256))
9472     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9473
9474   if (isUNPCKHMask(M, VT, HasInt256))
9475     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9476
9477   if (V2IsSplat) {
9478     // Normalize mask so all entries that point to V2 points to its first
9479     // element then try to match unpck{h|l} again. If match, return a
9480     // new vector_shuffle with the corrected mask.p
9481     SmallVector<int, 8> NewMask(M.begin(), M.end());
9482     NormalizeMask(NewMask, NumElems);
9483     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9484       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9485     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9486       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9487   }
9488
9489   if (Commuted) {
9490     // Commute is back and try unpck* again.
9491     // FIXME: this seems wrong.
9492     CommuteVectorShuffleMask(M, NumElems);
9493     std::swap(V1, V2);
9494     std::swap(V1IsSplat, V2IsSplat);
9495
9496     if (isUNPCKLMask(M, VT, HasInt256))
9497       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9498
9499     if (isUNPCKHMask(M, VT, HasInt256))
9500       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9501   }
9502
9503   // Normalize the node to match x86 shuffle ops if needed
9504   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9505     return DAG.getCommutedVectorShuffle(*SVOp);
9506
9507   // The checks below are all present in isShuffleMaskLegal, but they are
9508   // inlined here right now to enable us to directly emit target specific
9509   // nodes, and remove one by one until they don't return Op anymore.
9510
9511   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9512       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9513     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9514       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9515   }
9516
9517   if (isPSHUFHWMask(M, VT, HasInt256))
9518     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9519                                 getShufflePSHUFHWImmediate(SVOp),
9520                                 DAG);
9521
9522   if (isPSHUFLWMask(M, VT, HasInt256))
9523     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9524                                 getShufflePSHUFLWImmediate(SVOp),
9525                                 DAG);
9526
9527   unsigned MaskValue;
9528   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9529                   &MaskValue))
9530     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9531
9532   if (isSHUFPMask(M, VT))
9533     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9534                                 getShuffleSHUFImmediate(SVOp), DAG);
9535
9536   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9537     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9538   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9539     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9540
9541   //===--------------------------------------------------------------------===//
9542   // Generate target specific nodes for 128 or 256-bit shuffles only
9543   // supported in the AVX instruction set.
9544   //
9545
9546   // Handle VMOVDDUPY permutations
9547   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9548     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9549
9550   // Handle VPERMILPS/D* permutations
9551   if (isVPERMILPMask(M, VT)) {
9552     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9553       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9554                                   getShuffleSHUFImmediate(SVOp), DAG);
9555     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9556                                 getShuffleSHUFImmediate(SVOp), DAG);
9557   }
9558
9559   unsigned Idx;
9560   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9561     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9562                               Idx*(NumElems/2), DAG, dl);
9563
9564   // Handle VPERM2F128/VPERM2I128 permutations
9565   if (isVPERM2X128Mask(M, VT, HasFp256))
9566     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9567                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9568
9569   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9570     return getINSERTPS(SVOp, dl, DAG);
9571
9572   unsigned Imm8;
9573   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9574     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9575
9576   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9577       VT.is512BitVector()) {
9578     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9579     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9580     SmallVector<SDValue, 16> permclMask;
9581     for (unsigned i = 0; i != NumElems; ++i) {
9582       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9583     }
9584
9585     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9586     if (V2IsUndef)
9587       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9588       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9589                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9590     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9591                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9592   }
9593
9594   //===--------------------------------------------------------------------===//
9595   // Since no target specific shuffle was selected for this generic one,
9596   // lower it into other known shuffles. FIXME: this isn't true yet, but
9597   // this is the plan.
9598   //
9599
9600   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9601   if (VT == MVT::v8i16) {
9602     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9603     if (NewOp.getNode())
9604       return NewOp;
9605   }
9606
9607   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9608     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9609     if (NewOp.getNode())
9610       return NewOp;
9611   }
9612
9613   if (VT == MVT::v16i8) {
9614     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9615     if (NewOp.getNode())
9616       return NewOp;
9617   }
9618
9619   if (VT == MVT::v32i8) {
9620     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9621     if (NewOp.getNode())
9622       return NewOp;
9623   }
9624
9625   // Handle all 128-bit wide vectors with 4 elements, and match them with
9626   // several different shuffle types.
9627   if (NumElems == 4 && VT.is128BitVector())
9628     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9629
9630   // Handle general 256-bit shuffles
9631   if (VT.is256BitVector())
9632     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9633
9634   return SDValue();
9635 }
9636
9637 // This function assumes its argument is a BUILD_VECTOR of constants or
9638 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9639 // true.
9640 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9641                                     unsigned &MaskValue) {
9642   MaskValue = 0;
9643   unsigned NumElems = BuildVector->getNumOperands();
9644   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9645   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9646   unsigned NumElemsInLane = NumElems / NumLanes;
9647
9648   // Blend for v16i16 should be symetric for the both lanes.
9649   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9650     SDValue EltCond = BuildVector->getOperand(i);
9651     SDValue SndLaneEltCond =
9652         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9653
9654     int Lane1Cond = -1, Lane2Cond = -1;
9655     if (isa<ConstantSDNode>(EltCond))
9656       Lane1Cond = !isZero(EltCond);
9657     if (isa<ConstantSDNode>(SndLaneEltCond))
9658       Lane2Cond = !isZero(SndLaneEltCond);
9659
9660     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9661       // Lane1Cond != 0, means we want the first argument.
9662       // Lane1Cond == 0, means we want the second argument.
9663       // The encoding of this argument is 0 for the first argument, 1
9664       // for the second. Therefore, invert the condition.
9665       MaskValue |= !Lane1Cond << i;
9666     else if (Lane1Cond < 0)
9667       MaskValue |= !Lane2Cond << i;
9668     else
9669       return false;
9670   }
9671   return true;
9672 }
9673
9674 // Try to lower a vselect node into a simple blend instruction.
9675 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9676                                    SelectionDAG &DAG) {
9677   SDValue Cond = Op.getOperand(0);
9678   SDValue LHS = Op.getOperand(1);
9679   SDValue RHS = Op.getOperand(2);
9680   SDLoc dl(Op);
9681   MVT VT = Op.getSimpleValueType();
9682   MVT EltVT = VT.getVectorElementType();
9683   unsigned NumElems = VT.getVectorNumElements();
9684
9685   // There is no blend with immediate in AVX-512.
9686   if (VT.is512BitVector())
9687     return SDValue();
9688
9689   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9690     return SDValue();
9691   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9692     return SDValue();
9693
9694   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9695     return SDValue();
9696
9697   // Check the mask for BLEND and build the value.
9698   unsigned MaskValue = 0;
9699   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9700     return SDValue();
9701
9702   // Convert i32 vectors to floating point if it is not AVX2.
9703   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9704   MVT BlendVT = VT;
9705   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9706     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9707                                NumElems);
9708     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9709     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9710   }
9711
9712   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9713                             DAG.getConstant(MaskValue, MVT::i32));
9714   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9715 }
9716
9717 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9718   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9719   if (BlendOp.getNode())
9720     return BlendOp;
9721
9722   // Some types for vselect were previously set to Expand, not Legal or
9723   // Custom. Return an empty SDValue so we fall-through to Expand, after
9724   // the Custom lowering phase.
9725   MVT VT = Op.getSimpleValueType();
9726   switch (VT.SimpleTy) {
9727   default:
9728     break;
9729   case MVT::v8i16:
9730   case MVT::v16i16:
9731     return SDValue();
9732   }
9733
9734   // We couldn't create a "Blend with immediate" node.
9735   // This node should still be legal, but we'll have to emit a blendv*
9736   // instruction.
9737   return Op;
9738 }
9739
9740 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9741   MVT VT = Op.getSimpleValueType();
9742   SDLoc dl(Op);
9743
9744   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9745     return SDValue();
9746
9747   if (VT.getSizeInBits() == 8) {
9748     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9749                                   Op.getOperand(0), Op.getOperand(1));
9750     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9751                                   DAG.getValueType(VT));
9752     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9753   }
9754
9755   if (VT.getSizeInBits() == 16) {
9756     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9757     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9758     if (Idx == 0)
9759       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9760                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9761                                      DAG.getNode(ISD::BITCAST, dl,
9762                                                  MVT::v4i32,
9763                                                  Op.getOperand(0)),
9764                                      Op.getOperand(1)));
9765     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9766                                   Op.getOperand(0), Op.getOperand(1));
9767     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9768                                   DAG.getValueType(VT));
9769     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9770   }
9771
9772   if (VT == MVT::f32) {
9773     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9774     // the result back to FR32 register. It's only worth matching if the
9775     // result has a single use which is a store or a bitcast to i32.  And in
9776     // the case of a store, it's not worth it if the index is a constant 0,
9777     // because a MOVSSmr can be used instead, which is smaller and faster.
9778     if (!Op.hasOneUse())
9779       return SDValue();
9780     SDNode *User = *Op.getNode()->use_begin();
9781     if ((User->getOpcode() != ISD::STORE ||
9782          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9783           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9784         (User->getOpcode() != ISD::BITCAST ||
9785          User->getValueType(0) != MVT::i32))
9786       return SDValue();
9787     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9788                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9789                                               Op.getOperand(0)),
9790                                               Op.getOperand(1));
9791     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9792   }
9793
9794   if (VT == MVT::i32 || VT == MVT::i64) {
9795     // ExtractPS/pextrq works with constant index.
9796     if (isa<ConstantSDNode>(Op.getOperand(1)))
9797       return Op;
9798   }
9799   return SDValue();
9800 }
9801
9802 /// Extract one bit from mask vector, like v16i1 or v8i1.
9803 /// AVX-512 feature.
9804 SDValue
9805 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9806   SDValue Vec = Op.getOperand(0);
9807   SDLoc dl(Vec);
9808   MVT VecVT = Vec.getSimpleValueType();
9809   SDValue Idx = Op.getOperand(1);
9810   MVT EltVT = Op.getSimpleValueType();
9811
9812   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9813
9814   // variable index can't be handled in mask registers,
9815   // extend vector to VR512
9816   if (!isa<ConstantSDNode>(Idx)) {
9817     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9818     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9819     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9820                               ExtVT.getVectorElementType(), Ext, Idx);
9821     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9822   }
9823
9824   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9825   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9826   unsigned MaxSift = rc->getSize()*8 - 1;
9827   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9828                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9829   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9830                     DAG.getConstant(MaxSift, MVT::i8));
9831   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9832                        DAG.getIntPtrConstant(0));
9833 }
9834
9835 SDValue
9836 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9837                                            SelectionDAG &DAG) const {
9838   SDLoc dl(Op);
9839   SDValue Vec = Op.getOperand(0);
9840   MVT VecVT = Vec.getSimpleValueType();
9841   SDValue Idx = Op.getOperand(1);
9842
9843   if (Op.getSimpleValueType() == MVT::i1)
9844     return ExtractBitFromMaskVector(Op, DAG);
9845
9846   if (!isa<ConstantSDNode>(Idx)) {
9847     if (VecVT.is512BitVector() ||
9848         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9849          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9850
9851       MVT MaskEltVT =
9852         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9853       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9854                                     MaskEltVT.getSizeInBits());
9855
9856       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9857       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9858                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9859                                 Idx, DAG.getConstant(0, getPointerTy()));
9860       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9861       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9862                         Perm, DAG.getConstant(0, getPointerTy()));
9863     }
9864     return SDValue();
9865   }
9866
9867   // If this is a 256-bit vector result, first extract the 128-bit vector and
9868   // then extract the element from the 128-bit vector.
9869   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9870
9871     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9872     // Get the 128-bit vector.
9873     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9874     MVT EltVT = VecVT.getVectorElementType();
9875
9876     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9877
9878     //if (IdxVal >= NumElems/2)
9879     //  IdxVal -= NumElems/2;
9880     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9881     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9882                        DAG.getConstant(IdxVal, MVT::i32));
9883   }
9884
9885   assert(VecVT.is128BitVector() && "Unexpected vector length");
9886
9887   if (Subtarget->hasSSE41()) {
9888     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9889     if (Res.getNode())
9890       return Res;
9891   }
9892
9893   MVT VT = Op.getSimpleValueType();
9894   // TODO: handle v16i8.
9895   if (VT.getSizeInBits() == 16) {
9896     SDValue Vec = Op.getOperand(0);
9897     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9898     if (Idx == 0)
9899       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9900                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9901                                      DAG.getNode(ISD::BITCAST, dl,
9902                                                  MVT::v4i32, Vec),
9903                                      Op.getOperand(1)));
9904     // Transform it so it match pextrw which produces a 32-bit result.
9905     MVT EltVT = MVT::i32;
9906     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9907                                   Op.getOperand(0), Op.getOperand(1));
9908     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9909                                   DAG.getValueType(VT));
9910     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9911   }
9912
9913   if (VT.getSizeInBits() == 32) {
9914     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9915     if (Idx == 0)
9916       return Op;
9917
9918     // SHUFPS the element to the lowest double word, then movss.
9919     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9920     MVT VVT = Op.getOperand(0).getSimpleValueType();
9921     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9922                                        DAG.getUNDEF(VVT), Mask);
9923     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9924                        DAG.getIntPtrConstant(0));
9925   }
9926
9927   if (VT.getSizeInBits() == 64) {
9928     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9929     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9930     //        to match extract_elt for f64.
9931     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9932     if (Idx == 0)
9933       return Op;
9934
9935     // UNPCKHPD the element to the lowest double word, then movsd.
9936     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9937     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9938     int Mask[2] = { 1, -1 };
9939     MVT VVT = Op.getOperand(0).getSimpleValueType();
9940     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9941                                        DAG.getUNDEF(VVT), Mask);
9942     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9943                        DAG.getIntPtrConstant(0));
9944   }
9945
9946   return SDValue();
9947 }
9948
9949 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9950   MVT VT = Op.getSimpleValueType();
9951   MVT EltVT = VT.getVectorElementType();
9952   SDLoc dl(Op);
9953
9954   SDValue N0 = Op.getOperand(0);
9955   SDValue N1 = Op.getOperand(1);
9956   SDValue N2 = Op.getOperand(2);
9957
9958   if (!VT.is128BitVector())
9959     return SDValue();
9960
9961   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9962       isa<ConstantSDNode>(N2)) {
9963     unsigned Opc;
9964     if (VT == MVT::v8i16)
9965       Opc = X86ISD::PINSRW;
9966     else if (VT == MVT::v16i8)
9967       Opc = X86ISD::PINSRB;
9968     else
9969       Opc = X86ISD::PINSRB;
9970
9971     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9972     // argument.
9973     if (N1.getValueType() != MVT::i32)
9974       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9975     if (N2.getValueType() != MVT::i32)
9976       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9977     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9978   }
9979
9980   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9981     // Bits [7:6] of the constant are the source select.  This will always be
9982     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9983     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9984     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9985     // Bits [5:4] of the constant are the destination select.  This is the
9986     //  value of the incoming immediate.
9987     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9988     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9989     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9990     // Create this as a scalar to vector..
9991     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9992     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9993   }
9994
9995   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9996     // PINSR* works with constant index.
9997     return Op;
9998   }
9999   return SDValue();
10000 }
10001
10002 /// Insert one bit to mask vector, like v16i1 or v8i1.
10003 /// AVX-512 feature.
10004 SDValue 
10005 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10006   SDLoc dl(Op);
10007   SDValue Vec = Op.getOperand(0);
10008   SDValue Elt = Op.getOperand(1);
10009   SDValue Idx = Op.getOperand(2);
10010   MVT VecVT = Vec.getSimpleValueType();
10011
10012   if (!isa<ConstantSDNode>(Idx)) {
10013     // Non constant index. Extend source and destination,
10014     // insert element and then truncate the result.
10015     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10016     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10017     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10018       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10019       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10020     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10021   }
10022
10023   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10024   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10025   if (Vec.getOpcode() == ISD::UNDEF)
10026     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10027                        DAG.getConstant(IdxVal, MVT::i8));
10028   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10029   unsigned MaxSift = rc->getSize()*8 - 1;
10030   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10031                     DAG.getConstant(MaxSift, MVT::i8));
10032   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10033                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10034   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10035 }
10036 SDValue
10037 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10038   MVT VT = Op.getSimpleValueType();
10039   MVT EltVT = VT.getVectorElementType();
10040   
10041   if (EltVT == MVT::i1)
10042     return InsertBitToMaskVector(Op, DAG);
10043
10044   SDLoc dl(Op);
10045   SDValue N0 = Op.getOperand(0);
10046   SDValue N1 = Op.getOperand(1);
10047   SDValue N2 = Op.getOperand(2);
10048
10049   // If this is a 256-bit vector result, first extract the 128-bit vector,
10050   // insert the element into the extracted half and then place it back.
10051   if (VT.is256BitVector() || VT.is512BitVector()) {
10052     if (!isa<ConstantSDNode>(N2))
10053       return SDValue();
10054
10055     // Get the desired 128-bit vector half.
10056     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10057     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10058
10059     // Insert the element into the desired half.
10060     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10061     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10062
10063     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10064                     DAG.getConstant(IdxIn128, MVT::i32));
10065
10066     // Insert the changed part back to the 256-bit vector
10067     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10068   }
10069
10070   if (Subtarget->hasSSE41())
10071     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10072
10073   if (EltVT == MVT::i8)
10074     return SDValue();
10075
10076   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10077     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10078     // as its second argument.
10079     if (N1.getValueType() != MVT::i32)
10080       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10081     if (N2.getValueType() != MVT::i32)
10082       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10083     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10084   }
10085   return SDValue();
10086 }
10087
10088 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10089   SDLoc dl(Op);
10090   MVT OpVT = Op.getSimpleValueType();
10091
10092   // If this is a 256-bit vector result, first insert into a 128-bit
10093   // vector and then insert into the 256-bit vector.
10094   if (!OpVT.is128BitVector()) {
10095     // Insert into a 128-bit vector.
10096     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10097     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10098                                  OpVT.getVectorNumElements() / SizeFactor);
10099
10100     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10101
10102     // Insert the 128-bit vector.
10103     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10104   }
10105
10106   if (OpVT == MVT::v1i64 &&
10107       Op.getOperand(0).getValueType() == MVT::i64)
10108     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10109
10110   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10111   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10112   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10113                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10114 }
10115
10116 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10117 // a simple subregister reference or explicit instructions to grab
10118 // upper bits of a vector.
10119 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10120                                       SelectionDAG &DAG) {
10121   SDLoc dl(Op);
10122   SDValue In =  Op.getOperand(0);
10123   SDValue Idx = Op.getOperand(1);
10124   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10125   MVT ResVT   = Op.getSimpleValueType();
10126   MVT InVT    = In.getSimpleValueType();
10127
10128   if (Subtarget->hasFp256()) {
10129     if (ResVT.is128BitVector() &&
10130         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10131         isa<ConstantSDNode>(Idx)) {
10132       return Extract128BitVector(In, IdxVal, DAG, dl);
10133     }
10134     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10135         isa<ConstantSDNode>(Idx)) {
10136       return Extract256BitVector(In, IdxVal, DAG, dl);
10137     }
10138   }
10139   return SDValue();
10140 }
10141
10142 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10143 // simple superregister reference or explicit instructions to insert
10144 // the upper bits of a vector.
10145 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10146                                      SelectionDAG &DAG) {
10147   if (Subtarget->hasFp256()) {
10148     SDLoc dl(Op.getNode());
10149     SDValue Vec = Op.getNode()->getOperand(0);
10150     SDValue SubVec = Op.getNode()->getOperand(1);
10151     SDValue Idx = Op.getNode()->getOperand(2);
10152
10153     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10154          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10155         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10156         isa<ConstantSDNode>(Idx)) {
10157       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10158       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10159     }
10160
10161     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10162         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10163         isa<ConstantSDNode>(Idx)) {
10164       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10165       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10166     }
10167   }
10168   return SDValue();
10169 }
10170
10171 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10172 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10173 // one of the above mentioned nodes. It has to be wrapped because otherwise
10174 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10175 // be used to form addressing mode. These wrapped nodes will be selected
10176 // into MOV32ri.
10177 SDValue
10178 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10179   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10180
10181   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10182   // global base reg.
10183   unsigned char OpFlag = 0;
10184   unsigned WrapperKind = X86ISD::Wrapper;
10185   CodeModel::Model M = DAG.getTarget().getCodeModel();
10186
10187   if (Subtarget->isPICStyleRIPRel() &&
10188       (M == CodeModel::Small || M == CodeModel::Kernel))
10189     WrapperKind = X86ISD::WrapperRIP;
10190   else if (Subtarget->isPICStyleGOT())
10191     OpFlag = X86II::MO_GOTOFF;
10192   else if (Subtarget->isPICStyleStubPIC())
10193     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10194
10195   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10196                                              CP->getAlignment(),
10197                                              CP->getOffset(), OpFlag);
10198   SDLoc DL(CP);
10199   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10200   // With PIC, the address is actually $g + Offset.
10201   if (OpFlag) {
10202     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10203                          DAG.getNode(X86ISD::GlobalBaseReg,
10204                                      SDLoc(), getPointerTy()),
10205                          Result);
10206   }
10207
10208   return Result;
10209 }
10210
10211 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10212   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10213
10214   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10215   // global base reg.
10216   unsigned char OpFlag = 0;
10217   unsigned WrapperKind = X86ISD::Wrapper;
10218   CodeModel::Model M = DAG.getTarget().getCodeModel();
10219
10220   if (Subtarget->isPICStyleRIPRel() &&
10221       (M == CodeModel::Small || M == CodeModel::Kernel))
10222     WrapperKind = X86ISD::WrapperRIP;
10223   else if (Subtarget->isPICStyleGOT())
10224     OpFlag = X86II::MO_GOTOFF;
10225   else if (Subtarget->isPICStyleStubPIC())
10226     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10227
10228   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10229                                           OpFlag);
10230   SDLoc DL(JT);
10231   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10232
10233   // With PIC, the address is actually $g + Offset.
10234   if (OpFlag)
10235     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10236                          DAG.getNode(X86ISD::GlobalBaseReg,
10237                                      SDLoc(), getPointerTy()),
10238                          Result);
10239
10240   return Result;
10241 }
10242
10243 SDValue
10244 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10245   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10246
10247   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10248   // global base reg.
10249   unsigned char OpFlag = 0;
10250   unsigned WrapperKind = X86ISD::Wrapper;
10251   CodeModel::Model M = DAG.getTarget().getCodeModel();
10252
10253   if (Subtarget->isPICStyleRIPRel() &&
10254       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10255     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10256       OpFlag = X86II::MO_GOTPCREL;
10257     WrapperKind = X86ISD::WrapperRIP;
10258   } else if (Subtarget->isPICStyleGOT()) {
10259     OpFlag = X86II::MO_GOT;
10260   } else if (Subtarget->isPICStyleStubPIC()) {
10261     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10262   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10263     OpFlag = X86II::MO_DARWIN_NONLAZY;
10264   }
10265
10266   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10267
10268   SDLoc DL(Op);
10269   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10270
10271   // With PIC, the address is actually $g + Offset.
10272   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10273       !Subtarget->is64Bit()) {
10274     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10275                          DAG.getNode(X86ISD::GlobalBaseReg,
10276                                      SDLoc(), getPointerTy()),
10277                          Result);
10278   }
10279
10280   // For symbols that require a load from a stub to get the address, emit the
10281   // load.
10282   if (isGlobalStubReference(OpFlag))
10283     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10284                          MachinePointerInfo::getGOT(), false, false, false, 0);
10285
10286   return Result;
10287 }
10288
10289 SDValue
10290 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10291   // Create the TargetBlockAddressAddress node.
10292   unsigned char OpFlags =
10293     Subtarget->ClassifyBlockAddressReference();
10294   CodeModel::Model M = DAG.getTarget().getCodeModel();
10295   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10296   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10297   SDLoc dl(Op);
10298   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10299                                              OpFlags);
10300
10301   if (Subtarget->isPICStyleRIPRel() &&
10302       (M == CodeModel::Small || M == CodeModel::Kernel))
10303     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10304   else
10305     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10306
10307   // With PIC, the address is actually $g + Offset.
10308   if (isGlobalRelativeToPICBase(OpFlags)) {
10309     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10310                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10311                          Result);
10312   }
10313
10314   return Result;
10315 }
10316
10317 SDValue
10318 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10319                                       int64_t Offset, SelectionDAG &DAG) const {
10320   // Create the TargetGlobalAddress node, folding in the constant
10321   // offset if it is legal.
10322   unsigned char OpFlags =
10323       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10324   CodeModel::Model M = DAG.getTarget().getCodeModel();
10325   SDValue Result;
10326   if (OpFlags == X86II::MO_NO_FLAG &&
10327       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10328     // A direct static reference to a global.
10329     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10330     Offset = 0;
10331   } else {
10332     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10333   }
10334
10335   if (Subtarget->isPICStyleRIPRel() &&
10336       (M == CodeModel::Small || M == CodeModel::Kernel))
10337     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10338   else
10339     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10340
10341   // With PIC, the address is actually $g + Offset.
10342   if (isGlobalRelativeToPICBase(OpFlags)) {
10343     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10344                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10345                          Result);
10346   }
10347
10348   // For globals that require a load from a stub to get the address, emit the
10349   // load.
10350   if (isGlobalStubReference(OpFlags))
10351     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10352                          MachinePointerInfo::getGOT(), false, false, false, 0);
10353
10354   // If there was a non-zero offset that we didn't fold, create an explicit
10355   // addition for it.
10356   if (Offset != 0)
10357     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10358                          DAG.getConstant(Offset, getPointerTy()));
10359
10360   return Result;
10361 }
10362
10363 SDValue
10364 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10365   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10366   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10367   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10368 }
10369
10370 static SDValue
10371 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10372            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10373            unsigned char OperandFlags, bool LocalDynamic = false) {
10374   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10375   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10376   SDLoc dl(GA);
10377   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10378                                            GA->getValueType(0),
10379                                            GA->getOffset(),
10380                                            OperandFlags);
10381
10382   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10383                                            : X86ISD::TLSADDR;
10384
10385   if (InFlag) {
10386     SDValue Ops[] = { Chain,  TGA, *InFlag };
10387     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10388   } else {
10389     SDValue Ops[]  = { Chain, TGA };
10390     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10391   }
10392
10393   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10394   MFI->setAdjustsStack(true);
10395
10396   SDValue Flag = Chain.getValue(1);
10397   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10398 }
10399
10400 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10401 static SDValue
10402 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10403                                 const EVT PtrVT) {
10404   SDValue InFlag;
10405   SDLoc dl(GA);  // ? function entry point might be better
10406   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10407                                    DAG.getNode(X86ISD::GlobalBaseReg,
10408                                                SDLoc(), PtrVT), InFlag);
10409   InFlag = Chain.getValue(1);
10410
10411   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10412 }
10413
10414 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10415 static SDValue
10416 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10417                                 const EVT PtrVT) {
10418   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10419                     X86::RAX, X86II::MO_TLSGD);
10420 }
10421
10422 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10423                                            SelectionDAG &DAG,
10424                                            const EVT PtrVT,
10425                                            bool is64Bit) {
10426   SDLoc dl(GA);
10427
10428   // Get the start address of the TLS block for this module.
10429   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10430       .getInfo<X86MachineFunctionInfo>();
10431   MFI->incNumLocalDynamicTLSAccesses();
10432
10433   SDValue Base;
10434   if (is64Bit) {
10435     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10436                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10437   } else {
10438     SDValue InFlag;
10439     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10440         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10441     InFlag = Chain.getValue(1);
10442     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10443                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10444   }
10445
10446   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10447   // of Base.
10448
10449   // Build x@dtpoff.
10450   unsigned char OperandFlags = X86II::MO_DTPOFF;
10451   unsigned WrapperKind = X86ISD::Wrapper;
10452   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10453                                            GA->getValueType(0),
10454                                            GA->getOffset(), OperandFlags);
10455   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10456
10457   // Add x@dtpoff with the base.
10458   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10459 }
10460
10461 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10462 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10463                                    const EVT PtrVT, TLSModel::Model model,
10464                                    bool is64Bit, bool isPIC) {
10465   SDLoc dl(GA);
10466
10467   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10468   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10469                                                          is64Bit ? 257 : 256));
10470
10471   SDValue ThreadPointer =
10472       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10473                   MachinePointerInfo(Ptr), false, false, false, 0);
10474
10475   unsigned char OperandFlags = 0;
10476   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10477   // initialexec.
10478   unsigned WrapperKind = X86ISD::Wrapper;
10479   if (model == TLSModel::LocalExec) {
10480     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10481   } else if (model == TLSModel::InitialExec) {
10482     if (is64Bit) {
10483       OperandFlags = X86II::MO_GOTTPOFF;
10484       WrapperKind = X86ISD::WrapperRIP;
10485     } else {
10486       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10487     }
10488   } else {
10489     llvm_unreachable("Unexpected model");
10490   }
10491
10492   // emit "addl x@ntpoff,%eax" (local exec)
10493   // or "addl x@indntpoff,%eax" (initial exec)
10494   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10495   SDValue TGA =
10496       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10497                                  GA->getOffset(), OperandFlags);
10498   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10499
10500   if (model == TLSModel::InitialExec) {
10501     if (isPIC && !is64Bit) {
10502       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10503                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10504                            Offset);
10505     }
10506
10507     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10508                          MachinePointerInfo::getGOT(), false, false, false, 0);
10509   }
10510
10511   // The address of the thread local variable is the add of the thread
10512   // pointer with the offset of the variable.
10513   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10514 }
10515
10516 SDValue
10517 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10518
10519   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10520   const GlobalValue *GV = GA->getGlobal();
10521
10522   if (Subtarget->isTargetELF()) {
10523     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10524
10525     switch (model) {
10526       case TLSModel::GeneralDynamic:
10527         if (Subtarget->is64Bit())
10528           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10529         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10530       case TLSModel::LocalDynamic:
10531         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10532                                            Subtarget->is64Bit());
10533       case TLSModel::InitialExec:
10534       case TLSModel::LocalExec:
10535         return LowerToTLSExecModel(
10536             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10537             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10538     }
10539     llvm_unreachable("Unknown TLS model.");
10540   }
10541
10542   if (Subtarget->isTargetDarwin()) {
10543     // Darwin only has one model of TLS.  Lower to that.
10544     unsigned char OpFlag = 0;
10545     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10546                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10547
10548     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10549     // global base reg.
10550     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10551                  !Subtarget->is64Bit();
10552     if (PIC32)
10553       OpFlag = X86II::MO_TLVP_PIC_BASE;
10554     else
10555       OpFlag = X86II::MO_TLVP;
10556     SDLoc DL(Op);
10557     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10558                                                 GA->getValueType(0),
10559                                                 GA->getOffset(), OpFlag);
10560     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10561
10562     // With PIC32, the address is actually $g + Offset.
10563     if (PIC32)
10564       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10565                            DAG.getNode(X86ISD::GlobalBaseReg,
10566                                        SDLoc(), getPointerTy()),
10567                            Offset);
10568
10569     // Lowering the machine isd will make sure everything is in the right
10570     // location.
10571     SDValue Chain = DAG.getEntryNode();
10572     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10573     SDValue Args[] = { Chain, Offset };
10574     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10575
10576     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10577     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10578     MFI->setAdjustsStack(true);
10579
10580     // And our return value (tls address) is in the standard call return value
10581     // location.
10582     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10583     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10584                               Chain.getValue(1));
10585   }
10586
10587   if (Subtarget->isTargetKnownWindowsMSVC() ||
10588       Subtarget->isTargetWindowsGNU()) {
10589     // Just use the implicit TLS architecture
10590     // Need to generate someting similar to:
10591     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10592     //                                  ; from TEB
10593     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10594     //   mov     rcx, qword [rdx+rcx*8]
10595     //   mov     eax, .tls$:tlsvar
10596     //   [rax+rcx] contains the address
10597     // Windows 64bit: gs:0x58
10598     // Windows 32bit: fs:__tls_array
10599
10600     SDLoc dl(GA);
10601     SDValue Chain = DAG.getEntryNode();
10602
10603     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10604     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10605     // use its literal value of 0x2C.
10606     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10607                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10608                                                              256)
10609                                         : Type::getInt32PtrTy(*DAG.getContext(),
10610                                                               257));
10611
10612     SDValue TlsArray =
10613         Subtarget->is64Bit()
10614             ? DAG.getIntPtrConstant(0x58)
10615             : (Subtarget->isTargetWindowsGNU()
10616                    ? DAG.getIntPtrConstant(0x2C)
10617                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10618
10619     SDValue ThreadPointer =
10620         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10621                     MachinePointerInfo(Ptr), false, false, false, 0);
10622
10623     // Load the _tls_index variable
10624     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10625     if (Subtarget->is64Bit())
10626       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10627                            IDX, MachinePointerInfo(), MVT::i32,
10628                            false, false, false, 0);
10629     else
10630       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10631                         false, false, false, 0);
10632
10633     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10634                                     getPointerTy());
10635     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10636
10637     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10638     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10639                       false, false, false, 0);
10640
10641     // Get the offset of start of .tls section
10642     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10643                                              GA->getValueType(0),
10644                                              GA->getOffset(), X86II::MO_SECREL);
10645     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10646
10647     // The address of the thread local variable is the add of the thread
10648     // pointer with the offset of the variable.
10649     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10650   }
10651
10652   llvm_unreachable("TLS not implemented for this target.");
10653 }
10654
10655 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10656 /// and take a 2 x i32 value to shift plus a shift amount.
10657 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10658   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10659   MVT VT = Op.getSimpleValueType();
10660   unsigned VTBits = VT.getSizeInBits();
10661   SDLoc dl(Op);
10662   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10663   SDValue ShOpLo = Op.getOperand(0);
10664   SDValue ShOpHi = Op.getOperand(1);
10665   SDValue ShAmt  = Op.getOperand(2);
10666   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10667   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10668   // during isel.
10669   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10670                                   DAG.getConstant(VTBits - 1, MVT::i8));
10671   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10672                                      DAG.getConstant(VTBits - 1, MVT::i8))
10673                        : DAG.getConstant(0, VT);
10674
10675   SDValue Tmp2, Tmp3;
10676   if (Op.getOpcode() == ISD::SHL_PARTS) {
10677     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10678     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10679   } else {
10680     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10681     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10682   }
10683
10684   // If the shift amount is larger or equal than the width of a part we can't
10685   // rely on the results of shld/shrd. Insert a test and select the appropriate
10686   // values for large shift amounts.
10687   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10688                                 DAG.getConstant(VTBits, MVT::i8));
10689   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10690                              AndNode, DAG.getConstant(0, MVT::i8));
10691
10692   SDValue Hi, Lo;
10693   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10694   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10695   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10696
10697   if (Op.getOpcode() == ISD::SHL_PARTS) {
10698     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10699     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10700   } else {
10701     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10702     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10703   }
10704
10705   SDValue Ops[2] = { Lo, Hi };
10706   return DAG.getMergeValues(Ops, dl);
10707 }
10708
10709 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10710                                            SelectionDAG &DAG) const {
10711   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10712
10713   if (SrcVT.isVector())
10714     return SDValue();
10715
10716   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10717          "Unknown SINT_TO_FP to lower!");
10718
10719   // These are really Legal; return the operand so the caller accepts it as
10720   // Legal.
10721   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10722     return Op;
10723   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10724       Subtarget->is64Bit()) {
10725     return Op;
10726   }
10727
10728   SDLoc dl(Op);
10729   unsigned Size = SrcVT.getSizeInBits()/8;
10730   MachineFunction &MF = DAG.getMachineFunction();
10731   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10732   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10733   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10734                                StackSlot,
10735                                MachinePointerInfo::getFixedStack(SSFI),
10736                                false, false, 0);
10737   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10738 }
10739
10740 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10741                                      SDValue StackSlot,
10742                                      SelectionDAG &DAG) const {
10743   // Build the FILD
10744   SDLoc DL(Op);
10745   SDVTList Tys;
10746   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10747   if (useSSE)
10748     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10749   else
10750     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10751
10752   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10753
10754   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10755   MachineMemOperand *MMO;
10756   if (FI) {
10757     int SSFI = FI->getIndex();
10758     MMO =
10759       DAG.getMachineFunction()
10760       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10761                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10762   } else {
10763     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10764     StackSlot = StackSlot.getOperand(1);
10765   }
10766   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10767   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10768                                            X86ISD::FILD, DL,
10769                                            Tys, Ops, SrcVT, MMO);
10770
10771   if (useSSE) {
10772     Chain = Result.getValue(1);
10773     SDValue InFlag = Result.getValue(2);
10774
10775     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10776     // shouldn't be necessary except that RFP cannot be live across
10777     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10778     MachineFunction &MF = DAG.getMachineFunction();
10779     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10780     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10781     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10782     Tys = DAG.getVTList(MVT::Other);
10783     SDValue Ops[] = {
10784       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10785     };
10786     MachineMemOperand *MMO =
10787       DAG.getMachineFunction()
10788       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10789                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10790
10791     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10792                                     Ops, Op.getValueType(), MMO);
10793     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10794                          MachinePointerInfo::getFixedStack(SSFI),
10795                          false, false, false, 0);
10796   }
10797
10798   return Result;
10799 }
10800
10801 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10802 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10803                                                SelectionDAG &DAG) const {
10804   // This algorithm is not obvious. Here it is what we're trying to output:
10805   /*
10806      movq       %rax,  %xmm0
10807      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10808      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10809      #ifdef __SSE3__
10810        haddpd   %xmm0, %xmm0
10811      #else
10812        pshufd   $0x4e, %xmm0, %xmm1
10813        addpd    %xmm1, %xmm0
10814      #endif
10815   */
10816
10817   SDLoc dl(Op);
10818   LLVMContext *Context = DAG.getContext();
10819
10820   // Build some magic constants.
10821   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10822   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10823   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10824
10825   SmallVector<Constant*,2> CV1;
10826   CV1.push_back(
10827     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10828                                       APInt(64, 0x4330000000000000ULL))));
10829   CV1.push_back(
10830     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10831                                       APInt(64, 0x4530000000000000ULL))));
10832   Constant *C1 = ConstantVector::get(CV1);
10833   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10834
10835   // Load the 64-bit value into an XMM register.
10836   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10837                             Op.getOperand(0));
10838   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10839                               MachinePointerInfo::getConstantPool(),
10840                               false, false, false, 16);
10841   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10842                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10843                               CLod0);
10844
10845   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10846                               MachinePointerInfo::getConstantPool(),
10847                               false, false, false, 16);
10848   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10849   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10850   SDValue Result;
10851
10852   if (Subtarget->hasSSE3()) {
10853     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10854     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10855   } else {
10856     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10857     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10858                                            S2F, 0x4E, DAG);
10859     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10860                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10861                          Sub);
10862   }
10863
10864   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10865                      DAG.getIntPtrConstant(0));
10866 }
10867
10868 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10869 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10870                                                SelectionDAG &DAG) const {
10871   SDLoc dl(Op);
10872   // FP constant to bias correct the final result.
10873   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10874                                    MVT::f64);
10875
10876   // Load the 32-bit value into an XMM register.
10877   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10878                              Op.getOperand(0));
10879
10880   // Zero out the upper parts of the register.
10881   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10882
10883   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10884                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10885                      DAG.getIntPtrConstant(0));
10886
10887   // Or the load with the bias.
10888   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10889                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10890                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10891                                                    MVT::v2f64, Load)),
10892                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10893                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10894                                                    MVT::v2f64, Bias)));
10895   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10896                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10897                    DAG.getIntPtrConstant(0));
10898
10899   // Subtract the bias.
10900   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10901
10902   // Handle final rounding.
10903   EVT DestVT = Op.getValueType();
10904
10905   if (DestVT.bitsLT(MVT::f64))
10906     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10907                        DAG.getIntPtrConstant(0));
10908   if (DestVT.bitsGT(MVT::f64))
10909     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10910
10911   // Handle final rounding.
10912   return Sub;
10913 }
10914
10915 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10916                                                SelectionDAG &DAG) const {
10917   SDValue N0 = Op.getOperand(0);
10918   MVT SVT = N0.getSimpleValueType();
10919   SDLoc dl(Op);
10920
10921   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10922           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10923          "Custom UINT_TO_FP is not supported!");
10924
10925   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10926   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10927                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10928 }
10929
10930 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10931                                            SelectionDAG &DAG) const {
10932   SDValue N0 = Op.getOperand(0);
10933   SDLoc dl(Op);
10934
10935   if (Op.getValueType().isVector())
10936     return lowerUINT_TO_FP_vec(Op, DAG);
10937
10938   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10939   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10940   // the optimization here.
10941   if (DAG.SignBitIsZero(N0))
10942     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10943
10944   MVT SrcVT = N0.getSimpleValueType();
10945   MVT DstVT = Op.getSimpleValueType();
10946   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10947     return LowerUINT_TO_FP_i64(Op, DAG);
10948   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10949     return LowerUINT_TO_FP_i32(Op, DAG);
10950   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10951     return SDValue();
10952
10953   // Make a 64-bit buffer, and use it to build an FILD.
10954   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10955   if (SrcVT == MVT::i32) {
10956     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10957     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10958                                      getPointerTy(), StackSlot, WordOff);
10959     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10960                                   StackSlot, MachinePointerInfo(),
10961                                   false, false, 0);
10962     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10963                                   OffsetSlot, MachinePointerInfo(),
10964                                   false, false, 0);
10965     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10966     return Fild;
10967   }
10968
10969   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10970   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10971                                StackSlot, MachinePointerInfo(),
10972                                false, false, 0);
10973   // For i64 source, we need to add the appropriate power of 2 if the input
10974   // was negative.  This is the same as the optimization in
10975   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10976   // we must be careful to do the computation in x87 extended precision, not
10977   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10978   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10979   MachineMemOperand *MMO =
10980     DAG.getMachineFunction()
10981     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10982                           MachineMemOperand::MOLoad, 8, 8);
10983
10984   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10985   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10986   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10987                                          MVT::i64, MMO);
10988
10989   APInt FF(32, 0x5F800000ULL);
10990
10991   // Check whether the sign bit is set.
10992   SDValue SignSet = DAG.getSetCC(dl,
10993                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10994                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10995                                  ISD::SETLT);
10996
10997   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10998   SDValue FudgePtr = DAG.getConstantPool(
10999                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11000                                          getPointerTy());
11001
11002   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11003   SDValue Zero = DAG.getIntPtrConstant(0);
11004   SDValue Four = DAG.getIntPtrConstant(4);
11005   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11006                                Zero, Four);
11007   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11008
11009   // Load the value out, extending it from f32 to f80.
11010   // FIXME: Avoid the extend by constructing the right constant pool?
11011   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11012                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11013                                  MVT::f32, false, false, false, 4);
11014   // Extend everything to 80 bits to force it to be done on x87.
11015   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11016   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11017 }
11018
11019 std::pair<SDValue,SDValue>
11020 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11021                                     bool IsSigned, bool IsReplace) const {
11022   SDLoc DL(Op);
11023
11024   EVT DstTy = Op.getValueType();
11025
11026   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11027     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11028     DstTy = MVT::i64;
11029   }
11030
11031   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11032          DstTy.getSimpleVT() >= MVT::i16 &&
11033          "Unknown FP_TO_INT to lower!");
11034
11035   // These are really Legal.
11036   if (DstTy == MVT::i32 &&
11037       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11038     return std::make_pair(SDValue(), SDValue());
11039   if (Subtarget->is64Bit() &&
11040       DstTy == MVT::i64 &&
11041       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11042     return std::make_pair(SDValue(), SDValue());
11043
11044   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11045   // stack slot, or into the FTOL runtime function.
11046   MachineFunction &MF = DAG.getMachineFunction();
11047   unsigned MemSize = DstTy.getSizeInBits()/8;
11048   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11049   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11050
11051   unsigned Opc;
11052   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11053     Opc = X86ISD::WIN_FTOL;
11054   else
11055     switch (DstTy.getSimpleVT().SimpleTy) {
11056     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11057     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11058     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11059     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11060     }
11061
11062   SDValue Chain = DAG.getEntryNode();
11063   SDValue Value = Op.getOperand(0);
11064   EVT TheVT = Op.getOperand(0).getValueType();
11065   // FIXME This causes a redundant load/store if the SSE-class value is already
11066   // in memory, such as if it is on the callstack.
11067   if (isScalarFPTypeInSSEReg(TheVT)) {
11068     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11069     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11070                          MachinePointerInfo::getFixedStack(SSFI),
11071                          false, false, 0);
11072     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11073     SDValue Ops[] = {
11074       Chain, StackSlot, DAG.getValueType(TheVT)
11075     };
11076
11077     MachineMemOperand *MMO =
11078       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11079                               MachineMemOperand::MOLoad, MemSize, MemSize);
11080     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11081     Chain = Value.getValue(1);
11082     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11083     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11084   }
11085
11086   MachineMemOperand *MMO =
11087     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11088                             MachineMemOperand::MOStore, MemSize, MemSize);
11089
11090   if (Opc != X86ISD::WIN_FTOL) {
11091     // Build the FP_TO_INT*_IN_MEM
11092     SDValue Ops[] = { Chain, Value, StackSlot };
11093     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11094                                            Ops, DstTy, MMO);
11095     return std::make_pair(FIST, StackSlot);
11096   } else {
11097     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11098       DAG.getVTList(MVT::Other, MVT::Glue),
11099       Chain, Value);
11100     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11101       MVT::i32, ftol.getValue(1));
11102     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11103       MVT::i32, eax.getValue(2));
11104     SDValue Ops[] = { eax, edx };
11105     SDValue pair = IsReplace
11106       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11107       : DAG.getMergeValues(Ops, DL);
11108     return std::make_pair(pair, SDValue());
11109   }
11110 }
11111
11112 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11113                               const X86Subtarget *Subtarget) {
11114   MVT VT = Op->getSimpleValueType(0);
11115   SDValue In = Op->getOperand(0);
11116   MVT InVT = In.getSimpleValueType();
11117   SDLoc dl(Op);
11118
11119   // Optimize vectors in AVX mode:
11120   //
11121   //   v8i16 -> v8i32
11122   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11123   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11124   //   Concat upper and lower parts.
11125   //
11126   //   v4i32 -> v4i64
11127   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11128   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11129   //   Concat upper and lower parts.
11130   //
11131
11132   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11133       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11134       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11135     return SDValue();
11136
11137   if (Subtarget->hasInt256())
11138     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11139
11140   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11141   SDValue Undef = DAG.getUNDEF(InVT);
11142   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11143   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11144   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11145
11146   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11147                              VT.getVectorNumElements()/2);
11148
11149   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11150   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11151
11152   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11153 }
11154
11155 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11156                                         SelectionDAG &DAG) {
11157   MVT VT = Op->getSimpleValueType(0);
11158   SDValue In = Op->getOperand(0);
11159   MVT InVT = In.getSimpleValueType();
11160   SDLoc DL(Op);
11161   unsigned int NumElts = VT.getVectorNumElements();
11162   if (NumElts != 8 && NumElts != 16)
11163     return SDValue();
11164
11165   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11166     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11167
11168   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11169   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11170   // Now we have only mask extension
11171   assert(InVT.getVectorElementType() == MVT::i1);
11172   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11173   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11174   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11175   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11176   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11177                            MachinePointerInfo::getConstantPool(),
11178                            false, false, false, Alignment);
11179
11180   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11181   if (VT.is512BitVector())
11182     return Brcst;
11183   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11184 }
11185
11186 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11187                                SelectionDAG &DAG) {
11188   if (Subtarget->hasFp256()) {
11189     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11190     if (Res.getNode())
11191       return Res;
11192   }
11193
11194   return SDValue();
11195 }
11196
11197 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11198                                 SelectionDAG &DAG) {
11199   SDLoc DL(Op);
11200   MVT VT = Op.getSimpleValueType();
11201   SDValue In = Op.getOperand(0);
11202   MVT SVT = In.getSimpleValueType();
11203
11204   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11205     return LowerZERO_EXTEND_AVX512(Op, DAG);
11206
11207   if (Subtarget->hasFp256()) {
11208     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11209     if (Res.getNode())
11210       return Res;
11211   }
11212
11213   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11214          VT.getVectorNumElements() != SVT.getVectorNumElements());
11215   return SDValue();
11216 }
11217
11218 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11219   SDLoc DL(Op);
11220   MVT VT = Op.getSimpleValueType();
11221   SDValue In = Op.getOperand(0);
11222   MVT InVT = In.getSimpleValueType();
11223
11224   if (VT == MVT::i1) {
11225     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11226            "Invalid scalar TRUNCATE operation");
11227     if (InVT == MVT::i32)
11228       return SDValue();
11229     if (InVT.getSizeInBits() == 64)
11230       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11231     else if (InVT.getSizeInBits() < 32)
11232       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11233     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11234   }
11235   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11236          "Invalid TRUNCATE operation");
11237
11238   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11239     if (VT.getVectorElementType().getSizeInBits() >=8)
11240       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11241
11242     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11243     unsigned NumElts = InVT.getVectorNumElements();
11244     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11245     if (InVT.getSizeInBits() < 512) {
11246       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11247       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11248       InVT = ExtVT;
11249     }
11250     
11251     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11252     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11253     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11254     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11255     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11256                            MachinePointerInfo::getConstantPool(),
11257                            false, false, false, Alignment);
11258     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11259     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11260     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11261   }
11262
11263   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11264     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11265     if (Subtarget->hasInt256()) {
11266       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11267       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11268       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11269                                 ShufMask);
11270       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11271                          DAG.getIntPtrConstant(0));
11272     }
11273
11274     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11275                                DAG.getIntPtrConstant(0));
11276     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11277                                DAG.getIntPtrConstant(2));
11278     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11279     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11280     static const int ShufMask[] = {0, 2, 4, 6};
11281     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11282   }
11283
11284   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11285     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11286     if (Subtarget->hasInt256()) {
11287       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11288
11289       SmallVector<SDValue,32> pshufbMask;
11290       for (unsigned i = 0; i < 2; ++i) {
11291         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11292         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11293         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11294         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11295         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11296         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11297         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11298         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11299         for (unsigned j = 0; j < 8; ++j)
11300           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11301       }
11302       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11303       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11304       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11305
11306       static const int ShufMask[] = {0,  2,  -1,  -1};
11307       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11308                                 &ShufMask[0]);
11309       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11310                        DAG.getIntPtrConstant(0));
11311       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11312     }
11313
11314     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11315                                DAG.getIntPtrConstant(0));
11316
11317     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11318                                DAG.getIntPtrConstant(4));
11319
11320     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11321     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11322
11323     // The PSHUFB mask:
11324     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11325                                    -1, -1, -1, -1, -1, -1, -1, -1};
11326
11327     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11328     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11329     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11330
11331     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11332     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11333
11334     // The MOVLHPS Mask:
11335     static const int ShufMask2[] = {0, 1, 4, 5};
11336     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11337     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11338   }
11339
11340   // Handle truncation of V256 to V128 using shuffles.
11341   if (!VT.is128BitVector() || !InVT.is256BitVector())
11342     return SDValue();
11343
11344   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11345
11346   unsigned NumElems = VT.getVectorNumElements();
11347   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11348
11349   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11350   // Prepare truncation shuffle mask
11351   for (unsigned i = 0; i != NumElems; ++i)
11352     MaskVec[i] = i * 2;
11353   SDValue V = DAG.getVectorShuffle(NVT, DL,
11354                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11355                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11356   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11357                      DAG.getIntPtrConstant(0));
11358 }
11359
11360 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11361                                            SelectionDAG &DAG) const {
11362   assert(!Op.getSimpleValueType().isVector());
11363
11364   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11365     /*IsSigned=*/ true, /*IsReplace=*/ false);
11366   SDValue FIST = Vals.first, StackSlot = Vals.second;
11367   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11368   if (!FIST.getNode()) return Op;
11369
11370   if (StackSlot.getNode())
11371     // Load the result.
11372     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11373                        FIST, StackSlot, MachinePointerInfo(),
11374                        false, false, false, 0);
11375
11376   // The node is the result.
11377   return FIST;
11378 }
11379
11380 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11381                                            SelectionDAG &DAG) const {
11382   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11383     /*IsSigned=*/ false, /*IsReplace=*/ false);
11384   SDValue FIST = Vals.first, StackSlot = Vals.second;
11385   assert(FIST.getNode() && "Unexpected failure");
11386
11387   if (StackSlot.getNode())
11388     // Load the result.
11389     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11390                        FIST, StackSlot, MachinePointerInfo(),
11391                        false, false, false, 0);
11392
11393   // The node is the result.
11394   return FIST;
11395 }
11396
11397 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11398   SDLoc DL(Op);
11399   MVT VT = Op.getSimpleValueType();
11400   SDValue In = Op.getOperand(0);
11401   MVT SVT = In.getSimpleValueType();
11402
11403   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11404
11405   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11406                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11407                                  In, DAG.getUNDEF(SVT)));
11408 }
11409
11410 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11411   LLVMContext *Context = DAG.getContext();
11412   SDLoc dl(Op);
11413   MVT VT = Op.getSimpleValueType();
11414   MVT EltVT = VT;
11415   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11416   if (VT.isVector()) {
11417     EltVT = VT.getVectorElementType();
11418     NumElts = VT.getVectorNumElements();
11419   }
11420   Constant *C;
11421   if (EltVT == MVT::f64)
11422     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11423                                           APInt(64, ~(1ULL << 63))));
11424   else
11425     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11426                                           APInt(32, ~(1U << 31))));
11427   C = ConstantVector::getSplat(NumElts, C);
11428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11429   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11430   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11431   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11432                              MachinePointerInfo::getConstantPool(),
11433                              false, false, false, Alignment);
11434   if (VT.isVector()) {
11435     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11436     return DAG.getNode(ISD::BITCAST, dl, VT,
11437                        DAG.getNode(ISD::AND, dl, ANDVT,
11438                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11439                                                Op.getOperand(0)),
11440                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11441   }
11442   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11443 }
11444
11445 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11446   LLVMContext *Context = DAG.getContext();
11447   SDLoc dl(Op);
11448   MVT VT = Op.getSimpleValueType();
11449   MVT EltVT = VT;
11450   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11451   if (VT.isVector()) {
11452     EltVT = VT.getVectorElementType();
11453     NumElts = VT.getVectorNumElements();
11454   }
11455   Constant *C;
11456   if (EltVT == MVT::f64)
11457     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11458                                           APInt(64, 1ULL << 63)));
11459   else
11460     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11461                                           APInt(32, 1U << 31)));
11462   C = ConstantVector::getSplat(NumElts, C);
11463   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11464   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11465   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11466   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11467                              MachinePointerInfo::getConstantPool(),
11468                              false, false, false, Alignment);
11469   if (VT.isVector()) {
11470     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11471     return DAG.getNode(ISD::BITCAST, dl, VT,
11472                        DAG.getNode(ISD::XOR, dl, XORVT,
11473                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11474                                                Op.getOperand(0)),
11475                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11476   }
11477
11478   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11479 }
11480
11481 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11483   LLVMContext *Context = DAG.getContext();
11484   SDValue Op0 = Op.getOperand(0);
11485   SDValue Op1 = Op.getOperand(1);
11486   SDLoc dl(Op);
11487   MVT VT = Op.getSimpleValueType();
11488   MVT SrcVT = Op1.getSimpleValueType();
11489
11490   // If second operand is smaller, extend it first.
11491   if (SrcVT.bitsLT(VT)) {
11492     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11493     SrcVT = VT;
11494   }
11495   // And if it is bigger, shrink it first.
11496   if (SrcVT.bitsGT(VT)) {
11497     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11498     SrcVT = VT;
11499   }
11500
11501   // At this point the operands and the result should have the same
11502   // type, and that won't be f80 since that is not custom lowered.
11503
11504   // First get the sign bit of second operand.
11505   SmallVector<Constant*,4> CV;
11506   if (SrcVT == MVT::f64) {
11507     const fltSemantics &Sem = APFloat::IEEEdouble;
11508     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11509     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11510   } else {
11511     const fltSemantics &Sem = APFloat::IEEEsingle;
11512     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11513     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11514     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11515     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11516   }
11517   Constant *C = ConstantVector::get(CV);
11518   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11519   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11520                               MachinePointerInfo::getConstantPool(),
11521                               false, false, false, 16);
11522   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11523
11524   // Shift sign bit right or left if the two operands have different types.
11525   if (SrcVT.bitsGT(VT)) {
11526     // Op0 is MVT::f32, Op1 is MVT::f64.
11527     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11528     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11529                           DAG.getConstant(32, MVT::i32));
11530     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11531     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11532                           DAG.getIntPtrConstant(0));
11533   }
11534
11535   // Clear first operand sign bit.
11536   CV.clear();
11537   if (VT == MVT::f64) {
11538     const fltSemantics &Sem = APFloat::IEEEdouble;
11539     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11540                                                    APInt(64, ~(1ULL << 63)))));
11541     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11542   } else {
11543     const fltSemantics &Sem = APFloat::IEEEsingle;
11544     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11545                                                    APInt(32, ~(1U << 31)))));
11546     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11547     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11548     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11549   }
11550   C = ConstantVector::get(CV);
11551   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11552   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11553                               MachinePointerInfo::getConstantPool(),
11554                               false, false, false, 16);
11555   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11556
11557   // Or the value with the sign bit.
11558   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11559 }
11560
11561 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11562   SDValue N0 = Op.getOperand(0);
11563   SDLoc dl(Op);
11564   MVT VT = Op.getSimpleValueType();
11565
11566   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11567   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11568                                   DAG.getConstant(1, VT));
11569   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11570 }
11571
11572 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11573 //
11574 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11575                                       SelectionDAG &DAG) {
11576   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11577
11578   if (!Subtarget->hasSSE41())
11579     return SDValue();
11580
11581   if (!Op->hasOneUse())
11582     return SDValue();
11583
11584   SDNode *N = Op.getNode();
11585   SDLoc DL(N);
11586
11587   SmallVector<SDValue, 8> Opnds;
11588   DenseMap<SDValue, unsigned> VecInMap;
11589   SmallVector<SDValue, 8> VecIns;
11590   EVT VT = MVT::Other;
11591
11592   // Recognize a special case where a vector is casted into wide integer to
11593   // test all 0s.
11594   Opnds.push_back(N->getOperand(0));
11595   Opnds.push_back(N->getOperand(1));
11596
11597   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11598     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11599     // BFS traverse all OR'd operands.
11600     if (I->getOpcode() == ISD::OR) {
11601       Opnds.push_back(I->getOperand(0));
11602       Opnds.push_back(I->getOperand(1));
11603       // Re-evaluate the number of nodes to be traversed.
11604       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11605       continue;
11606     }
11607
11608     // Quit if a non-EXTRACT_VECTOR_ELT
11609     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11610       return SDValue();
11611
11612     // Quit if without a constant index.
11613     SDValue Idx = I->getOperand(1);
11614     if (!isa<ConstantSDNode>(Idx))
11615       return SDValue();
11616
11617     SDValue ExtractedFromVec = I->getOperand(0);
11618     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11619     if (M == VecInMap.end()) {
11620       VT = ExtractedFromVec.getValueType();
11621       // Quit if not 128/256-bit vector.
11622       if (!VT.is128BitVector() && !VT.is256BitVector())
11623         return SDValue();
11624       // Quit if not the same type.
11625       if (VecInMap.begin() != VecInMap.end() &&
11626           VT != VecInMap.begin()->first.getValueType())
11627         return SDValue();
11628       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11629       VecIns.push_back(ExtractedFromVec);
11630     }
11631     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11632   }
11633
11634   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11635          "Not extracted from 128-/256-bit vector.");
11636
11637   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11638
11639   for (DenseMap<SDValue, unsigned>::const_iterator
11640         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11641     // Quit if not all elements are used.
11642     if (I->second != FullMask)
11643       return SDValue();
11644   }
11645
11646   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11647
11648   // Cast all vectors into TestVT for PTEST.
11649   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11650     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11651
11652   // If more than one full vectors are evaluated, OR them first before PTEST.
11653   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11654     // Each iteration will OR 2 nodes and append the result until there is only
11655     // 1 node left, i.e. the final OR'd value of all vectors.
11656     SDValue LHS = VecIns[Slot];
11657     SDValue RHS = VecIns[Slot + 1];
11658     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11659   }
11660
11661   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11662                      VecIns.back(), VecIns.back());
11663 }
11664
11665 /// \brief return true if \c Op has a use that doesn't just read flags.
11666 static bool hasNonFlagsUse(SDValue Op) {
11667   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11668        ++UI) {
11669     SDNode *User = *UI;
11670     unsigned UOpNo = UI.getOperandNo();
11671     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11672       // Look pass truncate.
11673       UOpNo = User->use_begin().getOperandNo();
11674       User = *User->use_begin();
11675     }
11676
11677     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11678         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11679       return true;
11680   }
11681   return false;
11682 }
11683
11684 /// Emit nodes that will be selected as "test Op0,Op0", or something
11685 /// equivalent.
11686 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11687                                     SelectionDAG &DAG) const {
11688   if (Op.getValueType() == MVT::i1)
11689     // KORTEST instruction should be selected
11690     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11691                        DAG.getConstant(0, Op.getValueType()));
11692
11693   // CF and OF aren't always set the way we want. Determine which
11694   // of these we need.
11695   bool NeedCF = false;
11696   bool NeedOF = false;
11697   switch (X86CC) {
11698   default: break;
11699   case X86::COND_A: case X86::COND_AE:
11700   case X86::COND_B: case X86::COND_BE:
11701     NeedCF = true;
11702     break;
11703   case X86::COND_G: case X86::COND_GE:
11704   case X86::COND_L: case X86::COND_LE:
11705   case X86::COND_O: case X86::COND_NO: {
11706     // Check if we really need to set the
11707     // Overflow flag. If NoSignedWrap is present
11708     // that is not actually needed.
11709     switch (Op->getOpcode()) {
11710     case ISD::ADD:
11711     case ISD::SUB:
11712     case ISD::MUL:
11713     case ISD::SHL: {
11714       const BinaryWithFlagsSDNode *BinNode =
11715           cast<BinaryWithFlagsSDNode>(Op.getNode());
11716       if (BinNode->hasNoSignedWrap())
11717         break;
11718     }
11719     default:
11720       NeedOF = true;
11721       break;
11722     }
11723     break;
11724   }
11725   }
11726   // See if we can use the EFLAGS value from the operand instead of
11727   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11728   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11729   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11730     // Emit a CMP with 0, which is the TEST pattern.
11731     //if (Op.getValueType() == MVT::i1)
11732     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11733     //                     DAG.getConstant(0, MVT::i1));
11734     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11735                        DAG.getConstant(0, Op.getValueType()));
11736   }
11737   unsigned Opcode = 0;
11738   unsigned NumOperands = 0;
11739
11740   // Truncate operations may prevent the merge of the SETCC instruction
11741   // and the arithmetic instruction before it. Attempt to truncate the operands
11742   // of the arithmetic instruction and use a reduced bit-width instruction.
11743   bool NeedTruncation = false;
11744   SDValue ArithOp = Op;
11745   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11746     SDValue Arith = Op->getOperand(0);
11747     // Both the trunc and the arithmetic op need to have one user each.
11748     if (Arith->hasOneUse())
11749       switch (Arith.getOpcode()) {
11750         default: break;
11751         case ISD::ADD:
11752         case ISD::SUB:
11753         case ISD::AND:
11754         case ISD::OR:
11755         case ISD::XOR: {
11756           NeedTruncation = true;
11757           ArithOp = Arith;
11758         }
11759       }
11760   }
11761
11762   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11763   // which may be the result of a CAST.  We use the variable 'Op', which is the
11764   // non-casted variable when we check for possible users.
11765   switch (ArithOp.getOpcode()) {
11766   case ISD::ADD:
11767     // Due to an isel shortcoming, be conservative if this add is likely to be
11768     // selected as part of a load-modify-store instruction. When the root node
11769     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11770     // uses of other nodes in the match, such as the ADD in this case. This
11771     // leads to the ADD being left around and reselected, with the result being
11772     // two adds in the output.  Alas, even if none our users are stores, that
11773     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11774     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11775     // climbing the DAG back to the root, and it doesn't seem to be worth the
11776     // effort.
11777     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11778          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11779       if (UI->getOpcode() != ISD::CopyToReg &&
11780           UI->getOpcode() != ISD::SETCC &&
11781           UI->getOpcode() != ISD::STORE)
11782         goto default_case;
11783
11784     if (ConstantSDNode *C =
11785         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11786       // An add of one will be selected as an INC.
11787       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11788         Opcode = X86ISD::INC;
11789         NumOperands = 1;
11790         break;
11791       }
11792
11793       // An add of negative one (subtract of one) will be selected as a DEC.
11794       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11795         Opcode = X86ISD::DEC;
11796         NumOperands = 1;
11797         break;
11798       }
11799     }
11800
11801     // Otherwise use a regular EFLAGS-setting add.
11802     Opcode = X86ISD::ADD;
11803     NumOperands = 2;
11804     break;
11805   case ISD::SHL:
11806   case ISD::SRL:
11807     // If we have a constant logical shift that's only used in a comparison
11808     // against zero turn it into an equivalent AND. This allows turning it into
11809     // a TEST instruction later.
11810     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11811         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11812       EVT VT = Op.getValueType();
11813       unsigned BitWidth = VT.getSizeInBits();
11814       unsigned ShAmt = Op->getConstantOperandVal(1);
11815       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11816         break;
11817       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11818                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11819                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11820       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11821         break;
11822       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11823                                 DAG.getConstant(Mask, VT));
11824       DAG.ReplaceAllUsesWith(Op, New);
11825       Op = New;
11826     }
11827     break;
11828
11829   case ISD::AND:
11830     // If the primary and result isn't used, don't bother using X86ISD::AND,
11831     // because a TEST instruction will be better.
11832     if (!hasNonFlagsUse(Op))
11833       break;
11834     // FALL THROUGH
11835   case ISD::SUB:
11836   case ISD::OR:
11837   case ISD::XOR:
11838     // Due to the ISEL shortcoming noted above, be conservative if this op is
11839     // likely to be selected as part of a load-modify-store instruction.
11840     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11841            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11842       if (UI->getOpcode() == ISD::STORE)
11843         goto default_case;
11844
11845     // Otherwise use a regular EFLAGS-setting instruction.
11846     switch (ArithOp.getOpcode()) {
11847     default: llvm_unreachable("unexpected operator!");
11848     case ISD::SUB: Opcode = X86ISD::SUB; break;
11849     case ISD::XOR: Opcode = X86ISD::XOR; break;
11850     case ISD::AND: Opcode = X86ISD::AND; break;
11851     case ISD::OR: {
11852       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11853         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11854         if (EFLAGS.getNode())
11855           return EFLAGS;
11856       }
11857       Opcode = X86ISD::OR;
11858       break;
11859     }
11860     }
11861
11862     NumOperands = 2;
11863     break;
11864   case X86ISD::ADD:
11865   case X86ISD::SUB:
11866   case X86ISD::INC:
11867   case X86ISD::DEC:
11868   case X86ISD::OR:
11869   case X86ISD::XOR:
11870   case X86ISD::AND:
11871     return SDValue(Op.getNode(), 1);
11872   default:
11873   default_case:
11874     break;
11875   }
11876
11877   // If we found that truncation is beneficial, perform the truncation and
11878   // update 'Op'.
11879   if (NeedTruncation) {
11880     EVT VT = Op.getValueType();
11881     SDValue WideVal = Op->getOperand(0);
11882     EVT WideVT = WideVal.getValueType();
11883     unsigned ConvertedOp = 0;
11884     // Use a target machine opcode to prevent further DAGCombine
11885     // optimizations that may separate the arithmetic operations
11886     // from the setcc node.
11887     switch (WideVal.getOpcode()) {
11888       default: break;
11889       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11890       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11891       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11892       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11893       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11894     }
11895
11896     if (ConvertedOp) {
11897       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11898       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11899         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11900         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11901         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11902       }
11903     }
11904   }
11905
11906   if (Opcode == 0)
11907     // Emit a CMP with 0, which is the TEST pattern.
11908     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11909                        DAG.getConstant(0, Op.getValueType()));
11910
11911   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11912   SmallVector<SDValue, 4> Ops;
11913   for (unsigned i = 0; i != NumOperands; ++i)
11914     Ops.push_back(Op.getOperand(i));
11915
11916   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11917   DAG.ReplaceAllUsesWith(Op, New);
11918   return SDValue(New.getNode(), 1);
11919 }
11920
11921 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11922 /// equivalent.
11923 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11924                                    SDLoc dl, SelectionDAG &DAG) const {
11925   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11926     if (C->getAPIntValue() == 0)
11927       return EmitTest(Op0, X86CC, dl, DAG);
11928
11929      if (Op0.getValueType() == MVT::i1)
11930        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11931   }
11932  
11933   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11934        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11935     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11936     // This avoids subregister aliasing issues. Keep the smaller reference 
11937     // if we're optimizing for size, however, as that'll allow better folding 
11938     // of memory operations.
11939     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11940         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11941              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11942         !Subtarget->isAtom()) {
11943       unsigned ExtendOp =
11944           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11945       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11946       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11947     }
11948     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11949     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11950     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11951                               Op0, Op1);
11952     return SDValue(Sub.getNode(), 1);
11953   }
11954   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11955 }
11956
11957 /// Convert a comparison if required by the subtarget.
11958 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11959                                                  SelectionDAG &DAG) const {
11960   // If the subtarget does not support the FUCOMI instruction, floating-point
11961   // comparisons have to be converted.
11962   if (Subtarget->hasCMov() ||
11963       Cmp.getOpcode() != X86ISD::CMP ||
11964       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11965       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11966     return Cmp;
11967
11968   // The instruction selector will select an FUCOM instruction instead of
11969   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11970   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11971   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11972   SDLoc dl(Cmp);
11973   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11974   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11975   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11976                             DAG.getConstant(8, MVT::i8));
11977   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11978   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11979 }
11980
11981 static bool isAllOnes(SDValue V) {
11982   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11983   return C && C->isAllOnesValue();
11984 }
11985
11986 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11987 /// if it's possible.
11988 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11989                                      SDLoc dl, SelectionDAG &DAG) const {
11990   SDValue Op0 = And.getOperand(0);
11991   SDValue Op1 = And.getOperand(1);
11992   if (Op0.getOpcode() == ISD::TRUNCATE)
11993     Op0 = Op0.getOperand(0);
11994   if (Op1.getOpcode() == ISD::TRUNCATE)
11995     Op1 = Op1.getOperand(0);
11996
11997   SDValue LHS, RHS;
11998   if (Op1.getOpcode() == ISD::SHL)
11999     std::swap(Op0, Op1);
12000   if (Op0.getOpcode() == ISD::SHL) {
12001     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12002       if (And00C->getZExtValue() == 1) {
12003         // If we looked past a truncate, check that it's only truncating away
12004         // known zeros.
12005         unsigned BitWidth = Op0.getValueSizeInBits();
12006         unsigned AndBitWidth = And.getValueSizeInBits();
12007         if (BitWidth > AndBitWidth) {
12008           APInt Zeros, Ones;
12009           DAG.computeKnownBits(Op0, Zeros, Ones);
12010           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12011             return SDValue();
12012         }
12013         LHS = Op1;
12014         RHS = Op0.getOperand(1);
12015       }
12016   } else if (Op1.getOpcode() == ISD::Constant) {
12017     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12018     uint64_t AndRHSVal = AndRHS->getZExtValue();
12019     SDValue AndLHS = Op0;
12020
12021     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12022       LHS = AndLHS.getOperand(0);
12023       RHS = AndLHS.getOperand(1);
12024     }
12025
12026     // Use BT if the immediate can't be encoded in a TEST instruction.
12027     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12028       LHS = AndLHS;
12029       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12030     }
12031   }
12032
12033   if (LHS.getNode()) {
12034     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12035     // instruction.  Since the shift amount is in-range-or-undefined, we know
12036     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12037     // the encoding for the i16 version is larger than the i32 version.
12038     // Also promote i16 to i32 for performance / code size reason.
12039     if (LHS.getValueType() == MVT::i8 ||
12040         LHS.getValueType() == MVT::i16)
12041       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12042
12043     // If the operand types disagree, extend the shift amount to match.  Since
12044     // BT ignores high bits (like shifts) we can use anyextend.
12045     if (LHS.getValueType() != RHS.getValueType())
12046       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12047
12048     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12049     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12050     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12051                        DAG.getConstant(Cond, MVT::i8), BT);
12052   }
12053
12054   return SDValue();
12055 }
12056
12057 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12058 /// mask CMPs.
12059 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12060                               SDValue &Op1) {
12061   unsigned SSECC;
12062   bool Swap = false;
12063
12064   // SSE Condition code mapping:
12065   //  0 - EQ
12066   //  1 - LT
12067   //  2 - LE
12068   //  3 - UNORD
12069   //  4 - NEQ
12070   //  5 - NLT
12071   //  6 - NLE
12072   //  7 - ORD
12073   switch (SetCCOpcode) {
12074   default: llvm_unreachable("Unexpected SETCC condition");
12075   case ISD::SETOEQ:
12076   case ISD::SETEQ:  SSECC = 0; break;
12077   case ISD::SETOGT:
12078   case ISD::SETGT:  Swap = true; // Fallthrough
12079   case ISD::SETLT:
12080   case ISD::SETOLT: SSECC = 1; break;
12081   case ISD::SETOGE:
12082   case ISD::SETGE:  Swap = true; // Fallthrough
12083   case ISD::SETLE:
12084   case ISD::SETOLE: SSECC = 2; break;
12085   case ISD::SETUO:  SSECC = 3; break;
12086   case ISD::SETUNE:
12087   case ISD::SETNE:  SSECC = 4; break;
12088   case ISD::SETULE: Swap = true; // Fallthrough
12089   case ISD::SETUGE: SSECC = 5; break;
12090   case ISD::SETULT: Swap = true; // Fallthrough
12091   case ISD::SETUGT: SSECC = 6; break;
12092   case ISD::SETO:   SSECC = 7; break;
12093   case ISD::SETUEQ:
12094   case ISD::SETONE: SSECC = 8; break;
12095   }
12096   if (Swap)
12097     std::swap(Op0, Op1);
12098
12099   return SSECC;
12100 }
12101
12102 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12103 // ones, and then concatenate the result back.
12104 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12105   MVT VT = Op.getSimpleValueType();
12106
12107   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12108          "Unsupported value type for operation");
12109
12110   unsigned NumElems = VT.getVectorNumElements();
12111   SDLoc dl(Op);
12112   SDValue CC = Op.getOperand(2);
12113
12114   // Extract the LHS vectors
12115   SDValue LHS = Op.getOperand(0);
12116   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12117   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12118
12119   // Extract the RHS vectors
12120   SDValue RHS = Op.getOperand(1);
12121   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12122   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12123
12124   // Issue the operation on the smaller types and concatenate the result back
12125   MVT EltVT = VT.getVectorElementType();
12126   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12127   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12128                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12129                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12130 }
12131
12132 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12133                                      const X86Subtarget *Subtarget) {
12134   SDValue Op0 = Op.getOperand(0);
12135   SDValue Op1 = Op.getOperand(1);
12136   SDValue CC = Op.getOperand(2);
12137   MVT VT = Op.getSimpleValueType();
12138   SDLoc dl(Op);
12139
12140   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12141          Op.getValueType().getScalarType() == MVT::i1 &&
12142          "Cannot set masked compare for this operation");
12143
12144   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12145   unsigned  Opc = 0;
12146   bool Unsigned = false;
12147   bool Swap = false;
12148   unsigned SSECC;
12149   switch (SetCCOpcode) {
12150   default: llvm_unreachable("Unexpected SETCC condition");
12151   case ISD::SETNE:  SSECC = 4; break;
12152   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12153   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12154   case ISD::SETLT:  Swap = true; //fall-through
12155   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12156   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12157   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12158   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12159   case ISD::SETULE: Unsigned = true; //fall-through
12160   case ISD::SETLE:  SSECC = 2; break;
12161   }
12162
12163   if (Swap)
12164     std::swap(Op0, Op1);
12165   if (Opc)
12166     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12167   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12168   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12169                      DAG.getConstant(SSECC, MVT::i8));
12170 }
12171
12172 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12173 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12174 /// return an empty value.
12175 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12176 {
12177   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12178   if (!BV)
12179     return SDValue();
12180
12181   MVT VT = Op1.getSimpleValueType();
12182   MVT EVT = VT.getVectorElementType();
12183   unsigned n = VT.getVectorNumElements();
12184   SmallVector<SDValue, 8> ULTOp1;
12185
12186   for (unsigned i = 0; i < n; ++i) {
12187     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12188     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12189       return SDValue();
12190
12191     // Avoid underflow.
12192     APInt Val = Elt->getAPIntValue();
12193     if (Val == 0)
12194       return SDValue();
12195
12196     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12197   }
12198
12199   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12200 }
12201
12202 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12203                            SelectionDAG &DAG) {
12204   SDValue Op0 = Op.getOperand(0);
12205   SDValue Op1 = Op.getOperand(1);
12206   SDValue CC = Op.getOperand(2);
12207   MVT VT = Op.getSimpleValueType();
12208   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12209   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12210   SDLoc dl(Op);
12211
12212   if (isFP) {
12213 #ifndef NDEBUG
12214     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12215     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12216 #endif
12217
12218     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12219     unsigned Opc = X86ISD::CMPP;
12220     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12221       assert(VT.getVectorNumElements() <= 16);
12222       Opc = X86ISD::CMPM;
12223     }
12224     // In the two special cases we can't handle, emit two comparisons.
12225     if (SSECC == 8) {
12226       unsigned CC0, CC1;
12227       unsigned CombineOpc;
12228       if (SetCCOpcode == ISD::SETUEQ) {
12229         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12230       } else {
12231         assert(SetCCOpcode == ISD::SETONE);
12232         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12233       }
12234
12235       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12236                                  DAG.getConstant(CC0, MVT::i8));
12237       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12238                                  DAG.getConstant(CC1, MVT::i8));
12239       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12240     }
12241     // Handle all other FP comparisons here.
12242     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12243                        DAG.getConstant(SSECC, MVT::i8));
12244   }
12245
12246   // Break 256-bit integer vector compare into smaller ones.
12247   if (VT.is256BitVector() && !Subtarget->hasInt256())
12248     return Lower256IntVSETCC(Op, DAG);
12249
12250   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12251   EVT OpVT = Op1.getValueType();
12252   if (Subtarget->hasAVX512()) {
12253     if (Op1.getValueType().is512BitVector() ||
12254         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12255       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12256
12257     // In AVX-512 architecture setcc returns mask with i1 elements,
12258     // But there is no compare instruction for i8 and i16 elements.
12259     // We are not talking about 512-bit operands in this case, these
12260     // types are illegal.
12261     if (MaskResult &&
12262         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12263          OpVT.getVectorElementType().getSizeInBits() >= 8))
12264       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12265                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12266   }
12267
12268   // We are handling one of the integer comparisons here.  Since SSE only has
12269   // GT and EQ comparisons for integer, swapping operands and multiple
12270   // operations may be required for some comparisons.
12271   unsigned Opc;
12272   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12273   bool Subus = false;
12274
12275   switch (SetCCOpcode) {
12276   default: llvm_unreachable("Unexpected SETCC condition");
12277   case ISD::SETNE:  Invert = true;
12278   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12279   case ISD::SETLT:  Swap = true;
12280   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12281   case ISD::SETGE:  Swap = true;
12282   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12283                     Invert = true; break;
12284   case ISD::SETULT: Swap = true;
12285   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12286                     FlipSigns = true; break;
12287   case ISD::SETUGE: Swap = true;
12288   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12289                     FlipSigns = true; Invert = true; break;
12290   }
12291
12292   // Special case: Use min/max operations for SETULE/SETUGE
12293   MVT VET = VT.getVectorElementType();
12294   bool hasMinMax =
12295        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12296     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12297
12298   if (hasMinMax) {
12299     switch (SetCCOpcode) {
12300     default: break;
12301     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12302     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12303     }
12304
12305     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12306   }
12307
12308   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12309   if (!MinMax && hasSubus) {
12310     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12311     // Op0 u<= Op1:
12312     //   t = psubus Op0, Op1
12313     //   pcmpeq t, <0..0>
12314     switch (SetCCOpcode) {
12315     default: break;
12316     case ISD::SETULT: {
12317       // If the comparison is against a constant we can turn this into a
12318       // setule.  With psubus, setule does not require a swap.  This is
12319       // beneficial because the constant in the register is no longer
12320       // destructed as the destination so it can be hoisted out of a loop.
12321       // Only do this pre-AVX since vpcmp* is no longer destructive.
12322       if (Subtarget->hasAVX())
12323         break;
12324       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12325       if (ULEOp1.getNode()) {
12326         Op1 = ULEOp1;
12327         Subus = true; Invert = false; Swap = false;
12328       }
12329       break;
12330     }
12331     // Psubus is better than flip-sign because it requires no inversion.
12332     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12333     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12334     }
12335
12336     if (Subus) {
12337       Opc = X86ISD::SUBUS;
12338       FlipSigns = false;
12339     }
12340   }
12341
12342   if (Swap)
12343     std::swap(Op0, Op1);
12344
12345   // Check that the operation in question is available (most are plain SSE2,
12346   // but PCMPGTQ and PCMPEQQ have different requirements).
12347   if (VT == MVT::v2i64) {
12348     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12349       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12350
12351       // First cast everything to the right type.
12352       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12353       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12354
12355       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12356       // bits of the inputs before performing those operations. The lower
12357       // compare is always unsigned.
12358       SDValue SB;
12359       if (FlipSigns) {
12360         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12361       } else {
12362         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12363         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12364         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12365                          Sign, Zero, Sign, Zero);
12366       }
12367       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12368       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12369
12370       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12371       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12372       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12373
12374       // Create masks for only the low parts/high parts of the 64 bit integers.
12375       static const int MaskHi[] = { 1, 1, 3, 3 };
12376       static const int MaskLo[] = { 0, 0, 2, 2 };
12377       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12378       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12379       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12380
12381       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12382       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12383
12384       if (Invert)
12385         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12386
12387       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12388     }
12389
12390     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12391       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12392       // pcmpeqd + pshufd + pand.
12393       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12394
12395       // First cast everything to the right type.
12396       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12397       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12398
12399       // Do the compare.
12400       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12401
12402       // Make sure the lower and upper halves are both all-ones.
12403       static const int Mask[] = { 1, 0, 3, 2 };
12404       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12405       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12406
12407       if (Invert)
12408         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12409
12410       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12411     }
12412   }
12413
12414   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12415   // bits of the inputs before performing those operations.
12416   if (FlipSigns) {
12417     EVT EltVT = VT.getVectorElementType();
12418     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12419     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12420     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12421   }
12422
12423   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12424
12425   // If the logical-not of the result is required, perform that now.
12426   if (Invert)
12427     Result = DAG.getNOT(dl, Result, VT);
12428
12429   if (MinMax)
12430     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12431
12432   if (Subus)
12433     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12434                          getZeroVector(VT, Subtarget, DAG, dl));
12435
12436   return Result;
12437 }
12438
12439 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12440
12441   MVT VT = Op.getSimpleValueType();
12442
12443   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12444
12445   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12446          && "SetCC type must be 8-bit or 1-bit integer");
12447   SDValue Op0 = Op.getOperand(0);
12448   SDValue Op1 = Op.getOperand(1);
12449   SDLoc dl(Op);
12450   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12451
12452   // Optimize to BT if possible.
12453   // Lower (X & (1 << N)) == 0 to BT(X, N).
12454   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12455   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12456   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12457       Op1.getOpcode() == ISD::Constant &&
12458       cast<ConstantSDNode>(Op1)->isNullValue() &&
12459       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12460     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12461     if (NewSetCC.getNode())
12462       return NewSetCC;
12463   }
12464
12465   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12466   // these.
12467   if (Op1.getOpcode() == ISD::Constant &&
12468       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12469        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12470       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12471
12472     // If the input is a setcc, then reuse the input setcc or use a new one with
12473     // the inverted condition.
12474     if (Op0.getOpcode() == X86ISD::SETCC) {
12475       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12476       bool Invert = (CC == ISD::SETNE) ^
12477         cast<ConstantSDNode>(Op1)->isNullValue();
12478       if (!Invert)
12479         return Op0;
12480
12481       CCode = X86::GetOppositeBranchCondition(CCode);
12482       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12483                                   DAG.getConstant(CCode, MVT::i8),
12484                                   Op0.getOperand(1));
12485       if (VT == MVT::i1)
12486         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12487       return SetCC;
12488     }
12489   }
12490   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12491       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12492       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12493
12494     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12495     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12496   }
12497
12498   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12499   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12500   if (X86CC == X86::COND_INVALID)
12501     return SDValue();
12502
12503   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12504   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12505   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12506                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12507   if (VT == MVT::i1)
12508     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12509   return SetCC;
12510 }
12511
12512 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12513 static bool isX86LogicalCmp(SDValue Op) {
12514   unsigned Opc = Op.getNode()->getOpcode();
12515   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12516       Opc == X86ISD::SAHF)
12517     return true;
12518   if (Op.getResNo() == 1 &&
12519       (Opc == X86ISD::ADD ||
12520        Opc == X86ISD::SUB ||
12521        Opc == X86ISD::ADC ||
12522        Opc == X86ISD::SBB ||
12523        Opc == X86ISD::SMUL ||
12524        Opc == X86ISD::UMUL ||
12525        Opc == X86ISD::INC ||
12526        Opc == X86ISD::DEC ||
12527        Opc == X86ISD::OR ||
12528        Opc == X86ISD::XOR ||
12529        Opc == X86ISD::AND))
12530     return true;
12531
12532   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12533     return true;
12534
12535   return false;
12536 }
12537
12538 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12539   if (V.getOpcode() != ISD::TRUNCATE)
12540     return false;
12541
12542   SDValue VOp0 = V.getOperand(0);
12543   unsigned InBits = VOp0.getValueSizeInBits();
12544   unsigned Bits = V.getValueSizeInBits();
12545   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12546 }
12547
12548 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12549   bool addTest = true;
12550   SDValue Cond  = Op.getOperand(0);
12551   SDValue Op1 = Op.getOperand(1);
12552   SDValue Op2 = Op.getOperand(2);
12553   SDLoc DL(Op);
12554   EVT VT = Op1.getValueType();
12555   SDValue CC;
12556
12557   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12558   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12559   // sequence later on.
12560   if (Cond.getOpcode() == ISD::SETCC &&
12561       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12562        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12563       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12564     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12565     int SSECC = translateX86FSETCC(
12566         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12567
12568     if (SSECC != 8) {
12569       if (Subtarget->hasAVX512()) {
12570         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12571                                   DAG.getConstant(SSECC, MVT::i8));
12572         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12573       }
12574       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12575                                 DAG.getConstant(SSECC, MVT::i8));
12576       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12577       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12578       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12579     }
12580   }
12581
12582   if (Cond.getOpcode() == ISD::SETCC) {
12583     SDValue NewCond = LowerSETCC(Cond, DAG);
12584     if (NewCond.getNode())
12585       Cond = NewCond;
12586   }
12587
12588   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12589   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12590   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12591   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12592   if (Cond.getOpcode() == X86ISD::SETCC &&
12593       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12594       isZero(Cond.getOperand(1).getOperand(1))) {
12595     SDValue Cmp = Cond.getOperand(1);
12596
12597     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12598
12599     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12600         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12601       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12602
12603       SDValue CmpOp0 = Cmp.getOperand(0);
12604       // Apply further optimizations for special cases
12605       // (select (x != 0), -1, 0) -> neg & sbb
12606       // (select (x == 0), 0, -1) -> neg & sbb
12607       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12608         if (YC->isNullValue() &&
12609             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12610           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12611           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12612                                     DAG.getConstant(0, CmpOp0.getValueType()),
12613                                     CmpOp0);
12614           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12615                                     DAG.getConstant(X86::COND_B, MVT::i8),
12616                                     SDValue(Neg.getNode(), 1));
12617           return Res;
12618         }
12619
12620       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12621                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12622       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12623
12624       SDValue Res =   // Res = 0 or -1.
12625         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12626                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12627
12628       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12629         Res = DAG.getNOT(DL, Res, Res.getValueType());
12630
12631       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12632       if (!N2C || !N2C->isNullValue())
12633         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12634       return Res;
12635     }
12636   }
12637
12638   // Look past (and (setcc_carry (cmp ...)), 1).
12639   if (Cond.getOpcode() == ISD::AND &&
12640       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12641     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12642     if (C && C->getAPIntValue() == 1)
12643       Cond = Cond.getOperand(0);
12644   }
12645
12646   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12647   // setting operand in place of the X86ISD::SETCC.
12648   unsigned CondOpcode = Cond.getOpcode();
12649   if (CondOpcode == X86ISD::SETCC ||
12650       CondOpcode == X86ISD::SETCC_CARRY) {
12651     CC = Cond.getOperand(0);
12652
12653     SDValue Cmp = Cond.getOperand(1);
12654     unsigned Opc = Cmp.getOpcode();
12655     MVT VT = Op.getSimpleValueType();
12656
12657     bool IllegalFPCMov = false;
12658     if (VT.isFloatingPoint() && !VT.isVector() &&
12659         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12660       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12661
12662     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12663         Opc == X86ISD::BT) { // FIXME
12664       Cond = Cmp;
12665       addTest = false;
12666     }
12667   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12668              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12669              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12670               Cond.getOperand(0).getValueType() != MVT::i8)) {
12671     SDValue LHS = Cond.getOperand(0);
12672     SDValue RHS = Cond.getOperand(1);
12673     unsigned X86Opcode;
12674     unsigned X86Cond;
12675     SDVTList VTs;
12676     switch (CondOpcode) {
12677     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12678     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12679     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12680     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12681     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12682     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12683     default: llvm_unreachable("unexpected overflowing operator");
12684     }
12685     if (CondOpcode == ISD::UMULO)
12686       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12687                           MVT::i32);
12688     else
12689       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12690
12691     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12692
12693     if (CondOpcode == ISD::UMULO)
12694       Cond = X86Op.getValue(2);
12695     else
12696       Cond = X86Op.getValue(1);
12697
12698     CC = DAG.getConstant(X86Cond, MVT::i8);
12699     addTest = false;
12700   }
12701
12702   if (addTest) {
12703     // Look pass the truncate if the high bits are known zero.
12704     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12705         Cond = Cond.getOperand(0);
12706
12707     // We know the result of AND is compared against zero. Try to match
12708     // it to BT.
12709     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12710       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12711       if (NewSetCC.getNode()) {
12712         CC = NewSetCC.getOperand(0);
12713         Cond = NewSetCC.getOperand(1);
12714         addTest = false;
12715       }
12716     }
12717   }
12718
12719   if (addTest) {
12720     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12721     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12722   }
12723
12724   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12725   // a <  b ?  0 : -1 -> RES = setcc_carry
12726   // a >= b ? -1 :  0 -> RES = setcc_carry
12727   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12728   if (Cond.getOpcode() == X86ISD::SUB) {
12729     Cond = ConvertCmpIfNecessary(Cond, DAG);
12730     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12731
12732     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12733         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12734       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12735                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12736       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12737         return DAG.getNOT(DL, Res, Res.getValueType());
12738       return Res;
12739     }
12740   }
12741
12742   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12743   // widen the cmov and push the truncate through. This avoids introducing a new
12744   // branch during isel and doesn't add any extensions.
12745   if (Op.getValueType() == MVT::i8 &&
12746       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12747     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12748     if (T1.getValueType() == T2.getValueType() &&
12749         // Blacklist CopyFromReg to avoid partial register stalls.
12750         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12751       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12752       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12753       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12754     }
12755   }
12756
12757   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12758   // condition is true.
12759   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12760   SDValue Ops[] = { Op2, Op1, CC, Cond };
12761   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12762 }
12763
12764 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12765   MVT VT = Op->getSimpleValueType(0);
12766   SDValue In = Op->getOperand(0);
12767   MVT InVT = In.getSimpleValueType();
12768   SDLoc dl(Op);
12769
12770   unsigned int NumElts = VT.getVectorNumElements();
12771   if (NumElts != 8 && NumElts != 16)
12772     return SDValue();
12773
12774   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12775     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12776
12777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12778   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12779
12780   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12781   Constant *C = ConstantInt::get(*DAG.getContext(),
12782     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12783
12784   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12785   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12786   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12787                           MachinePointerInfo::getConstantPool(),
12788                           false, false, false, Alignment);
12789   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12790   if (VT.is512BitVector())
12791     return Brcst;
12792   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12793 }
12794
12795 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12796                                 SelectionDAG &DAG) {
12797   MVT VT = Op->getSimpleValueType(0);
12798   SDValue In = Op->getOperand(0);
12799   MVT InVT = In.getSimpleValueType();
12800   SDLoc dl(Op);
12801
12802   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12803     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12804
12805   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12806       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12807       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12808     return SDValue();
12809
12810   if (Subtarget->hasInt256())
12811     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12812
12813   // Optimize vectors in AVX mode
12814   // Sign extend  v8i16 to v8i32 and
12815   //              v4i32 to v4i64
12816   //
12817   // Divide input vector into two parts
12818   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12819   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12820   // concat the vectors to original VT
12821
12822   unsigned NumElems = InVT.getVectorNumElements();
12823   SDValue Undef = DAG.getUNDEF(InVT);
12824
12825   SmallVector<int,8> ShufMask1(NumElems, -1);
12826   for (unsigned i = 0; i != NumElems/2; ++i)
12827     ShufMask1[i] = i;
12828
12829   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12830
12831   SmallVector<int,8> ShufMask2(NumElems, -1);
12832   for (unsigned i = 0; i != NumElems/2; ++i)
12833     ShufMask2[i] = i + NumElems/2;
12834
12835   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12836
12837   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12838                                 VT.getVectorNumElements()/2);
12839
12840   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12841   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12842
12843   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12844 }
12845
12846 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
12847 // may emit an illegal shuffle but the expansion is still better than scalar
12848 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
12849 // we'll emit a shuffle and a arithmetic shift.
12850 // TODO: It is possible to support ZExt by zeroing the undef values during
12851 // the shuffle phase or after the shuffle.
12852 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
12853                                  SelectionDAG &DAG) {
12854   MVT RegVT = Op.getSimpleValueType();
12855   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
12856   assert(RegVT.isInteger() &&
12857          "We only custom lower integer vector sext loads.");
12858
12859   // Nothing useful we can do without SSE2 shuffles.
12860   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
12861
12862   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
12863   SDLoc dl(Ld);
12864   EVT MemVT = Ld->getMemoryVT();
12865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12866   unsigned RegSz = RegVT.getSizeInBits();
12867
12868   ISD::LoadExtType Ext = Ld->getExtensionType();
12869
12870   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
12871          && "Only anyext and sext are currently implemented.");
12872   assert(MemVT != RegVT && "Cannot extend to the same type");
12873   assert(MemVT.isVector() && "Must load a vector from memory");
12874
12875   unsigned NumElems = RegVT.getVectorNumElements();
12876   unsigned MemSz = MemVT.getSizeInBits();
12877   assert(RegSz > MemSz && "Register size must be greater than the mem size");
12878
12879   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
12880     // The only way in which we have a legal 256-bit vector result but not the
12881     // integer 256-bit operations needed to directly lower a sextload is if we
12882     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
12883     // a 128-bit vector and a normal sign_extend to 256-bits that should get
12884     // correctly legalized. We do this late to allow the canonical form of
12885     // sextload to persist throughout the rest of the DAG combiner -- it wants
12886     // to fold together any extensions it can, and so will fuse a sign_extend
12887     // of an sextload into an sextload targeting a wider value.
12888     SDValue Load;
12889     if (MemSz == 128) {
12890       // Just switch this to a normal load.
12891       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
12892                                        "it must be a legal 128-bit vector "
12893                                        "type!");
12894       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
12895                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
12896                   Ld->isInvariant(), Ld->getAlignment());
12897     } else {
12898       assert(MemSz < 128 &&
12899              "Can't extend a type wider than 128 bits to a 256 bit vector!");
12900       // Do an sext load to a 128-bit vector type. We want to use the same
12901       // number of elements, but elements half as wide. This will end up being
12902       // recursively lowered by this routine, but will succeed as we definitely
12903       // have all the necessary features if we're using AVX1.
12904       EVT HalfEltVT =
12905           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
12906       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
12907       Load =
12908           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
12909                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
12910                          Ld->isNonTemporal(), Ld->isInvariant(),
12911                          Ld->getAlignment());
12912     }
12913
12914     // Replace chain users with the new chain.
12915     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
12916     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
12917
12918     // Finally, do a normal sign-extend to the desired register.
12919     return DAG.getSExtOrTrunc(Load, dl, RegVT);
12920   }
12921
12922   // All sizes must be a power of two.
12923   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
12924          "Non-power-of-two elements are not custom lowered!");
12925
12926   // Attempt to load the original value using scalar loads.
12927   // Find the largest scalar type that divides the total loaded size.
12928   MVT SclrLoadTy = MVT::i8;
12929   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
12930        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
12931     MVT Tp = (MVT::SimpleValueType)tp;
12932     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
12933       SclrLoadTy = Tp;
12934     }
12935   }
12936
12937   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
12938   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
12939       (64 <= MemSz))
12940     SclrLoadTy = MVT::f64;
12941
12942   // Calculate the number of scalar loads that we need to perform
12943   // in order to load our vector from memory.
12944   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
12945
12946   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
12947          "Can only lower sext loads with a single scalar load!");
12948
12949   unsigned loadRegZize = RegSz;
12950   if (Ext == ISD::SEXTLOAD && RegSz == 256)
12951     loadRegZize /= 2;
12952
12953   // Represent our vector as a sequence of elements which are the
12954   // largest scalar that we can load.
12955   EVT LoadUnitVecVT = EVT::getVectorVT(
12956       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
12957
12958   // Represent the data using the same element type that is stored in
12959   // memory. In practice, we ''widen'' MemVT.
12960   EVT WideVecVT =
12961       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
12962                        loadRegZize / MemVT.getScalarType().getSizeInBits());
12963
12964   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
12965          "Invalid vector type");
12966
12967   // We can't shuffle using an illegal type.
12968   assert(TLI.isTypeLegal(WideVecVT) &&
12969          "We only lower types that form legal widened vector types");
12970
12971   SmallVector<SDValue, 8> Chains;
12972   SDValue Ptr = Ld->getBasePtr();
12973   SDValue Increment =
12974       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
12975   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
12976
12977   for (unsigned i = 0; i < NumLoads; ++i) {
12978     // Perform a single load.
12979     SDValue ScalarLoad =
12980         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
12981                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
12982                     Ld->getAlignment());
12983     Chains.push_back(ScalarLoad.getValue(1));
12984     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
12985     // another round of DAGCombining.
12986     if (i == 0)
12987       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
12988     else
12989       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
12990                         ScalarLoad, DAG.getIntPtrConstant(i));
12991
12992     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
12993   }
12994
12995   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
12996
12997   // Bitcast the loaded value to a vector of the original element type, in
12998   // the size of the target vector type.
12999   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13000   unsigned SizeRatio = RegSz / MemSz;
13001
13002   if (Ext == ISD::SEXTLOAD) {
13003     // If we have SSE4.1 we can directly emit a VSEXT node.
13004     if (Subtarget->hasSSE41()) {
13005       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13006       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13007       return Sext;
13008     }
13009
13010     // Otherwise we'll shuffle the small elements in the high bits of the
13011     // larger type and perform an arithmetic shift. If the shift is not legal
13012     // it's better to scalarize.
13013     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13014            "We can't implement an sext load without a arithmetic right shift!");
13015
13016     // Redistribute the loaded elements into the different locations.
13017     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13018     for (unsigned i = 0; i != NumElems; ++i)
13019       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13020
13021     SDValue Shuff = DAG.getVectorShuffle(
13022         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13023
13024     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13025
13026     // Build the arithmetic shift.
13027     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13028                    MemVT.getVectorElementType().getSizeInBits();
13029     Shuff =
13030         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13031
13032     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13033     return Shuff;
13034   }
13035
13036   // Redistribute the loaded elements into the different locations.
13037   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13038   for (unsigned i = 0; i != NumElems; ++i)
13039     ShuffleVec[i * SizeRatio] = i;
13040
13041   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13042                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13043
13044   // Bitcast to the requested type.
13045   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13046   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13047   return Shuff;
13048 }
13049
13050 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13051 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13052 // from the AND / OR.
13053 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13054   Opc = Op.getOpcode();
13055   if (Opc != ISD::OR && Opc != ISD::AND)
13056     return false;
13057   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13058           Op.getOperand(0).hasOneUse() &&
13059           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13060           Op.getOperand(1).hasOneUse());
13061 }
13062
13063 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13064 // 1 and that the SETCC node has a single use.
13065 static bool isXor1OfSetCC(SDValue Op) {
13066   if (Op.getOpcode() != ISD::XOR)
13067     return false;
13068   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13069   if (N1C && N1C->getAPIntValue() == 1) {
13070     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13071       Op.getOperand(0).hasOneUse();
13072   }
13073   return false;
13074 }
13075
13076 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13077   bool addTest = true;
13078   SDValue Chain = Op.getOperand(0);
13079   SDValue Cond  = Op.getOperand(1);
13080   SDValue Dest  = Op.getOperand(2);
13081   SDLoc dl(Op);
13082   SDValue CC;
13083   bool Inverted = false;
13084
13085   if (Cond.getOpcode() == ISD::SETCC) {
13086     // Check for setcc([su]{add,sub,mul}o == 0).
13087     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13088         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13089         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13090         Cond.getOperand(0).getResNo() == 1 &&
13091         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13092          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13093          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13094          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13095          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13096          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13097       Inverted = true;
13098       Cond = Cond.getOperand(0);
13099     } else {
13100       SDValue NewCond = LowerSETCC(Cond, DAG);
13101       if (NewCond.getNode())
13102         Cond = NewCond;
13103     }
13104   }
13105 #if 0
13106   // FIXME: LowerXALUO doesn't handle these!!
13107   else if (Cond.getOpcode() == X86ISD::ADD  ||
13108            Cond.getOpcode() == X86ISD::SUB  ||
13109            Cond.getOpcode() == X86ISD::SMUL ||
13110            Cond.getOpcode() == X86ISD::UMUL)
13111     Cond = LowerXALUO(Cond, DAG);
13112 #endif
13113
13114   // Look pass (and (setcc_carry (cmp ...)), 1).
13115   if (Cond.getOpcode() == ISD::AND &&
13116       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13117     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13118     if (C && C->getAPIntValue() == 1)
13119       Cond = Cond.getOperand(0);
13120   }
13121
13122   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13123   // setting operand in place of the X86ISD::SETCC.
13124   unsigned CondOpcode = Cond.getOpcode();
13125   if (CondOpcode == X86ISD::SETCC ||
13126       CondOpcode == X86ISD::SETCC_CARRY) {
13127     CC = Cond.getOperand(0);
13128
13129     SDValue Cmp = Cond.getOperand(1);
13130     unsigned Opc = Cmp.getOpcode();
13131     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13132     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13133       Cond = Cmp;
13134       addTest = false;
13135     } else {
13136       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13137       default: break;
13138       case X86::COND_O:
13139       case X86::COND_B:
13140         // These can only come from an arithmetic instruction with overflow,
13141         // e.g. SADDO, UADDO.
13142         Cond = Cond.getNode()->getOperand(1);
13143         addTest = false;
13144         break;
13145       }
13146     }
13147   }
13148   CondOpcode = Cond.getOpcode();
13149   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13150       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13151       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13152        Cond.getOperand(0).getValueType() != MVT::i8)) {
13153     SDValue LHS = Cond.getOperand(0);
13154     SDValue RHS = Cond.getOperand(1);
13155     unsigned X86Opcode;
13156     unsigned X86Cond;
13157     SDVTList VTs;
13158     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13159     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13160     // X86ISD::INC).
13161     switch (CondOpcode) {
13162     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13163     case ISD::SADDO:
13164       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13165         if (C->isOne()) {
13166           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13167           break;
13168         }
13169       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13170     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13171     case ISD::SSUBO:
13172       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13173         if (C->isOne()) {
13174           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13175           break;
13176         }
13177       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13178     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13179     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13180     default: llvm_unreachable("unexpected overflowing operator");
13181     }
13182     if (Inverted)
13183       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13184     if (CondOpcode == ISD::UMULO)
13185       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13186                           MVT::i32);
13187     else
13188       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13189
13190     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13191
13192     if (CondOpcode == ISD::UMULO)
13193       Cond = X86Op.getValue(2);
13194     else
13195       Cond = X86Op.getValue(1);
13196
13197     CC = DAG.getConstant(X86Cond, MVT::i8);
13198     addTest = false;
13199   } else {
13200     unsigned CondOpc;
13201     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13202       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13203       if (CondOpc == ISD::OR) {
13204         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13205         // two branches instead of an explicit OR instruction with a
13206         // separate test.
13207         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13208             isX86LogicalCmp(Cmp)) {
13209           CC = Cond.getOperand(0).getOperand(0);
13210           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13211                               Chain, Dest, CC, Cmp);
13212           CC = Cond.getOperand(1).getOperand(0);
13213           Cond = Cmp;
13214           addTest = false;
13215         }
13216       } else { // ISD::AND
13217         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13218         // two branches instead of an explicit AND instruction with a
13219         // separate test. However, we only do this if this block doesn't
13220         // have a fall-through edge, because this requires an explicit
13221         // jmp when the condition is false.
13222         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13223             isX86LogicalCmp(Cmp) &&
13224             Op.getNode()->hasOneUse()) {
13225           X86::CondCode CCode =
13226             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13227           CCode = X86::GetOppositeBranchCondition(CCode);
13228           CC = DAG.getConstant(CCode, MVT::i8);
13229           SDNode *User = *Op.getNode()->use_begin();
13230           // Look for an unconditional branch following this conditional branch.
13231           // We need this because we need to reverse the successors in order
13232           // to implement FCMP_OEQ.
13233           if (User->getOpcode() == ISD::BR) {
13234             SDValue FalseBB = User->getOperand(1);
13235             SDNode *NewBR =
13236               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13237             assert(NewBR == User);
13238             (void)NewBR;
13239             Dest = FalseBB;
13240
13241             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13242                                 Chain, Dest, CC, Cmp);
13243             X86::CondCode CCode =
13244               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13245             CCode = X86::GetOppositeBranchCondition(CCode);
13246             CC = DAG.getConstant(CCode, MVT::i8);
13247             Cond = Cmp;
13248             addTest = false;
13249           }
13250         }
13251       }
13252     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13253       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13254       // It should be transformed during dag combiner except when the condition
13255       // is set by a arithmetics with overflow node.
13256       X86::CondCode CCode =
13257         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13258       CCode = X86::GetOppositeBranchCondition(CCode);
13259       CC = DAG.getConstant(CCode, MVT::i8);
13260       Cond = Cond.getOperand(0).getOperand(1);
13261       addTest = false;
13262     } else if (Cond.getOpcode() == ISD::SETCC &&
13263                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13264       // For FCMP_OEQ, we can emit
13265       // two branches instead of an explicit AND instruction with a
13266       // separate test. However, we only do this if this block doesn't
13267       // have a fall-through edge, because this requires an explicit
13268       // jmp when the condition is false.
13269       if (Op.getNode()->hasOneUse()) {
13270         SDNode *User = *Op.getNode()->use_begin();
13271         // Look for an unconditional branch following this conditional branch.
13272         // We need this because we need to reverse the successors in order
13273         // to implement FCMP_OEQ.
13274         if (User->getOpcode() == ISD::BR) {
13275           SDValue FalseBB = User->getOperand(1);
13276           SDNode *NewBR =
13277             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13278           assert(NewBR == User);
13279           (void)NewBR;
13280           Dest = FalseBB;
13281
13282           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13283                                     Cond.getOperand(0), Cond.getOperand(1));
13284           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13285           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13286           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13287                               Chain, Dest, CC, Cmp);
13288           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13289           Cond = Cmp;
13290           addTest = false;
13291         }
13292       }
13293     } else if (Cond.getOpcode() == ISD::SETCC &&
13294                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13295       // For FCMP_UNE, we can emit
13296       // two branches instead of an explicit AND instruction with a
13297       // separate test. However, we only do this if this block doesn't
13298       // have a fall-through edge, because this requires an explicit
13299       // jmp when the condition is false.
13300       if (Op.getNode()->hasOneUse()) {
13301         SDNode *User = *Op.getNode()->use_begin();
13302         // Look for an unconditional branch following this conditional branch.
13303         // We need this because we need to reverse the successors in order
13304         // to implement FCMP_UNE.
13305         if (User->getOpcode() == ISD::BR) {
13306           SDValue FalseBB = User->getOperand(1);
13307           SDNode *NewBR =
13308             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13309           assert(NewBR == User);
13310           (void)NewBR;
13311
13312           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13313                                     Cond.getOperand(0), Cond.getOperand(1));
13314           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13315           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13316           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13317                               Chain, Dest, CC, Cmp);
13318           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13319           Cond = Cmp;
13320           addTest = false;
13321           Dest = FalseBB;
13322         }
13323       }
13324     }
13325   }
13326
13327   if (addTest) {
13328     // Look pass the truncate if the high bits are known zero.
13329     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13330         Cond = Cond.getOperand(0);
13331
13332     // We know the result of AND is compared against zero. Try to match
13333     // it to BT.
13334     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13335       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13336       if (NewSetCC.getNode()) {
13337         CC = NewSetCC.getOperand(0);
13338         Cond = NewSetCC.getOperand(1);
13339         addTest = false;
13340       }
13341     }
13342   }
13343
13344   if (addTest) {
13345     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13346     CC = DAG.getConstant(X86Cond, MVT::i8);
13347     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13348   }
13349   Cond = ConvertCmpIfNecessary(Cond, DAG);
13350   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13351                      Chain, Dest, CC, Cond);
13352 }
13353
13354 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13355 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13356 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13357 // that the guard pages used by the OS virtual memory manager are allocated in
13358 // correct sequence.
13359 SDValue
13360 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13361                                            SelectionDAG &DAG) const {
13362   MachineFunction &MF = DAG.getMachineFunction();
13363   bool SplitStack = MF.shouldSplitStack();
13364   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13365                SplitStack;
13366   SDLoc dl(Op);
13367
13368   if (!Lower) {
13369     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13370     SDNode* Node = Op.getNode();
13371
13372     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13373     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13374         " not tell us which reg is the stack pointer!");
13375     EVT VT = Node->getValueType(0);
13376     SDValue Tmp1 = SDValue(Node, 0);
13377     SDValue Tmp2 = SDValue(Node, 1);
13378     SDValue Tmp3 = Node->getOperand(2);
13379     SDValue Chain = Tmp1.getOperand(0);
13380
13381     // Chain the dynamic stack allocation so that it doesn't modify the stack
13382     // pointer when other instructions are using the stack.
13383     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13384         SDLoc(Node));
13385
13386     SDValue Size = Tmp2.getOperand(1);
13387     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13388     Chain = SP.getValue(1);
13389     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13390     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13391     unsigned StackAlign = TFI.getStackAlignment();
13392     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13393     if (Align > StackAlign)
13394       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13395           DAG.getConstant(-(uint64_t)Align, VT));
13396     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13397
13398     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13399         DAG.getIntPtrConstant(0, true), SDValue(),
13400         SDLoc(Node));
13401
13402     SDValue Ops[2] = { Tmp1, Tmp2 };
13403     return DAG.getMergeValues(Ops, dl);
13404   }
13405
13406   // Get the inputs.
13407   SDValue Chain = Op.getOperand(0);
13408   SDValue Size  = Op.getOperand(1);
13409   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13410   EVT VT = Op.getNode()->getValueType(0);
13411
13412   bool Is64Bit = Subtarget->is64Bit();
13413   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13414
13415   if (SplitStack) {
13416     MachineRegisterInfo &MRI = MF.getRegInfo();
13417
13418     if (Is64Bit) {
13419       // The 64 bit implementation of segmented stacks needs to clobber both r10
13420       // r11. This makes it impossible to use it along with nested parameters.
13421       const Function *F = MF.getFunction();
13422
13423       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13424            I != E; ++I)
13425         if (I->hasNestAttr())
13426           report_fatal_error("Cannot use segmented stacks with functions that "
13427                              "have nested arguments.");
13428     }
13429
13430     const TargetRegisterClass *AddrRegClass =
13431       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13432     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13433     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13434     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13435                                 DAG.getRegister(Vreg, SPTy));
13436     SDValue Ops1[2] = { Value, Chain };
13437     return DAG.getMergeValues(Ops1, dl);
13438   } else {
13439     SDValue Flag;
13440     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13441
13442     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13443     Flag = Chain.getValue(1);
13444     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13445
13446     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13447
13448     const X86RegisterInfo *RegInfo =
13449       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13450     unsigned SPReg = RegInfo->getStackRegister();
13451     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13452     Chain = SP.getValue(1);
13453
13454     if (Align) {
13455       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13456                        DAG.getConstant(-(uint64_t)Align, VT));
13457       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13458     }
13459
13460     SDValue Ops1[2] = { SP, Chain };
13461     return DAG.getMergeValues(Ops1, dl);
13462   }
13463 }
13464
13465 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13466   MachineFunction &MF = DAG.getMachineFunction();
13467   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13468
13469   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13470   SDLoc DL(Op);
13471
13472   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13473     // vastart just stores the address of the VarArgsFrameIndex slot into the
13474     // memory location argument.
13475     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13476                                    getPointerTy());
13477     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13478                         MachinePointerInfo(SV), false, false, 0);
13479   }
13480
13481   // __va_list_tag:
13482   //   gp_offset         (0 - 6 * 8)
13483   //   fp_offset         (48 - 48 + 8 * 16)
13484   //   overflow_arg_area (point to parameters coming in memory).
13485   //   reg_save_area
13486   SmallVector<SDValue, 8> MemOps;
13487   SDValue FIN = Op.getOperand(1);
13488   // Store gp_offset
13489   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13490                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13491                                                MVT::i32),
13492                                FIN, MachinePointerInfo(SV), false, false, 0);
13493   MemOps.push_back(Store);
13494
13495   // Store fp_offset
13496   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13497                     FIN, DAG.getIntPtrConstant(4));
13498   Store = DAG.getStore(Op.getOperand(0), DL,
13499                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13500                                        MVT::i32),
13501                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13502   MemOps.push_back(Store);
13503
13504   // Store ptr to overflow_arg_area
13505   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13506                     FIN, DAG.getIntPtrConstant(4));
13507   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13508                                     getPointerTy());
13509   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13510                        MachinePointerInfo(SV, 8),
13511                        false, false, 0);
13512   MemOps.push_back(Store);
13513
13514   // Store ptr to reg_save_area.
13515   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13516                     FIN, DAG.getIntPtrConstant(8));
13517   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13518                                     getPointerTy());
13519   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13520                        MachinePointerInfo(SV, 16), false, false, 0);
13521   MemOps.push_back(Store);
13522   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13523 }
13524
13525 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13526   assert(Subtarget->is64Bit() &&
13527          "LowerVAARG only handles 64-bit va_arg!");
13528   assert((Subtarget->isTargetLinux() ||
13529           Subtarget->isTargetDarwin()) &&
13530           "Unhandled target in LowerVAARG");
13531   assert(Op.getNode()->getNumOperands() == 4);
13532   SDValue Chain = Op.getOperand(0);
13533   SDValue SrcPtr = Op.getOperand(1);
13534   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13535   unsigned Align = Op.getConstantOperandVal(3);
13536   SDLoc dl(Op);
13537
13538   EVT ArgVT = Op.getNode()->getValueType(0);
13539   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13540   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13541   uint8_t ArgMode;
13542
13543   // Decide which area this value should be read from.
13544   // TODO: Implement the AMD64 ABI in its entirety. This simple
13545   // selection mechanism works only for the basic types.
13546   if (ArgVT == MVT::f80) {
13547     llvm_unreachable("va_arg for f80 not yet implemented");
13548   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13549     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13550   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13551     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13552   } else {
13553     llvm_unreachable("Unhandled argument type in LowerVAARG");
13554   }
13555
13556   if (ArgMode == 2) {
13557     // Sanity Check: Make sure using fp_offset makes sense.
13558     assert(!DAG.getTarget().Options.UseSoftFloat &&
13559            !(DAG.getMachineFunction()
13560                 .getFunction()->getAttributes()
13561                 .hasAttribute(AttributeSet::FunctionIndex,
13562                               Attribute::NoImplicitFloat)) &&
13563            Subtarget->hasSSE1());
13564   }
13565
13566   // Insert VAARG_64 node into the DAG
13567   // VAARG_64 returns two values: Variable Argument Address, Chain
13568   SmallVector<SDValue, 11> InstOps;
13569   InstOps.push_back(Chain);
13570   InstOps.push_back(SrcPtr);
13571   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13572   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13573   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13574   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13575   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13576                                           VTs, InstOps, MVT::i64,
13577                                           MachinePointerInfo(SV),
13578                                           /*Align=*/0,
13579                                           /*Volatile=*/false,
13580                                           /*ReadMem=*/true,
13581                                           /*WriteMem=*/true);
13582   Chain = VAARG.getValue(1);
13583
13584   // Load the next argument and return it
13585   return DAG.getLoad(ArgVT, dl,
13586                      Chain,
13587                      VAARG,
13588                      MachinePointerInfo(),
13589                      false, false, false, 0);
13590 }
13591
13592 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13593                            SelectionDAG &DAG) {
13594   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13595   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13596   SDValue Chain = Op.getOperand(0);
13597   SDValue DstPtr = Op.getOperand(1);
13598   SDValue SrcPtr = Op.getOperand(2);
13599   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13600   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13601   SDLoc DL(Op);
13602
13603   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13604                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13605                        false,
13606                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13607 }
13608
13609 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13610 // amount is a constant. Takes immediate version of shift as input.
13611 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13612                                           SDValue SrcOp, uint64_t ShiftAmt,
13613                                           SelectionDAG &DAG) {
13614   MVT ElementType = VT.getVectorElementType();
13615
13616   // Fold this packed shift into its first operand if ShiftAmt is 0.
13617   if (ShiftAmt == 0)
13618     return SrcOp;
13619
13620   // Check for ShiftAmt >= element width
13621   if (ShiftAmt >= ElementType.getSizeInBits()) {
13622     if (Opc == X86ISD::VSRAI)
13623       ShiftAmt = ElementType.getSizeInBits() - 1;
13624     else
13625       return DAG.getConstant(0, VT);
13626   }
13627
13628   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13629          && "Unknown target vector shift-by-constant node");
13630
13631   // Fold this packed vector shift into a build vector if SrcOp is a
13632   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13633   if (VT == SrcOp.getSimpleValueType() &&
13634       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13635     SmallVector<SDValue, 8> Elts;
13636     unsigned NumElts = SrcOp->getNumOperands();
13637     ConstantSDNode *ND;
13638
13639     switch(Opc) {
13640     default: llvm_unreachable(nullptr);
13641     case X86ISD::VSHLI:
13642       for (unsigned i=0; i!=NumElts; ++i) {
13643         SDValue CurrentOp = SrcOp->getOperand(i);
13644         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13645           Elts.push_back(CurrentOp);
13646           continue;
13647         }
13648         ND = cast<ConstantSDNode>(CurrentOp);
13649         const APInt &C = ND->getAPIntValue();
13650         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13651       }
13652       break;
13653     case X86ISD::VSRLI:
13654       for (unsigned i=0; i!=NumElts; ++i) {
13655         SDValue CurrentOp = SrcOp->getOperand(i);
13656         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13657           Elts.push_back(CurrentOp);
13658           continue;
13659         }
13660         ND = cast<ConstantSDNode>(CurrentOp);
13661         const APInt &C = ND->getAPIntValue();
13662         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13663       }
13664       break;
13665     case X86ISD::VSRAI:
13666       for (unsigned i=0; i!=NumElts; ++i) {
13667         SDValue CurrentOp = SrcOp->getOperand(i);
13668         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13669           Elts.push_back(CurrentOp);
13670           continue;
13671         }
13672         ND = cast<ConstantSDNode>(CurrentOp);
13673         const APInt &C = ND->getAPIntValue();
13674         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13675       }
13676       break;
13677     }
13678
13679     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13680   }
13681
13682   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13683 }
13684
13685 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13686 // may or may not be a constant. Takes immediate version of shift as input.
13687 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13688                                    SDValue SrcOp, SDValue ShAmt,
13689                                    SelectionDAG &DAG) {
13690   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13691
13692   // Catch shift-by-constant.
13693   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13694     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13695                                       CShAmt->getZExtValue(), DAG);
13696
13697   // Change opcode to non-immediate version
13698   switch (Opc) {
13699     default: llvm_unreachable("Unknown target vector shift node");
13700     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13701     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13702     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13703   }
13704
13705   // Need to build a vector containing shift amount
13706   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13707   SDValue ShOps[4];
13708   ShOps[0] = ShAmt;
13709   ShOps[1] = DAG.getConstant(0, MVT::i32);
13710   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13711   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13712
13713   // The return type has to be a 128-bit type with the same element
13714   // type as the input type.
13715   MVT EltVT = VT.getVectorElementType();
13716   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13717
13718   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13719   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13720 }
13721
13722 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13723   SDLoc dl(Op);
13724   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13725   switch (IntNo) {
13726   default: return SDValue();    // Don't custom lower most intrinsics.
13727   // Comparison intrinsics.
13728   case Intrinsic::x86_sse_comieq_ss:
13729   case Intrinsic::x86_sse_comilt_ss:
13730   case Intrinsic::x86_sse_comile_ss:
13731   case Intrinsic::x86_sse_comigt_ss:
13732   case Intrinsic::x86_sse_comige_ss:
13733   case Intrinsic::x86_sse_comineq_ss:
13734   case Intrinsic::x86_sse_ucomieq_ss:
13735   case Intrinsic::x86_sse_ucomilt_ss:
13736   case Intrinsic::x86_sse_ucomile_ss:
13737   case Intrinsic::x86_sse_ucomigt_ss:
13738   case Intrinsic::x86_sse_ucomige_ss:
13739   case Intrinsic::x86_sse_ucomineq_ss:
13740   case Intrinsic::x86_sse2_comieq_sd:
13741   case Intrinsic::x86_sse2_comilt_sd:
13742   case Intrinsic::x86_sse2_comile_sd:
13743   case Intrinsic::x86_sse2_comigt_sd:
13744   case Intrinsic::x86_sse2_comige_sd:
13745   case Intrinsic::x86_sse2_comineq_sd:
13746   case Intrinsic::x86_sse2_ucomieq_sd:
13747   case Intrinsic::x86_sse2_ucomilt_sd:
13748   case Intrinsic::x86_sse2_ucomile_sd:
13749   case Intrinsic::x86_sse2_ucomigt_sd:
13750   case Intrinsic::x86_sse2_ucomige_sd:
13751   case Intrinsic::x86_sse2_ucomineq_sd: {
13752     unsigned Opc;
13753     ISD::CondCode CC;
13754     switch (IntNo) {
13755     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13756     case Intrinsic::x86_sse_comieq_ss:
13757     case Intrinsic::x86_sse2_comieq_sd:
13758       Opc = X86ISD::COMI;
13759       CC = ISD::SETEQ;
13760       break;
13761     case Intrinsic::x86_sse_comilt_ss:
13762     case Intrinsic::x86_sse2_comilt_sd:
13763       Opc = X86ISD::COMI;
13764       CC = ISD::SETLT;
13765       break;
13766     case Intrinsic::x86_sse_comile_ss:
13767     case Intrinsic::x86_sse2_comile_sd:
13768       Opc = X86ISD::COMI;
13769       CC = ISD::SETLE;
13770       break;
13771     case Intrinsic::x86_sse_comigt_ss:
13772     case Intrinsic::x86_sse2_comigt_sd:
13773       Opc = X86ISD::COMI;
13774       CC = ISD::SETGT;
13775       break;
13776     case Intrinsic::x86_sse_comige_ss:
13777     case Intrinsic::x86_sse2_comige_sd:
13778       Opc = X86ISD::COMI;
13779       CC = ISD::SETGE;
13780       break;
13781     case Intrinsic::x86_sse_comineq_ss:
13782     case Intrinsic::x86_sse2_comineq_sd:
13783       Opc = X86ISD::COMI;
13784       CC = ISD::SETNE;
13785       break;
13786     case Intrinsic::x86_sse_ucomieq_ss:
13787     case Intrinsic::x86_sse2_ucomieq_sd:
13788       Opc = X86ISD::UCOMI;
13789       CC = ISD::SETEQ;
13790       break;
13791     case Intrinsic::x86_sse_ucomilt_ss:
13792     case Intrinsic::x86_sse2_ucomilt_sd:
13793       Opc = X86ISD::UCOMI;
13794       CC = ISD::SETLT;
13795       break;
13796     case Intrinsic::x86_sse_ucomile_ss:
13797     case Intrinsic::x86_sse2_ucomile_sd:
13798       Opc = X86ISD::UCOMI;
13799       CC = ISD::SETLE;
13800       break;
13801     case Intrinsic::x86_sse_ucomigt_ss:
13802     case Intrinsic::x86_sse2_ucomigt_sd:
13803       Opc = X86ISD::UCOMI;
13804       CC = ISD::SETGT;
13805       break;
13806     case Intrinsic::x86_sse_ucomige_ss:
13807     case Intrinsic::x86_sse2_ucomige_sd:
13808       Opc = X86ISD::UCOMI;
13809       CC = ISD::SETGE;
13810       break;
13811     case Intrinsic::x86_sse_ucomineq_ss:
13812     case Intrinsic::x86_sse2_ucomineq_sd:
13813       Opc = X86ISD::UCOMI;
13814       CC = ISD::SETNE;
13815       break;
13816     }
13817
13818     SDValue LHS = Op.getOperand(1);
13819     SDValue RHS = Op.getOperand(2);
13820     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13821     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13822     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13823     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13824                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13825     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13826   }
13827
13828   // Arithmetic intrinsics.
13829   case Intrinsic::x86_sse2_pmulu_dq:
13830   case Intrinsic::x86_avx2_pmulu_dq:
13831     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13832                        Op.getOperand(1), Op.getOperand(2));
13833
13834   case Intrinsic::x86_sse41_pmuldq:
13835   case Intrinsic::x86_avx2_pmul_dq:
13836     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13837                        Op.getOperand(1), Op.getOperand(2));
13838
13839   case Intrinsic::x86_sse2_pmulhu_w:
13840   case Intrinsic::x86_avx2_pmulhu_w:
13841     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13842                        Op.getOperand(1), Op.getOperand(2));
13843
13844   case Intrinsic::x86_sse2_pmulh_w:
13845   case Intrinsic::x86_avx2_pmulh_w:
13846     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13847                        Op.getOperand(1), Op.getOperand(2));
13848
13849   // SSE2/AVX2 sub with unsigned saturation intrinsics
13850   case Intrinsic::x86_sse2_psubus_b:
13851   case Intrinsic::x86_sse2_psubus_w:
13852   case Intrinsic::x86_avx2_psubus_b:
13853   case Intrinsic::x86_avx2_psubus_w:
13854     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13855                        Op.getOperand(1), Op.getOperand(2));
13856
13857   // SSE3/AVX horizontal add/sub intrinsics
13858   case Intrinsic::x86_sse3_hadd_ps:
13859   case Intrinsic::x86_sse3_hadd_pd:
13860   case Intrinsic::x86_avx_hadd_ps_256:
13861   case Intrinsic::x86_avx_hadd_pd_256:
13862   case Intrinsic::x86_sse3_hsub_ps:
13863   case Intrinsic::x86_sse3_hsub_pd:
13864   case Intrinsic::x86_avx_hsub_ps_256:
13865   case Intrinsic::x86_avx_hsub_pd_256:
13866   case Intrinsic::x86_ssse3_phadd_w_128:
13867   case Intrinsic::x86_ssse3_phadd_d_128:
13868   case Intrinsic::x86_avx2_phadd_w:
13869   case Intrinsic::x86_avx2_phadd_d:
13870   case Intrinsic::x86_ssse3_phsub_w_128:
13871   case Intrinsic::x86_ssse3_phsub_d_128:
13872   case Intrinsic::x86_avx2_phsub_w:
13873   case Intrinsic::x86_avx2_phsub_d: {
13874     unsigned Opcode;
13875     switch (IntNo) {
13876     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13877     case Intrinsic::x86_sse3_hadd_ps:
13878     case Intrinsic::x86_sse3_hadd_pd:
13879     case Intrinsic::x86_avx_hadd_ps_256:
13880     case Intrinsic::x86_avx_hadd_pd_256:
13881       Opcode = X86ISD::FHADD;
13882       break;
13883     case Intrinsic::x86_sse3_hsub_ps:
13884     case Intrinsic::x86_sse3_hsub_pd:
13885     case Intrinsic::x86_avx_hsub_ps_256:
13886     case Intrinsic::x86_avx_hsub_pd_256:
13887       Opcode = X86ISD::FHSUB;
13888       break;
13889     case Intrinsic::x86_ssse3_phadd_w_128:
13890     case Intrinsic::x86_ssse3_phadd_d_128:
13891     case Intrinsic::x86_avx2_phadd_w:
13892     case Intrinsic::x86_avx2_phadd_d:
13893       Opcode = X86ISD::HADD;
13894       break;
13895     case Intrinsic::x86_ssse3_phsub_w_128:
13896     case Intrinsic::x86_ssse3_phsub_d_128:
13897     case Intrinsic::x86_avx2_phsub_w:
13898     case Intrinsic::x86_avx2_phsub_d:
13899       Opcode = X86ISD::HSUB;
13900       break;
13901     }
13902     return DAG.getNode(Opcode, dl, Op.getValueType(),
13903                        Op.getOperand(1), Op.getOperand(2));
13904   }
13905
13906   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13907   case Intrinsic::x86_sse2_pmaxu_b:
13908   case Intrinsic::x86_sse41_pmaxuw:
13909   case Intrinsic::x86_sse41_pmaxud:
13910   case Intrinsic::x86_avx2_pmaxu_b:
13911   case Intrinsic::x86_avx2_pmaxu_w:
13912   case Intrinsic::x86_avx2_pmaxu_d:
13913   case Intrinsic::x86_sse2_pminu_b:
13914   case Intrinsic::x86_sse41_pminuw:
13915   case Intrinsic::x86_sse41_pminud:
13916   case Intrinsic::x86_avx2_pminu_b:
13917   case Intrinsic::x86_avx2_pminu_w:
13918   case Intrinsic::x86_avx2_pminu_d:
13919   case Intrinsic::x86_sse41_pmaxsb:
13920   case Intrinsic::x86_sse2_pmaxs_w:
13921   case Intrinsic::x86_sse41_pmaxsd:
13922   case Intrinsic::x86_avx2_pmaxs_b:
13923   case Intrinsic::x86_avx2_pmaxs_w:
13924   case Intrinsic::x86_avx2_pmaxs_d:
13925   case Intrinsic::x86_sse41_pminsb:
13926   case Intrinsic::x86_sse2_pmins_w:
13927   case Intrinsic::x86_sse41_pminsd:
13928   case Intrinsic::x86_avx2_pmins_b:
13929   case Intrinsic::x86_avx2_pmins_w:
13930   case Intrinsic::x86_avx2_pmins_d: {
13931     unsigned Opcode;
13932     switch (IntNo) {
13933     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13934     case Intrinsic::x86_sse2_pmaxu_b:
13935     case Intrinsic::x86_sse41_pmaxuw:
13936     case Intrinsic::x86_sse41_pmaxud:
13937     case Intrinsic::x86_avx2_pmaxu_b:
13938     case Intrinsic::x86_avx2_pmaxu_w:
13939     case Intrinsic::x86_avx2_pmaxu_d:
13940       Opcode = X86ISD::UMAX;
13941       break;
13942     case Intrinsic::x86_sse2_pminu_b:
13943     case Intrinsic::x86_sse41_pminuw:
13944     case Intrinsic::x86_sse41_pminud:
13945     case Intrinsic::x86_avx2_pminu_b:
13946     case Intrinsic::x86_avx2_pminu_w:
13947     case Intrinsic::x86_avx2_pminu_d:
13948       Opcode = X86ISD::UMIN;
13949       break;
13950     case Intrinsic::x86_sse41_pmaxsb:
13951     case Intrinsic::x86_sse2_pmaxs_w:
13952     case Intrinsic::x86_sse41_pmaxsd:
13953     case Intrinsic::x86_avx2_pmaxs_b:
13954     case Intrinsic::x86_avx2_pmaxs_w:
13955     case Intrinsic::x86_avx2_pmaxs_d:
13956       Opcode = X86ISD::SMAX;
13957       break;
13958     case Intrinsic::x86_sse41_pminsb:
13959     case Intrinsic::x86_sse2_pmins_w:
13960     case Intrinsic::x86_sse41_pminsd:
13961     case Intrinsic::x86_avx2_pmins_b:
13962     case Intrinsic::x86_avx2_pmins_w:
13963     case Intrinsic::x86_avx2_pmins_d:
13964       Opcode = X86ISD::SMIN;
13965       break;
13966     }
13967     return DAG.getNode(Opcode, dl, Op.getValueType(),
13968                        Op.getOperand(1), Op.getOperand(2));
13969   }
13970
13971   // SSE/SSE2/AVX floating point max/min intrinsics.
13972   case Intrinsic::x86_sse_max_ps:
13973   case Intrinsic::x86_sse2_max_pd:
13974   case Intrinsic::x86_avx_max_ps_256:
13975   case Intrinsic::x86_avx_max_pd_256:
13976   case Intrinsic::x86_sse_min_ps:
13977   case Intrinsic::x86_sse2_min_pd:
13978   case Intrinsic::x86_avx_min_ps_256:
13979   case Intrinsic::x86_avx_min_pd_256: {
13980     unsigned Opcode;
13981     switch (IntNo) {
13982     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13983     case Intrinsic::x86_sse_max_ps:
13984     case Intrinsic::x86_sse2_max_pd:
13985     case Intrinsic::x86_avx_max_ps_256:
13986     case Intrinsic::x86_avx_max_pd_256:
13987       Opcode = X86ISD::FMAX;
13988       break;
13989     case Intrinsic::x86_sse_min_ps:
13990     case Intrinsic::x86_sse2_min_pd:
13991     case Intrinsic::x86_avx_min_ps_256:
13992     case Intrinsic::x86_avx_min_pd_256:
13993       Opcode = X86ISD::FMIN;
13994       break;
13995     }
13996     return DAG.getNode(Opcode, dl, Op.getValueType(),
13997                        Op.getOperand(1), Op.getOperand(2));
13998   }
13999
14000   // AVX2 variable shift intrinsics
14001   case Intrinsic::x86_avx2_psllv_d:
14002   case Intrinsic::x86_avx2_psllv_q:
14003   case Intrinsic::x86_avx2_psllv_d_256:
14004   case Intrinsic::x86_avx2_psllv_q_256:
14005   case Intrinsic::x86_avx2_psrlv_d:
14006   case Intrinsic::x86_avx2_psrlv_q:
14007   case Intrinsic::x86_avx2_psrlv_d_256:
14008   case Intrinsic::x86_avx2_psrlv_q_256:
14009   case Intrinsic::x86_avx2_psrav_d:
14010   case Intrinsic::x86_avx2_psrav_d_256: {
14011     unsigned Opcode;
14012     switch (IntNo) {
14013     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14014     case Intrinsic::x86_avx2_psllv_d:
14015     case Intrinsic::x86_avx2_psllv_q:
14016     case Intrinsic::x86_avx2_psllv_d_256:
14017     case Intrinsic::x86_avx2_psllv_q_256:
14018       Opcode = ISD::SHL;
14019       break;
14020     case Intrinsic::x86_avx2_psrlv_d:
14021     case Intrinsic::x86_avx2_psrlv_q:
14022     case Intrinsic::x86_avx2_psrlv_d_256:
14023     case Intrinsic::x86_avx2_psrlv_q_256:
14024       Opcode = ISD::SRL;
14025       break;
14026     case Intrinsic::x86_avx2_psrav_d:
14027     case Intrinsic::x86_avx2_psrav_d_256:
14028       Opcode = ISD::SRA;
14029       break;
14030     }
14031     return DAG.getNode(Opcode, dl, Op.getValueType(),
14032                        Op.getOperand(1), Op.getOperand(2));
14033   }
14034
14035   case Intrinsic::x86_sse2_packssdw_128:
14036   case Intrinsic::x86_sse2_packsswb_128:
14037   case Intrinsic::x86_avx2_packssdw:
14038   case Intrinsic::x86_avx2_packsswb:
14039     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14040                        Op.getOperand(1), Op.getOperand(2));
14041
14042   case Intrinsic::x86_sse2_packuswb_128:
14043   case Intrinsic::x86_sse41_packusdw:
14044   case Intrinsic::x86_avx2_packuswb:
14045   case Intrinsic::x86_avx2_packusdw:
14046     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14047                        Op.getOperand(1), Op.getOperand(2));
14048
14049   case Intrinsic::x86_ssse3_pshuf_b_128:
14050   case Intrinsic::x86_avx2_pshuf_b:
14051     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14052                        Op.getOperand(1), Op.getOperand(2));
14053
14054   case Intrinsic::x86_sse2_pshuf_d:
14055     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14056                        Op.getOperand(1), Op.getOperand(2));
14057
14058   case Intrinsic::x86_sse2_pshufl_w:
14059     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14060                        Op.getOperand(1), Op.getOperand(2));
14061
14062   case Intrinsic::x86_sse2_pshufh_w:
14063     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14064                        Op.getOperand(1), Op.getOperand(2));
14065
14066   case Intrinsic::x86_ssse3_psign_b_128:
14067   case Intrinsic::x86_ssse3_psign_w_128:
14068   case Intrinsic::x86_ssse3_psign_d_128:
14069   case Intrinsic::x86_avx2_psign_b:
14070   case Intrinsic::x86_avx2_psign_w:
14071   case Intrinsic::x86_avx2_psign_d:
14072     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14073                        Op.getOperand(1), Op.getOperand(2));
14074
14075   case Intrinsic::x86_sse41_insertps:
14076     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14077                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14078
14079   case Intrinsic::x86_avx_vperm2f128_ps_256:
14080   case Intrinsic::x86_avx_vperm2f128_pd_256:
14081   case Intrinsic::x86_avx_vperm2f128_si_256:
14082   case Intrinsic::x86_avx2_vperm2i128:
14083     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14084                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14085
14086   case Intrinsic::x86_avx2_permd:
14087   case Intrinsic::x86_avx2_permps:
14088     // Operands intentionally swapped. Mask is last operand to intrinsic,
14089     // but second operand for node/instruction.
14090     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14091                        Op.getOperand(2), Op.getOperand(1));
14092
14093   case Intrinsic::x86_sse_sqrt_ps:
14094   case Intrinsic::x86_sse2_sqrt_pd:
14095   case Intrinsic::x86_avx_sqrt_ps_256:
14096   case Intrinsic::x86_avx_sqrt_pd_256:
14097     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14098
14099   // ptest and testp intrinsics. The intrinsic these come from are designed to
14100   // return an integer value, not just an instruction so lower it to the ptest
14101   // or testp pattern and a setcc for the result.
14102   case Intrinsic::x86_sse41_ptestz:
14103   case Intrinsic::x86_sse41_ptestc:
14104   case Intrinsic::x86_sse41_ptestnzc:
14105   case Intrinsic::x86_avx_ptestz_256:
14106   case Intrinsic::x86_avx_ptestc_256:
14107   case Intrinsic::x86_avx_ptestnzc_256:
14108   case Intrinsic::x86_avx_vtestz_ps:
14109   case Intrinsic::x86_avx_vtestc_ps:
14110   case Intrinsic::x86_avx_vtestnzc_ps:
14111   case Intrinsic::x86_avx_vtestz_pd:
14112   case Intrinsic::x86_avx_vtestc_pd:
14113   case Intrinsic::x86_avx_vtestnzc_pd:
14114   case Intrinsic::x86_avx_vtestz_ps_256:
14115   case Intrinsic::x86_avx_vtestc_ps_256:
14116   case Intrinsic::x86_avx_vtestnzc_ps_256:
14117   case Intrinsic::x86_avx_vtestz_pd_256:
14118   case Intrinsic::x86_avx_vtestc_pd_256:
14119   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14120     bool IsTestPacked = false;
14121     unsigned X86CC;
14122     switch (IntNo) {
14123     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14124     case Intrinsic::x86_avx_vtestz_ps:
14125     case Intrinsic::x86_avx_vtestz_pd:
14126     case Intrinsic::x86_avx_vtestz_ps_256:
14127     case Intrinsic::x86_avx_vtestz_pd_256:
14128       IsTestPacked = true; // Fallthrough
14129     case Intrinsic::x86_sse41_ptestz:
14130     case Intrinsic::x86_avx_ptestz_256:
14131       // ZF = 1
14132       X86CC = X86::COND_E;
14133       break;
14134     case Intrinsic::x86_avx_vtestc_ps:
14135     case Intrinsic::x86_avx_vtestc_pd:
14136     case Intrinsic::x86_avx_vtestc_ps_256:
14137     case Intrinsic::x86_avx_vtestc_pd_256:
14138       IsTestPacked = true; // Fallthrough
14139     case Intrinsic::x86_sse41_ptestc:
14140     case Intrinsic::x86_avx_ptestc_256:
14141       // CF = 1
14142       X86CC = X86::COND_B;
14143       break;
14144     case Intrinsic::x86_avx_vtestnzc_ps:
14145     case Intrinsic::x86_avx_vtestnzc_pd:
14146     case Intrinsic::x86_avx_vtestnzc_ps_256:
14147     case Intrinsic::x86_avx_vtestnzc_pd_256:
14148       IsTestPacked = true; // Fallthrough
14149     case Intrinsic::x86_sse41_ptestnzc:
14150     case Intrinsic::x86_avx_ptestnzc_256:
14151       // ZF and CF = 0
14152       X86CC = X86::COND_A;
14153       break;
14154     }
14155
14156     SDValue LHS = Op.getOperand(1);
14157     SDValue RHS = Op.getOperand(2);
14158     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14159     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14160     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14161     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14162     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14163   }
14164   case Intrinsic::x86_avx512_kortestz_w:
14165   case Intrinsic::x86_avx512_kortestc_w: {
14166     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14167     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14168     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14169     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14170     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14171     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14172     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14173   }
14174
14175   // SSE/AVX shift intrinsics
14176   case Intrinsic::x86_sse2_psll_w:
14177   case Intrinsic::x86_sse2_psll_d:
14178   case Intrinsic::x86_sse2_psll_q:
14179   case Intrinsic::x86_avx2_psll_w:
14180   case Intrinsic::x86_avx2_psll_d:
14181   case Intrinsic::x86_avx2_psll_q:
14182   case Intrinsic::x86_sse2_psrl_w:
14183   case Intrinsic::x86_sse2_psrl_d:
14184   case Intrinsic::x86_sse2_psrl_q:
14185   case Intrinsic::x86_avx2_psrl_w:
14186   case Intrinsic::x86_avx2_psrl_d:
14187   case Intrinsic::x86_avx2_psrl_q:
14188   case Intrinsic::x86_sse2_psra_w:
14189   case Intrinsic::x86_sse2_psra_d:
14190   case Intrinsic::x86_avx2_psra_w:
14191   case Intrinsic::x86_avx2_psra_d: {
14192     unsigned Opcode;
14193     switch (IntNo) {
14194     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14195     case Intrinsic::x86_sse2_psll_w:
14196     case Intrinsic::x86_sse2_psll_d:
14197     case Intrinsic::x86_sse2_psll_q:
14198     case Intrinsic::x86_avx2_psll_w:
14199     case Intrinsic::x86_avx2_psll_d:
14200     case Intrinsic::x86_avx2_psll_q:
14201       Opcode = X86ISD::VSHL;
14202       break;
14203     case Intrinsic::x86_sse2_psrl_w:
14204     case Intrinsic::x86_sse2_psrl_d:
14205     case Intrinsic::x86_sse2_psrl_q:
14206     case Intrinsic::x86_avx2_psrl_w:
14207     case Intrinsic::x86_avx2_psrl_d:
14208     case Intrinsic::x86_avx2_psrl_q:
14209       Opcode = X86ISD::VSRL;
14210       break;
14211     case Intrinsic::x86_sse2_psra_w:
14212     case Intrinsic::x86_sse2_psra_d:
14213     case Intrinsic::x86_avx2_psra_w:
14214     case Intrinsic::x86_avx2_psra_d:
14215       Opcode = X86ISD::VSRA;
14216       break;
14217     }
14218     return DAG.getNode(Opcode, dl, Op.getValueType(),
14219                        Op.getOperand(1), Op.getOperand(2));
14220   }
14221
14222   // SSE/AVX immediate shift intrinsics
14223   case Intrinsic::x86_sse2_pslli_w:
14224   case Intrinsic::x86_sse2_pslli_d:
14225   case Intrinsic::x86_sse2_pslli_q:
14226   case Intrinsic::x86_avx2_pslli_w:
14227   case Intrinsic::x86_avx2_pslli_d:
14228   case Intrinsic::x86_avx2_pslli_q:
14229   case Intrinsic::x86_sse2_psrli_w:
14230   case Intrinsic::x86_sse2_psrli_d:
14231   case Intrinsic::x86_sse2_psrli_q:
14232   case Intrinsic::x86_avx2_psrli_w:
14233   case Intrinsic::x86_avx2_psrli_d:
14234   case Intrinsic::x86_avx2_psrli_q:
14235   case Intrinsic::x86_sse2_psrai_w:
14236   case Intrinsic::x86_sse2_psrai_d:
14237   case Intrinsic::x86_avx2_psrai_w:
14238   case Intrinsic::x86_avx2_psrai_d: {
14239     unsigned Opcode;
14240     switch (IntNo) {
14241     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14242     case Intrinsic::x86_sse2_pslli_w:
14243     case Intrinsic::x86_sse2_pslli_d:
14244     case Intrinsic::x86_sse2_pslli_q:
14245     case Intrinsic::x86_avx2_pslli_w:
14246     case Intrinsic::x86_avx2_pslli_d:
14247     case Intrinsic::x86_avx2_pslli_q:
14248       Opcode = X86ISD::VSHLI;
14249       break;
14250     case Intrinsic::x86_sse2_psrli_w:
14251     case Intrinsic::x86_sse2_psrli_d:
14252     case Intrinsic::x86_sse2_psrli_q:
14253     case Intrinsic::x86_avx2_psrli_w:
14254     case Intrinsic::x86_avx2_psrli_d:
14255     case Intrinsic::x86_avx2_psrli_q:
14256       Opcode = X86ISD::VSRLI;
14257       break;
14258     case Intrinsic::x86_sse2_psrai_w:
14259     case Intrinsic::x86_sse2_psrai_d:
14260     case Intrinsic::x86_avx2_psrai_w:
14261     case Intrinsic::x86_avx2_psrai_d:
14262       Opcode = X86ISD::VSRAI;
14263       break;
14264     }
14265     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14266                                Op.getOperand(1), Op.getOperand(2), DAG);
14267   }
14268
14269   case Intrinsic::x86_sse42_pcmpistria128:
14270   case Intrinsic::x86_sse42_pcmpestria128:
14271   case Intrinsic::x86_sse42_pcmpistric128:
14272   case Intrinsic::x86_sse42_pcmpestric128:
14273   case Intrinsic::x86_sse42_pcmpistrio128:
14274   case Intrinsic::x86_sse42_pcmpestrio128:
14275   case Intrinsic::x86_sse42_pcmpistris128:
14276   case Intrinsic::x86_sse42_pcmpestris128:
14277   case Intrinsic::x86_sse42_pcmpistriz128:
14278   case Intrinsic::x86_sse42_pcmpestriz128: {
14279     unsigned Opcode;
14280     unsigned X86CC;
14281     switch (IntNo) {
14282     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14283     case Intrinsic::x86_sse42_pcmpistria128:
14284       Opcode = X86ISD::PCMPISTRI;
14285       X86CC = X86::COND_A;
14286       break;
14287     case Intrinsic::x86_sse42_pcmpestria128:
14288       Opcode = X86ISD::PCMPESTRI;
14289       X86CC = X86::COND_A;
14290       break;
14291     case Intrinsic::x86_sse42_pcmpistric128:
14292       Opcode = X86ISD::PCMPISTRI;
14293       X86CC = X86::COND_B;
14294       break;
14295     case Intrinsic::x86_sse42_pcmpestric128:
14296       Opcode = X86ISD::PCMPESTRI;
14297       X86CC = X86::COND_B;
14298       break;
14299     case Intrinsic::x86_sse42_pcmpistrio128:
14300       Opcode = X86ISD::PCMPISTRI;
14301       X86CC = X86::COND_O;
14302       break;
14303     case Intrinsic::x86_sse42_pcmpestrio128:
14304       Opcode = X86ISD::PCMPESTRI;
14305       X86CC = X86::COND_O;
14306       break;
14307     case Intrinsic::x86_sse42_pcmpistris128:
14308       Opcode = X86ISD::PCMPISTRI;
14309       X86CC = X86::COND_S;
14310       break;
14311     case Intrinsic::x86_sse42_pcmpestris128:
14312       Opcode = X86ISD::PCMPESTRI;
14313       X86CC = X86::COND_S;
14314       break;
14315     case Intrinsic::x86_sse42_pcmpistriz128:
14316       Opcode = X86ISD::PCMPISTRI;
14317       X86CC = X86::COND_E;
14318       break;
14319     case Intrinsic::x86_sse42_pcmpestriz128:
14320       Opcode = X86ISD::PCMPESTRI;
14321       X86CC = X86::COND_E;
14322       break;
14323     }
14324     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14325     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14326     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14327     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14328                                 DAG.getConstant(X86CC, MVT::i8),
14329                                 SDValue(PCMP.getNode(), 1));
14330     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14331   }
14332
14333   case Intrinsic::x86_sse42_pcmpistri128:
14334   case Intrinsic::x86_sse42_pcmpestri128: {
14335     unsigned Opcode;
14336     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14337       Opcode = X86ISD::PCMPISTRI;
14338     else
14339       Opcode = X86ISD::PCMPESTRI;
14340
14341     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14342     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14343     return DAG.getNode(Opcode, dl, VTs, NewOps);
14344   }
14345   case Intrinsic::x86_fma_vfmadd_ps:
14346   case Intrinsic::x86_fma_vfmadd_pd:
14347   case Intrinsic::x86_fma_vfmsub_ps:
14348   case Intrinsic::x86_fma_vfmsub_pd:
14349   case Intrinsic::x86_fma_vfnmadd_ps:
14350   case Intrinsic::x86_fma_vfnmadd_pd:
14351   case Intrinsic::x86_fma_vfnmsub_ps:
14352   case Intrinsic::x86_fma_vfnmsub_pd:
14353   case Intrinsic::x86_fma_vfmaddsub_ps:
14354   case Intrinsic::x86_fma_vfmaddsub_pd:
14355   case Intrinsic::x86_fma_vfmsubadd_ps:
14356   case Intrinsic::x86_fma_vfmsubadd_pd:
14357   case Intrinsic::x86_fma_vfmadd_ps_256:
14358   case Intrinsic::x86_fma_vfmadd_pd_256:
14359   case Intrinsic::x86_fma_vfmsub_ps_256:
14360   case Intrinsic::x86_fma_vfmsub_pd_256:
14361   case Intrinsic::x86_fma_vfnmadd_ps_256:
14362   case Intrinsic::x86_fma_vfnmadd_pd_256:
14363   case Intrinsic::x86_fma_vfnmsub_ps_256:
14364   case Intrinsic::x86_fma_vfnmsub_pd_256:
14365   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14366   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14367   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14368   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14369   case Intrinsic::x86_fma_vfmadd_ps_512:
14370   case Intrinsic::x86_fma_vfmadd_pd_512:
14371   case Intrinsic::x86_fma_vfmsub_ps_512:
14372   case Intrinsic::x86_fma_vfmsub_pd_512:
14373   case Intrinsic::x86_fma_vfnmadd_ps_512:
14374   case Intrinsic::x86_fma_vfnmadd_pd_512:
14375   case Intrinsic::x86_fma_vfnmsub_ps_512:
14376   case Intrinsic::x86_fma_vfnmsub_pd_512:
14377   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14378   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14379   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14380   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14381     unsigned Opc;
14382     switch (IntNo) {
14383     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14384     case Intrinsic::x86_fma_vfmadd_ps:
14385     case Intrinsic::x86_fma_vfmadd_pd:
14386     case Intrinsic::x86_fma_vfmadd_ps_256:
14387     case Intrinsic::x86_fma_vfmadd_pd_256:
14388     case Intrinsic::x86_fma_vfmadd_ps_512:
14389     case Intrinsic::x86_fma_vfmadd_pd_512:
14390       Opc = X86ISD::FMADD;
14391       break;
14392     case Intrinsic::x86_fma_vfmsub_ps:
14393     case Intrinsic::x86_fma_vfmsub_pd:
14394     case Intrinsic::x86_fma_vfmsub_ps_256:
14395     case Intrinsic::x86_fma_vfmsub_pd_256:
14396     case Intrinsic::x86_fma_vfmsub_ps_512:
14397     case Intrinsic::x86_fma_vfmsub_pd_512:
14398       Opc = X86ISD::FMSUB;
14399       break;
14400     case Intrinsic::x86_fma_vfnmadd_ps:
14401     case Intrinsic::x86_fma_vfnmadd_pd:
14402     case Intrinsic::x86_fma_vfnmadd_ps_256:
14403     case Intrinsic::x86_fma_vfnmadd_pd_256:
14404     case Intrinsic::x86_fma_vfnmadd_ps_512:
14405     case Intrinsic::x86_fma_vfnmadd_pd_512:
14406       Opc = X86ISD::FNMADD;
14407       break;
14408     case Intrinsic::x86_fma_vfnmsub_ps:
14409     case Intrinsic::x86_fma_vfnmsub_pd:
14410     case Intrinsic::x86_fma_vfnmsub_ps_256:
14411     case Intrinsic::x86_fma_vfnmsub_pd_256:
14412     case Intrinsic::x86_fma_vfnmsub_ps_512:
14413     case Intrinsic::x86_fma_vfnmsub_pd_512:
14414       Opc = X86ISD::FNMSUB;
14415       break;
14416     case Intrinsic::x86_fma_vfmaddsub_ps:
14417     case Intrinsic::x86_fma_vfmaddsub_pd:
14418     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14419     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14420     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14421     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14422       Opc = X86ISD::FMADDSUB;
14423       break;
14424     case Intrinsic::x86_fma_vfmsubadd_ps:
14425     case Intrinsic::x86_fma_vfmsubadd_pd:
14426     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14427     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14428     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14429     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14430       Opc = X86ISD::FMSUBADD;
14431       break;
14432     }
14433
14434     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14435                        Op.getOperand(2), Op.getOperand(3));
14436   }
14437   }
14438 }
14439
14440 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14441                               SDValue Src, SDValue Mask, SDValue Base,
14442                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14443                               const X86Subtarget * Subtarget) {
14444   SDLoc dl(Op);
14445   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14446   assert(C && "Invalid scale type");
14447   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14448   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14449                              Index.getSimpleValueType().getVectorNumElements());
14450   SDValue MaskInReg;
14451   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14452   if (MaskC)
14453     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14454   else
14455     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14456   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14457   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14458   SDValue Segment = DAG.getRegister(0, MVT::i32);
14459   if (Src.getOpcode() == ISD::UNDEF)
14460     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14461   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14462   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14463   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14464   return DAG.getMergeValues(RetOps, dl);
14465 }
14466
14467 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14468                                SDValue Src, SDValue Mask, SDValue Base,
14469                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14470   SDLoc dl(Op);
14471   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14472   assert(C && "Invalid scale type");
14473   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14474   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14475   SDValue Segment = DAG.getRegister(0, MVT::i32);
14476   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14477                              Index.getSimpleValueType().getVectorNumElements());
14478   SDValue MaskInReg;
14479   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14480   if (MaskC)
14481     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14482   else
14483     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14484   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14485   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14486   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14487   return SDValue(Res, 1);
14488 }
14489
14490 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14491                                SDValue Mask, SDValue Base, SDValue Index,
14492                                SDValue ScaleOp, SDValue Chain) {
14493   SDLoc dl(Op);
14494   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14495   assert(C && "Invalid scale type");
14496   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14497   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14498   SDValue Segment = DAG.getRegister(0, MVT::i32);
14499   EVT MaskVT =
14500     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14501   SDValue MaskInReg;
14502   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14503   if (MaskC)
14504     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14505   else
14506     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14507   //SDVTList VTs = DAG.getVTList(MVT::Other);
14508   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14509   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14510   return SDValue(Res, 0);
14511 }
14512
14513 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14514 // read performance monitor counters (x86_rdpmc).
14515 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14516                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14517                               SmallVectorImpl<SDValue> &Results) {
14518   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14519   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14520   SDValue LO, HI;
14521
14522   // The ECX register is used to select the index of the performance counter
14523   // to read.
14524   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14525                                    N->getOperand(2));
14526   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14527
14528   // Reads the content of a 64-bit performance counter and returns it in the
14529   // registers EDX:EAX.
14530   if (Subtarget->is64Bit()) {
14531     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14532     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14533                             LO.getValue(2));
14534   } else {
14535     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14536     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14537                             LO.getValue(2));
14538   }
14539   Chain = HI.getValue(1);
14540
14541   if (Subtarget->is64Bit()) {
14542     // The EAX register is loaded with the low-order 32 bits. The EDX register
14543     // is loaded with the supported high-order bits of the counter.
14544     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14545                               DAG.getConstant(32, MVT::i8));
14546     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14547     Results.push_back(Chain);
14548     return;
14549   }
14550
14551   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14552   SDValue Ops[] = { LO, HI };
14553   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14554   Results.push_back(Pair);
14555   Results.push_back(Chain);
14556 }
14557
14558 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14559 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14560 // also used to custom lower READCYCLECOUNTER nodes.
14561 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14562                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14563                               SmallVectorImpl<SDValue> &Results) {
14564   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14565   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14566   SDValue LO, HI;
14567
14568   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14569   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14570   // and the EAX register is loaded with the low-order 32 bits.
14571   if (Subtarget->is64Bit()) {
14572     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14573     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14574                             LO.getValue(2));
14575   } else {
14576     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14577     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14578                             LO.getValue(2));
14579   }
14580   SDValue Chain = HI.getValue(1);
14581
14582   if (Opcode == X86ISD::RDTSCP_DAG) {
14583     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14584
14585     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14586     // the ECX register. Add 'ecx' explicitly to the chain.
14587     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14588                                      HI.getValue(2));
14589     // Explicitly store the content of ECX at the location passed in input
14590     // to the 'rdtscp' intrinsic.
14591     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14592                          MachinePointerInfo(), false, false, 0);
14593   }
14594
14595   if (Subtarget->is64Bit()) {
14596     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14597     // the EAX register is loaded with the low-order 32 bits.
14598     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14599                               DAG.getConstant(32, MVT::i8));
14600     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14601     Results.push_back(Chain);
14602     return;
14603   }
14604
14605   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14606   SDValue Ops[] = { LO, HI };
14607   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14608   Results.push_back(Pair);
14609   Results.push_back(Chain);
14610 }
14611
14612 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14613                                      SelectionDAG &DAG) {
14614   SmallVector<SDValue, 2> Results;
14615   SDLoc DL(Op);
14616   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14617                           Results);
14618   return DAG.getMergeValues(Results, DL);
14619 }
14620
14621 enum IntrinsicType {
14622   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14623 };
14624
14625 struct IntrinsicData {
14626   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14627     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14628   IntrinsicType Type;
14629   unsigned      Opc0;
14630   unsigned      Opc1;
14631 };
14632
14633 std::map < unsigned, IntrinsicData> IntrMap;
14634 static void InitIntinsicsMap() {
14635   static bool Initialized = false;
14636   if (Initialized) 
14637     return;
14638   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14639                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14640   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14641                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14642   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14643                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14644   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14645                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14646   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14647                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14648   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14649                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14650   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14651                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14652   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14653                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14654   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14655                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14656
14657   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14658                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14659   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14660                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14661   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14662                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14663   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14664                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14665   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14666                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14667   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14668                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14669   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14670                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14671   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14672                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14673    
14674   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14675                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14676                                                         X86::VGATHERPF1QPSm)));
14677   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14678                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14679                                                         X86::VGATHERPF1QPDm)));
14680   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14681                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14682                                                         X86::VGATHERPF1DPDm)));
14683   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14684                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14685                                                         X86::VGATHERPF1DPSm)));
14686   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14687                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14688                                                         X86::VSCATTERPF1QPSm)));
14689   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14690                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14691                                                         X86::VSCATTERPF1QPDm)));
14692   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14693                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14694                                                         X86::VSCATTERPF1DPDm)));
14695   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14696                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14697                                                         X86::VSCATTERPF1DPSm)));
14698   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14699                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14700   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14701                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14702   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14703                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14704   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14705                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14706   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14707                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14708   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14709                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14710   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14711                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14712   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14713                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14714   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14715                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14716   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14717                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14718   Initialized = true;
14719 }
14720
14721 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14722                                       SelectionDAG &DAG) {
14723   InitIntinsicsMap();
14724   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14725   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14726   if (itr == IntrMap.end())
14727     return SDValue();
14728
14729   SDLoc dl(Op);
14730   IntrinsicData Intr = itr->second;
14731   switch(Intr.Type) {
14732   case RDSEED:
14733   case RDRAND: {
14734     // Emit the node with the right value type.
14735     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14736     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14737
14738     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14739     // Otherwise return the value from Rand, which is always 0, casted to i32.
14740     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14741                       DAG.getConstant(1, Op->getValueType(1)),
14742                       DAG.getConstant(X86::COND_B, MVT::i32),
14743                       SDValue(Result.getNode(), 1) };
14744     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14745                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14746                                   Ops);
14747
14748     // Return { result, isValid, chain }.
14749     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14750                        SDValue(Result.getNode(), 2));
14751   }
14752   case GATHER: {
14753   //gather(v1, mask, index, base, scale);
14754     SDValue Chain = Op.getOperand(0);
14755     SDValue Src   = Op.getOperand(2);
14756     SDValue Base  = Op.getOperand(3);
14757     SDValue Index = Op.getOperand(4);
14758     SDValue Mask  = Op.getOperand(5);
14759     SDValue Scale = Op.getOperand(6);
14760     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14761                           Subtarget);
14762   }
14763   case SCATTER: {
14764   //scatter(base, mask, index, v1, scale);
14765     SDValue Chain = Op.getOperand(0);
14766     SDValue Base  = Op.getOperand(2);
14767     SDValue Mask  = Op.getOperand(3);
14768     SDValue Index = Op.getOperand(4);
14769     SDValue Src   = Op.getOperand(5);
14770     SDValue Scale = Op.getOperand(6);
14771     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14772   }
14773   case PREFETCH: {
14774     SDValue Hint = Op.getOperand(6);
14775     unsigned HintVal;
14776     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14777         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14778       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14779     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14780     SDValue Chain = Op.getOperand(0);
14781     SDValue Mask  = Op.getOperand(2);
14782     SDValue Index = Op.getOperand(3);
14783     SDValue Base  = Op.getOperand(4);
14784     SDValue Scale = Op.getOperand(5);
14785     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14786   }
14787   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14788   case RDTSC: {
14789     SmallVector<SDValue, 2> Results;
14790     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14791     return DAG.getMergeValues(Results, dl);
14792   }
14793   // Read Performance Monitoring Counters.
14794   case RDPMC: {
14795     SmallVector<SDValue, 2> Results;
14796     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14797     return DAG.getMergeValues(Results, dl);
14798   }
14799   // XTEST intrinsics.
14800   case XTEST: {
14801     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14802     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14803     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14804                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14805                                 InTrans);
14806     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14807     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14808                        Ret, SDValue(InTrans.getNode(), 1));
14809   }
14810   }
14811   llvm_unreachable("Unknown Intrinsic Type");
14812 }
14813
14814 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14815                                            SelectionDAG &DAG) const {
14816   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14817   MFI->setReturnAddressIsTaken(true);
14818
14819   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14820     return SDValue();
14821
14822   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14823   SDLoc dl(Op);
14824   EVT PtrVT = getPointerTy();
14825
14826   if (Depth > 0) {
14827     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14828     const X86RegisterInfo *RegInfo =
14829       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14830     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14831     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14832                        DAG.getNode(ISD::ADD, dl, PtrVT,
14833                                    FrameAddr, Offset),
14834                        MachinePointerInfo(), false, false, false, 0);
14835   }
14836
14837   // Just load the return address.
14838   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14839   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14840                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14841 }
14842
14843 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14844   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14845   MFI->setFrameAddressIsTaken(true);
14846
14847   EVT VT = Op.getValueType();
14848   SDLoc dl(Op);  // FIXME probably not meaningful
14849   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14850   const X86RegisterInfo *RegInfo =
14851     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14852   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14853   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14854           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14855          "Invalid Frame Register!");
14856   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14857   while (Depth--)
14858     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14859                             MachinePointerInfo(),
14860                             false, false, false, 0);
14861   return FrameAddr;
14862 }
14863
14864 // FIXME? Maybe this could be a TableGen attribute on some registers and
14865 // this table could be generated automatically from RegInfo.
14866 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14867                                               EVT VT) const {
14868   unsigned Reg = StringSwitch<unsigned>(RegName)
14869                        .Case("esp", X86::ESP)
14870                        .Case("rsp", X86::RSP)
14871                        .Default(0);
14872   if (Reg)
14873     return Reg;
14874   report_fatal_error("Invalid register name global variable");
14875 }
14876
14877 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14878                                                      SelectionDAG &DAG) const {
14879   const X86RegisterInfo *RegInfo =
14880     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14881   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14882 }
14883
14884 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14885   SDValue Chain     = Op.getOperand(0);
14886   SDValue Offset    = Op.getOperand(1);
14887   SDValue Handler   = Op.getOperand(2);
14888   SDLoc dl      (Op);
14889
14890   EVT PtrVT = getPointerTy();
14891   const X86RegisterInfo *RegInfo =
14892     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14893   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14894   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14895           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14896          "Invalid Frame Register!");
14897   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14898   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14899
14900   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14901                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14902   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14903   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14904                        false, false, 0);
14905   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14906
14907   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14908                      DAG.getRegister(StoreAddrReg, PtrVT));
14909 }
14910
14911 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14912                                                SelectionDAG &DAG) const {
14913   SDLoc DL(Op);
14914   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14915                      DAG.getVTList(MVT::i32, MVT::Other),
14916                      Op.getOperand(0), Op.getOperand(1));
14917 }
14918
14919 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14920                                                 SelectionDAG &DAG) const {
14921   SDLoc DL(Op);
14922   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14923                      Op.getOperand(0), Op.getOperand(1));
14924 }
14925
14926 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14927   return Op.getOperand(0);
14928 }
14929
14930 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14931                                                 SelectionDAG &DAG) const {
14932   SDValue Root = Op.getOperand(0);
14933   SDValue Trmp = Op.getOperand(1); // trampoline
14934   SDValue FPtr = Op.getOperand(2); // nested function
14935   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14936   SDLoc dl (Op);
14937
14938   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14939   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14940
14941   if (Subtarget->is64Bit()) {
14942     SDValue OutChains[6];
14943
14944     // Large code-model.
14945     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14946     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14947
14948     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14949     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14950
14951     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14952
14953     // Load the pointer to the nested function into R11.
14954     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14955     SDValue Addr = Trmp;
14956     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14957                                 Addr, MachinePointerInfo(TrmpAddr),
14958                                 false, false, 0);
14959
14960     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14961                        DAG.getConstant(2, MVT::i64));
14962     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14963                                 MachinePointerInfo(TrmpAddr, 2),
14964                                 false, false, 2);
14965
14966     // Load the 'nest' parameter value into R10.
14967     // R10 is specified in X86CallingConv.td
14968     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14969     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14970                        DAG.getConstant(10, MVT::i64));
14971     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14972                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14973                                 false, false, 0);
14974
14975     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14976                        DAG.getConstant(12, MVT::i64));
14977     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14978                                 MachinePointerInfo(TrmpAddr, 12),
14979                                 false, false, 2);
14980
14981     // Jump to the nested function.
14982     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14983     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14984                        DAG.getConstant(20, MVT::i64));
14985     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14986                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14987                                 false, false, 0);
14988
14989     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14990     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14991                        DAG.getConstant(22, MVT::i64));
14992     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14993                                 MachinePointerInfo(TrmpAddr, 22),
14994                                 false, false, 0);
14995
14996     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14997   } else {
14998     const Function *Func =
14999       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15000     CallingConv::ID CC = Func->getCallingConv();
15001     unsigned NestReg;
15002
15003     switch (CC) {
15004     default:
15005       llvm_unreachable("Unsupported calling convention");
15006     case CallingConv::C:
15007     case CallingConv::X86_StdCall: {
15008       // Pass 'nest' parameter in ECX.
15009       // Must be kept in sync with X86CallingConv.td
15010       NestReg = X86::ECX;
15011
15012       // Check that ECX wasn't needed by an 'inreg' parameter.
15013       FunctionType *FTy = Func->getFunctionType();
15014       const AttributeSet &Attrs = Func->getAttributes();
15015
15016       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15017         unsigned InRegCount = 0;
15018         unsigned Idx = 1;
15019
15020         for (FunctionType::param_iterator I = FTy->param_begin(),
15021              E = FTy->param_end(); I != E; ++I, ++Idx)
15022           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15023             // FIXME: should only count parameters that are lowered to integers.
15024             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15025
15026         if (InRegCount > 2) {
15027           report_fatal_error("Nest register in use - reduce number of inreg"
15028                              " parameters!");
15029         }
15030       }
15031       break;
15032     }
15033     case CallingConv::X86_FastCall:
15034     case CallingConv::X86_ThisCall:
15035     case CallingConv::Fast:
15036       // Pass 'nest' parameter in EAX.
15037       // Must be kept in sync with X86CallingConv.td
15038       NestReg = X86::EAX;
15039       break;
15040     }
15041
15042     SDValue OutChains[4];
15043     SDValue Addr, Disp;
15044
15045     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15046                        DAG.getConstant(10, MVT::i32));
15047     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15048
15049     // This is storing the opcode for MOV32ri.
15050     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15051     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15052     OutChains[0] = DAG.getStore(Root, dl,
15053                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15054                                 Trmp, MachinePointerInfo(TrmpAddr),
15055                                 false, false, 0);
15056
15057     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15058                        DAG.getConstant(1, MVT::i32));
15059     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15060                                 MachinePointerInfo(TrmpAddr, 1),
15061                                 false, false, 1);
15062
15063     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15064     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15065                        DAG.getConstant(5, MVT::i32));
15066     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15067                                 MachinePointerInfo(TrmpAddr, 5),
15068                                 false, false, 1);
15069
15070     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15071                        DAG.getConstant(6, MVT::i32));
15072     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15073                                 MachinePointerInfo(TrmpAddr, 6),
15074                                 false, false, 1);
15075
15076     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15077   }
15078 }
15079
15080 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15081                                             SelectionDAG &DAG) const {
15082   /*
15083    The rounding mode is in bits 11:10 of FPSR, and has the following
15084    settings:
15085      00 Round to nearest
15086      01 Round to -inf
15087      10 Round to +inf
15088      11 Round to 0
15089
15090   FLT_ROUNDS, on the other hand, expects the following:
15091     -1 Undefined
15092      0 Round to 0
15093      1 Round to nearest
15094      2 Round to +inf
15095      3 Round to -inf
15096
15097   To perform the conversion, we do:
15098     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15099   */
15100
15101   MachineFunction &MF = DAG.getMachineFunction();
15102   const TargetMachine &TM = MF.getTarget();
15103   const TargetFrameLowering &TFI = *TM.getFrameLowering();
15104   unsigned StackAlignment = TFI.getStackAlignment();
15105   MVT VT = Op.getSimpleValueType();
15106   SDLoc DL(Op);
15107
15108   // Save FP Control Word to stack slot
15109   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15110   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15111
15112   MachineMemOperand *MMO =
15113    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15114                            MachineMemOperand::MOStore, 2, 2);
15115
15116   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15117   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15118                                           DAG.getVTList(MVT::Other),
15119                                           Ops, MVT::i16, MMO);
15120
15121   // Load FP Control Word from stack slot
15122   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15123                             MachinePointerInfo(), false, false, false, 0);
15124
15125   // Transform as necessary
15126   SDValue CWD1 =
15127     DAG.getNode(ISD::SRL, DL, MVT::i16,
15128                 DAG.getNode(ISD::AND, DL, MVT::i16,
15129                             CWD, DAG.getConstant(0x800, MVT::i16)),
15130                 DAG.getConstant(11, MVT::i8));
15131   SDValue CWD2 =
15132     DAG.getNode(ISD::SRL, DL, MVT::i16,
15133                 DAG.getNode(ISD::AND, DL, MVT::i16,
15134                             CWD, DAG.getConstant(0x400, MVT::i16)),
15135                 DAG.getConstant(9, MVT::i8));
15136
15137   SDValue RetVal =
15138     DAG.getNode(ISD::AND, DL, MVT::i16,
15139                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15140                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15141                             DAG.getConstant(1, MVT::i16)),
15142                 DAG.getConstant(3, MVT::i16));
15143
15144   return DAG.getNode((VT.getSizeInBits() < 16 ?
15145                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15146 }
15147
15148 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15149   MVT VT = Op.getSimpleValueType();
15150   EVT OpVT = VT;
15151   unsigned NumBits = VT.getSizeInBits();
15152   SDLoc dl(Op);
15153
15154   Op = Op.getOperand(0);
15155   if (VT == MVT::i8) {
15156     // Zero extend to i32 since there is not an i8 bsr.
15157     OpVT = MVT::i32;
15158     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15159   }
15160
15161   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15162   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15163   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15164
15165   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15166   SDValue Ops[] = {
15167     Op,
15168     DAG.getConstant(NumBits+NumBits-1, OpVT),
15169     DAG.getConstant(X86::COND_E, MVT::i8),
15170     Op.getValue(1)
15171   };
15172   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15173
15174   // Finally xor with NumBits-1.
15175   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15176
15177   if (VT == MVT::i8)
15178     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15179   return Op;
15180 }
15181
15182 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15183   MVT VT = Op.getSimpleValueType();
15184   EVT OpVT = VT;
15185   unsigned NumBits = VT.getSizeInBits();
15186   SDLoc dl(Op);
15187
15188   Op = Op.getOperand(0);
15189   if (VT == MVT::i8) {
15190     // Zero extend to i32 since there is not an i8 bsr.
15191     OpVT = MVT::i32;
15192     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15193   }
15194
15195   // Issue a bsr (scan bits in reverse).
15196   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15197   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15198
15199   // And xor with NumBits-1.
15200   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15201
15202   if (VT == MVT::i8)
15203     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15204   return Op;
15205 }
15206
15207 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15208   MVT VT = Op.getSimpleValueType();
15209   unsigned NumBits = VT.getSizeInBits();
15210   SDLoc dl(Op);
15211   Op = Op.getOperand(0);
15212
15213   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15214   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15215   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15216
15217   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15218   SDValue Ops[] = {
15219     Op,
15220     DAG.getConstant(NumBits, VT),
15221     DAG.getConstant(X86::COND_E, MVT::i8),
15222     Op.getValue(1)
15223   };
15224   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15225 }
15226
15227 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15228 // ones, and then concatenate the result back.
15229 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15230   MVT VT = Op.getSimpleValueType();
15231
15232   assert(VT.is256BitVector() && VT.isInteger() &&
15233          "Unsupported value type for operation");
15234
15235   unsigned NumElems = VT.getVectorNumElements();
15236   SDLoc dl(Op);
15237
15238   // Extract the LHS vectors
15239   SDValue LHS = Op.getOperand(0);
15240   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15241   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15242
15243   // Extract the RHS vectors
15244   SDValue RHS = Op.getOperand(1);
15245   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15246   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15247
15248   MVT EltVT = VT.getVectorElementType();
15249   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15250
15251   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15252                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15253                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15254 }
15255
15256 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15257   assert(Op.getSimpleValueType().is256BitVector() &&
15258          Op.getSimpleValueType().isInteger() &&
15259          "Only handle AVX 256-bit vector integer operation");
15260   return Lower256IntArith(Op, DAG);
15261 }
15262
15263 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15264   assert(Op.getSimpleValueType().is256BitVector() &&
15265          Op.getSimpleValueType().isInteger() &&
15266          "Only handle AVX 256-bit vector integer operation");
15267   return Lower256IntArith(Op, DAG);
15268 }
15269
15270 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15271                         SelectionDAG &DAG) {
15272   SDLoc dl(Op);
15273   MVT VT = Op.getSimpleValueType();
15274
15275   // Decompose 256-bit ops into smaller 128-bit ops.
15276   if (VT.is256BitVector() && !Subtarget->hasInt256())
15277     return Lower256IntArith(Op, DAG);
15278
15279   SDValue A = Op.getOperand(0);
15280   SDValue B = Op.getOperand(1);
15281
15282   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15283   if (VT == MVT::v4i32) {
15284     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15285            "Should not custom lower when pmuldq is available!");
15286
15287     // Extract the odd parts.
15288     static const int UnpackMask[] = { 1, -1, 3, -1 };
15289     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15290     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15291
15292     // Multiply the even parts.
15293     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15294     // Now multiply odd parts.
15295     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15296
15297     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15298     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15299
15300     // Merge the two vectors back together with a shuffle. This expands into 2
15301     // shuffles.
15302     static const int ShufMask[] = { 0, 4, 2, 6 };
15303     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15304   }
15305
15306   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15307          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15308
15309   //  Ahi = psrlqi(a, 32);
15310   //  Bhi = psrlqi(b, 32);
15311   //
15312   //  AloBlo = pmuludq(a, b);
15313   //  AloBhi = pmuludq(a, Bhi);
15314   //  AhiBlo = pmuludq(Ahi, b);
15315
15316   //  AloBhi = psllqi(AloBhi, 32);
15317   //  AhiBlo = psllqi(AhiBlo, 32);
15318   //  return AloBlo + AloBhi + AhiBlo;
15319
15320   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15321   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15322
15323   // Bit cast to 32-bit vectors for MULUDQ
15324   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15325                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15326   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15327   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15328   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15329   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15330
15331   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15332   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15333   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15334
15335   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15336   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15337
15338   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15339   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15340 }
15341
15342 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15343   assert(Subtarget->isTargetWin64() && "Unexpected target");
15344   EVT VT = Op.getValueType();
15345   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15346          "Unexpected return type for lowering");
15347
15348   RTLIB::Libcall LC;
15349   bool isSigned;
15350   switch (Op->getOpcode()) {
15351   default: llvm_unreachable("Unexpected request for libcall!");
15352   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15353   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15354   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15355   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15356   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15357   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15358   }
15359
15360   SDLoc dl(Op);
15361   SDValue InChain = DAG.getEntryNode();
15362
15363   TargetLowering::ArgListTy Args;
15364   TargetLowering::ArgListEntry Entry;
15365   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15366     EVT ArgVT = Op->getOperand(i).getValueType();
15367     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15368            "Unexpected argument type for lowering");
15369     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15370     Entry.Node = StackPtr;
15371     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15372                            false, false, 16);
15373     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15374     Entry.Ty = PointerType::get(ArgTy,0);
15375     Entry.isSExt = false;
15376     Entry.isZExt = false;
15377     Args.push_back(Entry);
15378   }
15379
15380   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15381                                          getPointerTy());
15382
15383   TargetLowering::CallLoweringInfo CLI(DAG);
15384   CLI.setDebugLoc(dl).setChain(InChain)
15385     .setCallee(getLibcallCallingConv(LC),
15386                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15387                Callee, std::move(Args), 0)
15388     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15389
15390   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15391   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15392 }
15393
15394 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15395                              SelectionDAG &DAG) {
15396   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15397   EVT VT = Op0.getValueType();
15398   SDLoc dl(Op);
15399
15400   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15401          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15402
15403   // PMULxD operations multiply each even value (starting at 0) of LHS with
15404   // the related value of RHS and produce a widen result.
15405   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15406   // => <2 x i64> <ae|cg>
15407   //
15408   // In other word, to have all the results, we need to perform two PMULxD:
15409   // 1. one with the even values.
15410   // 2. one with the odd values.
15411   // To achieve #2, with need to place the odd values at an even position.
15412   //
15413   // Place the odd value at an even position (basically, shift all values 1
15414   // step to the left):
15415   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15416   // <a|b|c|d> => <b|undef|d|undef>
15417   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15418   // <e|f|g|h> => <f|undef|h|undef>
15419   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15420
15421   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15422   // ints.
15423   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15424   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15425   unsigned Opcode =
15426       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15427   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15428   // => <2 x i64> <ae|cg>
15429   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15430                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15431   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15432   // => <2 x i64> <bf|dh>
15433   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15434                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15435
15436   // Shuffle it back into the right order.
15437   SDValue Highs, Lows;
15438   if (VT == MVT::v8i32) {
15439     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15440     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15441     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15442     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15443   } else {
15444     const int HighMask[] = {1, 5, 3, 7};
15445     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15446     const int LowMask[] = {1, 4, 2, 6};
15447     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15448   }
15449
15450   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15451   // unsigned multiply.
15452   if (IsSigned && !Subtarget->hasSSE41()) {
15453     SDValue ShAmt =
15454         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15455     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15456                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15457     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15458                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15459
15460     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15461     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15462   }
15463
15464   // The first result of MUL_LOHI is actually the low value, followed by the
15465   // high value.
15466   SDValue Ops[] = {Lows, Highs};
15467   return DAG.getMergeValues(Ops, dl);
15468 }
15469
15470 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15471                                          const X86Subtarget *Subtarget) {
15472   MVT VT = Op.getSimpleValueType();
15473   SDLoc dl(Op);
15474   SDValue R = Op.getOperand(0);
15475   SDValue Amt = Op.getOperand(1);
15476
15477   // Optimize shl/srl/sra with constant shift amount.
15478   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15479     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15480       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15481
15482       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15483           (Subtarget->hasInt256() &&
15484            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15485           (Subtarget->hasAVX512() &&
15486            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15487         if (Op.getOpcode() == ISD::SHL)
15488           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15489                                             DAG);
15490         if (Op.getOpcode() == ISD::SRL)
15491           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15492                                             DAG);
15493         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15494           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15495                                             DAG);
15496       }
15497
15498       if (VT == MVT::v16i8) {
15499         if (Op.getOpcode() == ISD::SHL) {
15500           // Make a large shift.
15501           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15502                                                    MVT::v8i16, R, ShiftAmt,
15503                                                    DAG);
15504           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15505           // Zero out the rightmost bits.
15506           SmallVector<SDValue, 16> V(16,
15507                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15508                                                      MVT::i8));
15509           return DAG.getNode(ISD::AND, dl, VT, SHL,
15510                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15511         }
15512         if (Op.getOpcode() == ISD::SRL) {
15513           // Make a large shift.
15514           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15515                                                    MVT::v8i16, R, ShiftAmt,
15516                                                    DAG);
15517           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15518           // Zero out the leftmost bits.
15519           SmallVector<SDValue, 16> V(16,
15520                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15521                                                      MVT::i8));
15522           return DAG.getNode(ISD::AND, dl, VT, SRL,
15523                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15524         }
15525         if (Op.getOpcode() == ISD::SRA) {
15526           if (ShiftAmt == 7) {
15527             // R s>> 7  ===  R s< 0
15528             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15529             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15530           }
15531
15532           // R s>> a === ((R u>> a) ^ m) - m
15533           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15534           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15535                                                          MVT::i8));
15536           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15537           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15538           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15539           return Res;
15540         }
15541         llvm_unreachable("Unknown shift opcode.");
15542       }
15543
15544       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15545         if (Op.getOpcode() == ISD::SHL) {
15546           // Make a large shift.
15547           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15548                                                    MVT::v16i16, R, ShiftAmt,
15549                                                    DAG);
15550           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15551           // Zero out the rightmost bits.
15552           SmallVector<SDValue, 32> V(32,
15553                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15554                                                      MVT::i8));
15555           return DAG.getNode(ISD::AND, dl, VT, SHL,
15556                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15557         }
15558         if (Op.getOpcode() == ISD::SRL) {
15559           // Make a large shift.
15560           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15561                                                    MVT::v16i16, R, ShiftAmt,
15562                                                    DAG);
15563           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15564           // Zero out the leftmost bits.
15565           SmallVector<SDValue, 32> V(32,
15566                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15567                                                      MVT::i8));
15568           return DAG.getNode(ISD::AND, dl, VT, SRL,
15569                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15570         }
15571         if (Op.getOpcode() == ISD::SRA) {
15572           if (ShiftAmt == 7) {
15573             // R s>> 7  ===  R s< 0
15574             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15575             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15576           }
15577
15578           // R s>> a === ((R u>> a) ^ m) - m
15579           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15580           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15581                                                          MVT::i8));
15582           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15583           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15584           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15585           return Res;
15586         }
15587         llvm_unreachable("Unknown shift opcode.");
15588       }
15589     }
15590   }
15591
15592   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15593   if (!Subtarget->is64Bit() &&
15594       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15595       Amt.getOpcode() == ISD::BITCAST &&
15596       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15597     Amt = Amt.getOperand(0);
15598     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15599                      VT.getVectorNumElements();
15600     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15601     uint64_t ShiftAmt = 0;
15602     for (unsigned i = 0; i != Ratio; ++i) {
15603       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15604       if (!C)
15605         return SDValue();
15606       // 6 == Log2(64)
15607       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15608     }
15609     // Check remaining shift amounts.
15610     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15611       uint64_t ShAmt = 0;
15612       for (unsigned j = 0; j != Ratio; ++j) {
15613         ConstantSDNode *C =
15614           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15615         if (!C)
15616           return SDValue();
15617         // 6 == Log2(64)
15618         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15619       }
15620       if (ShAmt != ShiftAmt)
15621         return SDValue();
15622     }
15623     switch (Op.getOpcode()) {
15624     default:
15625       llvm_unreachable("Unknown shift opcode!");
15626     case ISD::SHL:
15627       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15628                                         DAG);
15629     case ISD::SRL:
15630       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15631                                         DAG);
15632     case ISD::SRA:
15633       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15634                                         DAG);
15635     }
15636   }
15637
15638   return SDValue();
15639 }
15640
15641 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15642                                         const X86Subtarget* Subtarget) {
15643   MVT VT = Op.getSimpleValueType();
15644   SDLoc dl(Op);
15645   SDValue R = Op.getOperand(0);
15646   SDValue Amt = Op.getOperand(1);
15647
15648   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15649       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15650       (Subtarget->hasInt256() &&
15651        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15652         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15653        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15654     SDValue BaseShAmt;
15655     EVT EltVT = VT.getVectorElementType();
15656
15657     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15658       unsigned NumElts = VT.getVectorNumElements();
15659       unsigned i, j;
15660       for (i = 0; i != NumElts; ++i) {
15661         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15662           continue;
15663         break;
15664       }
15665       for (j = i; j != NumElts; ++j) {
15666         SDValue Arg = Amt.getOperand(j);
15667         if (Arg.getOpcode() == ISD::UNDEF) continue;
15668         if (Arg != Amt.getOperand(i))
15669           break;
15670       }
15671       if (i != NumElts && j == NumElts)
15672         BaseShAmt = Amt.getOperand(i);
15673     } else {
15674       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15675         Amt = Amt.getOperand(0);
15676       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15677                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15678         SDValue InVec = Amt.getOperand(0);
15679         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15680           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15681           unsigned i = 0;
15682           for (; i != NumElts; ++i) {
15683             SDValue Arg = InVec.getOperand(i);
15684             if (Arg.getOpcode() == ISD::UNDEF) continue;
15685             BaseShAmt = Arg;
15686             break;
15687           }
15688         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15689            if (ConstantSDNode *C =
15690                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15691              unsigned SplatIdx =
15692                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15693              if (C->getZExtValue() == SplatIdx)
15694                BaseShAmt = InVec.getOperand(1);
15695            }
15696         }
15697         if (!BaseShAmt.getNode())
15698           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15699                                   DAG.getIntPtrConstant(0));
15700       }
15701     }
15702
15703     if (BaseShAmt.getNode()) {
15704       if (EltVT.bitsGT(MVT::i32))
15705         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15706       else if (EltVT.bitsLT(MVT::i32))
15707         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15708
15709       switch (Op.getOpcode()) {
15710       default:
15711         llvm_unreachable("Unknown shift opcode!");
15712       case ISD::SHL:
15713         switch (VT.SimpleTy) {
15714         default: return SDValue();
15715         case MVT::v2i64:
15716         case MVT::v4i32:
15717         case MVT::v8i16:
15718         case MVT::v4i64:
15719         case MVT::v8i32:
15720         case MVT::v16i16:
15721         case MVT::v16i32:
15722         case MVT::v8i64:
15723           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15724         }
15725       case ISD::SRA:
15726         switch (VT.SimpleTy) {
15727         default: return SDValue();
15728         case MVT::v4i32:
15729         case MVT::v8i16:
15730         case MVT::v8i32:
15731         case MVT::v16i16:
15732         case MVT::v16i32:
15733         case MVT::v8i64:
15734           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15735         }
15736       case ISD::SRL:
15737         switch (VT.SimpleTy) {
15738         default: return SDValue();
15739         case MVT::v2i64:
15740         case MVT::v4i32:
15741         case MVT::v8i16:
15742         case MVT::v4i64:
15743         case MVT::v8i32:
15744         case MVT::v16i16:
15745         case MVT::v16i32:
15746         case MVT::v8i64:
15747           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15748         }
15749       }
15750     }
15751   }
15752
15753   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15754   if (!Subtarget->is64Bit() &&
15755       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15756       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15757       Amt.getOpcode() == ISD::BITCAST &&
15758       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15759     Amt = Amt.getOperand(0);
15760     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15761                      VT.getVectorNumElements();
15762     std::vector<SDValue> Vals(Ratio);
15763     for (unsigned i = 0; i != Ratio; ++i)
15764       Vals[i] = Amt.getOperand(i);
15765     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15766       for (unsigned j = 0; j != Ratio; ++j)
15767         if (Vals[j] != Amt.getOperand(i + j))
15768           return SDValue();
15769     }
15770     switch (Op.getOpcode()) {
15771     default:
15772       llvm_unreachable("Unknown shift opcode!");
15773     case ISD::SHL:
15774       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15775     case ISD::SRL:
15776       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15777     case ISD::SRA:
15778       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15779     }
15780   }
15781
15782   return SDValue();
15783 }
15784
15785 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15786                           SelectionDAG &DAG) {
15787   MVT VT = Op.getSimpleValueType();
15788   SDLoc dl(Op);
15789   SDValue R = Op.getOperand(0);
15790   SDValue Amt = Op.getOperand(1);
15791   SDValue V;
15792
15793   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15794   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15795
15796   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15797   if (V.getNode())
15798     return V;
15799
15800   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15801   if (V.getNode())
15802       return V;
15803
15804   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15805     return Op;
15806   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15807   if (Subtarget->hasInt256()) {
15808     if (Op.getOpcode() == ISD::SRL &&
15809         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15810          VT == MVT::v4i64 || VT == MVT::v8i32))
15811       return Op;
15812     if (Op.getOpcode() == ISD::SHL &&
15813         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15814          VT == MVT::v4i64 || VT == MVT::v8i32))
15815       return Op;
15816     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15817       return Op;
15818   }
15819
15820   // If possible, lower this packed shift into a vector multiply instead of
15821   // expanding it into a sequence of scalar shifts.
15822   // Do this only if the vector shift count is a constant build_vector.
15823   if (Op.getOpcode() == ISD::SHL && 
15824       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15825        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15826       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15827     SmallVector<SDValue, 8> Elts;
15828     EVT SVT = VT.getScalarType();
15829     unsigned SVTBits = SVT.getSizeInBits();
15830     const APInt &One = APInt(SVTBits, 1);
15831     unsigned NumElems = VT.getVectorNumElements();
15832
15833     for (unsigned i=0; i !=NumElems; ++i) {
15834       SDValue Op = Amt->getOperand(i);
15835       if (Op->getOpcode() == ISD::UNDEF) {
15836         Elts.push_back(Op);
15837         continue;
15838       }
15839
15840       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15841       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15842       uint64_t ShAmt = C.getZExtValue();
15843       if (ShAmt >= SVTBits) {
15844         Elts.push_back(DAG.getUNDEF(SVT));
15845         continue;
15846       }
15847       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15848     }
15849     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15850     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15851   }
15852
15853   // Lower SHL with variable shift amount.
15854   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15855     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15856
15857     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15858     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15859     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15860     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15861   }
15862
15863   // If possible, lower this shift as a sequence of two shifts by
15864   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15865   // Example:
15866   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15867   //
15868   // Could be rewritten as:
15869   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15870   //
15871   // The advantage is that the two shifts from the example would be
15872   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15873   // the vector shift into four scalar shifts plus four pairs of vector
15874   // insert/extract.
15875   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15876       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15877     unsigned TargetOpcode = X86ISD::MOVSS;
15878     bool CanBeSimplified;
15879     // The splat value for the first packed shift (the 'X' from the example).
15880     SDValue Amt1 = Amt->getOperand(0);
15881     // The splat value for the second packed shift (the 'Y' from the example).
15882     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15883                                         Amt->getOperand(2);
15884
15885     // See if it is possible to replace this node with a sequence of
15886     // two shifts followed by a MOVSS/MOVSD
15887     if (VT == MVT::v4i32) {
15888       // Check if it is legal to use a MOVSS.
15889       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15890                         Amt2 == Amt->getOperand(3);
15891       if (!CanBeSimplified) {
15892         // Otherwise, check if we can still simplify this node using a MOVSD.
15893         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15894                           Amt->getOperand(2) == Amt->getOperand(3);
15895         TargetOpcode = X86ISD::MOVSD;
15896         Amt2 = Amt->getOperand(2);
15897       }
15898     } else {
15899       // Do similar checks for the case where the machine value type
15900       // is MVT::v8i16.
15901       CanBeSimplified = Amt1 == Amt->getOperand(1);
15902       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15903         CanBeSimplified = Amt2 == Amt->getOperand(i);
15904
15905       if (!CanBeSimplified) {
15906         TargetOpcode = X86ISD::MOVSD;
15907         CanBeSimplified = true;
15908         Amt2 = Amt->getOperand(4);
15909         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15910           CanBeSimplified = Amt1 == Amt->getOperand(i);
15911         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15912           CanBeSimplified = Amt2 == Amt->getOperand(j);
15913       }
15914     }
15915     
15916     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15917         isa<ConstantSDNode>(Amt2)) {
15918       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15919       EVT CastVT = MVT::v4i32;
15920       SDValue Splat1 = 
15921         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15922       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15923       SDValue Splat2 = 
15924         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15925       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15926       if (TargetOpcode == X86ISD::MOVSD)
15927         CastVT = MVT::v2i64;
15928       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15929       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15930       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15931                                             BitCast1, DAG);
15932       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15933     }
15934   }
15935
15936   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15937     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15938
15939     // a = a << 5;
15940     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15941     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15942
15943     // Turn 'a' into a mask suitable for VSELECT
15944     SDValue VSelM = DAG.getConstant(0x80, VT);
15945     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15946     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15947
15948     SDValue CM1 = DAG.getConstant(0x0f, VT);
15949     SDValue CM2 = DAG.getConstant(0x3f, VT);
15950
15951     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15952     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15953     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15954     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15955     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15956
15957     // a += a
15958     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15959     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15960     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15961
15962     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15963     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15964     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15965     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15966     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15967
15968     // a += a
15969     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15970     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15971     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15972
15973     // return VSELECT(r, r+r, a);
15974     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15975                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15976     return R;
15977   }
15978
15979   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15980   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15981   // solution better.
15982   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15983     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15984     unsigned ExtOpc =
15985         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15986     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15987     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15988     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15989                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15990     }
15991
15992   // Decompose 256-bit shifts into smaller 128-bit shifts.
15993   if (VT.is256BitVector()) {
15994     unsigned NumElems = VT.getVectorNumElements();
15995     MVT EltVT = VT.getVectorElementType();
15996     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15997
15998     // Extract the two vectors
15999     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16000     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16001
16002     // Recreate the shift amount vectors
16003     SDValue Amt1, Amt2;
16004     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16005       // Constant shift amount
16006       SmallVector<SDValue, 4> Amt1Csts;
16007       SmallVector<SDValue, 4> Amt2Csts;
16008       for (unsigned i = 0; i != NumElems/2; ++i)
16009         Amt1Csts.push_back(Amt->getOperand(i));
16010       for (unsigned i = NumElems/2; i != NumElems; ++i)
16011         Amt2Csts.push_back(Amt->getOperand(i));
16012
16013       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16014       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16015     } else {
16016       // Variable shift amount
16017       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16018       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16019     }
16020
16021     // Issue new vector shifts for the smaller types
16022     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16023     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16024
16025     // Concatenate the result back
16026     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16027   }
16028
16029   return SDValue();
16030 }
16031
16032 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16033   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16034   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16035   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16036   // has only one use.
16037   SDNode *N = Op.getNode();
16038   SDValue LHS = N->getOperand(0);
16039   SDValue RHS = N->getOperand(1);
16040   unsigned BaseOp = 0;
16041   unsigned Cond = 0;
16042   SDLoc DL(Op);
16043   switch (Op.getOpcode()) {
16044   default: llvm_unreachable("Unknown ovf instruction!");
16045   case ISD::SADDO:
16046     // A subtract of one will be selected as a INC. Note that INC doesn't
16047     // set CF, so we can't do this for UADDO.
16048     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16049       if (C->isOne()) {
16050         BaseOp = X86ISD::INC;
16051         Cond = X86::COND_O;
16052         break;
16053       }
16054     BaseOp = X86ISD::ADD;
16055     Cond = X86::COND_O;
16056     break;
16057   case ISD::UADDO:
16058     BaseOp = X86ISD::ADD;
16059     Cond = X86::COND_B;
16060     break;
16061   case ISD::SSUBO:
16062     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16063     // set CF, so we can't do this for USUBO.
16064     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16065       if (C->isOne()) {
16066         BaseOp = X86ISD::DEC;
16067         Cond = X86::COND_O;
16068         break;
16069       }
16070     BaseOp = X86ISD::SUB;
16071     Cond = X86::COND_O;
16072     break;
16073   case ISD::USUBO:
16074     BaseOp = X86ISD::SUB;
16075     Cond = X86::COND_B;
16076     break;
16077   case ISD::SMULO:
16078     BaseOp = X86ISD::SMUL;
16079     Cond = X86::COND_O;
16080     break;
16081   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16082     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16083                                  MVT::i32);
16084     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16085
16086     SDValue SetCC =
16087       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16088                   DAG.getConstant(X86::COND_O, MVT::i32),
16089                   SDValue(Sum.getNode(), 2));
16090
16091     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16092   }
16093   }
16094
16095   // Also sets EFLAGS.
16096   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16097   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16098
16099   SDValue SetCC =
16100     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16101                 DAG.getConstant(Cond, MVT::i32),
16102                 SDValue(Sum.getNode(), 1));
16103
16104   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16105 }
16106
16107 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16108                                                   SelectionDAG &DAG) const {
16109   SDLoc dl(Op);
16110   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16111   MVT VT = Op.getSimpleValueType();
16112
16113   if (!Subtarget->hasSSE2() || !VT.isVector())
16114     return SDValue();
16115
16116   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16117                       ExtraVT.getScalarType().getSizeInBits();
16118
16119   switch (VT.SimpleTy) {
16120     default: return SDValue();
16121     case MVT::v8i32:
16122     case MVT::v16i16:
16123       if (!Subtarget->hasFp256())
16124         return SDValue();
16125       if (!Subtarget->hasInt256()) {
16126         // needs to be split
16127         unsigned NumElems = VT.getVectorNumElements();
16128
16129         // Extract the LHS vectors
16130         SDValue LHS = Op.getOperand(0);
16131         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16132         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16133
16134         MVT EltVT = VT.getVectorElementType();
16135         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16136
16137         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16138         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16139         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16140                                    ExtraNumElems/2);
16141         SDValue Extra = DAG.getValueType(ExtraVT);
16142
16143         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16144         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16145
16146         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16147       }
16148       // fall through
16149     case MVT::v4i32:
16150     case MVT::v8i16: {
16151       SDValue Op0 = Op.getOperand(0);
16152       SDValue Op00 = Op0.getOperand(0);
16153       SDValue Tmp1;
16154       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16155       if (Op0.getOpcode() == ISD::BITCAST &&
16156           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16157         // (sext (vzext x)) -> (vsext x)
16158         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16159         if (Tmp1.getNode()) {
16160           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16161           // This folding is only valid when the in-reg type is a vector of i8,
16162           // i16, or i32.
16163           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16164               ExtraEltVT == MVT::i32) {
16165             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16166             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16167                    "This optimization is invalid without a VZEXT.");
16168             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16169           }
16170           Op0 = Tmp1;
16171         }
16172       }
16173
16174       // If the above didn't work, then just use Shift-Left + Shift-Right.
16175       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16176                                         DAG);
16177       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16178                                         DAG);
16179     }
16180   }
16181 }
16182
16183 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16184                                  SelectionDAG &DAG) {
16185   SDLoc dl(Op);
16186   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16187     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16188   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16189     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16190
16191   // The only fence that needs an instruction is a sequentially-consistent
16192   // cross-thread fence.
16193   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16194     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16195     // no-sse2). There isn't any reason to disable it if the target processor
16196     // supports it.
16197     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16198       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16199
16200     SDValue Chain = Op.getOperand(0);
16201     SDValue Zero = DAG.getConstant(0, MVT::i32);
16202     SDValue Ops[] = {
16203       DAG.getRegister(X86::ESP, MVT::i32), // Base
16204       DAG.getTargetConstant(1, MVT::i8),   // Scale
16205       DAG.getRegister(0, MVT::i32),        // Index
16206       DAG.getTargetConstant(0, MVT::i32),  // Disp
16207       DAG.getRegister(0, MVT::i32),        // Segment.
16208       Zero,
16209       Chain
16210     };
16211     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16212     return SDValue(Res, 0);
16213   }
16214
16215   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16216   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16217 }
16218
16219 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16220                              SelectionDAG &DAG) {
16221   MVT T = Op.getSimpleValueType();
16222   SDLoc DL(Op);
16223   unsigned Reg = 0;
16224   unsigned size = 0;
16225   switch(T.SimpleTy) {
16226   default: llvm_unreachable("Invalid value type!");
16227   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16228   case MVT::i16: Reg = X86::AX;  size = 2; break;
16229   case MVT::i32: Reg = X86::EAX; size = 4; break;
16230   case MVT::i64:
16231     assert(Subtarget->is64Bit() && "Node not type legal!");
16232     Reg = X86::RAX; size = 8;
16233     break;
16234   }
16235   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16236                                   Op.getOperand(2), SDValue());
16237   SDValue Ops[] = { cpIn.getValue(0),
16238                     Op.getOperand(1),
16239                     Op.getOperand(3),
16240                     DAG.getTargetConstant(size, MVT::i8),
16241                     cpIn.getValue(1) };
16242   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16243   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16244   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16245                                            Ops, T, MMO);
16246
16247   SDValue cpOut =
16248     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16249   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16250                                       MVT::i32, cpOut.getValue(2));
16251   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16252                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16253
16254   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16255   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16256   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16257   return SDValue();
16258 }
16259
16260 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16261                             SelectionDAG &DAG) {
16262   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16263   MVT DstVT = Op.getSimpleValueType();
16264
16265   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16266     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16267     if (DstVT != MVT::f64)
16268       // This conversion needs to be expanded.
16269       return SDValue();
16270
16271     SDValue InVec = Op->getOperand(0);
16272     SDLoc dl(Op);
16273     unsigned NumElts = SrcVT.getVectorNumElements();
16274     EVT SVT = SrcVT.getVectorElementType();
16275
16276     // Widen the vector in input in the case of MVT::v2i32.
16277     // Example: from MVT::v2i32 to MVT::v4i32.
16278     SmallVector<SDValue, 16> Elts;
16279     for (unsigned i = 0, e = NumElts; i != e; ++i)
16280       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16281                                  DAG.getIntPtrConstant(i)));
16282
16283     // Explicitly mark the extra elements as Undef.
16284     SDValue Undef = DAG.getUNDEF(SVT);
16285     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16286       Elts.push_back(Undef);
16287
16288     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16289     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16290     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16291     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16292                        DAG.getIntPtrConstant(0));
16293   }
16294
16295   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16296          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16297   assert((DstVT == MVT::i64 ||
16298           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16299          "Unexpected custom BITCAST");
16300   // i64 <=> MMX conversions are Legal.
16301   if (SrcVT==MVT::i64 && DstVT.isVector())
16302     return Op;
16303   if (DstVT==MVT::i64 && SrcVT.isVector())
16304     return Op;
16305   // MMX <=> MMX conversions are Legal.
16306   if (SrcVT.isVector() && DstVT.isVector())
16307     return Op;
16308   // All other conversions need to be expanded.
16309   return SDValue();
16310 }
16311
16312 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16313   SDNode *Node = Op.getNode();
16314   SDLoc dl(Node);
16315   EVT T = Node->getValueType(0);
16316   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16317                               DAG.getConstant(0, T), Node->getOperand(2));
16318   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16319                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16320                        Node->getOperand(0),
16321                        Node->getOperand(1), negOp,
16322                        cast<AtomicSDNode>(Node)->getMemOperand(),
16323                        cast<AtomicSDNode>(Node)->getOrdering(),
16324                        cast<AtomicSDNode>(Node)->getSynchScope());
16325 }
16326
16327 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16328   SDNode *Node = Op.getNode();
16329   SDLoc dl(Node);
16330   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16331
16332   // Convert seq_cst store -> xchg
16333   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16334   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16335   //        (The only way to get a 16-byte store is cmpxchg16b)
16336   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16337   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16338       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16339     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16340                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16341                                  Node->getOperand(0),
16342                                  Node->getOperand(1), Node->getOperand(2),
16343                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16344                                  cast<AtomicSDNode>(Node)->getOrdering(),
16345                                  cast<AtomicSDNode>(Node)->getSynchScope());
16346     return Swap.getValue(1);
16347   }
16348   // Other atomic stores have a simple pattern.
16349   return Op;
16350 }
16351
16352 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16353   EVT VT = Op.getNode()->getSimpleValueType(0);
16354
16355   // Let legalize expand this if it isn't a legal type yet.
16356   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16357     return SDValue();
16358
16359   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16360
16361   unsigned Opc;
16362   bool ExtraOp = false;
16363   switch (Op.getOpcode()) {
16364   default: llvm_unreachable("Invalid code");
16365   case ISD::ADDC: Opc = X86ISD::ADD; break;
16366   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16367   case ISD::SUBC: Opc = X86ISD::SUB; break;
16368   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16369   }
16370
16371   if (!ExtraOp)
16372     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16373                        Op.getOperand(1));
16374   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16375                      Op.getOperand(1), Op.getOperand(2));
16376 }
16377
16378 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16379                             SelectionDAG &DAG) {
16380   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16381
16382   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16383   // which returns the values as { float, float } (in XMM0) or
16384   // { double, double } (which is returned in XMM0, XMM1).
16385   SDLoc dl(Op);
16386   SDValue Arg = Op.getOperand(0);
16387   EVT ArgVT = Arg.getValueType();
16388   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16389
16390   TargetLowering::ArgListTy Args;
16391   TargetLowering::ArgListEntry Entry;
16392
16393   Entry.Node = Arg;
16394   Entry.Ty = ArgTy;
16395   Entry.isSExt = false;
16396   Entry.isZExt = false;
16397   Args.push_back(Entry);
16398
16399   bool isF64 = ArgVT == MVT::f64;
16400   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16401   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16402   // the results are returned via SRet in memory.
16403   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16404   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16405   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16406
16407   Type *RetTy = isF64
16408     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16409     : (Type*)VectorType::get(ArgTy, 4);
16410
16411   TargetLowering::CallLoweringInfo CLI(DAG);
16412   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16413     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16414
16415   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16416
16417   if (isF64)
16418     // Returned in xmm0 and xmm1.
16419     return CallResult.first;
16420
16421   // Returned in bits 0:31 and 32:64 xmm0.
16422   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16423                                CallResult.first, DAG.getIntPtrConstant(0));
16424   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16425                                CallResult.first, DAG.getIntPtrConstant(1));
16426   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16427   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16428 }
16429
16430 /// LowerOperation - Provide custom lowering hooks for some operations.
16431 ///
16432 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16433   switch (Op.getOpcode()) {
16434   default: llvm_unreachable("Should not custom lower this!");
16435   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16436   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16437   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16438     return LowerCMP_SWAP(Op, Subtarget, DAG);
16439   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16440   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16441   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16442   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16443   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16444   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16445   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16446   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16447   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16448   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16449   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16450   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16451   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16452   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16453   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16454   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16455   case ISD::SHL_PARTS:
16456   case ISD::SRA_PARTS:
16457   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16458   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16459   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16460   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16461   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16462   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16463   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16464   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16465   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16466   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16467   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16468   case ISD::FABS:               return LowerFABS(Op, DAG);
16469   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16470   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16471   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16472   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16473   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16474   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16475   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16476   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16477   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16478   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16479   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16480   case ISD::INTRINSIC_VOID:
16481   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16482   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16483   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16484   case ISD::FRAME_TO_ARGS_OFFSET:
16485                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16486   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16487   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16488   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16489   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16490   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16491   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16492   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16493   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16494   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16495   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16496   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16497   case ISD::UMUL_LOHI:
16498   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16499   case ISD::SRA:
16500   case ISD::SRL:
16501   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16502   case ISD::SADDO:
16503   case ISD::UADDO:
16504   case ISD::SSUBO:
16505   case ISD::USUBO:
16506   case ISD::SMULO:
16507   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16508   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16509   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16510   case ISD::ADDC:
16511   case ISD::ADDE:
16512   case ISD::SUBC:
16513   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16514   case ISD::ADD:                return LowerADD(Op, DAG);
16515   case ISD::SUB:                return LowerSUB(Op, DAG);
16516   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16517   }
16518 }
16519
16520 static void ReplaceATOMIC_LOAD(SDNode *Node,
16521                                SmallVectorImpl<SDValue> &Results,
16522                                SelectionDAG &DAG) {
16523   SDLoc dl(Node);
16524   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16525
16526   // Convert wide load -> cmpxchg8b/cmpxchg16b
16527   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16528   //        (The only way to get a 16-byte load is cmpxchg16b)
16529   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16530   SDValue Zero = DAG.getConstant(0, VT);
16531   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16532   SDValue Swap =
16533       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16534                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16535                            cast<AtomicSDNode>(Node)->getMemOperand(),
16536                            cast<AtomicSDNode>(Node)->getOrdering(),
16537                            cast<AtomicSDNode>(Node)->getOrdering(),
16538                            cast<AtomicSDNode>(Node)->getSynchScope());
16539   Results.push_back(Swap.getValue(0));
16540   Results.push_back(Swap.getValue(2));
16541 }
16542
16543 /// ReplaceNodeResults - Replace a node with an illegal result type
16544 /// with a new node built out of custom code.
16545 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16546                                            SmallVectorImpl<SDValue>&Results,
16547                                            SelectionDAG &DAG) const {
16548   SDLoc dl(N);
16549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16550   switch (N->getOpcode()) {
16551   default:
16552     llvm_unreachable("Do not know how to custom type legalize this operation!");
16553   case ISD::SIGN_EXTEND_INREG:
16554   case ISD::ADDC:
16555   case ISD::ADDE:
16556   case ISD::SUBC:
16557   case ISD::SUBE:
16558     // We don't want to expand or promote these.
16559     return;
16560   case ISD::SDIV:
16561   case ISD::UDIV:
16562   case ISD::SREM:
16563   case ISD::UREM:
16564   case ISD::SDIVREM:
16565   case ISD::UDIVREM: {
16566     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16567     Results.push_back(V);
16568     return;
16569   }
16570   case ISD::FP_TO_SINT:
16571   case ISD::FP_TO_UINT: {
16572     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16573
16574     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16575       return;
16576
16577     std::pair<SDValue,SDValue> Vals =
16578         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16579     SDValue FIST = Vals.first, StackSlot = Vals.second;
16580     if (FIST.getNode()) {
16581       EVT VT = N->getValueType(0);
16582       // Return a load from the stack slot.
16583       if (StackSlot.getNode())
16584         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16585                                       MachinePointerInfo(),
16586                                       false, false, false, 0));
16587       else
16588         Results.push_back(FIST);
16589     }
16590     return;
16591   }
16592   case ISD::UINT_TO_FP: {
16593     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16594     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16595         N->getValueType(0) != MVT::v2f32)
16596       return;
16597     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16598                                  N->getOperand(0));
16599     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16600                                      MVT::f64);
16601     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16602     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16603                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16604     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16605     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16606     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16607     return;
16608   }
16609   case ISD::FP_ROUND: {
16610     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16611         return;
16612     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16613     Results.push_back(V);
16614     return;
16615   }
16616   case ISD::INTRINSIC_W_CHAIN: {
16617     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16618     switch (IntNo) {
16619     default : llvm_unreachable("Do not know how to custom type "
16620                                "legalize this intrinsic operation!");
16621     case Intrinsic::x86_rdtsc:
16622       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16623                                      Results);
16624     case Intrinsic::x86_rdtscp:
16625       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16626                                      Results);
16627     case Intrinsic::x86_rdpmc:
16628       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16629     }
16630   }
16631   case ISD::READCYCLECOUNTER: {
16632     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16633                                    Results);
16634   }
16635   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16636     EVT T = N->getValueType(0);
16637     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16638     bool Regs64bit = T == MVT::i128;
16639     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16640     SDValue cpInL, cpInH;
16641     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16642                         DAG.getConstant(0, HalfT));
16643     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16644                         DAG.getConstant(1, HalfT));
16645     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16646                              Regs64bit ? X86::RAX : X86::EAX,
16647                              cpInL, SDValue());
16648     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16649                              Regs64bit ? X86::RDX : X86::EDX,
16650                              cpInH, cpInL.getValue(1));
16651     SDValue swapInL, swapInH;
16652     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16653                           DAG.getConstant(0, HalfT));
16654     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16655                           DAG.getConstant(1, HalfT));
16656     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16657                                Regs64bit ? X86::RBX : X86::EBX,
16658                                swapInL, cpInH.getValue(1));
16659     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16660                                Regs64bit ? X86::RCX : X86::ECX,
16661                                swapInH, swapInL.getValue(1));
16662     SDValue Ops[] = { swapInH.getValue(0),
16663                       N->getOperand(1),
16664                       swapInH.getValue(1) };
16665     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16666     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16667     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16668                                   X86ISD::LCMPXCHG8_DAG;
16669     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16670     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16671                                         Regs64bit ? X86::RAX : X86::EAX,
16672                                         HalfT, Result.getValue(1));
16673     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16674                                         Regs64bit ? X86::RDX : X86::EDX,
16675                                         HalfT, cpOutL.getValue(2));
16676     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16677
16678     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16679                                         MVT::i32, cpOutH.getValue(2));
16680     SDValue Success =
16681         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16682                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16683     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16684
16685     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16686     Results.push_back(Success);
16687     Results.push_back(EFLAGS.getValue(1));
16688     return;
16689   }
16690   case ISD::ATOMIC_SWAP:
16691   case ISD::ATOMIC_LOAD_ADD:
16692   case ISD::ATOMIC_LOAD_SUB:
16693   case ISD::ATOMIC_LOAD_AND:
16694   case ISD::ATOMIC_LOAD_OR:
16695   case ISD::ATOMIC_LOAD_XOR:
16696   case ISD::ATOMIC_LOAD_NAND:
16697   case ISD::ATOMIC_LOAD_MIN:
16698   case ISD::ATOMIC_LOAD_MAX:
16699   case ISD::ATOMIC_LOAD_UMIN:
16700   case ISD::ATOMIC_LOAD_UMAX:
16701     // Delegate to generic TypeLegalization. Situations we can really handle
16702     // should have already been dealt with by X86AtomicExpand.cpp.
16703     break;
16704   case ISD::ATOMIC_LOAD: {
16705     ReplaceATOMIC_LOAD(N, Results, DAG);
16706     return;
16707   }
16708   case ISD::BITCAST: {
16709     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16710     EVT DstVT = N->getValueType(0);
16711     EVT SrcVT = N->getOperand(0)->getValueType(0);
16712
16713     if (SrcVT != MVT::f64 ||
16714         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16715       return;
16716
16717     unsigned NumElts = DstVT.getVectorNumElements();
16718     EVT SVT = DstVT.getVectorElementType();
16719     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16720     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16721                                    MVT::v2f64, N->getOperand(0));
16722     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16723
16724     if (ExperimentalVectorWideningLegalization) {
16725       // If we are legalizing vectors by widening, we already have the desired
16726       // legal vector type, just return it.
16727       Results.push_back(ToVecInt);
16728       return;
16729     }
16730
16731     SmallVector<SDValue, 8> Elts;
16732     for (unsigned i = 0, e = NumElts; i != e; ++i)
16733       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16734                                    ToVecInt, DAG.getIntPtrConstant(i)));
16735
16736     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16737   }
16738   }
16739 }
16740
16741 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16742   switch (Opcode) {
16743   default: return nullptr;
16744   case X86ISD::BSF:                return "X86ISD::BSF";
16745   case X86ISD::BSR:                return "X86ISD::BSR";
16746   case X86ISD::SHLD:               return "X86ISD::SHLD";
16747   case X86ISD::SHRD:               return "X86ISD::SHRD";
16748   case X86ISD::FAND:               return "X86ISD::FAND";
16749   case X86ISD::FANDN:              return "X86ISD::FANDN";
16750   case X86ISD::FOR:                return "X86ISD::FOR";
16751   case X86ISD::FXOR:               return "X86ISD::FXOR";
16752   case X86ISD::FSRL:               return "X86ISD::FSRL";
16753   case X86ISD::FILD:               return "X86ISD::FILD";
16754   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16755   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16756   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16757   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16758   case X86ISD::FLD:                return "X86ISD::FLD";
16759   case X86ISD::FST:                return "X86ISD::FST";
16760   case X86ISD::CALL:               return "X86ISD::CALL";
16761   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16762   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16763   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16764   case X86ISD::BT:                 return "X86ISD::BT";
16765   case X86ISD::CMP:                return "X86ISD::CMP";
16766   case X86ISD::COMI:               return "X86ISD::COMI";
16767   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16768   case X86ISD::CMPM:               return "X86ISD::CMPM";
16769   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16770   case X86ISD::SETCC:              return "X86ISD::SETCC";
16771   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16772   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16773   case X86ISD::CMOV:               return "X86ISD::CMOV";
16774   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16775   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16776   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16777   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16778   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16779   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16780   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16781   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16782   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16783   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16784   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16785   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16786   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16787   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16788   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16789   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16790   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16791   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16792   case X86ISD::HADD:               return "X86ISD::HADD";
16793   case X86ISD::HSUB:               return "X86ISD::HSUB";
16794   case X86ISD::FHADD:              return "X86ISD::FHADD";
16795   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16796   case X86ISD::UMAX:               return "X86ISD::UMAX";
16797   case X86ISD::UMIN:               return "X86ISD::UMIN";
16798   case X86ISD::SMAX:               return "X86ISD::SMAX";
16799   case X86ISD::SMIN:               return "X86ISD::SMIN";
16800   case X86ISD::FMAX:               return "X86ISD::FMAX";
16801   case X86ISD::FMIN:               return "X86ISD::FMIN";
16802   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16803   case X86ISD::FMINC:              return "X86ISD::FMINC";
16804   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16805   case X86ISD::FRCP:               return "X86ISD::FRCP";
16806   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16807   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16808   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16809   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16810   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16811   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16812   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16813   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16814   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16815   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16816   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16817   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16818   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16819   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16820   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16821   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16822   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16823   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16824   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16825   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16826   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16827   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16828   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16829   case X86ISD::VSHL:               return "X86ISD::VSHL";
16830   case X86ISD::VSRL:               return "X86ISD::VSRL";
16831   case X86ISD::VSRA:               return "X86ISD::VSRA";
16832   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16833   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16834   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16835   case X86ISD::CMPP:               return "X86ISD::CMPP";
16836   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16837   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16838   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16839   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16840   case X86ISD::ADD:                return "X86ISD::ADD";
16841   case X86ISD::SUB:                return "X86ISD::SUB";
16842   case X86ISD::ADC:                return "X86ISD::ADC";
16843   case X86ISD::SBB:                return "X86ISD::SBB";
16844   case X86ISD::SMUL:               return "X86ISD::SMUL";
16845   case X86ISD::UMUL:               return "X86ISD::UMUL";
16846   case X86ISD::INC:                return "X86ISD::INC";
16847   case X86ISD::DEC:                return "X86ISD::DEC";
16848   case X86ISD::OR:                 return "X86ISD::OR";
16849   case X86ISD::XOR:                return "X86ISD::XOR";
16850   case X86ISD::AND:                return "X86ISD::AND";
16851   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16852   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16853   case X86ISD::PTEST:              return "X86ISD::PTEST";
16854   case X86ISD::TESTP:              return "X86ISD::TESTP";
16855   case X86ISD::TESTM:              return "X86ISD::TESTM";
16856   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16857   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16858   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16859   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16860   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16861   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16862   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16863   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16864   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16865   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16866   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16867   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16868   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16869   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16870   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16871   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16872   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16873   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16874   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16875   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16876   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16877   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16878   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16879   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16880   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16881   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16882   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16883   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16884   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16885   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16886   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16887   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16888   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16889   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16890   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16891   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16892   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16893   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16894   case X86ISD::SAHF:               return "X86ISD::SAHF";
16895   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16896   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16897   case X86ISD::FMADD:              return "X86ISD::FMADD";
16898   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16899   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16900   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16901   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16902   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16903   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16904   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16905   case X86ISD::XTEST:              return "X86ISD::XTEST";
16906   }
16907 }
16908
16909 // isLegalAddressingMode - Return true if the addressing mode represented
16910 // by AM is legal for this target, for a load/store of the specified type.
16911 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16912                                               Type *Ty) const {
16913   // X86 supports extremely general addressing modes.
16914   CodeModel::Model M = getTargetMachine().getCodeModel();
16915   Reloc::Model R = getTargetMachine().getRelocationModel();
16916
16917   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16918   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16919     return false;
16920
16921   if (AM.BaseGV) {
16922     unsigned GVFlags =
16923       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16924
16925     // If a reference to this global requires an extra load, we can't fold it.
16926     if (isGlobalStubReference(GVFlags))
16927       return false;
16928
16929     // If BaseGV requires a register for the PIC base, we cannot also have a
16930     // BaseReg specified.
16931     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16932       return false;
16933
16934     // If lower 4G is not available, then we must use rip-relative addressing.
16935     if ((M != CodeModel::Small || R != Reloc::Static) &&
16936         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16937       return false;
16938   }
16939
16940   switch (AM.Scale) {
16941   case 0:
16942   case 1:
16943   case 2:
16944   case 4:
16945   case 8:
16946     // These scales always work.
16947     break;
16948   case 3:
16949   case 5:
16950   case 9:
16951     // These scales are formed with basereg+scalereg.  Only accept if there is
16952     // no basereg yet.
16953     if (AM.HasBaseReg)
16954       return false;
16955     break;
16956   default:  // Other stuff never works.
16957     return false;
16958   }
16959
16960   return true;
16961 }
16962
16963 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16964   unsigned Bits = Ty->getScalarSizeInBits();
16965
16966   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16967   // particularly cheaper than those without.
16968   if (Bits == 8)
16969     return false;
16970
16971   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16972   // variable shifts just as cheap as scalar ones.
16973   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16974     return false;
16975
16976   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16977   // fully general vector.
16978   return true;
16979 }
16980
16981 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16982   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16983     return false;
16984   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16985   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16986   return NumBits1 > NumBits2;
16987 }
16988
16989 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16990   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16991     return false;
16992
16993   if (!isTypeLegal(EVT::getEVT(Ty1)))
16994     return false;
16995
16996   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16997
16998   // Assuming the caller doesn't have a zeroext or signext return parameter,
16999   // truncation all the way down to i1 is valid.
17000   return true;
17001 }
17002
17003 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17004   return isInt<32>(Imm);
17005 }
17006
17007 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17008   // Can also use sub to handle negated immediates.
17009   return isInt<32>(Imm);
17010 }
17011
17012 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17013   if (!VT1.isInteger() || !VT2.isInteger())
17014     return false;
17015   unsigned NumBits1 = VT1.getSizeInBits();
17016   unsigned NumBits2 = VT2.getSizeInBits();
17017   return NumBits1 > NumBits2;
17018 }
17019
17020 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17021   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17022   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17023 }
17024
17025 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17026   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17027   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17028 }
17029
17030 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17031   EVT VT1 = Val.getValueType();
17032   if (isZExtFree(VT1, VT2))
17033     return true;
17034
17035   if (Val.getOpcode() != ISD::LOAD)
17036     return false;
17037
17038   if (!VT1.isSimple() || !VT1.isInteger() ||
17039       !VT2.isSimple() || !VT2.isInteger())
17040     return false;
17041
17042   switch (VT1.getSimpleVT().SimpleTy) {
17043   default: break;
17044   case MVT::i8:
17045   case MVT::i16:
17046   case MVT::i32:
17047     // X86 has 8, 16, and 32-bit zero-extending loads.
17048     return true;
17049   }
17050
17051   return false;
17052 }
17053
17054 bool
17055 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17056   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17057     return false;
17058
17059   VT = VT.getScalarType();
17060
17061   if (!VT.isSimple())
17062     return false;
17063
17064   switch (VT.getSimpleVT().SimpleTy) {
17065   case MVT::f32:
17066   case MVT::f64:
17067     return true;
17068   default:
17069     break;
17070   }
17071
17072   return false;
17073 }
17074
17075 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17076   // i16 instructions are longer (0x66 prefix) and potentially slower.
17077   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17078 }
17079
17080 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17081 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17082 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17083 /// are assumed to be legal.
17084 bool
17085 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17086                                       EVT VT) const {
17087   if (!VT.isSimple())
17088     return false;
17089
17090   MVT SVT = VT.getSimpleVT();
17091
17092   // Very little shuffling can be done for 64-bit vectors right now.
17093   if (VT.getSizeInBits() == 64)
17094     return false;
17095
17096   // If this is a single-input shuffle with no 128 bit lane crossings we can
17097   // lower it into pshufb.
17098   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17099       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17100     bool isLegal = true;
17101     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17102       if (M[I] >= (int)SVT.getVectorNumElements() ||
17103           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17104         isLegal = false;
17105         break;
17106       }
17107     }
17108     if (isLegal)
17109       return true;
17110   }
17111
17112   // FIXME: blends, shifts.
17113   return (SVT.getVectorNumElements() == 2 ||
17114           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17115           isMOVLMask(M, SVT) ||
17116           isMOVHLPSMask(M, SVT) ||
17117           isSHUFPMask(M, SVT) ||
17118           isPSHUFDMask(M, SVT) ||
17119           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17120           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17121           isPALIGNRMask(M, SVT, Subtarget) ||
17122           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17123           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17124           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17125           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17126           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17127 }
17128
17129 bool
17130 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17131                                           EVT VT) const {
17132   if (!VT.isSimple())
17133     return false;
17134
17135   MVT SVT = VT.getSimpleVT();
17136   unsigned NumElts = SVT.getVectorNumElements();
17137   // FIXME: This collection of masks seems suspect.
17138   if (NumElts == 2)
17139     return true;
17140   if (NumElts == 4 && SVT.is128BitVector()) {
17141     return (isMOVLMask(Mask, SVT)  ||
17142             isCommutedMOVLMask(Mask, SVT, true) ||
17143             isSHUFPMask(Mask, SVT) ||
17144             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17145   }
17146   return false;
17147 }
17148
17149 //===----------------------------------------------------------------------===//
17150 //                           X86 Scheduler Hooks
17151 //===----------------------------------------------------------------------===//
17152
17153 /// Utility function to emit xbegin specifying the start of an RTM region.
17154 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17155                                      const TargetInstrInfo *TII) {
17156   DebugLoc DL = MI->getDebugLoc();
17157
17158   const BasicBlock *BB = MBB->getBasicBlock();
17159   MachineFunction::iterator I = MBB;
17160   ++I;
17161
17162   // For the v = xbegin(), we generate
17163   //
17164   // thisMBB:
17165   //  xbegin sinkMBB
17166   //
17167   // mainMBB:
17168   //  eax = -1
17169   //
17170   // sinkMBB:
17171   //  v = eax
17172
17173   MachineBasicBlock *thisMBB = MBB;
17174   MachineFunction *MF = MBB->getParent();
17175   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17176   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17177   MF->insert(I, mainMBB);
17178   MF->insert(I, sinkMBB);
17179
17180   // Transfer the remainder of BB and its successor edges to sinkMBB.
17181   sinkMBB->splice(sinkMBB->begin(), MBB,
17182                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17183   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17184
17185   // thisMBB:
17186   //  xbegin sinkMBB
17187   //  # fallthrough to mainMBB
17188   //  # abortion to sinkMBB
17189   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17190   thisMBB->addSuccessor(mainMBB);
17191   thisMBB->addSuccessor(sinkMBB);
17192
17193   // mainMBB:
17194   //  EAX = -1
17195   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17196   mainMBB->addSuccessor(sinkMBB);
17197
17198   // sinkMBB:
17199   // EAX is live into the sinkMBB
17200   sinkMBB->addLiveIn(X86::EAX);
17201   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17202           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17203     .addReg(X86::EAX);
17204
17205   MI->eraseFromParent();
17206   return sinkMBB;
17207 }
17208
17209 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17210 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17211 // in the .td file.
17212 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17213                                        const TargetInstrInfo *TII) {
17214   unsigned Opc;
17215   switch (MI->getOpcode()) {
17216   default: llvm_unreachable("illegal opcode!");
17217   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17218   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17219   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17220   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17221   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17222   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17223   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17224   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17225   }
17226
17227   DebugLoc dl = MI->getDebugLoc();
17228   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17229
17230   unsigned NumArgs = MI->getNumOperands();
17231   for (unsigned i = 1; i < NumArgs; ++i) {
17232     MachineOperand &Op = MI->getOperand(i);
17233     if (!(Op.isReg() && Op.isImplicit()))
17234       MIB.addOperand(Op);
17235   }
17236   if (MI->hasOneMemOperand())
17237     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17238
17239   BuildMI(*BB, MI, dl,
17240     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17241     .addReg(X86::XMM0);
17242
17243   MI->eraseFromParent();
17244   return BB;
17245 }
17246
17247 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17248 // defs in an instruction pattern
17249 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17250                                        const TargetInstrInfo *TII) {
17251   unsigned Opc;
17252   switch (MI->getOpcode()) {
17253   default: llvm_unreachable("illegal opcode!");
17254   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17255   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17256   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17257   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17258   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17259   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17260   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17261   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17262   }
17263
17264   DebugLoc dl = MI->getDebugLoc();
17265   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17266
17267   unsigned NumArgs = MI->getNumOperands(); // remove the results
17268   for (unsigned i = 1; i < NumArgs; ++i) {
17269     MachineOperand &Op = MI->getOperand(i);
17270     if (!(Op.isReg() && Op.isImplicit()))
17271       MIB.addOperand(Op);
17272   }
17273   if (MI->hasOneMemOperand())
17274     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17275
17276   BuildMI(*BB, MI, dl,
17277     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17278     .addReg(X86::ECX);
17279
17280   MI->eraseFromParent();
17281   return BB;
17282 }
17283
17284 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17285                                        const TargetInstrInfo *TII,
17286                                        const X86Subtarget* Subtarget) {
17287   DebugLoc dl = MI->getDebugLoc();
17288
17289   // Address into RAX/EAX, other two args into ECX, EDX.
17290   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17291   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17292   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17293   for (int i = 0; i < X86::AddrNumOperands; ++i)
17294     MIB.addOperand(MI->getOperand(i));
17295
17296   unsigned ValOps = X86::AddrNumOperands;
17297   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17298     .addReg(MI->getOperand(ValOps).getReg());
17299   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17300     .addReg(MI->getOperand(ValOps+1).getReg());
17301
17302   // The instruction doesn't actually take any operands though.
17303   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17304
17305   MI->eraseFromParent(); // The pseudo is gone now.
17306   return BB;
17307 }
17308
17309 MachineBasicBlock *
17310 X86TargetLowering::EmitVAARG64WithCustomInserter(
17311                    MachineInstr *MI,
17312                    MachineBasicBlock *MBB) const {
17313   // Emit va_arg instruction on X86-64.
17314
17315   // Operands to this pseudo-instruction:
17316   // 0  ) Output        : destination address (reg)
17317   // 1-5) Input         : va_list address (addr, i64mem)
17318   // 6  ) ArgSize       : Size (in bytes) of vararg type
17319   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17320   // 8  ) Align         : Alignment of type
17321   // 9  ) EFLAGS (implicit-def)
17322
17323   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17324   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17325
17326   unsigned DestReg = MI->getOperand(0).getReg();
17327   MachineOperand &Base = MI->getOperand(1);
17328   MachineOperand &Scale = MI->getOperand(2);
17329   MachineOperand &Index = MI->getOperand(3);
17330   MachineOperand &Disp = MI->getOperand(4);
17331   MachineOperand &Segment = MI->getOperand(5);
17332   unsigned ArgSize = MI->getOperand(6).getImm();
17333   unsigned ArgMode = MI->getOperand(7).getImm();
17334   unsigned Align = MI->getOperand(8).getImm();
17335
17336   // Memory Reference
17337   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17338   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17339   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17340
17341   // Machine Information
17342   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17343   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17344   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17345   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17346   DebugLoc DL = MI->getDebugLoc();
17347
17348   // struct va_list {
17349   //   i32   gp_offset
17350   //   i32   fp_offset
17351   //   i64   overflow_area (address)
17352   //   i64   reg_save_area (address)
17353   // }
17354   // sizeof(va_list) = 24
17355   // alignment(va_list) = 8
17356
17357   unsigned TotalNumIntRegs = 6;
17358   unsigned TotalNumXMMRegs = 8;
17359   bool UseGPOffset = (ArgMode == 1);
17360   bool UseFPOffset = (ArgMode == 2);
17361   unsigned MaxOffset = TotalNumIntRegs * 8 +
17362                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17363
17364   /* Align ArgSize to a multiple of 8 */
17365   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17366   bool NeedsAlign = (Align > 8);
17367
17368   MachineBasicBlock *thisMBB = MBB;
17369   MachineBasicBlock *overflowMBB;
17370   MachineBasicBlock *offsetMBB;
17371   MachineBasicBlock *endMBB;
17372
17373   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17374   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17375   unsigned OffsetReg = 0;
17376
17377   if (!UseGPOffset && !UseFPOffset) {
17378     // If we only pull from the overflow region, we don't create a branch.
17379     // We don't need to alter control flow.
17380     OffsetDestReg = 0; // unused
17381     OverflowDestReg = DestReg;
17382
17383     offsetMBB = nullptr;
17384     overflowMBB = thisMBB;
17385     endMBB = thisMBB;
17386   } else {
17387     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17388     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17389     // If not, pull from overflow_area. (branch to overflowMBB)
17390     //
17391     //       thisMBB
17392     //         |     .
17393     //         |        .
17394     //     offsetMBB   overflowMBB
17395     //         |        .
17396     //         |     .
17397     //        endMBB
17398
17399     // Registers for the PHI in endMBB
17400     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17401     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17402
17403     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17404     MachineFunction *MF = MBB->getParent();
17405     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17406     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17407     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17408
17409     MachineFunction::iterator MBBIter = MBB;
17410     ++MBBIter;
17411
17412     // Insert the new basic blocks
17413     MF->insert(MBBIter, offsetMBB);
17414     MF->insert(MBBIter, overflowMBB);
17415     MF->insert(MBBIter, endMBB);
17416
17417     // Transfer the remainder of MBB and its successor edges to endMBB.
17418     endMBB->splice(endMBB->begin(), thisMBB,
17419                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17420     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17421
17422     // Make offsetMBB and overflowMBB successors of thisMBB
17423     thisMBB->addSuccessor(offsetMBB);
17424     thisMBB->addSuccessor(overflowMBB);
17425
17426     // endMBB is a successor of both offsetMBB and overflowMBB
17427     offsetMBB->addSuccessor(endMBB);
17428     overflowMBB->addSuccessor(endMBB);
17429
17430     // Load the offset value into a register
17431     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17432     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17433       .addOperand(Base)
17434       .addOperand(Scale)
17435       .addOperand(Index)
17436       .addDisp(Disp, UseFPOffset ? 4 : 0)
17437       .addOperand(Segment)
17438       .setMemRefs(MMOBegin, MMOEnd);
17439
17440     // Check if there is enough room left to pull this argument.
17441     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17442       .addReg(OffsetReg)
17443       .addImm(MaxOffset + 8 - ArgSizeA8);
17444
17445     // Branch to "overflowMBB" if offset >= max
17446     // Fall through to "offsetMBB" otherwise
17447     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17448       .addMBB(overflowMBB);
17449   }
17450
17451   // In offsetMBB, emit code to use the reg_save_area.
17452   if (offsetMBB) {
17453     assert(OffsetReg != 0);
17454
17455     // Read the reg_save_area address.
17456     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17457     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17458       .addOperand(Base)
17459       .addOperand(Scale)
17460       .addOperand(Index)
17461       .addDisp(Disp, 16)
17462       .addOperand(Segment)
17463       .setMemRefs(MMOBegin, MMOEnd);
17464
17465     // Zero-extend the offset
17466     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17467       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17468         .addImm(0)
17469         .addReg(OffsetReg)
17470         .addImm(X86::sub_32bit);
17471
17472     // Add the offset to the reg_save_area to get the final address.
17473     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17474       .addReg(OffsetReg64)
17475       .addReg(RegSaveReg);
17476
17477     // Compute the offset for the next argument
17478     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17479     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17480       .addReg(OffsetReg)
17481       .addImm(UseFPOffset ? 16 : 8);
17482
17483     // Store it back into the va_list.
17484     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17485       .addOperand(Base)
17486       .addOperand(Scale)
17487       .addOperand(Index)
17488       .addDisp(Disp, UseFPOffset ? 4 : 0)
17489       .addOperand(Segment)
17490       .addReg(NextOffsetReg)
17491       .setMemRefs(MMOBegin, MMOEnd);
17492
17493     // Jump to endMBB
17494     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17495       .addMBB(endMBB);
17496   }
17497
17498   //
17499   // Emit code to use overflow area
17500   //
17501
17502   // Load the overflow_area address into a register.
17503   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17504   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17505     .addOperand(Base)
17506     .addOperand(Scale)
17507     .addOperand(Index)
17508     .addDisp(Disp, 8)
17509     .addOperand(Segment)
17510     .setMemRefs(MMOBegin, MMOEnd);
17511
17512   // If we need to align it, do so. Otherwise, just copy the address
17513   // to OverflowDestReg.
17514   if (NeedsAlign) {
17515     // Align the overflow address
17516     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17517     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17518
17519     // aligned_addr = (addr + (align-1)) & ~(align-1)
17520     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17521       .addReg(OverflowAddrReg)
17522       .addImm(Align-1);
17523
17524     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17525       .addReg(TmpReg)
17526       .addImm(~(uint64_t)(Align-1));
17527   } else {
17528     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17529       .addReg(OverflowAddrReg);
17530   }
17531
17532   // Compute the next overflow address after this argument.
17533   // (the overflow address should be kept 8-byte aligned)
17534   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17535   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17536     .addReg(OverflowDestReg)
17537     .addImm(ArgSizeA8);
17538
17539   // Store the new overflow address.
17540   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17541     .addOperand(Base)
17542     .addOperand(Scale)
17543     .addOperand(Index)
17544     .addDisp(Disp, 8)
17545     .addOperand(Segment)
17546     .addReg(NextAddrReg)
17547     .setMemRefs(MMOBegin, MMOEnd);
17548
17549   // If we branched, emit the PHI to the front of endMBB.
17550   if (offsetMBB) {
17551     BuildMI(*endMBB, endMBB->begin(), DL,
17552             TII->get(X86::PHI), DestReg)
17553       .addReg(OffsetDestReg).addMBB(offsetMBB)
17554       .addReg(OverflowDestReg).addMBB(overflowMBB);
17555   }
17556
17557   // Erase the pseudo instruction
17558   MI->eraseFromParent();
17559
17560   return endMBB;
17561 }
17562
17563 MachineBasicBlock *
17564 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17565                                                  MachineInstr *MI,
17566                                                  MachineBasicBlock *MBB) const {
17567   // Emit code to save XMM registers to the stack. The ABI says that the
17568   // number of registers to save is given in %al, so it's theoretically
17569   // possible to do an indirect jump trick to avoid saving all of them,
17570   // however this code takes a simpler approach and just executes all
17571   // of the stores if %al is non-zero. It's less code, and it's probably
17572   // easier on the hardware branch predictor, and stores aren't all that
17573   // expensive anyway.
17574
17575   // Create the new basic blocks. One block contains all the XMM stores,
17576   // and one block is the final destination regardless of whether any
17577   // stores were performed.
17578   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17579   MachineFunction *F = MBB->getParent();
17580   MachineFunction::iterator MBBIter = MBB;
17581   ++MBBIter;
17582   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17583   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17584   F->insert(MBBIter, XMMSaveMBB);
17585   F->insert(MBBIter, EndMBB);
17586
17587   // Transfer the remainder of MBB and its successor edges to EndMBB.
17588   EndMBB->splice(EndMBB->begin(), MBB,
17589                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17590   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17591
17592   // The original block will now fall through to the XMM save block.
17593   MBB->addSuccessor(XMMSaveMBB);
17594   // The XMMSaveMBB will fall through to the end block.
17595   XMMSaveMBB->addSuccessor(EndMBB);
17596
17597   // Now add the instructions.
17598   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17599   DebugLoc DL = MI->getDebugLoc();
17600
17601   unsigned CountReg = MI->getOperand(0).getReg();
17602   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17603   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17604
17605   if (!Subtarget->isTargetWin64()) {
17606     // If %al is 0, branch around the XMM save block.
17607     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17608     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17609     MBB->addSuccessor(EndMBB);
17610   }
17611
17612   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17613   // that was just emitted, but clearly shouldn't be "saved".
17614   assert((MI->getNumOperands() <= 3 ||
17615           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17616           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17617          && "Expected last argument to be EFLAGS");
17618   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17619   // In the XMM save block, save all the XMM argument registers.
17620   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17621     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17622     MachineMemOperand *MMO =
17623       F->getMachineMemOperand(
17624           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17625         MachineMemOperand::MOStore,
17626         /*Size=*/16, /*Align=*/16);
17627     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17628       .addFrameIndex(RegSaveFrameIndex)
17629       .addImm(/*Scale=*/1)
17630       .addReg(/*IndexReg=*/0)
17631       .addImm(/*Disp=*/Offset)
17632       .addReg(/*Segment=*/0)
17633       .addReg(MI->getOperand(i).getReg())
17634       .addMemOperand(MMO);
17635   }
17636
17637   MI->eraseFromParent();   // The pseudo instruction is gone now.
17638
17639   return EndMBB;
17640 }
17641
17642 // The EFLAGS operand of SelectItr might be missing a kill marker
17643 // because there were multiple uses of EFLAGS, and ISel didn't know
17644 // which to mark. Figure out whether SelectItr should have had a
17645 // kill marker, and set it if it should. Returns the correct kill
17646 // marker value.
17647 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17648                                      MachineBasicBlock* BB,
17649                                      const TargetRegisterInfo* TRI) {
17650   // Scan forward through BB for a use/def of EFLAGS.
17651   MachineBasicBlock::iterator miI(std::next(SelectItr));
17652   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17653     const MachineInstr& mi = *miI;
17654     if (mi.readsRegister(X86::EFLAGS))
17655       return false;
17656     if (mi.definesRegister(X86::EFLAGS))
17657       break; // Should have kill-flag - update below.
17658   }
17659
17660   // If we hit the end of the block, check whether EFLAGS is live into a
17661   // successor.
17662   if (miI == BB->end()) {
17663     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17664                                           sEnd = BB->succ_end();
17665          sItr != sEnd; ++sItr) {
17666       MachineBasicBlock* succ = *sItr;
17667       if (succ->isLiveIn(X86::EFLAGS))
17668         return false;
17669     }
17670   }
17671
17672   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17673   // out. SelectMI should have a kill flag on EFLAGS.
17674   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17675   return true;
17676 }
17677
17678 MachineBasicBlock *
17679 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17680                                      MachineBasicBlock *BB) const {
17681   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17682   DebugLoc DL = MI->getDebugLoc();
17683
17684   // To "insert" a SELECT_CC instruction, we actually have to insert the
17685   // diamond control-flow pattern.  The incoming instruction knows the
17686   // destination vreg to set, the condition code register to branch on, the
17687   // true/false values to select between, and a branch opcode to use.
17688   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17689   MachineFunction::iterator It = BB;
17690   ++It;
17691
17692   //  thisMBB:
17693   //  ...
17694   //   TrueVal = ...
17695   //   cmpTY ccX, r1, r2
17696   //   bCC copy1MBB
17697   //   fallthrough --> copy0MBB
17698   MachineBasicBlock *thisMBB = BB;
17699   MachineFunction *F = BB->getParent();
17700   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17701   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17702   F->insert(It, copy0MBB);
17703   F->insert(It, sinkMBB);
17704
17705   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17706   // live into the sink and copy blocks.
17707   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17708   if (!MI->killsRegister(X86::EFLAGS) &&
17709       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17710     copy0MBB->addLiveIn(X86::EFLAGS);
17711     sinkMBB->addLiveIn(X86::EFLAGS);
17712   }
17713
17714   // Transfer the remainder of BB and its successor edges to sinkMBB.
17715   sinkMBB->splice(sinkMBB->begin(), BB,
17716                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17717   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17718
17719   // Add the true and fallthrough blocks as its successors.
17720   BB->addSuccessor(copy0MBB);
17721   BB->addSuccessor(sinkMBB);
17722
17723   // Create the conditional branch instruction.
17724   unsigned Opc =
17725     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17726   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17727
17728   //  copy0MBB:
17729   //   %FalseValue = ...
17730   //   # fallthrough to sinkMBB
17731   copy0MBB->addSuccessor(sinkMBB);
17732
17733   //  sinkMBB:
17734   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17735   //  ...
17736   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17737           TII->get(X86::PHI), MI->getOperand(0).getReg())
17738     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17739     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17740
17741   MI->eraseFromParent();   // The pseudo instruction is gone now.
17742   return sinkMBB;
17743 }
17744
17745 MachineBasicBlock *
17746 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17747                                         bool Is64Bit) const {
17748   MachineFunction *MF = BB->getParent();
17749   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17750   DebugLoc DL = MI->getDebugLoc();
17751   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17752
17753   assert(MF->shouldSplitStack());
17754
17755   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17756   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17757
17758   // BB:
17759   //  ... [Till the alloca]
17760   // If stacklet is not large enough, jump to mallocMBB
17761   //
17762   // bumpMBB:
17763   //  Allocate by subtracting from RSP
17764   //  Jump to continueMBB
17765   //
17766   // mallocMBB:
17767   //  Allocate by call to runtime
17768   //
17769   // continueMBB:
17770   //  ...
17771   //  [rest of original BB]
17772   //
17773
17774   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17775   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17776   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17777
17778   MachineRegisterInfo &MRI = MF->getRegInfo();
17779   const TargetRegisterClass *AddrRegClass =
17780     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17781
17782   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17783     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17784     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17785     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17786     sizeVReg = MI->getOperand(1).getReg(),
17787     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17788
17789   MachineFunction::iterator MBBIter = BB;
17790   ++MBBIter;
17791
17792   MF->insert(MBBIter, bumpMBB);
17793   MF->insert(MBBIter, mallocMBB);
17794   MF->insert(MBBIter, continueMBB);
17795
17796   continueMBB->splice(continueMBB->begin(), BB,
17797                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17798   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17799
17800   // Add code to the main basic block to check if the stack limit has been hit,
17801   // and if so, jump to mallocMBB otherwise to bumpMBB.
17802   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17803   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17804     .addReg(tmpSPVReg).addReg(sizeVReg);
17805   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17806     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17807     .addReg(SPLimitVReg);
17808   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17809
17810   // bumpMBB simply decreases the stack pointer, since we know the current
17811   // stacklet has enough space.
17812   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17813     .addReg(SPLimitVReg);
17814   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17815     .addReg(SPLimitVReg);
17816   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17817
17818   // Calls into a routine in libgcc to allocate more space from the heap.
17819   const uint32_t *RegMask =
17820     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17821   if (Is64Bit) {
17822     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17823       .addReg(sizeVReg);
17824     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17825       .addExternalSymbol("__morestack_allocate_stack_space")
17826       .addRegMask(RegMask)
17827       .addReg(X86::RDI, RegState::Implicit)
17828       .addReg(X86::RAX, RegState::ImplicitDefine);
17829   } else {
17830     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17831       .addImm(12);
17832     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17833     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17834       .addExternalSymbol("__morestack_allocate_stack_space")
17835       .addRegMask(RegMask)
17836       .addReg(X86::EAX, RegState::ImplicitDefine);
17837   }
17838
17839   if (!Is64Bit)
17840     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17841       .addImm(16);
17842
17843   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17844     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17845   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17846
17847   // Set up the CFG correctly.
17848   BB->addSuccessor(bumpMBB);
17849   BB->addSuccessor(mallocMBB);
17850   mallocMBB->addSuccessor(continueMBB);
17851   bumpMBB->addSuccessor(continueMBB);
17852
17853   // Take care of the PHI nodes.
17854   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17855           MI->getOperand(0).getReg())
17856     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17857     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17858
17859   // Delete the original pseudo instruction.
17860   MI->eraseFromParent();
17861
17862   // And we're done.
17863   return continueMBB;
17864 }
17865
17866 MachineBasicBlock *
17867 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17868                                         MachineBasicBlock *BB) const {
17869   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17870   DebugLoc DL = MI->getDebugLoc();
17871
17872   assert(!Subtarget->isTargetMacho());
17873
17874   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17875   // non-trivial part is impdef of ESP.
17876
17877   if (Subtarget->isTargetWin64()) {
17878     if (Subtarget->isTargetCygMing()) {
17879       // ___chkstk(Mingw64):
17880       // Clobbers R10, R11, RAX and EFLAGS.
17881       // Updates RSP.
17882       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17883         .addExternalSymbol("___chkstk")
17884         .addReg(X86::RAX, RegState::Implicit)
17885         .addReg(X86::RSP, RegState::Implicit)
17886         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17887         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17888         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17889     } else {
17890       // __chkstk(MSVCRT): does not update stack pointer.
17891       // Clobbers R10, R11 and EFLAGS.
17892       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17893         .addExternalSymbol("__chkstk")
17894         .addReg(X86::RAX, RegState::Implicit)
17895         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17896       // RAX has the offset to be subtracted from RSP.
17897       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17898         .addReg(X86::RSP)
17899         .addReg(X86::RAX);
17900     }
17901   } else {
17902     const char *StackProbeSymbol =
17903       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17904
17905     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17906       .addExternalSymbol(StackProbeSymbol)
17907       .addReg(X86::EAX, RegState::Implicit)
17908       .addReg(X86::ESP, RegState::Implicit)
17909       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17910       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17911       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17912   }
17913
17914   MI->eraseFromParent();   // The pseudo instruction is gone now.
17915   return BB;
17916 }
17917
17918 MachineBasicBlock *
17919 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17920                                       MachineBasicBlock *BB) const {
17921   // This is pretty easy.  We're taking the value that we received from
17922   // our load from the relocation, sticking it in either RDI (x86-64)
17923   // or EAX and doing an indirect call.  The return value will then
17924   // be in the normal return register.
17925   MachineFunction *F = BB->getParent();
17926   const X86InstrInfo *TII
17927     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17928   DebugLoc DL = MI->getDebugLoc();
17929
17930   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17931   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17932
17933   // Get a register mask for the lowered call.
17934   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17935   // proper register mask.
17936   const uint32_t *RegMask =
17937     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17938   if (Subtarget->is64Bit()) {
17939     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17940                                       TII->get(X86::MOV64rm), X86::RDI)
17941     .addReg(X86::RIP)
17942     .addImm(0).addReg(0)
17943     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17944                       MI->getOperand(3).getTargetFlags())
17945     .addReg(0);
17946     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17947     addDirectMem(MIB, X86::RDI);
17948     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17949   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17950     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17951                                       TII->get(X86::MOV32rm), X86::EAX)
17952     .addReg(0)
17953     .addImm(0).addReg(0)
17954     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17955                       MI->getOperand(3).getTargetFlags())
17956     .addReg(0);
17957     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17958     addDirectMem(MIB, X86::EAX);
17959     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17960   } else {
17961     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17962                                       TII->get(X86::MOV32rm), X86::EAX)
17963     .addReg(TII->getGlobalBaseReg(F))
17964     .addImm(0).addReg(0)
17965     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17966                       MI->getOperand(3).getTargetFlags())
17967     .addReg(0);
17968     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17969     addDirectMem(MIB, X86::EAX);
17970     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17971   }
17972
17973   MI->eraseFromParent(); // The pseudo instruction is gone now.
17974   return BB;
17975 }
17976
17977 MachineBasicBlock *
17978 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17979                                     MachineBasicBlock *MBB) const {
17980   DebugLoc DL = MI->getDebugLoc();
17981   MachineFunction *MF = MBB->getParent();
17982   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17983   MachineRegisterInfo &MRI = MF->getRegInfo();
17984
17985   const BasicBlock *BB = MBB->getBasicBlock();
17986   MachineFunction::iterator I = MBB;
17987   ++I;
17988
17989   // Memory Reference
17990   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17991   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17992
17993   unsigned DstReg;
17994   unsigned MemOpndSlot = 0;
17995
17996   unsigned CurOp = 0;
17997
17998   DstReg = MI->getOperand(CurOp++).getReg();
17999   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18000   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18001   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18002   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18003
18004   MemOpndSlot = CurOp;
18005
18006   MVT PVT = getPointerTy();
18007   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18008          "Invalid Pointer Size!");
18009
18010   // For v = setjmp(buf), we generate
18011   //
18012   // thisMBB:
18013   //  buf[LabelOffset] = restoreMBB
18014   //  SjLjSetup restoreMBB
18015   //
18016   // mainMBB:
18017   //  v_main = 0
18018   //
18019   // sinkMBB:
18020   //  v = phi(main, restore)
18021   //
18022   // restoreMBB:
18023   //  v_restore = 1
18024
18025   MachineBasicBlock *thisMBB = MBB;
18026   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18027   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18028   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18029   MF->insert(I, mainMBB);
18030   MF->insert(I, sinkMBB);
18031   MF->push_back(restoreMBB);
18032
18033   MachineInstrBuilder MIB;
18034
18035   // Transfer the remainder of BB and its successor edges to sinkMBB.
18036   sinkMBB->splice(sinkMBB->begin(), MBB,
18037                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18038   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18039
18040   // thisMBB:
18041   unsigned PtrStoreOpc = 0;
18042   unsigned LabelReg = 0;
18043   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18044   Reloc::Model RM = MF->getTarget().getRelocationModel();
18045   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18046                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18047
18048   // Prepare IP either in reg or imm.
18049   if (!UseImmLabel) {
18050     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18051     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18052     LabelReg = MRI.createVirtualRegister(PtrRC);
18053     if (Subtarget->is64Bit()) {
18054       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18055               .addReg(X86::RIP)
18056               .addImm(0)
18057               .addReg(0)
18058               .addMBB(restoreMBB)
18059               .addReg(0);
18060     } else {
18061       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18062       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18063               .addReg(XII->getGlobalBaseReg(MF))
18064               .addImm(0)
18065               .addReg(0)
18066               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18067               .addReg(0);
18068     }
18069   } else
18070     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18071   // Store IP
18072   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18073   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18074     if (i == X86::AddrDisp)
18075       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18076     else
18077       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18078   }
18079   if (!UseImmLabel)
18080     MIB.addReg(LabelReg);
18081   else
18082     MIB.addMBB(restoreMBB);
18083   MIB.setMemRefs(MMOBegin, MMOEnd);
18084   // Setup
18085   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18086           .addMBB(restoreMBB);
18087
18088   const X86RegisterInfo *RegInfo =
18089     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18090   MIB.addRegMask(RegInfo->getNoPreservedMask());
18091   thisMBB->addSuccessor(mainMBB);
18092   thisMBB->addSuccessor(restoreMBB);
18093
18094   // mainMBB:
18095   //  EAX = 0
18096   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18097   mainMBB->addSuccessor(sinkMBB);
18098
18099   // sinkMBB:
18100   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18101           TII->get(X86::PHI), DstReg)
18102     .addReg(mainDstReg).addMBB(mainMBB)
18103     .addReg(restoreDstReg).addMBB(restoreMBB);
18104
18105   // restoreMBB:
18106   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18107   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18108   restoreMBB->addSuccessor(sinkMBB);
18109
18110   MI->eraseFromParent();
18111   return sinkMBB;
18112 }
18113
18114 MachineBasicBlock *
18115 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18116                                      MachineBasicBlock *MBB) const {
18117   DebugLoc DL = MI->getDebugLoc();
18118   MachineFunction *MF = MBB->getParent();
18119   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18120   MachineRegisterInfo &MRI = MF->getRegInfo();
18121
18122   // Memory Reference
18123   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18124   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18125
18126   MVT PVT = getPointerTy();
18127   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18128          "Invalid Pointer Size!");
18129
18130   const TargetRegisterClass *RC =
18131     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18132   unsigned Tmp = MRI.createVirtualRegister(RC);
18133   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18134   const X86RegisterInfo *RegInfo =
18135     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18136   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18137   unsigned SP = RegInfo->getStackRegister();
18138
18139   MachineInstrBuilder MIB;
18140
18141   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18142   const int64_t SPOffset = 2 * PVT.getStoreSize();
18143
18144   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18145   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18146
18147   // Reload FP
18148   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18149   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18150     MIB.addOperand(MI->getOperand(i));
18151   MIB.setMemRefs(MMOBegin, MMOEnd);
18152   // Reload IP
18153   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18154   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18155     if (i == X86::AddrDisp)
18156       MIB.addDisp(MI->getOperand(i), LabelOffset);
18157     else
18158       MIB.addOperand(MI->getOperand(i));
18159   }
18160   MIB.setMemRefs(MMOBegin, MMOEnd);
18161   // Reload SP
18162   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18163   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18164     if (i == X86::AddrDisp)
18165       MIB.addDisp(MI->getOperand(i), SPOffset);
18166     else
18167       MIB.addOperand(MI->getOperand(i));
18168   }
18169   MIB.setMemRefs(MMOBegin, MMOEnd);
18170   // Jump
18171   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18172
18173   MI->eraseFromParent();
18174   return MBB;
18175 }
18176
18177 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18178 // accumulator loops. Writing back to the accumulator allows the coalescer
18179 // to remove extra copies in the loop.   
18180 MachineBasicBlock *
18181 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18182                                  MachineBasicBlock *MBB) const {
18183   MachineOperand &AddendOp = MI->getOperand(3);
18184
18185   // Bail out early if the addend isn't a register - we can't switch these.
18186   if (!AddendOp.isReg())
18187     return MBB;
18188
18189   MachineFunction &MF = *MBB->getParent();
18190   MachineRegisterInfo &MRI = MF.getRegInfo();
18191
18192   // Check whether the addend is defined by a PHI:
18193   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18194   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18195   if (!AddendDef.isPHI())
18196     return MBB;
18197
18198   // Look for the following pattern:
18199   // loop:
18200   //   %addend = phi [%entry, 0], [%loop, %result]
18201   //   ...
18202   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18203
18204   // Replace with:
18205   //   loop:
18206   //   %addend = phi [%entry, 0], [%loop, %result]
18207   //   ...
18208   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18209
18210   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18211     assert(AddendDef.getOperand(i).isReg());
18212     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18213     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18214     if (&PHISrcInst == MI) {
18215       // Found a matching instruction.
18216       unsigned NewFMAOpc = 0;
18217       switch (MI->getOpcode()) {
18218         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18219         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18220         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18221         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18222         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18223         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18224         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18225         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18226         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18227         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18228         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18229         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18230         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18231         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18232         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18233         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18234         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18235         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18236         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18237         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18238         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18239         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18240         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18241         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18242         default: llvm_unreachable("Unrecognized FMA variant.");
18243       }
18244
18245       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18246       MachineInstrBuilder MIB =
18247         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18248         .addOperand(MI->getOperand(0))
18249         .addOperand(MI->getOperand(3))
18250         .addOperand(MI->getOperand(2))
18251         .addOperand(MI->getOperand(1));
18252       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18253       MI->eraseFromParent();
18254     }
18255   }
18256
18257   return MBB;
18258 }
18259
18260 MachineBasicBlock *
18261 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18262                                                MachineBasicBlock *BB) const {
18263   switch (MI->getOpcode()) {
18264   default: llvm_unreachable("Unexpected instr type to insert");
18265   case X86::TAILJMPd64:
18266   case X86::TAILJMPr64:
18267   case X86::TAILJMPm64:
18268     llvm_unreachable("TAILJMP64 would not be touched here.");
18269   case X86::TCRETURNdi64:
18270   case X86::TCRETURNri64:
18271   case X86::TCRETURNmi64:
18272     return BB;
18273   case X86::WIN_ALLOCA:
18274     return EmitLoweredWinAlloca(MI, BB);
18275   case X86::SEG_ALLOCA_32:
18276     return EmitLoweredSegAlloca(MI, BB, false);
18277   case X86::SEG_ALLOCA_64:
18278     return EmitLoweredSegAlloca(MI, BB, true);
18279   case X86::TLSCall_32:
18280   case X86::TLSCall_64:
18281     return EmitLoweredTLSCall(MI, BB);
18282   case X86::CMOV_GR8:
18283   case X86::CMOV_FR32:
18284   case X86::CMOV_FR64:
18285   case X86::CMOV_V4F32:
18286   case X86::CMOV_V2F64:
18287   case X86::CMOV_V2I64:
18288   case X86::CMOV_V8F32:
18289   case X86::CMOV_V4F64:
18290   case X86::CMOV_V4I64:
18291   case X86::CMOV_V16F32:
18292   case X86::CMOV_V8F64:
18293   case X86::CMOV_V8I64:
18294   case X86::CMOV_GR16:
18295   case X86::CMOV_GR32:
18296   case X86::CMOV_RFP32:
18297   case X86::CMOV_RFP64:
18298   case X86::CMOV_RFP80:
18299     return EmitLoweredSelect(MI, BB);
18300
18301   case X86::FP32_TO_INT16_IN_MEM:
18302   case X86::FP32_TO_INT32_IN_MEM:
18303   case X86::FP32_TO_INT64_IN_MEM:
18304   case X86::FP64_TO_INT16_IN_MEM:
18305   case X86::FP64_TO_INT32_IN_MEM:
18306   case X86::FP64_TO_INT64_IN_MEM:
18307   case X86::FP80_TO_INT16_IN_MEM:
18308   case X86::FP80_TO_INT32_IN_MEM:
18309   case X86::FP80_TO_INT64_IN_MEM: {
18310     MachineFunction *F = BB->getParent();
18311     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18312     DebugLoc DL = MI->getDebugLoc();
18313
18314     // Change the floating point control register to use "round towards zero"
18315     // mode when truncating to an integer value.
18316     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18317     addFrameReference(BuildMI(*BB, MI, DL,
18318                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18319
18320     // Load the old value of the high byte of the control word...
18321     unsigned OldCW =
18322       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18323     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18324                       CWFrameIdx);
18325
18326     // Set the high part to be round to zero...
18327     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18328       .addImm(0xC7F);
18329
18330     // Reload the modified control word now...
18331     addFrameReference(BuildMI(*BB, MI, DL,
18332                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18333
18334     // Restore the memory image of control word to original value
18335     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18336       .addReg(OldCW);
18337
18338     // Get the X86 opcode to use.
18339     unsigned Opc;
18340     switch (MI->getOpcode()) {
18341     default: llvm_unreachable("illegal opcode!");
18342     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18343     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18344     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18345     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18346     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18347     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18348     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18349     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18350     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18351     }
18352
18353     X86AddressMode AM;
18354     MachineOperand &Op = MI->getOperand(0);
18355     if (Op.isReg()) {
18356       AM.BaseType = X86AddressMode::RegBase;
18357       AM.Base.Reg = Op.getReg();
18358     } else {
18359       AM.BaseType = X86AddressMode::FrameIndexBase;
18360       AM.Base.FrameIndex = Op.getIndex();
18361     }
18362     Op = MI->getOperand(1);
18363     if (Op.isImm())
18364       AM.Scale = Op.getImm();
18365     Op = MI->getOperand(2);
18366     if (Op.isImm())
18367       AM.IndexReg = Op.getImm();
18368     Op = MI->getOperand(3);
18369     if (Op.isGlobal()) {
18370       AM.GV = Op.getGlobal();
18371     } else {
18372       AM.Disp = Op.getImm();
18373     }
18374     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18375                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18376
18377     // Reload the original control word now.
18378     addFrameReference(BuildMI(*BB, MI, DL,
18379                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18380
18381     MI->eraseFromParent();   // The pseudo instruction is gone now.
18382     return BB;
18383   }
18384     // String/text processing lowering.
18385   case X86::PCMPISTRM128REG:
18386   case X86::VPCMPISTRM128REG:
18387   case X86::PCMPISTRM128MEM:
18388   case X86::VPCMPISTRM128MEM:
18389   case X86::PCMPESTRM128REG:
18390   case X86::VPCMPESTRM128REG:
18391   case X86::PCMPESTRM128MEM:
18392   case X86::VPCMPESTRM128MEM:
18393     assert(Subtarget->hasSSE42() &&
18394            "Target must have SSE4.2 or AVX features enabled");
18395     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18396
18397   // String/text processing lowering.
18398   case X86::PCMPISTRIREG:
18399   case X86::VPCMPISTRIREG:
18400   case X86::PCMPISTRIMEM:
18401   case X86::VPCMPISTRIMEM:
18402   case X86::PCMPESTRIREG:
18403   case X86::VPCMPESTRIREG:
18404   case X86::PCMPESTRIMEM:
18405   case X86::VPCMPESTRIMEM:
18406     assert(Subtarget->hasSSE42() &&
18407            "Target must have SSE4.2 or AVX features enabled");
18408     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18409
18410   // Thread synchronization.
18411   case X86::MONITOR:
18412     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18413
18414   // xbegin
18415   case X86::XBEGIN:
18416     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18417
18418   case X86::VASTART_SAVE_XMM_REGS:
18419     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18420
18421   case X86::VAARG_64:
18422     return EmitVAARG64WithCustomInserter(MI, BB);
18423
18424   case X86::EH_SjLj_SetJmp32:
18425   case X86::EH_SjLj_SetJmp64:
18426     return emitEHSjLjSetJmp(MI, BB);
18427
18428   case X86::EH_SjLj_LongJmp32:
18429   case X86::EH_SjLj_LongJmp64:
18430     return emitEHSjLjLongJmp(MI, BB);
18431
18432   case TargetOpcode::STACKMAP:
18433   case TargetOpcode::PATCHPOINT:
18434     return emitPatchPoint(MI, BB);
18435
18436   case X86::VFMADDPDr213r:
18437   case X86::VFMADDPSr213r:
18438   case X86::VFMADDSDr213r:
18439   case X86::VFMADDSSr213r:
18440   case X86::VFMSUBPDr213r:
18441   case X86::VFMSUBPSr213r:
18442   case X86::VFMSUBSDr213r:
18443   case X86::VFMSUBSSr213r:
18444   case X86::VFNMADDPDr213r:
18445   case X86::VFNMADDPSr213r:
18446   case X86::VFNMADDSDr213r:
18447   case X86::VFNMADDSSr213r:
18448   case X86::VFNMSUBPDr213r:
18449   case X86::VFNMSUBPSr213r:
18450   case X86::VFNMSUBSDr213r:
18451   case X86::VFNMSUBSSr213r:
18452   case X86::VFMADDPDr213rY:
18453   case X86::VFMADDPSr213rY:
18454   case X86::VFMSUBPDr213rY:
18455   case X86::VFMSUBPSr213rY:
18456   case X86::VFNMADDPDr213rY:
18457   case X86::VFNMADDPSr213rY:
18458   case X86::VFNMSUBPDr213rY:
18459   case X86::VFNMSUBPSr213rY:
18460     return emitFMA3Instr(MI, BB);
18461   }
18462 }
18463
18464 //===----------------------------------------------------------------------===//
18465 //                           X86 Optimization Hooks
18466 //===----------------------------------------------------------------------===//
18467
18468 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18469                                                       APInt &KnownZero,
18470                                                       APInt &KnownOne,
18471                                                       const SelectionDAG &DAG,
18472                                                       unsigned Depth) const {
18473   unsigned BitWidth = KnownZero.getBitWidth();
18474   unsigned Opc = Op.getOpcode();
18475   assert((Opc >= ISD::BUILTIN_OP_END ||
18476           Opc == ISD::INTRINSIC_WO_CHAIN ||
18477           Opc == ISD::INTRINSIC_W_CHAIN ||
18478           Opc == ISD::INTRINSIC_VOID) &&
18479          "Should use MaskedValueIsZero if you don't know whether Op"
18480          " is a target node!");
18481
18482   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18483   switch (Opc) {
18484   default: break;
18485   case X86ISD::ADD:
18486   case X86ISD::SUB:
18487   case X86ISD::ADC:
18488   case X86ISD::SBB:
18489   case X86ISD::SMUL:
18490   case X86ISD::UMUL:
18491   case X86ISD::INC:
18492   case X86ISD::DEC:
18493   case X86ISD::OR:
18494   case X86ISD::XOR:
18495   case X86ISD::AND:
18496     // These nodes' second result is a boolean.
18497     if (Op.getResNo() == 0)
18498       break;
18499     // Fallthrough
18500   case X86ISD::SETCC:
18501     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18502     break;
18503   case ISD::INTRINSIC_WO_CHAIN: {
18504     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18505     unsigned NumLoBits = 0;
18506     switch (IntId) {
18507     default: break;
18508     case Intrinsic::x86_sse_movmsk_ps:
18509     case Intrinsic::x86_avx_movmsk_ps_256:
18510     case Intrinsic::x86_sse2_movmsk_pd:
18511     case Intrinsic::x86_avx_movmsk_pd_256:
18512     case Intrinsic::x86_mmx_pmovmskb:
18513     case Intrinsic::x86_sse2_pmovmskb_128:
18514     case Intrinsic::x86_avx2_pmovmskb: {
18515       // High bits of movmskp{s|d}, pmovmskb are known zero.
18516       switch (IntId) {
18517         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18518         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18519         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18520         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18521         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18522         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18523         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18524         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18525       }
18526       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18527       break;
18528     }
18529     }
18530     break;
18531   }
18532   }
18533 }
18534
18535 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18536   SDValue Op,
18537   const SelectionDAG &,
18538   unsigned Depth) const {
18539   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18540   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18541     return Op.getValueType().getScalarType().getSizeInBits();
18542
18543   // Fallback case.
18544   return 1;
18545 }
18546
18547 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18548 /// node is a GlobalAddress + offset.
18549 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18550                                        const GlobalValue* &GA,
18551                                        int64_t &Offset) const {
18552   if (N->getOpcode() == X86ISD::Wrapper) {
18553     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18554       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18555       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18556       return true;
18557     }
18558   }
18559   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18560 }
18561
18562 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18563 /// same as extracting the high 128-bit part of 256-bit vector and then
18564 /// inserting the result into the low part of a new 256-bit vector
18565 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18566   EVT VT = SVOp->getValueType(0);
18567   unsigned NumElems = VT.getVectorNumElements();
18568
18569   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18570   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18571     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18572         SVOp->getMaskElt(j) >= 0)
18573       return false;
18574
18575   return true;
18576 }
18577
18578 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18579 /// same as extracting the low 128-bit part of 256-bit vector and then
18580 /// inserting the result into the high part of a new 256-bit vector
18581 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18582   EVT VT = SVOp->getValueType(0);
18583   unsigned NumElems = VT.getVectorNumElements();
18584
18585   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18586   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18587     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18588         SVOp->getMaskElt(j) >= 0)
18589       return false;
18590
18591   return true;
18592 }
18593
18594 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18595 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18596                                         TargetLowering::DAGCombinerInfo &DCI,
18597                                         const X86Subtarget* Subtarget) {
18598   SDLoc dl(N);
18599   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18600   SDValue V1 = SVOp->getOperand(0);
18601   SDValue V2 = SVOp->getOperand(1);
18602   EVT VT = SVOp->getValueType(0);
18603   unsigned NumElems = VT.getVectorNumElements();
18604
18605   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18606       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18607     //
18608     //                   0,0,0,...
18609     //                      |
18610     //    V      UNDEF    BUILD_VECTOR    UNDEF
18611     //     \      /           \           /
18612     //  CONCAT_VECTOR         CONCAT_VECTOR
18613     //         \                  /
18614     //          \                /
18615     //          RESULT: V + zero extended
18616     //
18617     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18618         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18619         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18620       return SDValue();
18621
18622     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18623       return SDValue();
18624
18625     // To match the shuffle mask, the first half of the mask should
18626     // be exactly the first vector, and all the rest a splat with the
18627     // first element of the second one.
18628     for (unsigned i = 0; i != NumElems/2; ++i)
18629       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18630           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18631         return SDValue();
18632
18633     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18634     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18635       if (Ld->hasNUsesOfValue(1, 0)) {
18636         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18637         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18638         SDValue ResNode =
18639           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18640                                   Ld->getMemoryVT(),
18641                                   Ld->getPointerInfo(),
18642                                   Ld->getAlignment(),
18643                                   false/*isVolatile*/, true/*ReadMem*/,
18644                                   false/*WriteMem*/);
18645
18646         // Make sure the newly-created LOAD is in the same position as Ld in
18647         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18648         // and update uses of Ld's output chain to use the TokenFactor.
18649         if (Ld->hasAnyUseOfValue(1)) {
18650           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18651                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18652           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18653           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18654                                  SDValue(ResNode.getNode(), 1));
18655         }
18656
18657         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18658       }
18659     }
18660
18661     // Emit a zeroed vector and insert the desired subvector on its
18662     // first half.
18663     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18664     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18665     return DCI.CombineTo(N, InsV);
18666   }
18667
18668   //===--------------------------------------------------------------------===//
18669   // Combine some shuffles into subvector extracts and inserts:
18670   //
18671
18672   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18673   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18674     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18675     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18676     return DCI.CombineTo(N, InsV);
18677   }
18678
18679   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18680   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18681     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18682     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18683     return DCI.CombineTo(N, InsV);
18684   }
18685
18686   return SDValue();
18687 }
18688
18689 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
18690 /// possible.
18691 ///
18692 /// This is the leaf of the recursive combinine below. When we have found some
18693 /// chain of single-use x86 shuffle instructions and accumulated the combined
18694 /// shuffle mask represented by them, this will try to pattern match that mask
18695 /// into either a single instruction if there is a special purpose instruction
18696 /// for this operation, or into a PSHUFB instruction which is a fully general
18697 /// instruction but should only be used to replace chains over a certain depth.
18698 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
18699                                    int Depth, SelectionDAG &DAG,
18700                                    TargetLowering::DAGCombinerInfo &DCI,
18701                                    const X86Subtarget *Subtarget) {
18702   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
18703
18704   // Find the operand that enters the chain. Note that multiple uses are OK
18705   // here, we're not going to remove the operand we find.
18706   SDValue Input = Op.getOperand(0);
18707   while (Input.getOpcode() == ISD::BITCAST)
18708     Input = Input.getOperand(0);
18709
18710   MVT VT = Input.getSimpleValueType();
18711   MVT RootVT = Root.getSimpleValueType();
18712   SDLoc DL(Root);
18713
18714   // Just remove no-op shuffle masks.
18715   if (Mask.size() == 1) {
18716     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
18717                   /*AddTo*/ true);
18718     return true;
18719   }
18720
18721   // Use the float domain if the operand type is a floatingc point type.
18722   bool FloatDomain = VT.isFloatingPoint();
18723
18724   // If we don't have access to VEX encodings, the generic PSHUF instructions
18725   // are preferable to some of the specialized forms despite requiring one more
18726   // byte to encode because they can implicitly copy.
18727   //
18728   // IF we *do* have VEX encodings, than we can use shorter, more specific
18729   // shuffle instructions freely as they can copy due to the extra register
18730   // operand.
18731   if (Subtarget->hasAVX()) {
18732     // We have both floatincg point and integer variants of shuffles that dup
18733     // either tho low or high half of the vector.
18734     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
18735       bool Lo = Mask.equals(0, 0);
18736       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
18737                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
18738       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
18739       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18740       DCI.AddToWorklist(Op.getNode());
18741       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
18742       DCI.AddToWorklist(Op.getNode());
18743       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18744                     /*AddTo*/ true);
18745       return true;
18746     }
18747
18748     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
18749
18750     // For the integer domain we have specialized instructions for duplicating
18751     // any element size from the low or high half.
18752     if (!FloatDomain &&
18753         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
18754          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
18755          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
18756          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
18757          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
18758                      15))) {
18759       bool Lo = Mask[0] == 0;
18760       MVT ShuffleVT;
18761       switch (Mask.size()) {
18762       case 4: ShuffleVT = MVT::v4i32; break;
18763       case 8: ShuffleVT = MVT::v8i32; break;
18764       case 16: ShuffleVT = MVT::v16i32; break;
18765       };
18766       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18767       DCI.AddToWorklist(Op.getNode());
18768       Op = DAG.getNode(Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL, ShuffleVT, Op,
18769                        Op);
18770       DCI.AddToWorklist(Op.getNode());
18771       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18772                     /*AddTo*/ true);
18773       return true;
18774     }
18775   }
18776
18777   // Bail if we have fewer than 3 shuffle instructions in the chain.
18778   if (Depth < 3)
18779     return false;
18780
18781   // If we have 3 or more shuffle instructions, we can replace them with
18782   // a single PSHUFB instruction profitably. Intel's manuals suggest only using
18783   // PSHUFB if doing so replacing 5 instructions, but in practice PSHUFB tends
18784   // to be *very* fast so we're more aggressive.
18785   if (Subtarget->hasSSSE3()) {
18786     SmallVector<SDValue, 16> PSHUFBMask;
18787     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
18788     int Ratio = 16 / Mask.size();
18789     for (unsigned i = 0; i < 16; ++i) {
18790       int M = Ratio * Mask[i / Ratio] + i % Ratio;
18791       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
18792     }
18793     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
18794     DCI.AddToWorklist(Op.getNode());
18795     SDValue PSHUFBMaskOp =
18796         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
18797     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
18798     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
18799     DCI.AddToWorklist(Op.getNode());
18800     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18801                   /*AddTo*/ true);
18802     return true;
18803   }
18804
18805   // Failed to find any combines.
18806   return false;
18807 }
18808
18809 /// \brief Fully generic combining of x86 shuffle instructions.
18810 ///
18811 /// This should be the last combine run over the x86 shuffle instructions. Once
18812 /// they have been fully optimized, this will recursively consdier all chains
18813 /// of single-use shuffle instructions, build a generic model of the cumulative
18814 /// shuffle operation, and check for simpler instructions which implement this
18815 /// operation. We use this primarily for two purposes:
18816 ///
18817 /// 1) Collapse generic shuffles to specialized single instructions when
18818 ///    equivalent. In most cases, this is just an encoding size win, but
18819 ///    sometimes we will collapse multiple generic shuffles into a single
18820 ///    special-purpose shuffle.
18821 /// 2) Look for sequences of shuffle instructions with 3 or more total
18822 ///    instructions, and replace them with the slightly more expensive SSSE3
18823 ///    PSHUFB instruction if available. We do this as the last combining step
18824 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
18825 ///    a suitable short sequence of other instructions. The PHUFB will either
18826 ///    use a register or have to read from memory and so is slightly (but only
18827 ///    slightly) more expensive than the other shuffle instructions.
18828 ///
18829 /// Because this is inherently a quadratic operation (for each shuffle in
18830 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
18831 /// This should never be an issue in practice as the shuffle lowering doesn't
18832 /// produce sequences of more than 8 instructions.
18833 ///
18834 /// FIXME: Currently, we don't collapse instructions *into* PSHUFB. We should,
18835 /// and we should do so more aggressively than we form PSHUFB because once we
18836 /// have a PSHUFB, we might as well do as much shuffling as we can.
18837 ///
18838 /// FIXME: We will currently miss some cases where the redundant shuffling
18839 /// would simplify under the threshold for PSHUFB formation because of
18840 /// combine-ordering. To fix this, we should do the redundant instruction
18841 /// combining in this recursive walk.
18842 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
18843                                           ArrayRef<int> IncomingMask, int Depth,
18844                                           SelectionDAG &DAG,
18845                                           TargetLowering::DAGCombinerInfo &DCI,
18846                                           const X86Subtarget *Subtarget) {
18847   // Bound the depth of our recursive combine because this is ultimately
18848   // quadratic in nature.
18849   if (Depth > 8)
18850     return false;
18851
18852   // Directly rip through bitcasts to find the underlying operand.
18853   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
18854     Op = Op.getOperand(0);
18855
18856   MVT VT = Op.getSimpleValueType();
18857   if (!VT.isVector())
18858     return false; // Bail if we hit a non-vector.
18859   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
18860   // version should be added.
18861   if (VT.getSizeInBits() != 128)
18862     return false;
18863
18864   assert(Root.getSimpleValueType().isVector() &&
18865          "Shuffles operate on vector types!");
18866   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
18867          "Can only combine shuffles of the same vector register size.");
18868
18869   if (!isTargetShuffle(Op.getOpcode()))
18870     return false;
18871   SmallVector<int, 16> OpMask;
18872   bool IsUnary;
18873   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
18874   // We only can combine unary shuffles which we can decode the mask for.
18875   if (!HaveMask || !IsUnary)
18876     return false;
18877
18878   assert(VT.getVectorNumElements() == OpMask.size() &&
18879          "Different mask size from vector size!");
18880
18881   SmallVector<int, 16> Mask;
18882   Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
18883
18884   // Merge this shuffle operation's mask into our accumulated mask. This is
18885   // a bit tricky as the shuffle may have a different size from the root.
18886   if (OpMask.size() == IncomingMask.size()) {
18887     for (int M : IncomingMask)
18888       Mask.push_back(OpMask[M]);
18889   } else if (OpMask.size() < IncomingMask.size()) {
18890     assert(IncomingMask.size() % OpMask.size() == 0 &&
18891            "The smaller number of elements must divide the larger.");
18892     int Ratio = IncomingMask.size() / OpMask.size();
18893     for (int M : IncomingMask)
18894       Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
18895   } else {
18896     assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
18897     assert(OpMask.size() % IncomingMask.size() == 0 &&
18898            "The smaller number of elements must divide the larger.");
18899     int Ratio = OpMask.size() / IncomingMask.size();
18900     for (int i = 0, e = OpMask.size(); i < e; ++i)
18901       Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
18902   }
18903
18904   // See if we can recurse into the operand to combine more things.
18905   switch (Op.getOpcode()) {
18906     case X86ISD::PSHUFD:
18907     case X86ISD::PSHUFHW:
18908     case X86ISD::PSHUFLW:
18909       if (Op.getOperand(0).hasOneUse() &&
18910           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
18911                                         DAG, DCI, Subtarget))
18912         return true;
18913       break;
18914
18915     case X86ISD::UNPCKL:
18916     case X86ISD::UNPCKH:
18917       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
18918       // We can't check for single use, we have to check that this shuffle is the only user.
18919       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
18920           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
18921                                         DAG, DCI, Subtarget))
18922           return true;
18923       break;
18924   }
18925
18926   // Minor canonicalization of the accumulated shuffle mask to make it easier
18927   // to match below. All this does is detect masks with squential pairs of
18928   // elements, and shrink them to the half-width mask. It does this in a loop
18929   // so it will reduce the size of the mask to the minimal width mask which
18930   // performs an equivalent shuffle.
18931   while (Mask.size() > 1) {
18932     SmallVector<int, 16> NewMask;
18933     for (int i = 0, e = Mask.size()/2; i < e; ++i) {
18934       if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
18935         NewMask.clear();
18936         break;
18937       }
18938       NewMask.push_back(Mask[2*i] / 2);
18939     }
18940     if (NewMask.empty())
18941       break;
18942     Mask.swap(NewMask);
18943   }
18944
18945   return combineX86ShuffleChain(Op, Root, Mask, Depth, DAG, DCI, Subtarget);
18946 }
18947
18948 /// \brief Get the PSHUF-style mask from PSHUF node.
18949 ///
18950 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18951 /// PSHUF-style masks that can be reused with such instructions.
18952 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18953   SmallVector<int, 4> Mask;
18954   bool IsUnary;
18955   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18956   (void)HaveMask;
18957   assert(HaveMask);
18958
18959   switch (N.getOpcode()) {
18960   case X86ISD::PSHUFD:
18961     return Mask;
18962   case X86ISD::PSHUFLW:
18963     Mask.resize(4);
18964     return Mask;
18965   case X86ISD::PSHUFHW:
18966     Mask.erase(Mask.begin(), Mask.begin() + 4);
18967     for (int &M : Mask)
18968       M -= 4;
18969     return Mask;
18970   default:
18971     llvm_unreachable("No valid shuffle instruction found!");
18972   }
18973 }
18974
18975 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18976 ///
18977 /// We walk up the chain and look for a combinable shuffle, skipping over
18978 /// shuffles that we could hoist this shuffle's transformation past without
18979 /// altering anything.
18980 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18981                                          SelectionDAG &DAG,
18982                                          TargetLowering::DAGCombinerInfo &DCI) {
18983   assert(N.getOpcode() == X86ISD::PSHUFD &&
18984          "Called with something other than an x86 128-bit half shuffle!");
18985   SDLoc DL(N);
18986
18987   // Walk up a single-use chain looking for a combinable shuffle.
18988   SDValue V = N.getOperand(0);
18989   for (; V.hasOneUse(); V = V.getOperand(0)) {
18990     switch (V.getOpcode()) {
18991     default:
18992       return false; // Nothing combined!
18993
18994     case ISD::BITCAST:
18995       // Skip bitcasts as we always know the type for the target specific
18996       // instructions.
18997       continue;
18998
18999     case X86ISD::PSHUFD:
19000       // Found another dword shuffle.
19001       break;
19002
19003     case X86ISD::PSHUFLW:
19004       // Check that the low words (being shuffled) are the identity in the
19005       // dword shuffle, and the high words are self-contained.
19006       if (Mask[0] != 0 || Mask[1] != 1 ||
19007           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19008         return false;
19009
19010       continue;
19011
19012     case X86ISD::PSHUFHW:
19013       // Check that the high words (being shuffled) are the identity in the
19014       // dword shuffle, and the low words are self-contained.
19015       if (Mask[2] != 2 || Mask[3] != 3 ||
19016           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19017         return false;
19018
19019       continue;
19020
19021     case X86ISD::UNPCKL:
19022     case X86ISD::UNPCKH:
19023       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19024       // shuffle into a preceding word shuffle.
19025       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19026         return false;
19027
19028       // Search for a half-shuffle which we can combine with.
19029       unsigned CombineOp =
19030           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19031       if (V.getOperand(0) != V.getOperand(1) ||
19032           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19033         return false;
19034       V = V.getOperand(0);
19035       do {
19036         switch (V.getOpcode()) {
19037         default:
19038           return false; // Nothing to combine.
19039
19040         case X86ISD::PSHUFLW:
19041         case X86ISD::PSHUFHW:
19042           if (V.getOpcode() == CombineOp)
19043             break;
19044
19045           // Fallthrough!
19046         case ISD::BITCAST:
19047           V = V.getOperand(0);
19048           continue;
19049         }
19050         break;
19051       } while (V.hasOneUse());
19052       break;
19053     }
19054     // Break out of the loop if we break out of the switch.
19055     break;
19056   }
19057
19058   if (!V.hasOneUse())
19059     // We fell out of the loop without finding a viable combining instruction.
19060     return false;
19061
19062   // Record the old value to use in RAUW-ing.
19063   SDValue Old = V;
19064
19065   // Merge this node's mask and our incoming mask.
19066   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19067   for (int &M : Mask)
19068     M = VMask[M];
19069   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19070                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19071
19072   // It is possible that one of the combinable shuffles was completely absorbed
19073   // by the other, just replace it and revisit all users in that case.
19074   if (Old.getNode() == V.getNode()) {
19075     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19076     return true;
19077   }
19078
19079   // Replace N with its operand as we're going to combine that shuffle away.
19080   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19081
19082   // Replace the combinable shuffle with the combined one, updating all users
19083   // so that we re-evaluate the chain here.
19084   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19085   return true;
19086 }
19087
19088 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19089 ///
19090 /// We walk up the chain, skipping shuffles of the other half and looking
19091 /// through shuffles which switch halves trying to find a shuffle of the same
19092 /// pair of dwords.
19093 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19094                                         SelectionDAG &DAG,
19095                                         TargetLowering::DAGCombinerInfo &DCI) {
19096   assert(
19097       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19098       "Called with something other than an x86 128-bit half shuffle!");
19099   SDLoc DL(N);
19100   unsigned CombineOpcode = N.getOpcode();
19101
19102   // Walk up a single-use chain looking for a combinable shuffle.
19103   SDValue V = N.getOperand(0);
19104   for (; V.hasOneUse(); V = V.getOperand(0)) {
19105     switch (V.getOpcode()) {
19106     default:
19107       return false; // Nothing combined!
19108
19109     case ISD::BITCAST:
19110       // Skip bitcasts as we always know the type for the target specific
19111       // instructions.
19112       continue;
19113
19114     case X86ISD::PSHUFLW:
19115     case X86ISD::PSHUFHW:
19116       if (V.getOpcode() == CombineOpcode)
19117         break;
19118
19119       // Other-half shuffles are no-ops.
19120       continue;
19121
19122     case X86ISD::PSHUFD: {
19123       // We can only handle pshufd if the half we are combining either stays in
19124       // its half, or switches to the other half. Bail if one of these isn't
19125       // true.
19126       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19127       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19128       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19129             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19130         return false;
19131
19132       // Map the mask through the pshufd and keep walking up the chain.
19133       for (int i = 0; i < 4; ++i)
19134         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19135
19136       // Switch halves if the pshufd does.
19137       CombineOpcode =
19138           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19139       continue;
19140     }
19141     }
19142     // Break out of the loop if we break out of the switch.
19143     break;
19144   }
19145
19146   if (!V.hasOneUse())
19147     // We fell out of the loop without finding a viable combining instruction.
19148     return false;
19149
19150   // Record the old value to use in RAUW-ing.
19151   SDValue Old = V;
19152
19153   // Merge this node's mask and our incoming mask (adjusted to account for all
19154   // the pshufd instructions encountered).
19155   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19156   for (int &M : Mask)
19157     M = VMask[M];
19158   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19159                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19160
19161   // Replace N with its operand as we're going to combine that shuffle away.
19162   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19163
19164   // Replace the combinable shuffle with the combined one, updating all users
19165   // so that we re-evaluate the chain here.
19166   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19167   return true;
19168 }
19169
19170 /// \brief Try to combine x86 target specific shuffles.
19171 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19172                                            TargetLowering::DAGCombinerInfo &DCI,
19173                                            const X86Subtarget *Subtarget) {
19174   SDLoc DL(N);
19175   MVT VT = N.getSimpleValueType();
19176   SmallVector<int, 4> Mask;
19177
19178   switch (N.getOpcode()) {
19179   case X86ISD::PSHUFD:
19180   case X86ISD::PSHUFLW:
19181   case X86ISD::PSHUFHW:
19182     Mask = getPSHUFShuffleMask(N);
19183     assert(Mask.size() == 4);
19184     break;
19185   default:
19186     return SDValue();
19187   }
19188
19189   // Nuke no-op shuffles that show up after combining.
19190   if (isNoopShuffleMask(Mask))
19191     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19192
19193   // Look for simplifications involving one or two shuffle instructions.
19194   SDValue V = N.getOperand(0);
19195   switch (N.getOpcode()) {
19196   default:
19197     break;
19198   case X86ISD::PSHUFLW:
19199   case X86ISD::PSHUFHW:
19200     assert(VT == MVT::v8i16);
19201     (void)VT;
19202
19203     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19204       return SDValue(); // We combined away this shuffle, so we're done.
19205
19206     // See if this reduces to a PSHUFD which is no more expensive and can
19207     // combine with more operations.
19208     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19209         areAdjacentMasksSequential(Mask)) {
19210       int DMask[] = {-1, -1, -1, -1};
19211       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19212       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19213       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19214       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19215       DCI.AddToWorklist(V.getNode());
19216       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19217                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19218       DCI.AddToWorklist(V.getNode());
19219       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19220     }
19221
19222     // Look for shuffle patterns which can be implemented as a single unpack.
19223     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19224     // only works when we have a PSHUFD followed by two half-shuffles.
19225     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19226         (V.getOpcode() == X86ISD::PSHUFLW ||
19227          V.getOpcode() == X86ISD::PSHUFHW) &&
19228         V.getOpcode() != N.getOpcode() &&
19229         V.hasOneUse()) {
19230       SDValue D = V.getOperand(0);
19231       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19232         D = D.getOperand(0);
19233       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19234         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19235         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19236         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19237         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19238         int WordMask[8];
19239         for (int i = 0; i < 4; ++i) {
19240           WordMask[i + NOffset] = Mask[i] + NOffset;
19241           WordMask[i + VOffset] = VMask[i] + VOffset;
19242         }
19243         // Map the word mask through the DWord mask.
19244         int MappedMask[8];
19245         for (int i = 0; i < 8; ++i)
19246           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19247         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19248         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19249         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19250                        std::begin(UnpackLoMask)) ||
19251             std::equal(std::begin(MappedMask), std::end(MappedMask),
19252                        std::begin(UnpackHiMask))) {
19253           // We can replace all three shuffles with an unpack.
19254           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19255           DCI.AddToWorklist(V.getNode());
19256           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19257                                                 : X86ISD::UNPCKH,
19258                              DL, MVT::v8i16, V, V);
19259         }
19260       }
19261     }
19262
19263     break;
19264
19265   case X86ISD::PSHUFD:
19266     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19267       return SDValue(); // We combined away this shuffle.
19268
19269     break;
19270   }
19271
19272   return SDValue();
19273 }
19274
19275 /// PerformShuffleCombine - Performs several different shuffle combines.
19276 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19277                                      TargetLowering::DAGCombinerInfo &DCI,
19278                                      const X86Subtarget *Subtarget) {
19279   SDLoc dl(N);
19280   SDValue N0 = N->getOperand(0);
19281   SDValue N1 = N->getOperand(1);
19282   EVT VT = N->getValueType(0);
19283
19284   // Don't create instructions with illegal types after legalize types has run.
19285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19286   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19287     return SDValue();
19288
19289   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19290   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19291       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19292     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19293
19294   // During Type Legalization, when promoting illegal vector types,
19295   // the backend might introduce new shuffle dag nodes and bitcasts.
19296   //
19297   // This code performs the following transformation:
19298   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19299   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19300   //
19301   // We do this only if both the bitcast and the BINOP dag nodes have
19302   // one use. Also, perform this transformation only if the new binary
19303   // operation is legal. This is to avoid introducing dag nodes that
19304   // potentially need to be further expanded (or custom lowered) into a
19305   // less optimal sequence of dag nodes.
19306   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19307       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19308       N0.getOpcode() == ISD::BITCAST) {
19309     SDValue BC0 = N0.getOperand(0);
19310     EVT SVT = BC0.getValueType();
19311     unsigned Opcode = BC0.getOpcode();
19312     unsigned NumElts = VT.getVectorNumElements();
19313     
19314     if (BC0.hasOneUse() && SVT.isVector() &&
19315         SVT.getVectorNumElements() * 2 == NumElts &&
19316         TLI.isOperationLegal(Opcode, VT)) {
19317       bool CanFold = false;
19318       switch (Opcode) {
19319       default : break;
19320       case ISD::ADD :
19321       case ISD::FADD :
19322       case ISD::SUB :
19323       case ISD::FSUB :
19324       case ISD::MUL :
19325       case ISD::FMUL :
19326         CanFold = true;
19327       }
19328
19329       unsigned SVTNumElts = SVT.getVectorNumElements();
19330       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19331       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19332         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19333       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19334         CanFold = SVOp->getMaskElt(i) < 0;
19335
19336       if (CanFold) {
19337         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19338         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19339         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19340         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19341       }
19342     }
19343   }
19344
19345   // Only handle 128 wide vector from here on.
19346   if (!VT.is128BitVector())
19347     return SDValue();
19348
19349   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19350   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19351   // consecutive, non-overlapping, and in the right order.
19352   SmallVector<SDValue, 16> Elts;
19353   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19354     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19355
19356   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19357   if (LD.getNode())
19358     return LD;
19359
19360   if (isTargetShuffle(N->getOpcode())) {
19361     SDValue Shuffle =
19362         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19363     if (Shuffle.getNode())
19364       return Shuffle;
19365
19366     // Try recursively combining arbitrary sequences of x86 shuffle
19367     // instructions into higher-order shuffles. We do this after combining
19368     // specific PSHUF instruction sequences into their minimal form so that we
19369     // can evaluate how many specialized shuffle instructions are involved in
19370     // a particular chain.
19371     SmallVector<int, 1> NonceMask; // Just a placeholder.
19372     NonceMask.push_back(0);
19373     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19374                                       /*Depth*/ 1, DAG, DCI, Subtarget))
19375       return SDValue(); // This routine will use CombineTo to replace N.
19376   }
19377
19378   return SDValue();
19379 }
19380
19381 /// PerformTruncateCombine - Converts truncate operation to
19382 /// a sequence of vector shuffle operations.
19383 /// It is possible when we truncate 256-bit vector to 128-bit vector
19384 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19385                                       TargetLowering::DAGCombinerInfo &DCI,
19386                                       const X86Subtarget *Subtarget)  {
19387   return SDValue();
19388 }
19389
19390 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19391 /// specific shuffle of a load can be folded into a single element load.
19392 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19393 /// shuffles have been customed lowered so we need to handle those here.
19394 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19395                                          TargetLowering::DAGCombinerInfo &DCI) {
19396   if (DCI.isBeforeLegalizeOps())
19397     return SDValue();
19398
19399   SDValue InVec = N->getOperand(0);
19400   SDValue EltNo = N->getOperand(1);
19401
19402   if (!isa<ConstantSDNode>(EltNo))
19403     return SDValue();
19404
19405   EVT VT = InVec.getValueType();
19406
19407   bool HasShuffleIntoBitcast = false;
19408   if (InVec.getOpcode() == ISD::BITCAST) {
19409     // Don't duplicate a load with other uses.
19410     if (!InVec.hasOneUse())
19411       return SDValue();
19412     EVT BCVT = InVec.getOperand(0).getValueType();
19413     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19414       return SDValue();
19415     InVec = InVec.getOperand(0);
19416     HasShuffleIntoBitcast = true;
19417   }
19418
19419   if (!isTargetShuffle(InVec.getOpcode()))
19420     return SDValue();
19421
19422   // Don't duplicate a load with other uses.
19423   if (!InVec.hasOneUse())
19424     return SDValue();
19425
19426   SmallVector<int, 16> ShuffleMask;
19427   bool UnaryShuffle;
19428   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19429                             UnaryShuffle))
19430     return SDValue();
19431
19432   // Select the input vector, guarding against out of range extract vector.
19433   unsigned NumElems = VT.getVectorNumElements();
19434   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19435   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19436   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19437                                          : InVec.getOperand(1);
19438
19439   // If inputs to shuffle are the same for both ops, then allow 2 uses
19440   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19441
19442   if (LdNode.getOpcode() == ISD::BITCAST) {
19443     // Don't duplicate a load with other uses.
19444     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19445       return SDValue();
19446
19447     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19448     LdNode = LdNode.getOperand(0);
19449   }
19450
19451   if (!ISD::isNormalLoad(LdNode.getNode()))
19452     return SDValue();
19453
19454   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19455
19456   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19457     return SDValue();
19458
19459   if (HasShuffleIntoBitcast) {
19460     // If there's a bitcast before the shuffle, check if the load type and
19461     // alignment is valid.
19462     unsigned Align = LN0->getAlignment();
19463     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19464     unsigned NewAlign = TLI.getDataLayout()->
19465       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19466
19467     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19468       return SDValue();
19469   }
19470
19471   // All checks match so transform back to vector_shuffle so that DAG combiner
19472   // can finish the job
19473   SDLoc dl(N);
19474
19475   // Create shuffle node taking into account the case that its a unary shuffle
19476   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19477   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19478                                  InVec.getOperand(0), Shuffle,
19479                                  &ShuffleMask[0]);
19480   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19481   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19482                      EltNo);
19483 }
19484
19485 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19486 /// generation and convert it from being a bunch of shuffles and extracts
19487 /// to a simple store and scalar loads to extract the elements.
19488 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19489                                          TargetLowering::DAGCombinerInfo &DCI) {
19490   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19491   if (NewOp.getNode())
19492     return NewOp;
19493
19494   SDValue InputVector = N->getOperand(0);
19495
19496   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19497   // from mmx to v2i32 has a single usage.
19498   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19499       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19500       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19501     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19502                        N->getValueType(0),
19503                        InputVector.getNode()->getOperand(0));
19504
19505   // Only operate on vectors of 4 elements, where the alternative shuffling
19506   // gets to be more expensive.
19507   if (InputVector.getValueType() != MVT::v4i32)
19508     return SDValue();
19509
19510   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19511   // single use which is a sign-extend or zero-extend, and all elements are
19512   // used.
19513   SmallVector<SDNode *, 4> Uses;
19514   unsigned ExtractedElements = 0;
19515   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19516        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19517     if (UI.getUse().getResNo() != InputVector.getResNo())
19518       return SDValue();
19519
19520     SDNode *Extract = *UI;
19521     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19522       return SDValue();
19523
19524     if (Extract->getValueType(0) != MVT::i32)
19525       return SDValue();
19526     if (!Extract->hasOneUse())
19527       return SDValue();
19528     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19529         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19530       return SDValue();
19531     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19532       return SDValue();
19533
19534     // Record which element was extracted.
19535     ExtractedElements |=
19536       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19537
19538     Uses.push_back(Extract);
19539   }
19540
19541   // If not all the elements were used, this may not be worthwhile.
19542   if (ExtractedElements != 15)
19543     return SDValue();
19544
19545   // Ok, we've now decided to do the transformation.
19546   SDLoc dl(InputVector);
19547
19548   // Store the value to a temporary stack slot.
19549   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19550   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19551                             MachinePointerInfo(), false, false, 0);
19552
19553   // Replace each use (extract) with a load of the appropriate element.
19554   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19555        UE = Uses.end(); UI != UE; ++UI) {
19556     SDNode *Extract = *UI;
19557
19558     // cOMpute the element's address.
19559     SDValue Idx = Extract->getOperand(1);
19560     unsigned EltSize =
19561         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19562     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19563     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19564     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19565
19566     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19567                                      StackPtr, OffsetVal);
19568
19569     // Load the scalar.
19570     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19571                                      ScalarAddr, MachinePointerInfo(),
19572                                      false, false, false, 0);
19573
19574     // Replace the exact with the load.
19575     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19576   }
19577
19578   // The replacement was made in place; don't return anything.
19579   return SDValue();
19580 }
19581
19582 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19583 static std::pair<unsigned, bool>
19584 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19585                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19586   if (!VT.isVector())
19587     return std::make_pair(0, false);
19588
19589   bool NeedSplit = false;
19590   switch (VT.getSimpleVT().SimpleTy) {
19591   default: return std::make_pair(0, false);
19592   case MVT::v32i8:
19593   case MVT::v16i16:
19594   case MVT::v8i32:
19595     if (!Subtarget->hasAVX2())
19596       NeedSplit = true;
19597     if (!Subtarget->hasAVX())
19598       return std::make_pair(0, false);
19599     break;
19600   case MVT::v16i8:
19601   case MVT::v8i16:
19602   case MVT::v4i32:
19603     if (!Subtarget->hasSSE2())
19604       return std::make_pair(0, false);
19605   }
19606
19607   // SSE2 has only a small subset of the operations.
19608   bool hasUnsigned = Subtarget->hasSSE41() ||
19609                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19610   bool hasSigned = Subtarget->hasSSE41() ||
19611                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19612
19613   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19614
19615   unsigned Opc = 0;
19616   // Check for x CC y ? x : y.
19617   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19618       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19619     switch (CC) {
19620     default: break;
19621     case ISD::SETULT:
19622     case ISD::SETULE:
19623       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19624     case ISD::SETUGT:
19625     case ISD::SETUGE:
19626       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19627     case ISD::SETLT:
19628     case ISD::SETLE:
19629       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19630     case ISD::SETGT:
19631     case ISD::SETGE:
19632       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19633     }
19634   // Check for x CC y ? y : x -- a min/max with reversed arms.
19635   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19636              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19637     switch (CC) {
19638     default: break;
19639     case ISD::SETULT:
19640     case ISD::SETULE:
19641       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19642     case ISD::SETUGT:
19643     case ISD::SETUGE:
19644       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19645     case ISD::SETLT:
19646     case ISD::SETLE:
19647       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19648     case ISD::SETGT:
19649     case ISD::SETGE:
19650       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19651     }
19652   }
19653
19654   return std::make_pair(Opc, NeedSplit);
19655 }
19656
19657 static SDValue
19658 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19659                                       const X86Subtarget *Subtarget) {
19660   SDLoc dl(N);
19661   SDValue Cond = N->getOperand(0);
19662   SDValue LHS = N->getOperand(1);
19663   SDValue RHS = N->getOperand(2);
19664
19665   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19666     SDValue CondSrc = Cond->getOperand(0);
19667     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19668       Cond = CondSrc->getOperand(0);
19669   }
19670
19671   MVT VT = N->getSimpleValueType(0);
19672   MVT EltVT = VT.getVectorElementType();
19673   unsigned NumElems = VT.getVectorNumElements();
19674   // There is no blend with immediate in AVX-512.
19675   if (VT.is512BitVector())
19676     return SDValue();
19677
19678   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19679     return SDValue();
19680   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19681     return SDValue();
19682
19683   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19684     return SDValue();
19685
19686   unsigned MaskValue = 0;
19687   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19688     return SDValue();
19689
19690   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19691   for (unsigned i = 0; i < NumElems; ++i) {
19692     // Be sure we emit undef where we can.
19693     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19694       ShuffleMask[i] = -1;
19695     else
19696       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19697   }
19698
19699   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19700 }
19701
19702 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19703 /// nodes.
19704 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19705                                     TargetLowering::DAGCombinerInfo &DCI,
19706                                     const X86Subtarget *Subtarget) {
19707   SDLoc DL(N);
19708   SDValue Cond = N->getOperand(0);
19709   // Get the LHS/RHS of the select.
19710   SDValue LHS = N->getOperand(1);
19711   SDValue RHS = N->getOperand(2);
19712   EVT VT = LHS.getValueType();
19713   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19714
19715   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19716   // instructions match the semantics of the common C idiom x<y?x:y but not
19717   // x<=y?x:y, because of how they handle negative zero (which can be
19718   // ignored in unsafe-math mode).
19719   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19720       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19721       (Subtarget->hasSSE2() ||
19722        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19723     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19724
19725     unsigned Opcode = 0;
19726     // Check for x CC y ? x : y.
19727     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19728         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19729       switch (CC) {
19730       default: break;
19731       case ISD::SETULT:
19732         // Converting this to a min would handle NaNs incorrectly, and swapping
19733         // the operands would cause it to handle comparisons between positive
19734         // and negative zero incorrectly.
19735         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19736           if (!DAG.getTarget().Options.UnsafeFPMath &&
19737               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19738             break;
19739           std::swap(LHS, RHS);
19740         }
19741         Opcode = X86ISD::FMIN;
19742         break;
19743       case ISD::SETOLE:
19744         // Converting this to a min would handle comparisons between positive
19745         // and negative zero incorrectly.
19746         if (!DAG.getTarget().Options.UnsafeFPMath &&
19747             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19748           break;
19749         Opcode = X86ISD::FMIN;
19750         break;
19751       case ISD::SETULE:
19752         // Converting this to a min would handle both negative zeros and NaNs
19753         // incorrectly, but we can swap the operands to fix both.
19754         std::swap(LHS, RHS);
19755       case ISD::SETOLT:
19756       case ISD::SETLT:
19757       case ISD::SETLE:
19758         Opcode = X86ISD::FMIN;
19759         break;
19760
19761       case ISD::SETOGE:
19762         // Converting this to a max would handle comparisons between positive
19763         // and negative zero incorrectly.
19764         if (!DAG.getTarget().Options.UnsafeFPMath &&
19765             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19766           break;
19767         Opcode = X86ISD::FMAX;
19768         break;
19769       case ISD::SETUGT:
19770         // Converting this to a max would handle NaNs incorrectly, and swapping
19771         // the operands would cause it to handle comparisons between positive
19772         // and negative zero incorrectly.
19773         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19774           if (!DAG.getTarget().Options.UnsafeFPMath &&
19775               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19776             break;
19777           std::swap(LHS, RHS);
19778         }
19779         Opcode = X86ISD::FMAX;
19780         break;
19781       case ISD::SETUGE:
19782         // Converting this to a max would handle both negative zeros and NaNs
19783         // incorrectly, but we can swap the operands to fix both.
19784         std::swap(LHS, RHS);
19785       case ISD::SETOGT:
19786       case ISD::SETGT:
19787       case ISD::SETGE:
19788         Opcode = X86ISD::FMAX;
19789         break;
19790       }
19791     // Check for x CC y ? y : x -- a min/max with reversed arms.
19792     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19793                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19794       switch (CC) {
19795       default: break;
19796       case ISD::SETOGE:
19797         // Converting this to a min would handle comparisons between positive
19798         // and negative zero incorrectly, and swapping the operands would
19799         // cause it to handle NaNs incorrectly.
19800         if (!DAG.getTarget().Options.UnsafeFPMath &&
19801             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19802           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19803             break;
19804           std::swap(LHS, RHS);
19805         }
19806         Opcode = X86ISD::FMIN;
19807         break;
19808       case ISD::SETUGT:
19809         // Converting this to a min would handle NaNs incorrectly.
19810         if (!DAG.getTarget().Options.UnsafeFPMath &&
19811             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19812           break;
19813         Opcode = X86ISD::FMIN;
19814         break;
19815       case ISD::SETUGE:
19816         // Converting this to a min would handle both negative zeros and NaNs
19817         // incorrectly, but we can swap the operands to fix both.
19818         std::swap(LHS, RHS);
19819       case ISD::SETOGT:
19820       case ISD::SETGT:
19821       case ISD::SETGE:
19822         Opcode = X86ISD::FMIN;
19823         break;
19824
19825       case ISD::SETULT:
19826         // Converting this to a max would handle NaNs incorrectly.
19827         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19828           break;
19829         Opcode = X86ISD::FMAX;
19830         break;
19831       case ISD::SETOLE:
19832         // Converting this to a max would handle comparisons between positive
19833         // and negative zero incorrectly, and swapping the operands would
19834         // cause it to handle NaNs incorrectly.
19835         if (!DAG.getTarget().Options.UnsafeFPMath &&
19836             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19837           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19838             break;
19839           std::swap(LHS, RHS);
19840         }
19841         Opcode = X86ISD::FMAX;
19842         break;
19843       case ISD::SETULE:
19844         // Converting this to a max would handle both negative zeros and NaNs
19845         // incorrectly, but we can swap the operands to fix both.
19846         std::swap(LHS, RHS);
19847       case ISD::SETOLT:
19848       case ISD::SETLT:
19849       case ISD::SETLE:
19850         Opcode = X86ISD::FMAX;
19851         break;
19852       }
19853     }
19854
19855     if (Opcode)
19856       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19857   }
19858
19859   EVT CondVT = Cond.getValueType();
19860   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19861       CondVT.getVectorElementType() == MVT::i1) {
19862     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19863     // lowering on AVX-512. In this case we convert it to
19864     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19865     // The same situation for all 128 and 256-bit vectors of i8 and i16
19866     EVT OpVT = LHS.getValueType();
19867     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19868         (OpVT.getVectorElementType() == MVT::i8 ||
19869          OpVT.getVectorElementType() == MVT::i16)) {
19870       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19871       DCI.AddToWorklist(Cond.getNode());
19872       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19873     }
19874   }
19875   // If this is a select between two integer constants, try to do some
19876   // optimizations.
19877   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19878     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19879       // Don't do this for crazy integer types.
19880       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19881         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19882         // so that TrueC (the true value) is larger than FalseC.
19883         bool NeedsCondInvert = false;
19884
19885         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19886             // Efficiently invertible.
19887             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19888              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19889               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19890           NeedsCondInvert = true;
19891           std::swap(TrueC, FalseC);
19892         }
19893
19894         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19895         if (FalseC->getAPIntValue() == 0 &&
19896             TrueC->getAPIntValue().isPowerOf2()) {
19897           if (NeedsCondInvert) // Invert the condition if needed.
19898             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19899                                DAG.getConstant(1, Cond.getValueType()));
19900
19901           // Zero extend the condition if needed.
19902           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19903
19904           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19905           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19906                              DAG.getConstant(ShAmt, MVT::i8));
19907         }
19908
19909         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19910         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19911           if (NeedsCondInvert) // Invert the condition if needed.
19912             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19913                                DAG.getConstant(1, Cond.getValueType()));
19914
19915           // Zero extend the condition if needed.
19916           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19917                              FalseC->getValueType(0), Cond);
19918           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19919                              SDValue(FalseC, 0));
19920         }
19921
19922         // Optimize cases that will turn into an LEA instruction.  This requires
19923         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19924         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19925           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19926           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19927
19928           bool isFastMultiplier = false;
19929           if (Diff < 10) {
19930             switch ((unsigned char)Diff) {
19931               default: break;
19932               case 1:  // result = add base, cond
19933               case 2:  // result = lea base(    , cond*2)
19934               case 3:  // result = lea base(cond, cond*2)
19935               case 4:  // result = lea base(    , cond*4)
19936               case 5:  // result = lea base(cond, cond*4)
19937               case 8:  // result = lea base(    , cond*8)
19938               case 9:  // result = lea base(cond, cond*8)
19939                 isFastMultiplier = true;
19940                 break;
19941             }
19942           }
19943
19944           if (isFastMultiplier) {
19945             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19946             if (NeedsCondInvert) // Invert the condition if needed.
19947               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19948                                  DAG.getConstant(1, Cond.getValueType()));
19949
19950             // Zero extend the condition if needed.
19951             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19952                                Cond);
19953             // Scale the condition by the difference.
19954             if (Diff != 1)
19955               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19956                                  DAG.getConstant(Diff, Cond.getValueType()));
19957
19958             // Add the base if non-zero.
19959             if (FalseC->getAPIntValue() != 0)
19960               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19961                                  SDValue(FalseC, 0));
19962             return Cond;
19963           }
19964         }
19965       }
19966   }
19967
19968   // Canonicalize max and min:
19969   // (x > y) ? x : y -> (x >= y) ? x : y
19970   // (x < y) ? x : y -> (x <= y) ? x : y
19971   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19972   // the need for an extra compare
19973   // against zero. e.g.
19974   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19975   // subl   %esi, %edi
19976   // testl  %edi, %edi
19977   // movl   $0, %eax
19978   // cmovgl %edi, %eax
19979   // =>
19980   // xorl   %eax, %eax
19981   // subl   %esi, $edi
19982   // cmovsl %eax, %edi
19983   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19984       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19985       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19986     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19987     switch (CC) {
19988     default: break;
19989     case ISD::SETLT:
19990     case ISD::SETGT: {
19991       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19992       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19993                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
19994       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19995     }
19996     }
19997   }
19998
19999   // Early exit check
20000   if (!TLI.isTypeLegal(VT))
20001     return SDValue();
20002
20003   // Match VSELECTs into subs with unsigned saturation.
20004   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20005       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20006       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20007        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20008     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20009
20010     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20011     // left side invert the predicate to simplify logic below.
20012     SDValue Other;
20013     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20014       Other = RHS;
20015       CC = ISD::getSetCCInverse(CC, true);
20016     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20017       Other = LHS;
20018     }
20019
20020     if (Other.getNode() && Other->getNumOperands() == 2 &&
20021         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20022       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20023       SDValue CondRHS = Cond->getOperand(1);
20024
20025       // Look for a general sub with unsigned saturation first.
20026       // x >= y ? x-y : 0 --> subus x, y
20027       // x >  y ? x-y : 0 --> subus x, y
20028       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20029           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20030         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20031
20032       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20033         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20034           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20035             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20036               // If the RHS is a constant we have to reverse the const
20037               // canonicalization.
20038               // x > C-1 ? x+-C : 0 --> subus x, C
20039               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20040                   CondRHSConst->getAPIntValue() ==
20041                       (-OpRHSConst->getAPIntValue() - 1))
20042                 return DAG.getNode(
20043                     X86ISD::SUBUS, DL, VT, OpLHS,
20044                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20045
20046           // Another special case: If C was a sign bit, the sub has been
20047           // canonicalized into a xor.
20048           // FIXME: Would it be better to use computeKnownBits to determine
20049           //        whether it's safe to decanonicalize the xor?
20050           // x s< 0 ? x^C : 0 --> subus x, C
20051           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20052               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20053               OpRHSConst->getAPIntValue().isSignBit())
20054             // Note that we have to rebuild the RHS constant here to ensure we
20055             // don't rely on particular values of undef lanes.
20056             return DAG.getNode(
20057                 X86ISD::SUBUS, DL, VT, OpLHS,
20058                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20059         }
20060     }
20061   }
20062
20063   // Try to match a min/max vector operation.
20064   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20065     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20066     unsigned Opc = ret.first;
20067     bool NeedSplit = ret.second;
20068
20069     if (Opc && NeedSplit) {
20070       unsigned NumElems = VT.getVectorNumElements();
20071       // Extract the LHS vectors
20072       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20073       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20074
20075       // Extract the RHS vectors
20076       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20077       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20078
20079       // Create min/max for each subvector
20080       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20081       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20082
20083       // Merge the result
20084       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20085     } else if (Opc)
20086       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20087   }
20088
20089   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20090   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20091       // Check if SETCC has already been promoted
20092       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20093       // Check that condition value type matches vselect operand type
20094       CondVT == VT) { 
20095
20096     assert(Cond.getValueType().isVector() &&
20097            "vector select expects a vector selector!");
20098
20099     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20100     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20101
20102     if (!TValIsAllOnes && !FValIsAllZeros) {
20103       // Try invert the condition if true value is not all 1s and false value
20104       // is not all 0s.
20105       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20106       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20107
20108       if (TValIsAllZeros || FValIsAllOnes) {
20109         SDValue CC = Cond.getOperand(2);
20110         ISD::CondCode NewCC =
20111           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20112                                Cond.getOperand(0).getValueType().isInteger());
20113         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20114         std::swap(LHS, RHS);
20115         TValIsAllOnes = FValIsAllOnes;
20116         FValIsAllZeros = TValIsAllZeros;
20117       }
20118     }
20119
20120     if (TValIsAllOnes || FValIsAllZeros) {
20121       SDValue Ret;
20122
20123       if (TValIsAllOnes && FValIsAllZeros)
20124         Ret = Cond;
20125       else if (TValIsAllOnes)
20126         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20127                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20128       else if (FValIsAllZeros)
20129         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20130                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20131
20132       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20133     }
20134   }
20135
20136   // Try to fold this VSELECT into a MOVSS/MOVSD
20137   if (N->getOpcode() == ISD::VSELECT &&
20138       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20139     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20140         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20141       bool CanFold = false;
20142       unsigned NumElems = Cond.getNumOperands();
20143       SDValue A = LHS;
20144       SDValue B = RHS;
20145       
20146       if (isZero(Cond.getOperand(0))) {
20147         CanFold = true;
20148
20149         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20150         // fold (vselect <0,-1> -> (movsd A, B)
20151         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20152           CanFold = isAllOnes(Cond.getOperand(i));
20153       } else if (isAllOnes(Cond.getOperand(0))) {
20154         CanFold = true;
20155         std::swap(A, B);
20156
20157         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20158         // fold (vselect <-1,0> -> (movsd B, A)
20159         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20160           CanFold = isZero(Cond.getOperand(i));
20161       }
20162
20163       if (CanFold) {
20164         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20165           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20166         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20167       }
20168
20169       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20170         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20171         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20172         //                             (v2i64 (bitcast B)))))
20173         //
20174         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20175         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20176         //                             (v2f64 (bitcast B)))))
20177         //
20178         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20179         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20180         //                             (v2i64 (bitcast A)))))
20181         //
20182         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20183         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20184         //                             (v2f64 (bitcast A)))))
20185
20186         CanFold = (isZero(Cond.getOperand(0)) &&
20187                    isZero(Cond.getOperand(1)) &&
20188                    isAllOnes(Cond.getOperand(2)) &&
20189                    isAllOnes(Cond.getOperand(3)));
20190
20191         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20192             isAllOnes(Cond.getOperand(1)) &&
20193             isZero(Cond.getOperand(2)) &&
20194             isZero(Cond.getOperand(3))) {
20195           CanFold = true;
20196           std::swap(LHS, RHS);
20197         }
20198
20199         if (CanFold) {
20200           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20201           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20202           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20203           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20204                                                 NewB, DAG);
20205           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20206         }
20207       }
20208     }
20209   }
20210
20211   // If we know that this node is legal then we know that it is going to be
20212   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20213   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20214   // to simplify previous instructions.
20215   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20216       !DCI.isBeforeLegalize() &&
20217       // We explicitly check against v8i16 and v16i16 because, although
20218       // they're marked as Custom, they might only be legal when Cond is a
20219       // build_vector of constants. This will be taken care in a later
20220       // condition.
20221       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20222        VT != MVT::v8i16)) {
20223     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20224
20225     // Don't optimize vector selects that map to mask-registers.
20226     if (BitWidth == 1)
20227       return SDValue();
20228
20229     // Check all uses of that condition operand to check whether it will be
20230     // consumed by non-BLEND instructions, which may depend on all bits are set
20231     // properly.
20232     for (SDNode::use_iterator I = Cond->use_begin(),
20233                               E = Cond->use_end(); I != E; ++I)
20234       if (I->getOpcode() != ISD::VSELECT)
20235         // TODO: Add other opcodes eventually lowered into BLEND.
20236         return SDValue();
20237
20238     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20239     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20240
20241     APInt KnownZero, KnownOne;
20242     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20243                                           DCI.isBeforeLegalizeOps());
20244     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20245         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20246       DCI.CommitTargetLoweringOpt(TLO);
20247   }
20248
20249   // We should generate an X86ISD::BLENDI from a vselect if its argument
20250   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20251   // constants. This specific pattern gets generated when we split a
20252   // selector for a 512 bit vector in a machine without AVX512 (but with
20253   // 256-bit vectors), during legalization:
20254   //
20255   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20256   //
20257   // Iff we find this pattern and the build_vectors are built from
20258   // constants, we translate the vselect into a shuffle_vector that we
20259   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20260   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20261     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20262     if (Shuffle.getNode())
20263       return Shuffle;
20264   }
20265
20266   return SDValue();
20267 }
20268
20269 // Check whether a boolean test is testing a boolean value generated by
20270 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20271 // code.
20272 //
20273 // Simplify the following patterns:
20274 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20275 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20276 // to (Op EFLAGS Cond)
20277 //
20278 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20279 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20280 // to (Op EFLAGS !Cond)
20281 //
20282 // where Op could be BRCOND or CMOV.
20283 //
20284 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20285   // Quit if not CMP and SUB with its value result used.
20286   if (Cmp.getOpcode() != X86ISD::CMP &&
20287       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20288       return SDValue();
20289
20290   // Quit if not used as a boolean value.
20291   if (CC != X86::COND_E && CC != X86::COND_NE)
20292     return SDValue();
20293
20294   // Check CMP operands. One of them should be 0 or 1 and the other should be
20295   // an SetCC or extended from it.
20296   SDValue Op1 = Cmp.getOperand(0);
20297   SDValue Op2 = Cmp.getOperand(1);
20298
20299   SDValue SetCC;
20300   const ConstantSDNode* C = nullptr;
20301   bool needOppositeCond = (CC == X86::COND_E);
20302   bool checkAgainstTrue = false; // Is it a comparison against 1?
20303
20304   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20305     SetCC = Op2;
20306   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20307     SetCC = Op1;
20308   else // Quit if all operands are not constants.
20309     return SDValue();
20310
20311   if (C->getZExtValue() == 1) {
20312     needOppositeCond = !needOppositeCond;
20313     checkAgainstTrue = true;
20314   } else if (C->getZExtValue() != 0)
20315     // Quit if the constant is neither 0 or 1.
20316     return SDValue();
20317
20318   bool truncatedToBoolWithAnd = false;
20319   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20320   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20321          SetCC.getOpcode() == ISD::TRUNCATE ||
20322          SetCC.getOpcode() == ISD::AND) {
20323     if (SetCC.getOpcode() == ISD::AND) {
20324       int OpIdx = -1;
20325       ConstantSDNode *CS;
20326       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20327           CS->getZExtValue() == 1)
20328         OpIdx = 1;
20329       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20330           CS->getZExtValue() == 1)
20331         OpIdx = 0;
20332       if (OpIdx == -1)
20333         break;
20334       SetCC = SetCC.getOperand(OpIdx);
20335       truncatedToBoolWithAnd = true;
20336     } else
20337       SetCC = SetCC.getOperand(0);
20338   }
20339
20340   switch (SetCC.getOpcode()) {
20341   case X86ISD::SETCC_CARRY:
20342     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20343     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20344     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20345     // truncated to i1 using 'and'.
20346     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20347       break;
20348     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20349            "Invalid use of SETCC_CARRY!");
20350     // FALL THROUGH
20351   case X86ISD::SETCC:
20352     // Set the condition code or opposite one if necessary.
20353     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20354     if (needOppositeCond)
20355       CC = X86::GetOppositeBranchCondition(CC);
20356     return SetCC.getOperand(1);
20357   case X86ISD::CMOV: {
20358     // Check whether false/true value has canonical one, i.e. 0 or 1.
20359     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20360     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20361     // Quit if true value is not a constant.
20362     if (!TVal)
20363       return SDValue();
20364     // Quit if false value is not a constant.
20365     if (!FVal) {
20366       SDValue Op = SetCC.getOperand(0);
20367       // Skip 'zext' or 'trunc' node.
20368       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20369           Op.getOpcode() == ISD::TRUNCATE)
20370         Op = Op.getOperand(0);
20371       // A special case for rdrand/rdseed, where 0 is set if false cond is
20372       // found.
20373       if ((Op.getOpcode() != X86ISD::RDRAND &&
20374            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20375         return SDValue();
20376     }
20377     // Quit if false value is not the constant 0 or 1.
20378     bool FValIsFalse = true;
20379     if (FVal && FVal->getZExtValue() != 0) {
20380       if (FVal->getZExtValue() != 1)
20381         return SDValue();
20382       // If FVal is 1, opposite cond is needed.
20383       needOppositeCond = !needOppositeCond;
20384       FValIsFalse = false;
20385     }
20386     // Quit if TVal is not the constant opposite of FVal.
20387     if (FValIsFalse && TVal->getZExtValue() != 1)
20388       return SDValue();
20389     if (!FValIsFalse && TVal->getZExtValue() != 0)
20390       return SDValue();
20391     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20392     if (needOppositeCond)
20393       CC = X86::GetOppositeBranchCondition(CC);
20394     return SetCC.getOperand(3);
20395   }
20396   }
20397
20398   return SDValue();
20399 }
20400
20401 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20402 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20403                                   TargetLowering::DAGCombinerInfo &DCI,
20404                                   const X86Subtarget *Subtarget) {
20405   SDLoc DL(N);
20406
20407   // If the flag operand isn't dead, don't touch this CMOV.
20408   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20409     return SDValue();
20410
20411   SDValue FalseOp = N->getOperand(0);
20412   SDValue TrueOp = N->getOperand(1);
20413   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20414   SDValue Cond = N->getOperand(3);
20415
20416   if (CC == X86::COND_E || CC == X86::COND_NE) {
20417     switch (Cond.getOpcode()) {
20418     default: break;
20419     case X86ISD::BSR:
20420     case X86ISD::BSF:
20421       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20422       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20423         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20424     }
20425   }
20426
20427   SDValue Flags;
20428
20429   Flags = checkBoolTestSetCCCombine(Cond, CC);
20430   if (Flags.getNode() &&
20431       // Extra check as FCMOV only supports a subset of X86 cond.
20432       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20433     SDValue Ops[] = { FalseOp, TrueOp,
20434                       DAG.getConstant(CC, MVT::i8), Flags };
20435     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20436   }
20437
20438   // If this is a select between two integer constants, try to do some
20439   // optimizations.  Note that the operands are ordered the opposite of SELECT
20440   // operands.
20441   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20442     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20443       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20444       // larger than FalseC (the false value).
20445       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20446         CC = X86::GetOppositeBranchCondition(CC);
20447         std::swap(TrueC, FalseC);
20448         std::swap(TrueOp, FalseOp);
20449       }
20450
20451       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20452       // This is efficient for any integer data type (including i8/i16) and
20453       // shift amount.
20454       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20455         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20456                            DAG.getConstant(CC, MVT::i8), Cond);
20457
20458         // Zero extend the condition if needed.
20459         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20460
20461         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20462         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20463                            DAG.getConstant(ShAmt, MVT::i8));
20464         if (N->getNumValues() == 2)  // Dead flag value?
20465           return DCI.CombineTo(N, Cond, SDValue());
20466         return Cond;
20467       }
20468
20469       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20470       // for any integer data type, including i8/i16.
20471       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20472         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20473                            DAG.getConstant(CC, MVT::i8), Cond);
20474
20475         // Zero extend the condition if needed.
20476         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20477                            FalseC->getValueType(0), Cond);
20478         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20479                            SDValue(FalseC, 0));
20480
20481         if (N->getNumValues() == 2)  // Dead flag value?
20482           return DCI.CombineTo(N, Cond, SDValue());
20483         return Cond;
20484       }
20485
20486       // Optimize cases that will turn into an LEA instruction.  This requires
20487       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20488       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20489         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20490         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20491
20492         bool isFastMultiplier = false;
20493         if (Diff < 10) {
20494           switch ((unsigned char)Diff) {
20495           default: break;
20496           case 1:  // result = add base, cond
20497           case 2:  // result = lea base(    , cond*2)
20498           case 3:  // result = lea base(cond, cond*2)
20499           case 4:  // result = lea base(    , cond*4)
20500           case 5:  // result = lea base(cond, cond*4)
20501           case 8:  // result = lea base(    , cond*8)
20502           case 9:  // result = lea base(cond, cond*8)
20503             isFastMultiplier = true;
20504             break;
20505           }
20506         }
20507
20508         if (isFastMultiplier) {
20509           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20510           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20511                              DAG.getConstant(CC, MVT::i8), Cond);
20512           // Zero extend the condition if needed.
20513           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20514                              Cond);
20515           // Scale the condition by the difference.
20516           if (Diff != 1)
20517             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20518                                DAG.getConstant(Diff, Cond.getValueType()));
20519
20520           // Add the base if non-zero.
20521           if (FalseC->getAPIntValue() != 0)
20522             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20523                                SDValue(FalseC, 0));
20524           if (N->getNumValues() == 2)  // Dead flag value?
20525             return DCI.CombineTo(N, Cond, SDValue());
20526           return Cond;
20527         }
20528       }
20529     }
20530   }
20531
20532   // Handle these cases:
20533   //   (select (x != c), e, c) -> select (x != c), e, x),
20534   //   (select (x == c), c, e) -> select (x == c), x, e)
20535   // where the c is an integer constant, and the "select" is the combination
20536   // of CMOV and CMP.
20537   //
20538   // The rationale for this change is that the conditional-move from a constant
20539   // needs two instructions, however, conditional-move from a register needs
20540   // only one instruction.
20541   //
20542   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20543   //  some instruction-combining opportunities. This opt needs to be
20544   //  postponed as late as possible.
20545   //
20546   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20547     // the DCI.xxxx conditions are provided to postpone the optimization as
20548     // late as possible.
20549
20550     ConstantSDNode *CmpAgainst = nullptr;
20551     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20552         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20553         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20554
20555       if (CC == X86::COND_NE &&
20556           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20557         CC = X86::GetOppositeBranchCondition(CC);
20558         std::swap(TrueOp, FalseOp);
20559       }
20560
20561       if (CC == X86::COND_E &&
20562           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20563         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20564                           DAG.getConstant(CC, MVT::i8), Cond };
20565         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20566       }
20567     }
20568   }
20569
20570   return SDValue();
20571 }
20572
20573 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20574                                                 const X86Subtarget *Subtarget) {
20575   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20576   switch (IntNo) {
20577   default: return SDValue();
20578   // SSE/AVX/AVX2 blend intrinsics.
20579   case Intrinsic::x86_avx2_pblendvb:
20580   case Intrinsic::x86_avx2_pblendw:
20581   case Intrinsic::x86_avx2_pblendd_128:
20582   case Intrinsic::x86_avx2_pblendd_256:
20583     // Don't try to simplify this intrinsic if we don't have AVX2.
20584     if (!Subtarget->hasAVX2())
20585       return SDValue();
20586     // FALL-THROUGH
20587   case Intrinsic::x86_avx_blend_pd_256:
20588   case Intrinsic::x86_avx_blend_ps_256:
20589   case Intrinsic::x86_avx_blendv_pd_256:
20590   case Intrinsic::x86_avx_blendv_ps_256:
20591     // Don't try to simplify this intrinsic if we don't have AVX.
20592     if (!Subtarget->hasAVX())
20593       return SDValue();
20594     // FALL-THROUGH
20595   case Intrinsic::x86_sse41_pblendw:
20596   case Intrinsic::x86_sse41_blendpd:
20597   case Intrinsic::x86_sse41_blendps:
20598   case Intrinsic::x86_sse41_blendvps:
20599   case Intrinsic::x86_sse41_blendvpd:
20600   case Intrinsic::x86_sse41_pblendvb: {
20601     SDValue Op0 = N->getOperand(1);
20602     SDValue Op1 = N->getOperand(2);
20603     SDValue Mask = N->getOperand(3);
20604
20605     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20606     if (!Subtarget->hasSSE41())
20607       return SDValue();
20608
20609     // fold (blend A, A, Mask) -> A
20610     if (Op0 == Op1)
20611       return Op0;
20612     // fold (blend A, B, allZeros) -> A
20613     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20614       return Op0;
20615     // fold (blend A, B, allOnes) -> B
20616     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20617       return Op1;
20618     
20619     // Simplify the case where the mask is a constant i32 value.
20620     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20621       if (C->isNullValue())
20622         return Op0;
20623       if (C->isAllOnesValue())
20624         return Op1;
20625     }
20626
20627     return SDValue();
20628   }
20629
20630   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20631   case Intrinsic::x86_sse2_psrai_w:
20632   case Intrinsic::x86_sse2_psrai_d:
20633   case Intrinsic::x86_avx2_psrai_w:
20634   case Intrinsic::x86_avx2_psrai_d:
20635   case Intrinsic::x86_sse2_psra_w:
20636   case Intrinsic::x86_sse2_psra_d:
20637   case Intrinsic::x86_avx2_psra_w:
20638   case Intrinsic::x86_avx2_psra_d: {
20639     SDValue Op0 = N->getOperand(1);
20640     SDValue Op1 = N->getOperand(2);
20641     EVT VT = Op0.getValueType();
20642     assert(VT.isVector() && "Expected a vector type!");
20643
20644     if (isa<BuildVectorSDNode>(Op1))
20645       Op1 = Op1.getOperand(0);
20646
20647     if (!isa<ConstantSDNode>(Op1))
20648       return SDValue();
20649
20650     EVT SVT = VT.getVectorElementType();
20651     unsigned SVTBits = SVT.getSizeInBits();
20652
20653     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20654     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20655     uint64_t ShAmt = C.getZExtValue();
20656
20657     // Don't try to convert this shift into a ISD::SRA if the shift
20658     // count is bigger than or equal to the element size.
20659     if (ShAmt >= SVTBits)
20660       return SDValue();
20661
20662     // Trivial case: if the shift count is zero, then fold this
20663     // into the first operand.
20664     if (ShAmt == 0)
20665       return Op0;
20666
20667     // Replace this packed shift intrinsic with a target independent
20668     // shift dag node.
20669     SDValue Splat = DAG.getConstant(C, VT);
20670     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20671   }
20672   }
20673 }
20674
20675 /// PerformMulCombine - Optimize a single multiply with constant into two
20676 /// in order to implement it with two cheaper instructions, e.g.
20677 /// LEA + SHL, LEA + LEA.
20678 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20679                                  TargetLowering::DAGCombinerInfo &DCI) {
20680   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20681     return SDValue();
20682
20683   EVT VT = N->getValueType(0);
20684   if (VT != MVT::i64)
20685     return SDValue();
20686
20687   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20688   if (!C)
20689     return SDValue();
20690   uint64_t MulAmt = C->getZExtValue();
20691   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20692     return SDValue();
20693
20694   uint64_t MulAmt1 = 0;
20695   uint64_t MulAmt2 = 0;
20696   if ((MulAmt % 9) == 0) {
20697     MulAmt1 = 9;
20698     MulAmt2 = MulAmt / 9;
20699   } else if ((MulAmt % 5) == 0) {
20700     MulAmt1 = 5;
20701     MulAmt2 = MulAmt / 5;
20702   } else if ((MulAmt % 3) == 0) {
20703     MulAmt1 = 3;
20704     MulAmt2 = MulAmt / 3;
20705   }
20706   if (MulAmt2 &&
20707       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20708     SDLoc DL(N);
20709
20710     if (isPowerOf2_64(MulAmt2) &&
20711         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20712       // If second multiplifer is pow2, issue it first. We want the multiply by
20713       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20714       // is an add.
20715       std::swap(MulAmt1, MulAmt2);
20716
20717     SDValue NewMul;
20718     if (isPowerOf2_64(MulAmt1))
20719       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20720                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20721     else
20722       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20723                            DAG.getConstant(MulAmt1, VT));
20724
20725     if (isPowerOf2_64(MulAmt2))
20726       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20727                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20728     else
20729       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20730                            DAG.getConstant(MulAmt2, VT));
20731
20732     // Do not add new nodes to DAG combiner worklist.
20733     DCI.CombineTo(N, NewMul, false);
20734   }
20735   return SDValue();
20736 }
20737
20738 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20739   SDValue N0 = N->getOperand(0);
20740   SDValue N1 = N->getOperand(1);
20741   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20742   EVT VT = N0.getValueType();
20743
20744   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20745   // since the result of setcc_c is all zero's or all ones.
20746   if (VT.isInteger() && !VT.isVector() &&
20747       N1C && N0.getOpcode() == ISD::AND &&
20748       N0.getOperand(1).getOpcode() == ISD::Constant) {
20749     SDValue N00 = N0.getOperand(0);
20750     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20751         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20752           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20753          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20754       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20755       APInt ShAmt = N1C->getAPIntValue();
20756       Mask = Mask.shl(ShAmt);
20757       if (Mask != 0)
20758         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20759                            N00, DAG.getConstant(Mask, VT));
20760     }
20761   }
20762
20763   // Hardware support for vector shifts is sparse which makes us scalarize the
20764   // vector operations in many cases. Also, on sandybridge ADD is faster than
20765   // shl.
20766   // (shl V, 1) -> add V,V
20767   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20768     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20769       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20770       // We shift all of the values by one. In many cases we do not have
20771       // hardware support for this operation. This is better expressed as an ADD
20772       // of two values.
20773       if (N1SplatC->getZExtValue() == 1)
20774         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20775     }
20776
20777   return SDValue();
20778 }
20779
20780 /// \brief Returns a vector of 0s if the node in input is a vector logical
20781 /// shift by a constant amount which is known to be bigger than or equal
20782 /// to the vector element size in bits.
20783 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20784                                       const X86Subtarget *Subtarget) {
20785   EVT VT = N->getValueType(0);
20786
20787   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20788       (!Subtarget->hasInt256() ||
20789        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20790     return SDValue();
20791
20792   SDValue Amt = N->getOperand(1);
20793   SDLoc DL(N);
20794   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20795     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20796       APInt ShiftAmt = AmtSplat->getAPIntValue();
20797       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20798
20799       // SSE2/AVX2 logical shifts always return a vector of 0s
20800       // if the shift amount is bigger than or equal to
20801       // the element size. The constant shift amount will be
20802       // encoded as a 8-bit immediate.
20803       if (ShiftAmt.trunc(8).uge(MaxAmount))
20804         return getZeroVector(VT, Subtarget, DAG, DL);
20805     }
20806
20807   return SDValue();
20808 }
20809
20810 /// PerformShiftCombine - Combine shifts.
20811 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20812                                    TargetLowering::DAGCombinerInfo &DCI,
20813                                    const X86Subtarget *Subtarget) {
20814   if (N->getOpcode() == ISD::SHL) {
20815     SDValue V = PerformSHLCombine(N, DAG);
20816     if (V.getNode()) return V;
20817   }
20818
20819   if (N->getOpcode() != ISD::SRA) {
20820     // Try to fold this logical shift into a zero vector.
20821     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20822     if (V.getNode()) return V;
20823   }
20824
20825   return SDValue();
20826 }
20827
20828 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20829 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20830 // and friends.  Likewise for OR -> CMPNEQSS.
20831 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20832                             TargetLowering::DAGCombinerInfo &DCI,
20833                             const X86Subtarget *Subtarget) {
20834   unsigned opcode;
20835
20836   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20837   // we're requiring SSE2 for both.
20838   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20839     SDValue N0 = N->getOperand(0);
20840     SDValue N1 = N->getOperand(1);
20841     SDValue CMP0 = N0->getOperand(1);
20842     SDValue CMP1 = N1->getOperand(1);
20843     SDLoc DL(N);
20844
20845     // The SETCCs should both refer to the same CMP.
20846     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20847       return SDValue();
20848
20849     SDValue CMP00 = CMP0->getOperand(0);
20850     SDValue CMP01 = CMP0->getOperand(1);
20851     EVT     VT    = CMP00.getValueType();
20852
20853     if (VT == MVT::f32 || VT == MVT::f64) {
20854       bool ExpectingFlags = false;
20855       // Check for any users that want flags:
20856       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20857            !ExpectingFlags && UI != UE; ++UI)
20858         switch (UI->getOpcode()) {
20859         default:
20860         case ISD::BR_CC:
20861         case ISD::BRCOND:
20862         case ISD::SELECT:
20863           ExpectingFlags = true;
20864           break;
20865         case ISD::CopyToReg:
20866         case ISD::SIGN_EXTEND:
20867         case ISD::ZERO_EXTEND:
20868         case ISD::ANY_EXTEND:
20869           break;
20870         }
20871
20872       if (!ExpectingFlags) {
20873         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20874         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20875
20876         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20877           X86::CondCode tmp = cc0;
20878           cc0 = cc1;
20879           cc1 = tmp;
20880         }
20881
20882         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20883             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20884           // FIXME: need symbolic constants for these magic numbers.
20885           // See X86ATTInstPrinter.cpp:printSSECC().
20886           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20887           if (Subtarget->hasAVX512()) {
20888             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20889                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20890             if (N->getValueType(0) != MVT::i1)
20891               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20892                                  FSetCC);
20893             return FSetCC;
20894           }
20895           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20896                                               CMP00.getValueType(), CMP00, CMP01,
20897                                               DAG.getConstant(x86cc, MVT::i8));
20898
20899           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20900           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20901
20902           if (is64BitFP && !Subtarget->is64Bit()) {
20903             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20904             // 64-bit integer, since that's not a legal type. Since
20905             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20906             // bits, but can do this little dance to extract the lowest 32 bits
20907             // and work with those going forward.
20908             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20909                                            OnesOrZeroesF);
20910             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20911                                            Vector64);
20912             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20913                                         Vector32, DAG.getIntPtrConstant(0));
20914             IntVT = MVT::i32;
20915           }
20916
20917           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20918           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20919                                       DAG.getConstant(1, IntVT));
20920           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20921           return OneBitOfTruth;
20922         }
20923       }
20924     }
20925   }
20926   return SDValue();
20927 }
20928
20929 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20930 /// so it can be folded inside ANDNP.
20931 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20932   EVT VT = N->getValueType(0);
20933
20934   // Match direct AllOnes for 128 and 256-bit vectors
20935   if (ISD::isBuildVectorAllOnes(N))
20936     return true;
20937
20938   // Look through a bit convert.
20939   if (N->getOpcode() == ISD::BITCAST)
20940     N = N->getOperand(0).getNode();
20941
20942   // Sometimes the operand may come from a insert_subvector building a 256-bit
20943   // allones vector
20944   if (VT.is256BitVector() &&
20945       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20946     SDValue V1 = N->getOperand(0);
20947     SDValue V2 = N->getOperand(1);
20948
20949     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20950         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20951         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20952         ISD::isBuildVectorAllOnes(V2.getNode()))
20953       return true;
20954   }
20955
20956   return false;
20957 }
20958
20959 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20960 // register. In most cases we actually compare or select YMM-sized registers
20961 // and mixing the two types creates horrible code. This method optimizes
20962 // some of the transition sequences.
20963 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20964                                  TargetLowering::DAGCombinerInfo &DCI,
20965                                  const X86Subtarget *Subtarget) {
20966   EVT VT = N->getValueType(0);
20967   if (!VT.is256BitVector())
20968     return SDValue();
20969
20970   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20971           N->getOpcode() == ISD::ZERO_EXTEND ||
20972           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20973
20974   SDValue Narrow = N->getOperand(0);
20975   EVT NarrowVT = Narrow->getValueType(0);
20976   if (!NarrowVT.is128BitVector())
20977     return SDValue();
20978
20979   if (Narrow->getOpcode() != ISD::XOR &&
20980       Narrow->getOpcode() != ISD::AND &&
20981       Narrow->getOpcode() != ISD::OR)
20982     return SDValue();
20983
20984   SDValue N0  = Narrow->getOperand(0);
20985   SDValue N1  = Narrow->getOperand(1);
20986   SDLoc DL(Narrow);
20987
20988   // The Left side has to be a trunc.
20989   if (N0.getOpcode() != ISD::TRUNCATE)
20990     return SDValue();
20991
20992   // The type of the truncated inputs.
20993   EVT WideVT = N0->getOperand(0)->getValueType(0);
20994   if (WideVT != VT)
20995     return SDValue();
20996
20997   // The right side has to be a 'trunc' or a constant vector.
20998   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20999   ConstantSDNode *RHSConstSplat = nullptr;
21000   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21001     RHSConstSplat = RHSBV->getConstantSplatNode();
21002   if (!RHSTrunc && !RHSConstSplat)
21003     return SDValue();
21004
21005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21006
21007   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21008     return SDValue();
21009
21010   // Set N0 and N1 to hold the inputs to the new wide operation.
21011   N0 = N0->getOperand(0);
21012   if (RHSConstSplat) {
21013     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21014                      SDValue(RHSConstSplat, 0));
21015     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21016     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21017   } else if (RHSTrunc) {
21018     N1 = N1->getOperand(0);
21019   }
21020
21021   // Generate the wide operation.
21022   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21023   unsigned Opcode = N->getOpcode();
21024   switch (Opcode) {
21025   case ISD::ANY_EXTEND:
21026     return Op;
21027   case ISD::ZERO_EXTEND: {
21028     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21029     APInt Mask = APInt::getAllOnesValue(InBits);
21030     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21031     return DAG.getNode(ISD::AND, DL, VT,
21032                        Op, DAG.getConstant(Mask, VT));
21033   }
21034   case ISD::SIGN_EXTEND:
21035     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21036                        Op, DAG.getValueType(NarrowVT));
21037   default:
21038     llvm_unreachable("Unexpected opcode");
21039   }
21040 }
21041
21042 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21043                                  TargetLowering::DAGCombinerInfo &DCI,
21044                                  const X86Subtarget *Subtarget) {
21045   EVT VT = N->getValueType(0);
21046   if (DCI.isBeforeLegalizeOps())
21047     return SDValue();
21048
21049   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21050   if (R.getNode())
21051     return R;
21052
21053   // Create BEXTR instructions
21054   // BEXTR is ((X >> imm) & (2**size-1))
21055   if (VT == MVT::i32 || VT == MVT::i64) {
21056     SDValue N0 = N->getOperand(0);
21057     SDValue N1 = N->getOperand(1);
21058     SDLoc DL(N);
21059
21060     // Check for BEXTR.
21061     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21062         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21063       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21064       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21065       if (MaskNode && ShiftNode) {
21066         uint64_t Mask = MaskNode->getZExtValue();
21067         uint64_t Shift = ShiftNode->getZExtValue();
21068         if (isMask_64(Mask)) {
21069           uint64_t MaskSize = CountPopulation_64(Mask);
21070           if (Shift + MaskSize <= VT.getSizeInBits())
21071             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21072                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21073         }
21074       }
21075     } // BEXTR
21076
21077     return SDValue();
21078   }
21079
21080   // Want to form ANDNP nodes:
21081   // 1) In the hopes of then easily combining them with OR and AND nodes
21082   //    to form PBLEND/PSIGN.
21083   // 2) To match ANDN packed intrinsics
21084   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21085     return SDValue();
21086
21087   SDValue N0 = N->getOperand(0);
21088   SDValue N1 = N->getOperand(1);
21089   SDLoc DL(N);
21090
21091   // Check LHS for vnot
21092   if (N0.getOpcode() == ISD::XOR &&
21093       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21094       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21095     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21096
21097   // Check RHS for vnot
21098   if (N1.getOpcode() == ISD::XOR &&
21099       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21100       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21101     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21102
21103   return SDValue();
21104 }
21105
21106 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21107                                 TargetLowering::DAGCombinerInfo &DCI,
21108                                 const X86Subtarget *Subtarget) {
21109   if (DCI.isBeforeLegalizeOps())
21110     return SDValue();
21111
21112   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21113   if (R.getNode())
21114     return R;
21115
21116   SDValue N0 = N->getOperand(0);
21117   SDValue N1 = N->getOperand(1);
21118   EVT VT = N->getValueType(0);
21119
21120   // look for psign/blend
21121   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21122     if (!Subtarget->hasSSSE3() ||
21123         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21124       return SDValue();
21125
21126     // Canonicalize pandn to RHS
21127     if (N0.getOpcode() == X86ISD::ANDNP)
21128       std::swap(N0, N1);
21129     // or (and (m, y), (pandn m, x))
21130     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21131       SDValue Mask = N1.getOperand(0);
21132       SDValue X    = N1.getOperand(1);
21133       SDValue Y;
21134       if (N0.getOperand(0) == Mask)
21135         Y = N0.getOperand(1);
21136       if (N0.getOperand(1) == Mask)
21137         Y = N0.getOperand(0);
21138
21139       // Check to see if the mask appeared in both the AND and ANDNP and
21140       if (!Y.getNode())
21141         return SDValue();
21142
21143       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21144       // Look through mask bitcast.
21145       if (Mask.getOpcode() == ISD::BITCAST)
21146         Mask = Mask.getOperand(0);
21147       if (X.getOpcode() == ISD::BITCAST)
21148         X = X.getOperand(0);
21149       if (Y.getOpcode() == ISD::BITCAST)
21150         Y = Y.getOperand(0);
21151
21152       EVT MaskVT = Mask.getValueType();
21153
21154       // Validate that the Mask operand is a vector sra node.
21155       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21156       // there is no psrai.b
21157       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21158       unsigned SraAmt = ~0;
21159       if (Mask.getOpcode() == ISD::SRA) {
21160         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21161           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21162             SraAmt = AmtConst->getZExtValue();
21163       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21164         SDValue SraC = Mask.getOperand(1);
21165         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21166       }
21167       if ((SraAmt + 1) != EltBits)
21168         return SDValue();
21169
21170       SDLoc DL(N);
21171
21172       // Now we know we at least have a plendvb with the mask val.  See if
21173       // we can form a psignb/w/d.
21174       // psign = x.type == y.type == mask.type && y = sub(0, x);
21175       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21176           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21177           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21178         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21179                "Unsupported VT for PSIGN");
21180         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21181         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21182       }
21183       // PBLENDVB only available on SSE 4.1
21184       if (!Subtarget->hasSSE41())
21185         return SDValue();
21186
21187       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21188
21189       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21190       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21191       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21192       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21193       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21194     }
21195   }
21196
21197   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21198     return SDValue();
21199
21200   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21201   MachineFunction &MF = DAG.getMachineFunction();
21202   bool OptForSize = MF.getFunction()->getAttributes().
21203     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21204
21205   // SHLD/SHRD instructions have lower register pressure, but on some
21206   // platforms they have higher latency than the equivalent
21207   // series of shifts/or that would otherwise be generated.
21208   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21209   // have higher latencies and we are not optimizing for size.
21210   if (!OptForSize && Subtarget->isSHLDSlow())
21211     return SDValue();
21212
21213   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21214     std::swap(N0, N1);
21215   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21216     return SDValue();
21217   if (!N0.hasOneUse() || !N1.hasOneUse())
21218     return SDValue();
21219
21220   SDValue ShAmt0 = N0.getOperand(1);
21221   if (ShAmt0.getValueType() != MVT::i8)
21222     return SDValue();
21223   SDValue ShAmt1 = N1.getOperand(1);
21224   if (ShAmt1.getValueType() != MVT::i8)
21225     return SDValue();
21226   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21227     ShAmt0 = ShAmt0.getOperand(0);
21228   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21229     ShAmt1 = ShAmt1.getOperand(0);
21230
21231   SDLoc DL(N);
21232   unsigned Opc = X86ISD::SHLD;
21233   SDValue Op0 = N0.getOperand(0);
21234   SDValue Op1 = N1.getOperand(0);
21235   if (ShAmt0.getOpcode() == ISD::SUB) {
21236     Opc = X86ISD::SHRD;
21237     std::swap(Op0, Op1);
21238     std::swap(ShAmt0, ShAmt1);
21239   }
21240
21241   unsigned Bits = VT.getSizeInBits();
21242   if (ShAmt1.getOpcode() == ISD::SUB) {
21243     SDValue Sum = ShAmt1.getOperand(0);
21244     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21245       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21246       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21247         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21248       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21249         return DAG.getNode(Opc, DL, VT,
21250                            Op0, Op1,
21251                            DAG.getNode(ISD::TRUNCATE, DL,
21252                                        MVT::i8, ShAmt0));
21253     }
21254   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21255     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21256     if (ShAmt0C &&
21257         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21258       return DAG.getNode(Opc, DL, VT,
21259                          N0.getOperand(0), N1.getOperand(0),
21260                          DAG.getNode(ISD::TRUNCATE, DL,
21261                                        MVT::i8, ShAmt0));
21262   }
21263
21264   return SDValue();
21265 }
21266
21267 // Generate NEG and CMOV for integer abs.
21268 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21269   EVT VT = N->getValueType(0);
21270
21271   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21272   // 8-bit integer abs to NEG and CMOV.
21273   if (VT.isInteger() && VT.getSizeInBits() == 8)
21274     return SDValue();
21275
21276   SDValue N0 = N->getOperand(0);
21277   SDValue N1 = N->getOperand(1);
21278   SDLoc DL(N);
21279
21280   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21281   // and change it to SUB and CMOV.
21282   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21283       N0.getOpcode() == ISD::ADD &&
21284       N0.getOperand(1) == N1 &&
21285       N1.getOpcode() == ISD::SRA &&
21286       N1.getOperand(0) == N0.getOperand(0))
21287     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21288       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21289         // Generate SUB & CMOV.
21290         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21291                                   DAG.getConstant(0, VT), N0.getOperand(0));
21292
21293         SDValue Ops[] = { N0.getOperand(0), Neg,
21294                           DAG.getConstant(X86::COND_GE, MVT::i8),
21295                           SDValue(Neg.getNode(), 1) };
21296         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21297       }
21298   return SDValue();
21299 }
21300
21301 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21302 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21303                                  TargetLowering::DAGCombinerInfo &DCI,
21304                                  const X86Subtarget *Subtarget) {
21305   if (DCI.isBeforeLegalizeOps())
21306     return SDValue();
21307
21308   if (Subtarget->hasCMov()) {
21309     SDValue RV = performIntegerAbsCombine(N, DAG);
21310     if (RV.getNode())
21311       return RV;
21312   }
21313
21314   return SDValue();
21315 }
21316
21317 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21318 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21319                                   TargetLowering::DAGCombinerInfo &DCI,
21320                                   const X86Subtarget *Subtarget) {
21321   LoadSDNode *Ld = cast<LoadSDNode>(N);
21322   EVT RegVT = Ld->getValueType(0);
21323   EVT MemVT = Ld->getMemoryVT();
21324   SDLoc dl(Ld);
21325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21326
21327   // On Sandybridge unaligned 256bit loads are inefficient.
21328   ISD::LoadExtType Ext = Ld->getExtensionType();
21329   unsigned Alignment = Ld->getAlignment();
21330   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21331   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21332       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21333     unsigned NumElems = RegVT.getVectorNumElements();
21334     if (NumElems < 2)
21335       return SDValue();
21336
21337     SDValue Ptr = Ld->getBasePtr();
21338     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21339
21340     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21341                                   NumElems/2);
21342     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21343                                 Ld->getPointerInfo(), Ld->isVolatile(),
21344                                 Ld->isNonTemporal(), Ld->isInvariant(),
21345                                 Alignment);
21346     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21347     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21348                                 Ld->getPointerInfo(), Ld->isVolatile(),
21349                                 Ld->isNonTemporal(), Ld->isInvariant(),
21350                                 std::min(16U, Alignment));
21351     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21352                              Load1.getValue(1),
21353                              Load2.getValue(1));
21354
21355     SDValue NewVec = DAG.getUNDEF(RegVT);
21356     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21357     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21358     return DCI.CombineTo(N, NewVec, TF, true);
21359   }
21360
21361   return SDValue();
21362 }
21363
21364 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21365 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21366                                    const X86Subtarget *Subtarget) {
21367   StoreSDNode *St = cast<StoreSDNode>(N);
21368   EVT VT = St->getValue().getValueType();
21369   EVT StVT = St->getMemoryVT();
21370   SDLoc dl(St);
21371   SDValue StoredVal = St->getOperand(1);
21372   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21373
21374   // If we are saving a concatenation of two XMM registers, perform two stores.
21375   // On Sandy Bridge, 256-bit memory operations are executed by two
21376   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21377   // memory  operation.
21378   unsigned Alignment = St->getAlignment();
21379   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21380   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21381       StVT == VT && !IsAligned) {
21382     unsigned NumElems = VT.getVectorNumElements();
21383     if (NumElems < 2)
21384       return SDValue();
21385
21386     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21387     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21388
21389     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21390     SDValue Ptr0 = St->getBasePtr();
21391     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21392
21393     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21394                                 St->getPointerInfo(), St->isVolatile(),
21395                                 St->isNonTemporal(), Alignment);
21396     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21397                                 St->getPointerInfo(), St->isVolatile(),
21398                                 St->isNonTemporal(),
21399                                 std::min(16U, Alignment));
21400     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21401   }
21402
21403   // Optimize trunc store (of multiple scalars) to shuffle and store.
21404   // First, pack all of the elements in one place. Next, store to memory
21405   // in fewer chunks.
21406   if (St->isTruncatingStore() && VT.isVector()) {
21407     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21408     unsigned NumElems = VT.getVectorNumElements();
21409     assert(StVT != VT && "Cannot truncate to the same type");
21410     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21411     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21412
21413     // From, To sizes and ElemCount must be pow of two
21414     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21415     // We are going to use the original vector elt for storing.
21416     // Accumulated smaller vector elements must be a multiple of the store size.
21417     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21418
21419     unsigned SizeRatio  = FromSz / ToSz;
21420
21421     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21422
21423     // Create a type on which we perform the shuffle
21424     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21425             StVT.getScalarType(), NumElems*SizeRatio);
21426
21427     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21428
21429     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21430     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21431     for (unsigned i = 0; i != NumElems; ++i)
21432       ShuffleVec[i] = i * SizeRatio;
21433
21434     // Can't shuffle using an illegal type.
21435     if (!TLI.isTypeLegal(WideVecVT))
21436       return SDValue();
21437
21438     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21439                                          DAG.getUNDEF(WideVecVT),
21440                                          &ShuffleVec[0]);
21441     // At this point all of the data is stored at the bottom of the
21442     // register. We now need to save it to mem.
21443
21444     // Find the largest store unit
21445     MVT StoreType = MVT::i8;
21446     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21447          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21448       MVT Tp = (MVT::SimpleValueType)tp;
21449       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21450         StoreType = Tp;
21451     }
21452
21453     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21454     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21455         (64 <= NumElems * ToSz))
21456       StoreType = MVT::f64;
21457
21458     // Bitcast the original vector into a vector of store-size units
21459     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21460             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21461     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21462     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21463     SmallVector<SDValue, 8> Chains;
21464     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21465                                         TLI.getPointerTy());
21466     SDValue Ptr = St->getBasePtr();
21467
21468     // Perform one or more big stores into memory.
21469     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21470       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21471                                    StoreType, ShuffWide,
21472                                    DAG.getIntPtrConstant(i));
21473       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21474                                 St->getPointerInfo(), St->isVolatile(),
21475                                 St->isNonTemporal(), St->getAlignment());
21476       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21477       Chains.push_back(Ch);
21478     }
21479
21480     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21481   }
21482
21483   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21484   // the FP state in cases where an emms may be missing.
21485   // A preferable solution to the general problem is to figure out the right
21486   // places to insert EMMS.  This qualifies as a quick hack.
21487
21488   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21489   if (VT.getSizeInBits() != 64)
21490     return SDValue();
21491
21492   const Function *F = DAG.getMachineFunction().getFunction();
21493   bool NoImplicitFloatOps = F->getAttributes().
21494     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21495   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21496                      && Subtarget->hasSSE2();
21497   if ((VT.isVector() ||
21498        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21499       isa<LoadSDNode>(St->getValue()) &&
21500       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21501       St->getChain().hasOneUse() && !St->isVolatile()) {
21502     SDNode* LdVal = St->getValue().getNode();
21503     LoadSDNode *Ld = nullptr;
21504     int TokenFactorIndex = -1;
21505     SmallVector<SDValue, 8> Ops;
21506     SDNode* ChainVal = St->getChain().getNode();
21507     // Must be a store of a load.  We currently handle two cases:  the load
21508     // is a direct child, and it's under an intervening TokenFactor.  It is
21509     // possible to dig deeper under nested TokenFactors.
21510     if (ChainVal == LdVal)
21511       Ld = cast<LoadSDNode>(St->getChain());
21512     else if (St->getValue().hasOneUse() &&
21513              ChainVal->getOpcode() == ISD::TokenFactor) {
21514       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21515         if (ChainVal->getOperand(i).getNode() == LdVal) {
21516           TokenFactorIndex = i;
21517           Ld = cast<LoadSDNode>(St->getValue());
21518         } else
21519           Ops.push_back(ChainVal->getOperand(i));
21520       }
21521     }
21522
21523     if (!Ld || !ISD::isNormalLoad(Ld))
21524       return SDValue();
21525
21526     // If this is not the MMX case, i.e. we are just turning i64 load/store
21527     // into f64 load/store, avoid the transformation if there are multiple
21528     // uses of the loaded value.
21529     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21530       return SDValue();
21531
21532     SDLoc LdDL(Ld);
21533     SDLoc StDL(N);
21534     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21535     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21536     // pair instead.
21537     if (Subtarget->is64Bit() || F64IsLegal) {
21538       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21539       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21540                                   Ld->getPointerInfo(), Ld->isVolatile(),
21541                                   Ld->isNonTemporal(), Ld->isInvariant(),
21542                                   Ld->getAlignment());
21543       SDValue NewChain = NewLd.getValue(1);
21544       if (TokenFactorIndex != -1) {
21545         Ops.push_back(NewChain);
21546         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21547       }
21548       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21549                           St->getPointerInfo(),
21550                           St->isVolatile(), St->isNonTemporal(),
21551                           St->getAlignment());
21552     }
21553
21554     // Otherwise, lower to two pairs of 32-bit loads / stores.
21555     SDValue LoAddr = Ld->getBasePtr();
21556     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21557                                  DAG.getConstant(4, MVT::i32));
21558
21559     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21560                                Ld->getPointerInfo(),
21561                                Ld->isVolatile(), Ld->isNonTemporal(),
21562                                Ld->isInvariant(), Ld->getAlignment());
21563     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21564                                Ld->getPointerInfo().getWithOffset(4),
21565                                Ld->isVolatile(), Ld->isNonTemporal(),
21566                                Ld->isInvariant(),
21567                                MinAlign(Ld->getAlignment(), 4));
21568
21569     SDValue NewChain = LoLd.getValue(1);
21570     if (TokenFactorIndex != -1) {
21571       Ops.push_back(LoLd);
21572       Ops.push_back(HiLd);
21573       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21574     }
21575
21576     LoAddr = St->getBasePtr();
21577     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21578                          DAG.getConstant(4, MVT::i32));
21579
21580     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21581                                 St->getPointerInfo(),
21582                                 St->isVolatile(), St->isNonTemporal(),
21583                                 St->getAlignment());
21584     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21585                                 St->getPointerInfo().getWithOffset(4),
21586                                 St->isVolatile(),
21587                                 St->isNonTemporal(),
21588                                 MinAlign(St->getAlignment(), 4));
21589     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21590   }
21591   return SDValue();
21592 }
21593
21594 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21595 /// and return the operands for the horizontal operation in LHS and RHS.  A
21596 /// horizontal operation performs the binary operation on successive elements
21597 /// of its first operand, then on successive elements of its second operand,
21598 /// returning the resulting values in a vector.  For example, if
21599 ///   A = < float a0, float a1, float a2, float a3 >
21600 /// and
21601 ///   B = < float b0, float b1, float b2, float b3 >
21602 /// then the result of doing a horizontal operation on A and B is
21603 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21604 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21605 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21606 /// set to A, RHS to B, and the routine returns 'true'.
21607 /// Note that the binary operation should have the property that if one of the
21608 /// operands is UNDEF then the result is UNDEF.
21609 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21610   // Look for the following pattern: if
21611   //   A = < float a0, float a1, float a2, float a3 >
21612   //   B = < float b0, float b1, float b2, float b3 >
21613   // and
21614   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21615   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21616   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21617   // which is A horizontal-op B.
21618
21619   // At least one of the operands should be a vector shuffle.
21620   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21621       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21622     return false;
21623
21624   MVT VT = LHS.getSimpleValueType();
21625
21626   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21627          "Unsupported vector type for horizontal add/sub");
21628
21629   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21630   // operate independently on 128-bit lanes.
21631   unsigned NumElts = VT.getVectorNumElements();
21632   unsigned NumLanes = VT.getSizeInBits()/128;
21633   unsigned NumLaneElts = NumElts / NumLanes;
21634   assert((NumLaneElts % 2 == 0) &&
21635          "Vector type should have an even number of elements in each lane");
21636   unsigned HalfLaneElts = NumLaneElts/2;
21637
21638   // View LHS in the form
21639   //   LHS = VECTOR_SHUFFLE A, B, LMask
21640   // If LHS is not a shuffle then pretend it is the shuffle
21641   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21642   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21643   // type VT.
21644   SDValue A, B;
21645   SmallVector<int, 16> LMask(NumElts);
21646   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21647     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21648       A = LHS.getOperand(0);
21649     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21650       B = LHS.getOperand(1);
21651     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21652     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21653   } else {
21654     if (LHS.getOpcode() != ISD::UNDEF)
21655       A = LHS;
21656     for (unsigned i = 0; i != NumElts; ++i)
21657       LMask[i] = i;
21658   }
21659
21660   // Likewise, view RHS in the form
21661   //   RHS = VECTOR_SHUFFLE C, D, RMask
21662   SDValue C, D;
21663   SmallVector<int, 16> RMask(NumElts);
21664   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21665     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21666       C = RHS.getOperand(0);
21667     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21668       D = RHS.getOperand(1);
21669     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21670     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21671   } else {
21672     if (RHS.getOpcode() != ISD::UNDEF)
21673       C = RHS;
21674     for (unsigned i = 0; i != NumElts; ++i)
21675       RMask[i] = i;
21676   }
21677
21678   // Check that the shuffles are both shuffling the same vectors.
21679   if (!(A == C && B == D) && !(A == D && B == C))
21680     return false;
21681
21682   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21683   if (!A.getNode() && !B.getNode())
21684     return false;
21685
21686   // If A and B occur in reverse order in RHS, then "swap" them (which means
21687   // rewriting the mask).
21688   if (A != C)
21689     CommuteVectorShuffleMask(RMask, NumElts);
21690
21691   // At this point LHS and RHS are equivalent to
21692   //   LHS = VECTOR_SHUFFLE A, B, LMask
21693   //   RHS = VECTOR_SHUFFLE A, B, RMask
21694   // Check that the masks correspond to performing a horizontal operation.
21695   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21696     for (unsigned i = 0; i != NumLaneElts; ++i) {
21697       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21698
21699       // Ignore any UNDEF components.
21700       if (LIdx < 0 || RIdx < 0 ||
21701           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21702           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21703         continue;
21704
21705       // Check that successive elements are being operated on.  If not, this is
21706       // not a horizontal operation.
21707       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21708       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21709       if (!(LIdx == Index && RIdx == Index + 1) &&
21710           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21711         return false;
21712     }
21713   }
21714
21715   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21716   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21717   return true;
21718 }
21719
21720 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21721 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21722                                   const X86Subtarget *Subtarget) {
21723   EVT VT = N->getValueType(0);
21724   SDValue LHS = N->getOperand(0);
21725   SDValue RHS = N->getOperand(1);
21726
21727   // Try to synthesize horizontal adds from adds of shuffles.
21728   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21729        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21730       isHorizontalBinOp(LHS, RHS, true))
21731     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21732   return SDValue();
21733 }
21734
21735 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21736 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21737                                   const X86Subtarget *Subtarget) {
21738   EVT VT = N->getValueType(0);
21739   SDValue LHS = N->getOperand(0);
21740   SDValue RHS = N->getOperand(1);
21741
21742   // Try to synthesize horizontal subs from subs of shuffles.
21743   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21744        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21745       isHorizontalBinOp(LHS, RHS, false))
21746     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21747   return SDValue();
21748 }
21749
21750 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21751 /// X86ISD::FXOR nodes.
21752 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21753   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21754   // F[X]OR(0.0, x) -> x
21755   // F[X]OR(x, 0.0) -> x
21756   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21757     if (C->getValueAPF().isPosZero())
21758       return N->getOperand(1);
21759   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21760     if (C->getValueAPF().isPosZero())
21761       return N->getOperand(0);
21762   return SDValue();
21763 }
21764
21765 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21766 /// X86ISD::FMAX nodes.
21767 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21768   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21769
21770   // Only perform optimizations if UnsafeMath is used.
21771   if (!DAG.getTarget().Options.UnsafeFPMath)
21772     return SDValue();
21773
21774   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21775   // into FMINC and FMAXC, which are Commutative operations.
21776   unsigned NewOp = 0;
21777   switch (N->getOpcode()) {
21778     default: llvm_unreachable("unknown opcode");
21779     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21780     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21781   }
21782
21783   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21784                      N->getOperand(0), N->getOperand(1));
21785 }
21786
21787 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21788 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21789   // FAND(0.0, x) -> 0.0
21790   // FAND(x, 0.0) -> 0.0
21791   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21792     if (C->getValueAPF().isPosZero())
21793       return N->getOperand(0);
21794   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21795     if (C->getValueAPF().isPosZero())
21796       return N->getOperand(1);
21797   return SDValue();
21798 }
21799
21800 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21801 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21802   // FANDN(x, 0.0) -> 0.0
21803   // FANDN(0.0, x) -> x
21804   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21805     if (C->getValueAPF().isPosZero())
21806       return N->getOperand(1);
21807   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21808     if (C->getValueAPF().isPosZero())
21809       return N->getOperand(1);
21810   return SDValue();
21811 }
21812
21813 static SDValue PerformBTCombine(SDNode *N,
21814                                 SelectionDAG &DAG,
21815                                 TargetLowering::DAGCombinerInfo &DCI) {
21816   // BT ignores high bits in the bit index operand.
21817   SDValue Op1 = N->getOperand(1);
21818   if (Op1.hasOneUse()) {
21819     unsigned BitWidth = Op1.getValueSizeInBits();
21820     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21821     APInt KnownZero, KnownOne;
21822     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21823                                           !DCI.isBeforeLegalizeOps());
21824     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21825     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21826         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21827       DCI.CommitTargetLoweringOpt(TLO);
21828   }
21829   return SDValue();
21830 }
21831
21832 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21833   SDValue Op = N->getOperand(0);
21834   if (Op.getOpcode() == ISD::BITCAST)
21835     Op = Op.getOperand(0);
21836   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21837   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21838       VT.getVectorElementType().getSizeInBits() ==
21839       OpVT.getVectorElementType().getSizeInBits()) {
21840     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21841   }
21842   return SDValue();
21843 }
21844
21845 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21846                                                const X86Subtarget *Subtarget) {
21847   EVT VT = N->getValueType(0);
21848   if (!VT.isVector())
21849     return SDValue();
21850
21851   SDValue N0 = N->getOperand(0);
21852   SDValue N1 = N->getOperand(1);
21853   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21854   SDLoc dl(N);
21855
21856   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21857   // both SSE and AVX2 since there is no sign-extended shift right
21858   // operation on a vector with 64-bit elements.
21859   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21860   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21861   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21862       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21863     SDValue N00 = N0.getOperand(0);
21864
21865     // EXTLOAD has a better solution on AVX2,
21866     // it may be replaced with X86ISD::VSEXT node.
21867     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21868       if (!ISD::isNormalLoad(N00.getNode()))
21869         return SDValue();
21870
21871     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21872         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21873                                   N00, N1);
21874       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21875     }
21876   }
21877   return SDValue();
21878 }
21879
21880 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21881                                   TargetLowering::DAGCombinerInfo &DCI,
21882                                   const X86Subtarget *Subtarget) {
21883   if (!DCI.isBeforeLegalizeOps())
21884     return SDValue();
21885
21886   if (!Subtarget->hasFp256())
21887     return SDValue();
21888
21889   EVT VT = N->getValueType(0);
21890   if (VT.isVector() && VT.getSizeInBits() == 256) {
21891     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21892     if (R.getNode())
21893       return R;
21894   }
21895
21896   return SDValue();
21897 }
21898
21899 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21900                                  const X86Subtarget* Subtarget) {
21901   SDLoc dl(N);
21902   EVT VT = N->getValueType(0);
21903
21904   // Let legalize expand this if it isn't a legal type yet.
21905   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21906     return SDValue();
21907
21908   EVT ScalarVT = VT.getScalarType();
21909   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21910       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21911     return SDValue();
21912
21913   SDValue A = N->getOperand(0);
21914   SDValue B = N->getOperand(1);
21915   SDValue C = N->getOperand(2);
21916
21917   bool NegA = (A.getOpcode() == ISD::FNEG);
21918   bool NegB = (B.getOpcode() == ISD::FNEG);
21919   bool NegC = (C.getOpcode() == ISD::FNEG);
21920
21921   // Negative multiplication when NegA xor NegB
21922   bool NegMul = (NegA != NegB);
21923   if (NegA)
21924     A = A.getOperand(0);
21925   if (NegB)
21926     B = B.getOperand(0);
21927   if (NegC)
21928     C = C.getOperand(0);
21929
21930   unsigned Opcode;
21931   if (!NegMul)
21932     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21933   else
21934     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21935
21936   return DAG.getNode(Opcode, dl, VT, A, B, C);
21937 }
21938
21939 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21940                                   TargetLowering::DAGCombinerInfo &DCI,
21941                                   const X86Subtarget *Subtarget) {
21942   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21943   //           (and (i32 x86isd::setcc_carry), 1)
21944   // This eliminates the zext. This transformation is necessary because
21945   // ISD::SETCC is always legalized to i8.
21946   SDLoc dl(N);
21947   SDValue N0 = N->getOperand(0);
21948   EVT VT = N->getValueType(0);
21949
21950   if (N0.getOpcode() == ISD::AND &&
21951       N0.hasOneUse() &&
21952       N0.getOperand(0).hasOneUse()) {
21953     SDValue N00 = N0.getOperand(0);
21954     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21955       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21956       if (!C || C->getZExtValue() != 1)
21957         return SDValue();
21958       return DAG.getNode(ISD::AND, dl, VT,
21959                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21960                                      N00.getOperand(0), N00.getOperand(1)),
21961                          DAG.getConstant(1, VT));
21962     }
21963   }
21964
21965   if (N0.getOpcode() == ISD::TRUNCATE &&
21966       N0.hasOneUse() &&
21967       N0.getOperand(0).hasOneUse()) {
21968     SDValue N00 = N0.getOperand(0);
21969     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21970       return DAG.getNode(ISD::AND, dl, VT,
21971                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21972                                      N00.getOperand(0), N00.getOperand(1)),
21973                          DAG.getConstant(1, VT));
21974     }
21975   }
21976   if (VT.is256BitVector()) {
21977     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21978     if (R.getNode())
21979       return R;
21980   }
21981
21982   return SDValue();
21983 }
21984
21985 // Optimize x == -y --> x+y == 0
21986 //          x != -y --> x+y != 0
21987 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21988                                       const X86Subtarget* Subtarget) {
21989   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21990   SDValue LHS = N->getOperand(0);
21991   SDValue RHS = N->getOperand(1);
21992   EVT VT = N->getValueType(0);
21993   SDLoc DL(N);
21994
21995   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21996     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21997       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21998         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21999                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22000         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22001                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22002       }
22003   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22004     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22005       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22006         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22007                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22008         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22009                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22010       }
22011
22012   if (VT.getScalarType() == MVT::i1) {
22013     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22014       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22015     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22016     if (!IsSEXT0 && !IsVZero0)
22017       return SDValue();
22018     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22019       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22020     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22021
22022     if (!IsSEXT1 && !IsVZero1)
22023       return SDValue();
22024
22025     if (IsSEXT0 && IsVZero1) {
22026       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22027       if (CC == ISD::SETEQ)
22028         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22029       return LHS.getOperand(0);
22030     }
22031     if (IsSEXT1 && IsVZero0) {
22032       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22033       if (CC == ISD::SETEQ)
22034         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22035       return RHS.getOperand(0);
22036     }
22037   }
22038
22039   return SDValue();
22040 }
22041
22042 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22043                                       const X86Subtarget *Subtarget) {
22044   SDLoc dl(N);
22045   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22046   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22047          "X86insertps is only defined for v4x32");
22048
22049   SDValue Ld = N->getOperand(1);
22050   if (MayFoldLoad(Ld)) {
22051     // Extract the countS bits from the immediate so we can get the proper
22052     // address when narrowing the vector load to a specific element.
22053     // When the second source op is a memory address, interps doesn't use
22054     // countS and just gets an f32 from that address.
22055     unsigned DestIndex =
22056         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22057     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22058   } else
22059     return SDValue();
22060
22061   // Create this as a scalar to vector to match the instruction pattern.
22062   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22063   // countS bits are ignored when loading from memory on insertps, which
22064   // means we don't need to explicitly set them to 0.
22065   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22066                      LoadScalarToVector, N->getOperand(2));
22067 }
22068
22069 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22070 // as "sbb reg,reg", since it can be extended without zext and produces
22071 // an all-ones bit which is more useful than 0/1 in some cases.
22072 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22073                                MVT VT) {
22074   if (VT == MVT::i8)
22075     return DAG.getNode(ISD::AND, DL, VT,
22076                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22077                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22078                        DAG.getConstant(1, VT));
22079   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22080   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22081                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22082                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22083 }
22084
22085 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22086 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22087                                    TargetLowering::DAGCombinerInfo &DCI,
22088                                    const X86Subtarget *Subtarget) {
22089   SDLoc DL(N);
22090   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22091   SDValue EFLAGS = N->getOperand(1);
22092
22093   if (CC == X86::COND_A) {
22094     // Try to convert COND_A into COND_B in an attempt to facilitate
22095     // materializing "setb reg".
22096     //
22097     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22098     // cannot take an immediate as its first operand.
22099     //
22100     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22101         EFLAGS.getValueType().isInteger() &&
22102         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22103       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22104                                    EFLAGS.getNode()->getVTList(),
22105                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22106       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22107       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22108     }
22109   }
22110
22111   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22112   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22113   // cases.
22114   if (CC == X86::COND_B)
22115     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22116
22117   SDValue Flags;
22118
22119   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22120   if (Flags.getNode()) {
22121     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22122     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22123   }
22124
22125   return SDValue();
22126 }
22127
22128 // Optimize branch condition evaluation.
22129 //
22130 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22131                                     TargetLowering::DAGCombinerInfo &DCI,
22132                                     const X86Subtarget *Subtarget) {
22133   SDLoc DL(N);
22134   SDValue Chain = N->getOperand(0);
22135   SDValue Dest = N->getOperand(1);
22136   SDValue EFLAGS = N->getOperand(3);
22137   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22138
22139   SDValue Flags;
22140
22141   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22142   if (Flags.getNode()) {
22143     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22144     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22145                        Flags);
22146   }
22147
22148   return SDValue();
22149 }
22150
22151 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22152                                                          SelectionDAG &DAG) {
22153   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22154   // optimize away operation when it's from a constant.
22155   //
22156   // The general transformation is:
22157   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22158   //       AND(VECTOR_CMP(x,y), constant2)
22159   //    constant2 = UNARYOP(constant)
22160
22161   // Early exit if this isn't a vector operation, the operand of the
22162   // unary operation isn't a bitwise AND, or if the sizes of the operations
22163   // aren't the same.
22164   EVT VT = N->getValueType(0);
22165   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22166       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22167       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22168     return SDValue();
22169
22170   // Now check that the other operand of the AND is a constant. We could
22171   // make the transformation for non-constant splats as well, but it's unclear
22172   // that would be a benefit as it would not eliminate any operations, just
22173   // perform one more step in scalar code before moving to the vector unit.
22174   if (BuildVectorSDNode *BV =
22175           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22176     // Bail out if the vector isn't a constant.
22177     if (!BV->isConstant())
22178       return SDValue();
22179
22180     // Everything checks out. Build up the new and improved node.
22181     SDLoc DL(N);
22182     EVT IntVT = BV->getValueType(0);
22183     // Create a new constant of the appropriate type for the transformed
22184     // DAG.
22185     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22186     // The AND node needs bitcasts to/from an integer vector type around it.
22187     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22188     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22189                                  N->getOperand(0)->getOperand(0), MaskConst);
22190     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22191     return Res;
22192   }
22193
22194   return SDValue();
22195 }
22196
22197 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22198                                         const X86TargetLowering *XTLI) {
22199   // First try to optimize away the conversion entirely when it's
22200   // conditionally from a constant. Vectors only.
22201   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22202   if (Res != SDValue())
22203     return Res;
22204
22205   // Now move on to more general possibilities.
22206   SDValue Op0 = N->getOperand(0);
22207   EVT InVT = Op0->getValueType(0);
22208
22209   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22210   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22211     SDLoc dl(N);
22212     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22213     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22214     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22215   }
22216
22217   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22218   // a 32-bit target where SSE doesn't support i64->FP operations.
22219   if (Op0.getOpcode() == ISD::LOAD) {
22220     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22221     EVT VT = Ld->getValueType(0);
22222     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22223         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22224         !XTLI->getSubtarget()->is64Bit() &&
22225         VT == MVT::i64) {
22226       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22227                                           Ld->getChain(), Op0, DAG);
22228       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22229       return FILDChain;
22230     }
22231   }
22232   return SDValue();
22233 }
22234
22235 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22236 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22237                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22238   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22239   // the result is either zero or one (depending on the input carry bit).
22240   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22241   if (X86::isZeroNode(N->getOperand(0)) &&
22242       X86::isZeroNode(N->getOperand(1)) &&
22243       // We don't have a good way to replace an EFLAGS use, so only do this when
22244       // dead right now.
22245       SDValue(N, 1).use_empty()) {
22246     SDLoc DL(N);
22247     EVT VT = N->getValueType(0);
22248     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22249     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22250                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22251                                            DAG.getConstant(X86::COND_B,MVT::i8),
22252                                            N->getOperand(2)),
22253                                DAG.getConstant(1, VT));
22254     return DCI.CombineTo(N, Res1, CarryOut);
22255   }
22256
22257   return SDValue();
22258 }
22259
22260 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22261 //      (add Y, (setne X, 0)) -> sbb -1, Y
22262 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22263 //      (sub (setne X, 0), Y) -> adc -1, Y
22264 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22265   SDLoc DL(N);
22266
22267   // Look through ZExts.
22268   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22269   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22270     return SDValue();
22271
22272   SDValue SetCC = Ext.getOperand(0);
22273   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22274     return SDValue();
22275
22276   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22277   if (CC != X86::COND_E && CC != X86::COND_NE)
22278     return SDValue();
22279
22280   SDValue Cmp = SetCC.getOperand(1);
22281   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22282       !X86::isZeroNode(Cmp.getOperand(1)) ||
22283       !Cmp.getOperand(0).getValueType().isInteger())
22284     return SDValue();
22285
22286   SDValue CmpOp0 = Cmp.getOperand(0);
22287   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22288                                DAG.getConstant(1, CmpOp0.getValueType()));
22289
22290   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22291   if (CC == X86::COND_NE)
22292     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22293                        DL, OtherVal.getValueType(), OtherVal,
22294                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22295   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22296                      DL, OtherVal.getValueType(), OtherVal,
22297                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22298 }
22299
22300 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22301 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22302                                  const X86Subtarget *Subtarget) {
22303   EVT VT = N->getValueType(0);
22304   SDValue Op0 = N->getOperand(0);
22305   SDValue Op1 = N->getOperand(1);
22306
22307   // Try to synthesize horizontal adds from adds of shuffles.
22308   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22309        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22310       isHorizontalBinOp(Op0, Op1, true))
22311     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22312
22313   return OptimizeConditionalInDecrement(N, DAG);
22314 }
22315
22316 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22317                                  const X86Subtarget *Subtarget) {
22318   SDValue Op0 = N->getOperand(0);
22319   SDValue Op1 = N->getOperand(1);
22320
22321   // X86 can't encode an immediate LHS of a sub. See if we can push the
22322   // negation into a preceding instruction.
22323   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22324     // If the RHS of the sub is a XOR with one use and a constant, invert the
22325     // immediate. Then add one to the LHS of the sub so we can turn
22326     // X-Y -> X+~Y+1, saving one register.
22327     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22328         isa<ConstantSDNode>(Op1.getOperand(1))) {
22329       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22330       EVT VT = Op0.getValueType();
22331       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22332                                    Op1.getOperand(0),
22333                                    DAG.getConstant(~XorC, VT));
22334       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22335                          DAG.getConstant(C->getAPIntValue()+1, VT));
22336     }
22337   }
22338
22339   // Try to synthesize horizontal adds from adds of shuffles.
22340   EVT VT = N->getValueType(0);
22341   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22342        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22343       isHorizontalBinOp(Op0, Op1, true))
22344     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22345
22346   return OptimizeConditionalInDecrement(N, DAG);
22347 }
22348
22349 /// performVZEXTCombine - Performs build vector combines
22350 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22351                                         TargetLowering::DAGCombinerInfo &DCI,
22352                                         const X86Subtarget *Subtarget) {
22353   // (vzext (bitcast (vzext (x)) -> (vzext x)
22354   SDValue In = N->getOperand(0);
22355   while (In.getOpcode() == ISD::BITCAST)
22356     In = In.getOperand(0);
22357
22358   if (In.getOpcode() != X86ISD::VZEXT)
22359     return SDValue();
22360
22361   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22362                      In.getOperand(0));
22363 }
22364
22365 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22366                                              DAGCombinerInfo &DCI) const {
22367   SelectionDAG &DAG = DCI.DAG;
22368   switch (N->getOpcode()) {
22369   default: break;
22370   case ISD::EXTRACT_VECTOR_ELT:
22371     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22372   case ISD::VSELECT:
22373   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22374   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22375   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22376   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22377   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22378   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22379   case ISD::SHL:
22380   case ISD::SRA:
22381   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22382   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22383   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22384   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22385   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22386   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22387   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22388   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22389   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22390   case X86ISD::FXOR:
22391   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22392   case X86ISD::FMIN:
22393   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22394   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22395   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22396   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22397   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22398   case ISD::ANY_EXTEND:
22399   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22400   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22401   case ISD::SIGN_EXTEND_INREG:
22402     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22403   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22404   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22405   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22406   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22407   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22408   case X86ISD::SHUFP:       // Handle all target specific shuffles
22409   case X86ISD::PALIGNR:
22410   case X86ISD::UNPCKH:
22411   case X86ISD::UNPCKL:
22412   case X86ISD::MOVHLPS:
22413   case X86ISD::MOVLHPS:
22414   case X86ISD::PSHUFD:
22415   case X86ISD::PSHUFHW:
22416   case X86ISD::PSHUFLW:
22417   case X86ISD::MOVSS:
22418   case X86ISD::MOVSD:
22419   case X86ISD::VPERMILP:
22420   case X86ISD::VPERM2X128:
22421   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22422   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22423   case ISD::INTRINSIC_WO_CHAIN:
22424     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22425   case X86ISD::INSERTPS:
22426     return PerformINSERTPSCombine(N, DAG, Subtarget);
22427   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22428   }
22429
22430   return SDValue();
22431 }
22432
22433 /// isTypeDesirableForOp - Return true if the target has native support for
22434 /// the specified value type and it is 'desirable' to use the type for the
22435 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22436 /// instruction encodings are longer and some i16 instructions are slow.
22437 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22438   if (!isTypeLegal(VT))
22439     return false;
22440   if (VT != MVT::i16)
22441     return true;
22442
22443   switch (Opc) {
22444   default:
22445     return true;
22446   case ISD::LOAD:
22447   case ISD::SIGN_EXTEND:
22448   case ISD::ZERO_EXTEND:
22449   case ISD::ANY_EXTEND:
22450   case ISD::SHL:
22451   case ISD::SRL:
22452   case ISD::SUB:
22453   case ISD::ADD:
22454   case ISD::MUL:
22455   case ISD::AND:
22456   case ISD::OR:
22457   case ISD::XOR:
22458     return false;
22459   }
22460 }
22461
22462 /// IsDesirableToPromoteOp - This method query the target whether it is
22463 /// beneficial for dag combiner to promote the specified node. If true, it
22464 /// should return the desired promotion type by reference.
22465 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22466   EVT VT = Op.getValueType();
22467   if (VT != MVT::i16)
22468     return false;
22469
22470   bool Promote = false;
22471   bool Commute = false;
22472   switch (Op.getOpcode()) {
22473   default: break;
22474   case ISD::LOAD: {
22475     LoadSDNode *LD = cast<LoadSDNode>(Op);
22476     // If the non-extending load has a single use and it's not live out, then it
22477     // might be folded.
22478     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22479                                                      Op.hasOneUse()*/) {
22480       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22481              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22482         // The only case where we'd want to promote LOAD (rather then it being
22483         // promoted as an operand is when it's only use is liveout.
22484         if (UI->getOpcode() != ISD::CopyToReg)
22485           return false;
22486       }
22487     }
22488     Promote = true;
22489     break;
22490   }
22491   case ISD::SIGN_EXTEND:
22492   case ISD::ZERO_EXTEND:
22493   case ISD::ANY_EXTEND:
22494     Promote = true;
22495     break;
22496   case ISD::SHL:
22497   case ISD::SRL: {
22498     SDValue N0 = Op.getOperand(0);
22499     // Look out for (store (shl (load), x)).
22500     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22501       return false;
22502     Promote = true;
22503     break;
22504   }
22505   case ISD::ADD:
22506   case ISD::MUL:
22507   case ISD::AND:
22508   case ISD::OR:
22509   case ISD::XOR:
22510     Commute = true;
22511     // fallthrough
22512   case ISD::SUB: {
22513     SDValue N0 = Op.getOperand(0);
22514     SDValue N1 = Op.getOperand(1);
22515     if (!Commute && MayFoldLoad(N1))
22516       return false;
22517     // Avoid disabling potential load folding opportunities.
22518     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22519       return false;
22520     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22521       return false;
22522     Promote = true;
22523   }
22524   }
22525
22526   PVT = MVT::i32;
22527   return Promote;
22528 }
22529
22530 //===----------------------------------------------------------------------===//
22531 //                           X86 Inline Assembly Support
22532 //===----------------------------------------------------------------------===//
22533
22534 namespace {
22535   // Helper to match a string separated by whitespace.
22536   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22537     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22538
22539     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22540       StringRef piece(*args[i]);
22541       if (!s.startswith(piece)) // Check if the piece matches.
22542         return false;
22543
22544       s = s.substr(piece.size());
22545       StringRef::size_type pos = s.find_first_not_of(" \t");
22546       if (pos == 0) // We matched a prefix.
22547         return false;
22548
22549       s = s.substr(pos);
22550     }
22551
22552     return s.empty();
22553   }
22554   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22555 }
22556
22557 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22558
22559   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22560     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22561         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22562         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22563
22564       if (AsmPieces.size() == 3)
22565         return true;
22566       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22567         return true;
22568     }
22569   }
22570   return false;
22571 }
22572
22573 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22574   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22575
22576   std::string AsmStr = IA->getAsmString();
22577
22578   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22579   if (!Ty || Ty->getBitWidth() % 16 != 0)
22580     return false;
22581
22582   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22583   SmallVector<StringRef, 4> AsmPieces;
22584   SplitString(AsmStr, AsmPieces, ";\n");
22585
22586   switch (AsmPieces.size()) {
22587   default: return false;
22588   case 1:
22589     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22590     // we will turn this bswap into something that will be lowered to logical
22591     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22592     // lower so don't worry about this.
22593     // bswap $0
22594     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22595         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22596         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22597         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22598         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22599         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22600       // No need to check constraints, nothing other than the equivalent of
22601       // "=r,0" would be valid here.
22602       return IntrinsicLowering::LowerToByteSwap(CI);
22603     }
22604
22605     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22606     if (CI->getType()->isIntegerTy(16) &&
22607         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22608         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22609          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22610       AsmPieces.clear();
22611       const std::string &ConstraintsStr = IA->getConstraintString();
22612       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22613       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22614       if (clobbersFlagRegisters(AsmPieces))
22615         return IntrinsicLowering::LowerToByteSwap(CI);
22616     }
22617     break;
22618   case 3:
22619     if (CI->getType()->isIntegerTy(32) &&
22620         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22621         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22622         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22623         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22624       AsmPieces.clear();
22625       const std::string &ConstraintsStr = IA->getConstraintString();
22626       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22627       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22628       if (clobbersFlagRegisters(AsmPieces))
22629         return IntrinsicLowering::LowerToByteSwap(CI);
22630     }
22631
22632     if (CI->getType()->isIntegerTy(64)) {
22633       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22634       if (Constraints.size() >= 2 &&
22635           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22636           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22637         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22638         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22639             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22640             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22641           return IntrinsicLowering::LowerToByteSwap(CI);
22642       }
22643     }
22644     break;
22645   }
22646   return false;
22647 }
22648
22649 /// getConstraintType - Given a constraint letter, return the type of
22650 /// constraint it is for this target.
22651 X86TargetLowering::ConstraintType
22652 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22653   if (Constraint.size() == 1) {
22654     switch (Constraint[0]) {
22655     case 'R':
22656     case 'q':
22657     case 'Q':
22658     case 'f':
22659     case 't':
22660     case 'u':
22661     case 'y':
22662     case 'x':
22663     case 'Y':
22664     case 'l':
22665       return C_RegisterClass;
22666     case 'a':
22667     case 'b':
22668     case 'c':
22669     case 'd':
22670     case 'S':
22671     case 'D':
22672     case 'A':
22673       return C_Register;
22674     case 'I':
22675     case 'J':
22676     case 'K':
22677     case 'L':
22678     case 'M':
22679     case 'N':
22680     case 'G':
22681     case 'C':
22682     case 'e':
22683     case 'Z':
22684       return C_Other;
22685     default:
22686       break;
22687     }
22688   }
22689   return TargetLowering::getConstraintType(Constraint);
22690 }
22691
22692 /// Examine constraint type and operand type and determine a weight value.
22693 /// This object must already have been set up with the operand type
22694 /// and the current alternative constraint selected.
22695 TargetLowering::ConstraintWeight
22696   X86TargetLowering::getSingleConstraintMatchWeight(
22697     AsmOperandInfo &info, const char *constraint) const {
22698   ConstraintWeight weight = CW_Invalid;
22699   Value *CallOperandVal = info.CallOperandVal;
22700     // If we don't have a value, we can't do a match,
22701     // but allow it at the lowest weight.
22702   if (!CallOperandVal)
22703     return CW_Default;
22704   Type *type = CallOperandVal->getType();
22705   // Look at the constraint type.
22706   switch (*constraint) {
22707   default:
22708     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22709   case 'R':
22710   case 'q':
22711   case 'Q':
22712   case 'a':
22713   case 'b':
22714   case 'c':
22715   case 'd':
22716   case 'S':
22717   case 'D':
22718   case 'A':
22719     if (CallOperandVal->getType()->isIntegerTy())
22720       weight = CW_SpecificReg;
22721     break;
22722   case 'f':
22723   case 't':
22724   case 'u':
22725     if (type->isFloatingPointTy())
22726       weight = CW_SpecificReg;
22727     break;
22728   case 'y':
22729     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22730       weight = CW_SpecificReg;
22731     break;
22732   case 'x':
22733   case 'Y':
22734     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22735         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22736       weight = CW_Register;
22737     break;
22738   case 'I':
22739     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22740       if (C->getZExtValue() <= 31)
22741         weight = CW_Constant;
22742     }
22743     break;
22744   case 'J':
22745     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22746       if (C->getZExtValue() <= 63)
22747         weight = CW_Constant;
22748     }
22749     break;
22750   case 'K':
22751     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22752       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22753         weight = CW_Constant;
22754     }
22755     break;
22756   case 'L':
22757     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22758       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22759         weight = CW_Constant;
22760     }
22761     break;
22762   case 'M':
22763     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22764       if (C->getZExtValue() <= 3)
22765         weight = CW_Constant;
22766     }
22767     break;
22768   case 'N':
22769     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22770       if (C->getZExtValue() <= 0xff)
22771         weight = CW_Constant;
22772     }
22773     break;
22774   case 'G':
22775   case 'C':
22776     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22777       weight = CW_Constant;
22778     }
22779     break;
22780   case 'e':
22781     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22782       if ((C->getSExtValue() >= -0x80000000LL) &&
22783           (C->getSExtValue() <= 0x7fffffffLL))
22784         weight = CW_Constant;
22785     }
22786     break;
22787   case 'Z':
22788     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22789       if (C->getZExtValue() <= 0xffffffff)
22790         weight = CW_Constant;
22791     }
22792     break;
22793   }
22794   return weight;
22795 }
22796
22797 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22798 /// with another that has more specific requirements based on the type of the
22799 /// corresponding operand.
22800 const char *X86TargetLowering::
22801 LowerXConstraint(EVT ConstraintVT) const {
22802   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22803   // 'f' like normal targets.
22804   if (ConstraintVT.isFloatingPoint()) {
22805     if (Subtarget->hasSSE2())
22806       return "Y";
22807     if (Subtarget->hasSSE1())
22808       return "x";
22809   }
22810
22811   return TargetLowering::LowerXConstraint(ConstraintVT);
22812 }
22813
22814 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22815 /// vector.  If it is invalid, don't add anything to Ops.
22816 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22817                                                      std::string &Constraint,
22818                                                      std::vector<SDValue>&Ops,
22819                                                      SelectionDAG &DAG) const {
22820   SDValue Result;
22821
22822   // Only support length 1 constraints for now.
22823   if (Constraint.length() > 1) return;
22824
22825   char ConstraintLetter = Constraint[0];
22826   switch (ConstraintLetter) {
22827   default: break;
22828   case 'I':
22829     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22830       if (C->getZExtValue() <= 31) {
22831         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22832         break;
22833       }
22834     }
22835     return;
22836   case 'J':
22837     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22838       if (C->getZExtValue() <= 63) {
22839         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22840         break;
22841       }
22842     }
22843     return;
22844   case 'K':
22845     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22846       if (isInt<8>(C->getSExtValue())) {
22847         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22848         break;
22849       }
22850     }
22851     return;
22852   case 'N':
22853     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22854       if (C->getZExtValue() <= 255) {
22855         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22856         break;
22857       }
22858     }
22859     return;
22860   case 'e': {
22861     // 32-bit signed value
22862     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22863       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22864                                            C->getSExtValue())) {
22865         // Widen to 64 bits here to get it sign extended.
22866         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22867         break;
22868       }
22869     // FIXME gcc accepts some relocatable values here too, but only in certain
22870     // memory models; it's complicated.
22871     }
22872     return;
22873   }
22874   case 'Z': {
22875     // 32-bit unsigned value
22876     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22877       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22878                                            C->getZExtValue())) {
22879         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22880         break;
22881       }
22882     }
22883     // FIXME gcc accepts some relocatable values here too, but only in certain
22884     // memory models; it's complicated.
22885     return;
22886   }
22887   case 'i': {
22888     // Literal immediates are always ok.
22889     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22890       // Widen to 64 bits here to get it sign extended.
22891       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22892       break;
22893     }
22894
22895     // In any sort of PIC mode addresses need to be computed at runtime by
22896     // adding in a register or some sort of table lookup.  These can't
22897     // be used as immediates.
22898     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22899       return;
22900
22901     // If we are in non-pic codegen mode, we allow the address of a global (with
22902     // an optional displacement) to be used with 'i'.
22903     GlobalAddressSDNode *GA = nullptr;
22904     int64_t Offset = 0;
22905
22906     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22907     while (1) {
22908       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22909         Offset += GA->getOffset();
22910         break;
22911       } else if (Op.getOpcode() == ISD::ADD) {
22912         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22913           Offset += C->getZExtValue();
22914           Op = Op.getOperand(0);
22915           continue;
22916         }
22917       } else if (Op.getOpcode() == ISD::SUB) {
22918         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22919           Offset += -C->getZExtValue();
22920           Op = Op.getOperand(0);
22921           continue;
22922         }
22923       }
22924
22925       // Otherwise, this isn't something we can handle, reject it.
22926       return;
22927     }
22928
22929     const GlobalValue *GV = GA->getGlobal();
22930     // If we require an extra load to get this address, as in PIC mode, we
22931     // can't accept it.
22932     if (isGlobalStubReference(
22933             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22934       return;
22935
22936     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22937                                         GA->getValueType(0), Offset);
22938     break;
22939   }
22940   }
22941
22942   if (Result.getNode()) {
22943     Ops.push_back(Result);
22944     return;
22945   }
22946   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22947 }
22948
22949 std::pair<unsigned, const TargetRegisterClass*>
22950 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22951                                                 MVT VT) const {
22952   // First, see if this is a constraint that directly corresponds to an LLVM
22953   // register class.
22954   if (Constraint.size() == 1) {
22955     // GCC Constraint Letters
22956     switch (Constraint[0]) {
22957     default: break;
22958       // TODO: Slight differences here in allocation order and leaving
22959       // RIP in the class. Do they matter any more here than they do
22960       // in the normal allocation?
22961     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22962       if (Subtarget->is64Bit()) {
22963         if (VT == MVT::i32 || VT == MVT::f32)
22964           return std::make_pair(0U, &X86::GR32RegClass);
22965         if (VT == MVT::i16)
22966           return std::make_pair(0U, &X86::GR16RegClass);
22967         if (VT == MVT::i8 || VT == MVT::i1)
22968           return std::make_pair(0U, &X86::GR8RegClass);
22969         if (VT == MVT::i64 || VT == MVT::f64)
22970           return std::make_pair(0U, &X86::GR64RegClass);
22971         break;
22972       }
22973       // 32-bit fallthrough
22974     case 'Q':   // Q_REGS
22975       if (VT == MVT::i32 || VT == MVT::f32)
22976         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22977       if (VT == MVT::i16)
22978         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22979       if (VT == MVT::i8 || VT == MVT::i1)
22980         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22981       if (VT == MVT::i64)
22982         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22983       break;
22984     case 'r':   // GENERAL_REGS
22985     case 'l':   // INDEX_REGS
22986       if (VT == MVT::i8 || VT == MVT::i1)
22987         return std::make_pair(0U, &X86::GR8RegClass);
22988       if (VT == MVT::i16)
22989         return std::make_pair(0U, &X86::GR16RegClass);
22990       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22991         return std::make_pair(0U, &X86::GR32RegClass);
22992       return std::make_pair(0U, &X86::GR64RegClass);
22993     case 'R':   // LEGACY_REGS
22994       if (VT == MVT::i8 || VT == MVT::i1)
22995         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22996       if (VT == MVT::i16)
22997         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22998       if (VT == MVT::i32 || !Subtarget->is64Bit())
22999         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23000       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23001     case 'f':  // FP Stack registers.
23002       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23003       // value to the correct fpstack register class.
23004       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23005         return std::make_pair(0U, &X86::RFP32RegClass);
23006       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23007         return std::make_pair(0U, &X86::RFP64RegClass);
23008       return std::make_pair(0U, &X86::RFP80RegClass);
23009     case 'y':   // MMX_REGS if MMX allowed.
23010       if (!Subtarget->hasMMX()) break;
23011       return std::make_pair(0U, &X86::VR64RegClass);
23012     case 'Y':   // SSE_REGS if SSE2 allowed
23013       if (!Subtarget->hasSSE2()) break;
23014       // FALL THROUGH.
23015     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23016       if (!Subtarget->hasSSE1()) break;
23017
23018       switch (VT.SimpleTy) {
23019       default: break;
23020       // Scalar SSE types.
23021       case MVT::f32:
23022       case MVT::i32:
23023         return std::make_pair(0U, &X86::FR32RegClass);
23024       case MVT::f64:
23025       case MVT::i64:
23026         return std::make_pair(0U, &X86::FR64RegClass);
23027       // Vector types.
23028       case MVT::v16i8:
23029       case MVT::v8i16:
23030       case MVT::v4i32:
23031       case MVT::v2i64:
23032       case MVT::v4f32:
23033       case MVT::v2f64:
23034         return std::make_pair(0U, &X86::VR128RegClass);
23035       // AVX types.
23036       case MVT::v32i8:
23037       case MVT::v16i16:
23038       case MVT::v8i32:
23039       case MVT::v4i64:
23040       case MVT::v8f32:
23041       case MVT::v4f64:
23042         return std::make_pair(0U, &X86::VR256RegClass);
23043       case MVT::v8f64:
23044       case MVT::v16f32:
23045       case MVT::v16i32:
23046       case MVT::v8i64:
23047         return std::make_pair(0U, &X86::VR512RegClass);
23048       }
23049       break;
23050     }
23051   }
23052
23053   // Use the default implementation in TargetLowering to convert the register
23054   // constraint into a member of a register class.
23055   std::pair<unsigned, const TargetRegisterClass*> Res;
23056   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23057
23058   // Not found as a standard register?
23059   if (!Res.second) {
23060     // Map st(0) -> st(7) -> ST0
23061     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23062         tolower(Constraint[1]) == 's' &&
23063         tolower(Constraint[2]) == 't' &&
23064         Constraint[3] == '(' &&
23065         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23066         Constraint[5] == ')' &&
23067         Constraint[6] == '}') {
23068
23069       Res.first = X86::FP0+Constraint[4]-'0';
23070       Res.second = &X86::RFP80RegClass;
23071       return Res;
23072     }
23073
23074     // GCC allows "st(0)" to be called just plain "st".
23075     if (StringRef("{st}").equals_lower(Constraint)) {
23076       Res.first = X86::FP0;
23077       Res.second = &X86::RFP80RegClass;
23078       return Res;
23079     }
23080
23081     // flags -> EFLAGS
23082     if (StringRef("{flags}").equals_lower(Constraint)) {
23083       Res.first = X86::EFLAGS;
23084       Res.second = &X86::CCRRegClass;
23085       return Res;
23086     }
23087
23088     // 'A' means EAX + EDX.
23089     if (Constraint == "A") {
23090       Res.first = X86::EAX;
23091       Res.second = &X86::GR32_ADRegClass;
23092       return Res;
23093     }
23094     return Res;
23095   }
23096
23097   // Otherwise, check to see if this is a register class of the wrong value
23098   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23099   // turn into {ax},{dx}.
23100   if (Res.second->hasType(VT))
23101     return Res;   // Correct type already, nothing to do.
23102
23103   // All of the single-register GCC register classes map their values onto
23104   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23105   // really want an 8-bit or 32-bit register, map to the appropriate register
23106   // class and return the appropriate register.
23107   if (Res.second == &X86::GR16RegClass) {
23108     if (VT == MVT::i8 || VT == MVT::i1) {
23109       unsigned DestReg = 0;
23110       switch (Res.first) {
23111       default: break;
23112       case X86::AX: DestReg = X86::AL; break;
23113       case X86::DX: DestReg = X86::DL; break;
23114       case X86::CX: DestReg = X86::CL; break;
23115       case X86::BX: DestReg = X86::BL; break;
23116       }
23117       if (DestReg) {
23118         Res.first = DestReg;
23119         Res.second = &X86::GR8RegClass;
23120       }
23121     } else if (VT == MVT::i32 || VT == MVT::f32) {
23122       unsigned DestReg = 0;
23123       switch (Res.first) {
23124       default: break;
23125       case X86::AX: DestReg = X86::EAX; break;
23126       case X86::DX: DestReg = X86::EDX; break;
23127       case X86::CX: DestReg = X86::ECX; break;
23128       case X86::BX: DestReg = X86::EBX; break;
23129       case X86::SI: DestReg = X86::ESI; break;
23130       case X86::DI: DestReg = X86::EDI; break;
23131       case X86::BP: DestReg = X86::EBP; break;
23132       case X86::SP: DestReg = X86::ESP; break;
23133       }
23134       if (DestReg) {
23135         Res.first = DestReg;
23136         Res.second = &X86::GR32RegClass;
23137       }
23138     } else if (VT == MVT::i64 || VT == MVT::f64) {
23139       unsigned DestReg = 0;
23140       switch (Res.first) {
23141       default: break;
23142       case X86::AX: DestReg = X86::RAX; break;
23143       case X86::DX: DestReg = X86::RDX; break;
23144       case X86::CX: DestReg = X86::RCX; break;
23145       case X86::BX: DestReg = X86::RBX; break;
23146       case X86::SI: DestReg = X86::RSI; break;
23147       case X86::DI: DestReg = X86::RDI; break;
23148       case X86::BP: DestReg = X86::RBP; break;
23149       case X86::SP: DestReg = X86::RSP; break;
23150       }
23151       if (DestReg) {
23152         Res.first = DestReg;
23153         Res.second = &X86::GR64RegClass;
23154       }
23155     }
23156   } else if (Res.second == &X86::FR32RegClass ||
23157              Res.second == &X86::FR64RegClass ||
23158              Res.second == &X86::VR128RegClass ||
23159              Res.second == &X86::VR256RegClass ||
23160              Res.second == &X86::FR32XRegClass ||
23161              Res.second == &X86::FR64XRegClass ||
23162              Res.second == &X86::VR128XRegClass ||
23163              Res.second == &X86::VR256XRegClass ||
23164              Res.second == &X86::VR512RegClass) {
23165     // Handle references to XMM physical registers that got mapped into the
23166     // wrong class.  This can happen with constraints like {xmm0} where the
23167     // target independent register mapper will just pick the first match it can
23168     // find, ignoring the required type.
23169
23170     if (VT == MVT::f32 || VT == MVT::i32)
23171       Res.second = &X86::FR32RegClass;
23172     else if (VT == MVT::f64 || VT == MVT::i64)
23173       Res.second = &X86::FR64RegClass;
23174     else if (X86::VR128RegClass.hasType(VT))
23175       Res.second = &X86::VR128RegClass;
23176     else if (X86::VR256RegClass.hasType(VT))
23177       Res.second = &X86::VR256RegClass;
23178     else if (X86::VR512RegClass.hasType(VT))
23179       Res.second = &X86::VR512RegClass;
23180   }
23181
23182   return Res;
23183 }
23184
23185 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23186                                             Type *Ty) const {
23187   // Scaling factors are not free at all.
23188   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23189   // will take 2 allocations in the out of order engine instead of 1
23190   // for plain addressing mode, i.e. inst (reg1).
23191   // E.g.,
23192   // vaddps (%rsi,%drx), %ymm0, %ymm1
23193   // Requires two allocations (one for the load, one for the computation)
23194   // whereas:
23195   // vaddps (%rsi), %ymm0, %ymm1
23196   // Requires just 1 allocation, i.e., freeing allocations for other operations
23197   // and having less micro operations to execute.
23198   //
23199   // For some X86 architectures, this is even worse because for instance for
23200   // stores, the complex addressing mode forces the instruction to use the
23201   // "load" ports instead of the dedicated "store" port.
23202   // E.g., on Haswell:
23203   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23204   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23205   if (isLegalAddressingMode(AM, Ty))
23206     // Scale represents reg2 * scale, thus account for 1
23207     // as soon as we use a second register.
23208     return AM.Scale != 0;
23209   return -1;
23210 }
23211
23212 bool X86TargetLowering::isTargetFTOL() const {
23213   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23214 }